palbase 0.11.0 → 0.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{KXY2SF4N.js → 4NC6D3AY.js} +2 -2
- package/dist/chunks/{AEAFASN2.js → 4OASGT7Q.js} +2 -2
- package/dist/chunks/{7JE4KOPN.js → 5FJNJOWL.js} +2 -2
- package/dist/chunks/{5D7BAVO5.js → 6FV2T52H.js} +1 -1
- package/dist/chunks/{2MS22NJC.js → 6S6MUPJA.js} +2 -2
- package/dist/chunks/{GUFHH4DP.js → BPFIGT6G.js} +2 -2
- package/dist/chunks/{D6RL5OCI.js → D5A6USBN.js} +2 -2
- package/dist/chunks/{LJ3VOTHH.js → E765DY7Q.js} +2 -2
- package/dist/chunks/{BAOQMZPI.js → FIWWCA6S.js} +2 -2
- package/dist/chunks/{476DZPIV.js → MWKPDZHT.js} +2 -2
- package/dist/chunks/{2CQIOY2Z.js → NT7K4S2X.js} +1 -1
- package/dist/chunks/{QX7E6TNL.js → NZRVCF6B.js} +1 -1
- package/dist/chunks/{NHNXW6EK.js → PF3S7VGN.js} +1 -1
- package/dist/chunks/{CQBT2Z2T.js → QNJK2UIR.js} +2 -2
- package/dist/chunks/{S4GBHZOR.js → SI2TXLYT.js} +1 -1
- package/dist/chunks/{GCVVMTWI.js → VPFDS7G7.js} +2 -2
- package/dist/chunks/{XBT3QJRS.js → W6LUHPMU.js} +2 -2
- package/dist/chunks/{DAYQLOBB.js → W7UOMPUA.js} +2 -2
- package/dist/chunks/{63TWL4SB.js → WUPBDP6G.js} +2 -2
- package/dist/chunks/{WYUC5N2T.js → XOPSQEWX.js} +1 -1
- package/dist/chunks/{52DZTUF7.js → XQUWS373.js} +2 -2
- package/dist/cli.js +102 -102
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/internal/src/modules/purchases.d.ts +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
2
|
-
import{a as yt,c as ae,d as zn,e as Hn,f as ge,h as E,i as Gn}from"./GUFHH4DP.js";import{b as et,d as mt,e as Nn,f as Un,g as ht,h as gt,k as Ln,q as In}from"./GCVVMTWI.js";import{b as ce}from"./7JE4KOPN.js";import"reflect-metadata";var zt=[{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}],Kn="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)",wt=/^\d+$/;function Ds(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),i=1;if(a!==-1){let g=s.slice(a+1);if(!wt.test(g)||Number(g)<1||Number(g)>n)return;i=Number(g)}let u=t,m=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),S=o.slice(g+1);if(!wt.test(k)||!wt.test(S)||Number(k)<t||Number(S)>n||Number(k)>Number(S))return;u=Number(k),m=Number(S)}else{if(!wt.test(o)||Number(o)<t||Number(o)>n)return;u=Number(o),m=a===-1?u:n}for(let g=u;g<=m;g+=i)r.add(g)}return r}function Fn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${Kn}; "${e}" is not`;let n=[];for(let m=0;m<5;m++){let g=Ds(t[m],zt[m].lo,zt[m].hi);if(!g)return`${Kn}; its ${zt[m].name} "${t[m]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),i=t[4].startsWith("*"),u=new Date(Date.UTC(2e3,0,1));for(let m=0;m<366*8+2;m++,u.setUTCDate(u.getUTCDate()+1)){if(!s.has(u.getUTCMonth()+1))continue;let g=r.has(u.getUTCDate()),k=a.has(u.getUTCDay());if(o||i?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Ce=Symbol.for("palbase.backend.controller"),je=Symbol.for("palbase.backend.routes"),Gt=Symbol.for("palbase.backend.params"),Kt=Symbol.for("palbase.backend.injectable"),Ft=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),Me=Symbol.for("palbase.backend.webhook"),ke=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks"),we=Symbol.for("palbase.backend.testUserTemplates");function ue(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Ht=Symbol.for("palbase.backend.declared");function oe(){let e=globalThis;return e[Ht]instanceof Set||(e[Ht]=new Set),e[Ht]}var De=new Set(["webhooks","_palbase"]);function bi(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&&De.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ue(n,Ce,()=>({basePath:e,options:t})),oe().add(n)}}function Ne(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ue(r.constructor,je,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var ki=Ne("GET"),vi=Ne("POST"),Ti=Ne("PUT"),$i=Ne("PATCH"),Ei=Ne("DELETE"),Si=Ne("QUERY");function fe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ue(n.constructor,Gt,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function Bt(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 _i=e=>fe("body",{schema:Bt("Body",e)}),xi=e=>fe("query",{schema:Bt("QueryParams",e)}),Oi=e=>fe("headers",e===void 0?{}:{schema:Bt("Headers",e)}),Ri=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return fe("param",{name:e})},Ai=()=>fe("user"),Pi=()=>fe("optionalUser"),Ci=()=>fe("req"),ji=()=>fe("requestId"),Mi=()=>fe("requestId"),Di=()=>fe("client");function Ni(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 fe("resolve",{resolver:e,options:t[0]})}function Ui(){return e=>{ue(e,Kt,()=>!0),oe().add(e)}}function Li(e){return t=>{ue(t,Ft,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Jn=/^[a-z]+(\.[a-z_]+)+$/,Ns=/^[a-z][a-z0-9-]{1,62}$/,qt=e=>e.startsWith("file.");function Ii(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"||!Ns.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(!qt(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ue(r.constructor,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),oe().add(r.constructor)}}var Jt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Us=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Bn(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(!Us.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 zi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Jt.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=Fn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Bn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Bn(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,ke))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,ke,{value:s,enumerable:!1}),oe().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ls=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Hi(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(!Ls.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&&!qn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${qn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Is(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Se)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:i}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ue(t,Me,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:i})=>({event:o,fn:i}))})),oe().add(t)}}function Is(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Gi(){return[...oe()].filter(e=>D(e,Ce)!==void 0)}function Ki(e){return(D(e,je)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var bt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Wi(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Jt.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,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),oe().add(s)}}var Zt;function Vn(e){Zt=e}function Wt(){if(!Zt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Zt}var zs=720*3600;function Hs(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>zs))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 Gs(e){if(typeof e=="string")return e;let t=e[ye];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Vi=yt("Tasks",{async enqueue(e,t,n={}){return Hs(n),Wt().enqueue(Gs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Wt().cancel(e,t.machine)},async get(e,t={}){return Wt().get(e,t.machine)}}),Vt=(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 Zn(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await ge.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 Vt(a.data,a.status===200)},async cancel(n,r){return Vt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Vt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ks=1e4,Fs=36e5,Wn=24*36e5,kt=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 ce({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 ce({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 ce({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 u of this.tasks.values())if(u.task===t&&u.key===r.key&&(u.finishedAt===void 0||this.now()-u.finishedAt<Wn))return this.view(u,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,i={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ce({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 ce({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(i){a={status:500,message:i.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ks*2**Math.min(t.attempt-1,16),Fs),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,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Wn&&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()}}};var vt="/_palbase/test-user-templates",Bs=/^[a-z][a-z0-9_-]{0,63}$/;function Xi(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bs.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,we))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,we,{value:r,enumerable:!1}),oe().add(s)}}function Qn(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Yn(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ce&&n.status===404)return!1;throw n}}var qs="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Xn(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,qs),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var Qt="/_palbase/storage/upload/authorize",er="/_palbase/storage/upload/complete",Yt="/_palbase/realtime/rooms";var Js=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ue(e){if(!Js(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function tr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function nr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Tt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ws=/^[a-z][a-z0-9-]{1,62}$/,rr=1024,Vs=new Set(["userId","uploadId","filename"]);function sd(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(!Ws.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=Zs(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,i,u)=>{if(typeof i!="string"||u===void 0||typeof u.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ue(o.constructor,je,()=>[]).push({method:"POST",subpath:e,fn:i,options:a,upload:s})}}function ad(){return fe("uploadedObject")}function Zs(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Vs.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 Qs(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ys(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ys(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 ar(e,t){let n=Qs(e,t);return sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${rr} bytes)`}}function or(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var 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:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Ue(t.user);if(!o)return"user is { id?, session?, role }";let i=tr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let u=Xs(t.uploadedObject);return u?u.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:"",uploadedObject:u,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Xs(e){if(!Xt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:i,height:u,thumbhash:m,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||u!==void 0&&typeof u!="number"||m!==void 0&&typeof m!="string")&&!(!Xt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...i!==void 0?{width:i}:{},...u!==void 0?{height:u}:{},...m!==void 0?{thumbhash:m}:{},variants:{...g}}}import{markData as ea}from"palgres";var _e=Symbol.for("palbase.backend.gateway"),ze=Symbol.for("palbase.backend.gatewayHooks"),dr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},ta={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(dr),output:()=>structuredClone(dr)}}},hr=Symbol.for("palbase.backend.gatewayRefusal"),cr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,hr,{value:!0})}},na=e=>typeof e=="object"&&e!==null&&e[hr]===!0&&typeof e.reason=="string",Le=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,ra=6e4,sa=86400,ur=604800,lr=65536,ve=255,aa=["roles:","flags:","messaging:","debug:"],oa=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ie=e=>new TextEncoder().encode(e).byteLength,en=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",rn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function ia(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(Ie(e)>ve)return`a channel is ${ve} 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=aa.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 gr(e){if(typeof e!="string"||e==="")return"is a name";if(Ie(e)>ve)return`is ${ve} bytes at most`}function ld(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=ia(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&rn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=da(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||oa.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let i=a.events??{};if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(i,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,k]of Object.entries(i)){let S=gr(g);if(S)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${S}`);if(!en(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let u=ue(a,ze,sn),m={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...i,chat:ta}:{...i},chat:r.chat===!0,graceMs:r.graceMs??ra,hooks:{...u.hooks},messages:Object.assign(Object.create(null),u.messages)};if(m.access===void 0&&m.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(m.access!==void 0&&m.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${m.access}' and @Authorize both say who may join \u2014 keep one`);if(m.publish&&Le(m))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(m.publish&&m.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(m.chat&&!Le(m))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ue(a,_e,()=>m),oe().add(a)}}function da(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return sa;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>ur)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${ur} (a week)`);return n}var sn=()=>({hooks:Object.create(null),messages:Object.create(null)}),ca={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function tt(e){let t=ca[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ue(n.constructor,ze,sn),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,oe().add(n.constructor)}}var fd=tt("authorize"),pd=tt("first"),md=tt("connect"),hd=tt("disconnect"),gd=tt("empty");function yd(e,t,n={}){let r=gr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!en(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!en(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let i=ue(s.constructor,ze,sn),u=i.messages[e];if(u!==void 0&&u.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${u.fn} and ${a}).`);i.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},oe().add(s.constructor)}}function ua(e){return D(e,_e)}function la(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function yr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ie(r)>ve?{problem:`a channel is ${ve} bytes at most`}:r}function fa(e,t,n){let r=rn(e).map(i=>i.slice(1,-1));for(let i of Object.keys(t))if(!r.includes(i))return{problem:`{${i}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(i=>Object.hasOwn(t,i))?yr(e,t):pa(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(i=>`{${i}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function pa(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var ma=1e4,ha=1e3,ga=100,an=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},pr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function wr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:w,instance:_}of e){let b=ua(w),x=a.get(b.name);if(x!==void 0&&x!==w)throw new TypeError(`@Gateway("${b.pattern}"): two gateways are named ${b.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(b.name,w);let P=s.get(pr(b.pattern));if(P!==void 0)throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: ${n.get(P)?.cls.name}'s "${P}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(pr(b.pattern),b.pattern);for(let[K,B]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([G,U])=>[`message ${G}`,U.fn])])if(typeof _[B]!="function")throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: its ${K} is ${B}, which is no method of it`);let N={cls:w,instance:_,g:b};n.set(b.pattern,N),r.set(w,N)}let o=new Map,i=new Set,u=new Set,m=new nn(t.broadcast),g=w=>{let _=o.get(w);return _||(_=new AbortController,o.set(w,_)),_},k=(w,_)=>{_?.abort(),o.get(w)===_&&o.delete(w)},S=(w,_,b,x,P,N)=>{if(!Object.hasOwn(w.g.events,b)){E.warn(`[palbase] ${P}: emit("${b}") is not sent \u2014 ${w.cls.name} declares no event "${b}" (static events)`);return}if(w.g.chat&&b==="chat"){E.warn(`[palbase] ${P}: emit("chat") is not sent \u2014 ${w.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}m.send({topic:_,event:b,payload:x??{},...N!==void 0?{conn_id:N}:{}},P)},I=async(w,_,b)=>{if(typeof w!="object"||w===null||typeof w.pipe!="function")throw new TypeError(`${b}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await w.pipe(_)};function H(w,_,b,x,P,N,K){let B=x?.signal??AbortSignal.abort(),G=`${w.cls.name} (${_})`;return{channel:_,params:Object.freeze({...b}),signal:B,count:P,user:N,emit:(U,W)=>S(w,_,U,W,G,K),pipe:U=>I(U,_,G),owner:{hold(U){ae.exit(async()=>{try{await U(B)}catch(W){B.aborted||E.error(`[palbase] ${G}: a task owner.hold ran failed`,{error:W})}}).catch(()=>{})},release:()=>k(_,x)}}}function z(w){let{room:_,channel:b}=w;if(typeof _!="string"||typeof b!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let x=n.get(_);return!x||!Le(x.g)?he(404,"not_found",`This app serves no gateway "${_}"`):{entry:x,channel:b,params:la(_,b)}}let te=(w,_)=>he(400,"bad_request",`"${_}" is not a channel of the gateway "${w}"`);async function ee(w,_){let b=z(w);if("status"in b)return b;let{entry:x,channel:P,params:N}=b,K={status:200,body:{subscribe:!1,publish:!1}};if(!N)return E.warn(`[palbase] ${x.cls.name}: realtime asked about "${P}", which is not a channel of the gateway "${x.g.pattern}"; the join is refused`),K;let B=Ue(w.user),G=B?.id;if(!G)return K;if(x.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}};if(x.g.access==="owner")return N[rn(x.g.pattern)[0].slice(1,-1)]===G?{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}}:K;let U=x.g.hooks.authorize;if(!U)return K;let W,V;try{W=await t.run(B,`${x.cls.name}.${U}`,_,async()=>x.instance[U]({user:{id:G},params:Object.freeze({...N})})),V=ya(W)}catch(Y){if(t.isOutage(Y)||_?.aborted)throw Y;return E.error(`[palbase] ${x.cls.name}.${U} (@Authorize of ${P}) failed; the join is refused`,{error:Y}),K}return V==="malformed"?(E.warn(`[palbase] ${x.cls.name}.${U} (@Authorize of ${P}) answered ${wa(W)}, which is no grant (true, { read, write } or null); the join is refused`),K):{status:200,body:V}}async function se(w,_){let b=z(w);if("status"in b)return b;if(!b.params)return te(b.entry.g.pattern,b.channel);let x=Ue(w.user);if(!x?.id||typeof w.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let P=Object.hasOwn(b.entry.g.messages,w.event)?b.entry.g.messages[w.event]:void 0;if(!P)return{status:200,body:{ok:!1,reason:tn(`gateway "${b.channel}" takes no message "${w.event}"`,$t)}};let N=await P.schema["~standard"].validate(ea(w.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:mr(N.issues)}};let K=g(b.channel),B={...H(b.entry,b.channel,b.params,K,0,{id:x.id}),payload:N.value},G=`${b.entry.cls.name}.${P.fn} (@Subscribe "${w.event}" of ${b.channel})`,U;try{U=await t.run(x,`${b.entry.cls.name}.${P.fn}`,_,async()=>b.entry.instance[P.fn](B))}catch(V){if(t.isOutage(V))throw V;return na(V)?{status:200,body:{ok:!1,reason:tn(V.reason,$t)}}:(_?.aborted||E.error(`[palbase] ${G} failed`,{error:V}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(U===void 0)return{status:200,body:{ok:!0}};if(P.reply){let V=await P.reply["~standard"].validate(U);if(V.issues)return E.error(`[palbase] ${G} returned an ack its reply schema refuses (${mr(V.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};U=V.value}let W;try{W=JSON.stringify(U)}catch(V){return E.error(`[palbase] ${G} returned an ack that is not JSON; the member is told it failed`,{error:V}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return W===void 0?{status:200,body:{ok:!0}}:Ie(W)>lr?(E.error(`[palbase] ${G} returned an ack of ${Ie(W)} bytes, past ${lr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(W)}}}async function v(w,_){let b=z(w);if("status"in b)return b;if(!b.params)return te(b.entry.g.pattern,b.channel);let x=w.event;if(typeof x!="string"||!Object.hasOwn(fr,x))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let P=typeof w.count=="number"&&Number.isInteger(w.count)&&w.count>=0?w.count:void 0;if(P===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let N=x==="join"||x==="leave",K=N?Ue(w.user):void 0,B=N?w.connId:void 0;if(N&&(!K?.id||typeof B!="string"||B===""))return he(400,"bad_request",`A ${x} names its member: user and connId`);let G=`${x}\0${b.channel}\0${typeof B=="string"?B:""}`;if(N&&i.has(G))return{status:204};if(u.has(G))return he(503,"in_progress","This moment of the gateway is being handled",5);u.add(G);try{let U=b.entry.g.hooks[fr[x]],W;if(x==="empty"?(W=o.get(b.channel),k(b.channel,W)):W=x==="leave"?o.get(b.channel):g(b.channel),U){let V=H(b.entry,b.channel,b.params,W,P,{id:K?.id??""},x==="join"?B:void 0);try{await t.run(K,`${b.entry.cls.name}.${U}`,_,async()=>b.entry.instance[U](V))}catch(Y){if(t.isOutage(Y))throw Y;return _?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${U} (${x} of ${b.channel}) failed; realtime tells it again`,{error:Y}),he(500,"handler_failed",`The gateway's ${x} could not be handled`)}}return N&&(i.add(G),i.size>ma&&i.delete(i.values().next().value)),{status:204}}finally{u.delete(G)}}function Q(w,_){let b=r.get(w),x=`Palbase.gateways.to(${w?.name??String(w)})`;if(!b)throw new TypeError(`${x}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let P=yr(b.g.pattern,_??{});if(typeof P!="string")throw new TypeError(`${x}: ${P.problem}`);return{entry:b,channel:P,where:x}}return{declarations:[...n.values()].map(w=>w.g),async serve(w,_,b){return an(_)?w==="authorize"?ee(_,b):w==="message"?se(_,b):w==="lifecycle"?v(_,b):he(404,"not_found",`No gateway call ${JSON.stringify(w)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(w,_,b,x){let{entry:P,channel:N,where:K}=Q(w,_);S(P,N,b,x,K)},async pipe(w,_,b){let{channel:x,where:P}=Q(w,_);await I(b,x,P)},async revalidate(w,_,b={}){let x=r.get(w),P=`Palbase.gateways.to(${w?.name??String(w)}).revalidate`;if(!x)throw new TypeError(`${P}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=fa(x.g.pattern,_??{},b);if("problem"in N)throw new TypeError(`${P}: ${N.problem}`);await t.revalidate(N)},close(){for(let w of o.values())w.abort();o.clear()}}}function ya(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!an(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function wa(e){return Array.isArray(e)?"an array":an(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 ba=20,$t=256;function mr(e){let t="";for(let n of e.slice(0,ba)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=$t)break}return tn(t,$t)}function tn(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 nn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ie(t.event)>ve){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${ve} bytes`);return}try{JSON.stringify(t.payload)}catch(a){E.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=ha?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),ae.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,ga);try{await this.broadcast(s)}catch(o){E.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),E.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as on,createHmac as ka,createPublicKey as Tr,timingSafeEqual as va,verify as $r}from"node:crypto";function vd(e){let t=D(e,Me);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 Er(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let i=D(o,Me),u=s.get(i.name);if(u)throw new TypeError(`@Webhook "${i.name}" is declared by ${u.cls.name} and by ${o.name}: /webhooks/${i.name} is one endpoint`);let m=`@Webhook "${i.name}" (${o.name})`,g=n[i.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${m} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=Ta(i,g)}catch(H){a.push(`${m}: ${i.secret.env} ${H.message}`)}let S=t(o),I=new Map(i.events.map(({event:H,fn:z})=>[H,{name:`${o.name}.${z}`,call:(te,ee)=>S[z](te,ee)}]));s.set(i.name,{name:i.name,cls:o,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:I})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as yt,c as ae,d as zn,e as Hn,f as ge,h as E,i as Gn}from"./BPFIGT6G.js";import{b as et,d as mt,e as Nn,f as Un,g as ht,h as gt,k as Ln,q as In}from"./VPFDS7G7.js";import{b as ce}from"./5FJNJOWL.js";import"reflect-metadata";var zt=[{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}],Kn="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)",wt=/^\d+$/;function Ds(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),i=1;if(a!==-1){let g=s.slice(a+1);if(!wt.test(g)||Number(g)<1||Number(g)>n)return;i=Number(g)}let u=t,m=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),S=o.slice(g+1);if(!wt.test(k)||!wt.test(S)||Number(k)<t||Number(S)>n||Number(k)>Number(S))return;u=Number(k),m=Number(S)}else{if(!wt.test(o)||Number(o)<t||Number(o)>n)return;u=Number(o),m=a===-1?u:n}for(let g=u;g<=m;g+=i)r.add(g)}return r}function Fn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${Kn}; "${e}" is not`;let n=[];for(let m=0;m<5;m++){let g=Ds(t[m],zt[m].lo,zt[m].hi);if(!g)return`${Kn}; its ${zt[m].name} "${t[m]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),i=t[4].startsWith("*"),u=new Date(Date.UTC(2e3,0,1));for(let m=0;m<366*8+2;m++,u.setUTCDate(u.getUTCDate()+1)){if(!s.has(u.getUTCMonth()+1))continue;let g=r.has(u.getUTCDate()),k=a.has(u.getUTCDay());if(o||i?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Ce=Symbol.for("palbase.backend.controller"),je=Symbol.for("palbase.backend.routes"),Gt=Symbol.for("palbase.backend.params"),Kt=Symbol.for("palbase.backend.injectable"),Ft=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),Me=Symbol.for("palbase.backend.webhook"),ke=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks"),we=Symbol.for("palbase.backend.testUserTemplates");function ue(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Ht=Symbol.for("palbase.backend.declared");function oe(){let e=globalThis;return e[Ht]instanceof Set||(e[Ht]=new Set),e[Ht]}var De=new Set(["webhooks","_palbase"]);function bi(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&&De.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ue(n,Ce,()=>({basePath:e,options:t})),oe().add(n)}}function Ne(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ue(r.constructor,je,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var ki=Ne("GET"),vi=Ne("POST"),Ti=Ne("PUT"),$i=Ne("PATCH"),Ei=Ne("DELETE"),Si=Ne("QUERY");function fe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ue(n.constructor,Gt,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function Bt(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 _i=e=>fe("body",{schema:Bt("Body",e)}),xi=e=>fe("query",{schema:Bt("QueryParams",e)}),Oi=e=>fe("headers",e===void 0?{}:{schema:Bt("Headers",e)}),Ri=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return fe("param",{name:e})},Ai=()=>fe("user"),Pi=()=>fe("optionalUser"),Ci=()=>fe("req"),ji=()=>fe("requestId"),Mi=()=>fe("requestId"),Di=()=>fe("client");function Ni(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 fe("resolve",{resolver:e,options:t[0]})}function Ui(){return e=>{ue(e,Kt,()=>!0),oe().add(e)}}function Li(e){return t=>{ue(t,Ft,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Jn=/^[a-z]+(\.[a-z_]+)+$/,Ns=/^[a-z][a-z0-9-]{1,62}$/,qt=e=>e.startsWith("file.");function Ii(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"||!Ns.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(!qt(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ue(r.constructor,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),oe().add(r.constructor)}}var Jt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Us=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Bn(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(!Us.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 zi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Jt.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=Fn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Bn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Bn(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,ke))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,ke,{value:s,enumerable:!1}),oe().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ls=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Hi(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(!Ls.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&&!qn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${qn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Is(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Se)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:i}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ue(t,Me,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:i})=>({event:o,fn:i}))})),oe().add(t)}}function Is(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Gi(){return[...oe()].filter(e=>D(e,Ce)!==void 0)}function Ki(e){return(D(e,je)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var bt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Wi(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Jt.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,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),oe().add(s)}}var Zt;function Vn(e){Zt=e}function Wt(){if(!Zt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Zt}var zs=720*3600;function Hs(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>zs))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 Gs(e){if(typeof e=="string")return e;let t=e[ye];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Vi=yt("Tasks",{async enqueue(e,t,n={}){return Hs(n),Wt().enqueue(Gs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Wt().cancel(e,t.machine)},async get(e,t={}){return Wt().get(e,t.machine)}}),Vt=(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 Zn(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await ge.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 Vt(a.data,a.status===200)},async cancel(n,r){return Vt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Vt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ks=1e4,Fs=36e5,Wn=24*36e5,kt=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 ce({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 ce({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 ce({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 u of this.tasks.values())if(u.task===t&&u.key===r.key&&(u.finishedAt===void 0||this.now()-u.finishedAt<Wn))return this.view(u,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,i={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ce({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 ce({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(i){a={status:500,message:i.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ks*2**Math.min(t.attempt-1,16),Fs),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,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Wn&&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()}}};var vt="/_palbase/test-user-templates",Bs=/^[a-z][a-z0-9_-]{0,63}$/;function Xi(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bs.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,we))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,we,{value:r,enumerable:!1}),oe().add(s)}}function Qn(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Yn(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ce&&n.status===404)return!1;throw n}}var qs="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Xn(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,qs),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var Qt="/_palbase/storage/upload/authorize",er="/_palbase/storage/upload/complete",Yt="/_palbase/realtime/rooms";var Js=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ue(e){if(!Js(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function tr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function nr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Tt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ws=/^[a-z][a-z0-9-]{1,62}$/,rr=1024,Vs=new Set(["userId","uploadId","filename"]);function sd(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(!Ws.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=Zs(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,i,u)=>{if(typeof i!="string"||u===void 0||typeof u.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ue(o.constructor,je,()=>[]).push({method:"POST",subpath:e,fn:i,options:a,upload:s})}}function ad(){return fe("uploadedObject")}function Zs(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Vs.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 Qs(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ys(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ys(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 ar(e,t){let n=Qs(e,t);return sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${rr} bytes)`}}function or(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var 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:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Ue(t.user);if(!o)return"user is { id?, session?, role }";let i=tr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let u=Xs(t.uploadedObject);return u?u.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:"",uploadedObject:u,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Xs(e){if(!Xt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:i,height:u,thumbhash:m,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||u!==void 0&&typeof u!="number"||m!==void 0&&typeof m!="string")&&!(!Xt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...i!==void 0?{width:i}:{},...u!==void 0?{height:u}:{},...m!==void 0?{thumbhash:m}:{},variants:{...g}}}import{markData as ea}from"palgres";var _e=Symbol.for("palbase.backend.gateway"),ze=Symbol.for("palbase.backend.gatewayHooks"),dr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},ta={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(dr),output:()=>structuredClone(dr)}}},hr=Symbol.for("palbase.backend.gatewayRefusal"),cr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,hr,{value:!0})}},na=e=>typeof e=="object"&&e!==null&&e[hr]===!0&&typeof e.reason=="string",Le=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,ra=6e4,sa=86400,ur=604800,lr=65536,ve=255,aa=["roles:","flags:","messaging:","debug:"],oa=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ie=e=>new TextEncoder().encode(e).byteLength,en=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",rn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function ia(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(Ie(e)>ve)return`a channel is ${ve} 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=aa.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 gr(e){if(typeof e!="string"||e==="")return"is a name";if(Ie(e)>ve)return`is ${ve} bytes at most`}function ld(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=ia(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&rn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=da(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||oa.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let i=a.events??{};if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(i,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,k]of Object.entries(i)){let S=gr(g);if(S)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${S}`);if(!en(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let u=ue(a,ze,sn),m={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...i,chat:ta}:{...i},chat:r.chat===!0,graceMs:r.graceMs??ra,hooks:{...u.hooks},messages:Object.assign(Object.create(null),u.messages)};if(m.access===void 0&&m.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(m.access!==void 0&&m.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${m.access}' and @Authorize both say who may join \u2014 keep one`);if(m.publish&&Le(m))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(m.publish&&m.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(m.chat&&!Le(m))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ue(a,_e,()=>m),oe().add(a)}}function da(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return sa;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>ur)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${ur} (a week)`);return n}var sn=()=>({hooks:Object.create(null),messages:Object.create(null)}),ca={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function tt(e){let t=ca[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ue(n.constructor,ze,sn),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,oe().add(n.constructor)}}var fd=tt("authorize"),pd=tt("first"),md=tt("connect"),hd=tt("disconnect"),gd=tt("empty");function yd(e,t,n={}){let r=gr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!en(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!en(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let i=ue(s.constructor,ze,sn),u=i.messages[e];if(u!==void 0&&u.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${u.fn} and ${a}).`);i.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},oe().add(s.constructor)}}function ua(e){return D(e,_e)}function la(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function yr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ie(r)>ve?{problem:`a channel is ${ve} bytes at most`}:r}function fa(e,t,n){let r=rn(e).map(i=>i.slice(1,-1));for(let i of Object.keys(t))if(!r.includes(i))return{problem:`{${i}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(i=>Object.hasOwn(t,i))?yr(e,t):pa(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(i=>`{${i}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function pa(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var ma=1e4,ha=1e3,ga=100,an=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},pr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function wr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:w,instance:_}of e){let b=ua(w),x=a.get(b.name);if(x!==void 0&&x!==w)throw new TypeError(`@Gateway("${b.pattern}"): two gateways are named ${b.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(b.name,w);let P=s.get(pr(b.pattern));if(P!==void 0)throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: ${n.get(P)?.cls.name}'s "${P}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(pr(b.pattern),b.pattern);for(let[K,B]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([G,U])=>[`message ${G}`,U.fn])])if(typeof _[B]!="function")throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: its ${K} is ${B}, which is no method of it`);let N={cls:w,instance:_,g:b};n.set(b.pattern,N),r.set(w,N)}let o=new Map,i=new Set,u=new Set,m=new nn(t.broadcast),g=w=>{let _=o.get(w);return _||(_=new AbortController,o.set(w,_)),_},k=(w,_)=>{_?.abort(),o.get(w)===_&&o.delete(w)},S=(w,_,b,x,P,N)=>{if(!Object.hasOwn(w.g.events,b)){E.warn(`[palbase] ${P}: emit("${b}") is not sent \u2014 ${w.cls.name} declares no event "${b}" (static events)`);return}if(w.g.chat&&b==="chat"){E.warn(`[palbase] ${P}: emit("chat") is not sent \u2014 ${w.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}m.send({topic:_,event:b,payload:x??{},...N!==void 0?{conn_id:N}:{}},P)},I=async(w,_,b)=>{if(typeof w!="object"||w===null||typeof w.pipe!="function")throw new TypeError(`${b}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await w.pipe(_)};function H(w,_,b,x,P,N,K){let B=x?.signal??AbortSignal.abort(),G=`${w.cls.name} (${_})`;return{channel:_,params:Object.freeze({...b}),signal:B,count:P,user:N,emit:(U,W)=>S(w,_,U,W,G,K),pipe:U=>I(U,_,G),owner:{hold(U){ae.exit(async()=>{try{await U(B)}catch(W){B.aborted||E.error(`[palbase] ${G}: a task owner.hold ran failed`,{error:W})}}).catch(()=>{})},release:()=>k(_,x)}}}function z(w){let{room:_,channel:b}=w;if(typeof _!="string"||typeof b!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let x=n.get(_);return!x||!Le(x.g)?he(404,"not_found",`This app serves no gateway "${_}"`):{entry:x,channel:b,params:la(_,b)}}let te=(w,_)=>he(400,"bad_request",`"${_}" is not a channel of the gateway "${w}"`);async function ee(w,_){let b=z(w);if("status"in b)return b;let{entry:x,channel:P,params:N}=b,K={status:200,body:{subscribe:!1,publish:!1}};if(!N)return E.warn(`[palbase] ${x.cls.name}: realtime asked about "${P}", which is not a channel of the gateway "${x.g.pattern}"; the join is refused`),K;let B=Ue(w.user),G=B?.id;if(!G)return K;if(x.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}};if(x.g.access==="owner")return N[rn(x.g.pattern)[0].slice(1,-1)]===G?{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}}:K;let U=x.g.hooks.authorize;if(!U)return K;let W,V;try{W=await t.run(B,`${x.cls.name}.${U}`,_,async()=>x.instance[U]({user:{id:G},params:Object.freeze({...N})})),V=ya(W)}catch(Y){if(t.isOutage(Y)||_?.aborted)throw Y;return E.error(`[palbase] ${x.cls.name}.${U} (@Authorize of ${P}) failed; the join is refused`,{error:Y}),K}return V==="malformed"?(E.warn(`[palbase] ${x.cls.name}.${U} (@Authorize of ${P}) answered ${wa(W)}, which is no grant (true, { read, write } or null); the join is refused`),K):{status:200,body:V}}async function se(w,_){let b=z(w);if("status"in b)return b;if(!b.params)return te(b.entry.g.pattern,b.channel);let x=Ue(w.user);if(!x?.id||typeof w.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let P=Object.hasOwn(b.entry.g.messages,w.event)?b.entry.g.messages[w.event]:void 0;if(!P)return{status:200,body:{ok:!1,reason:tn(`gateway "${b.channel}" takes no message "${w.event}"`,$t)}};let N=await P.schema["~standard"].validate(ea(w.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:mr(N.issues)}};let K=g(b.channel),B={...H(b.entry,b.channel,b.params,K,0,{id:x.id}),payload:N.value},G=`${b.entry.cls.name}.${P.fn} (@Subscribe "${w.event}" of ${b.channel})`,U;try{U=await t.run(x,`${b.entry.cls.name}.${P.fn}`,_,async()=>b.entry.instance[P.fn](B))}catch(V){if(t.isOutage(V))throw V;return na(V)?{status:200,body:{ok:!1,reason:tn(V.reason,$t)}}:(_?.aborted||E.error(`[palbase] ${G} failed`,{error:V}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(U===void 0)return{status:200,body:{ok:!0}};if(P.reply){let V=await P.reply["~standard"].validate(U);if(V.issues)return E.error(`[palbase] ${G} returned an ack its reply schema refuses (${mr(V.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};U=V.value}let W;try{W=JSON.stringify(U)}catch(V){return E.error(`[palbase] ${G} returned an ack that is not JSON; the member is told it failed`,{error:V}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return W===void 0?{status:200,body:{ok:!0}}:Ie(W)>lr?(E.error(`[palbase] ${G} returned an ack of ${Ie(W)} bytes, past ${lr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(W)}}}async function v(w,_){let b=z(w);if("status"in b)return b;if(!b.params)return te(b.entry.g.pattern,b.channel);let x=w.event;if(typeof x!="string"||!Object.hasOwn(fr,x))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let P=typeof w.count=="number"&&Number.isInteger(w.count)&&w.count>=0?w.count:void 0;if(P===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let N=x==="join"||x==="leave",K=N?Ue(w.user):void 0,B=N?w.connId:void 0;if(N&&(!K?.id||typeof B!="string"||B===""))return he(400,"bad_request",`A ${x} names its member: user and connId`);let G=`${x}\0${b.channel}\0${typeof B=="string"?B:""}`;if(N&&i.has(G))return{status:204};if(u.has(G))return he(503,"in_progress","This moment of the gateway is being handled",5);u.add(G);try{let U=b.entry.g.hooks[fr[x]],W;if(x==="empty"?(W=o.get(b.channel),k(b.channel,W)):W=x==="leave"?o.get(b.channel):g(b.channel),U){let V=H(b.entry,b.channel,b.params,W,P,{id:K?.id??""},x==="join"?B:void 0);try{await t.run(K,`${b.entry.cls.name}.${U}`,_,async()=>b.entry.instance[U](V))}catch(Y){if(t.isOutage(Y))throw Y;return _?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${U} (${x} of ${b.channel}) failed; realtime tells it again`,{error:Y}),he(500,"handler_failed",`The gateway's ${x} could not be handled`)}}return N&&(i.add(G),i.size>ma&&i.delete(i.values().next().value)),{status:204}}finally{u.delete(G)}}function Q(w,_){let b=r.get(w),x=`Palbase.gateways.to(${w?.name??String(w)})`;if(!b)throw new TypeError(`${x}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let P=yr(b.g.pattern,_??{});if(typeof P!="string")throw new TypeError(`${x}: ${P.problem}`);return{entry:b,channel:P,where:x}}return{declarations:[...n.values()].map(w=>w.g),async serve(w,_,b){return an(_)?w==="authorize"?ee(_,b):w==="message"?se(_,b):w==="lifecycle"?v(_,b):he(404,"not_found",`No gateway call ${JSON.stringify(w)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(w,_,b,x){let{entry:P,channel:N,where:K}=Q(w,_);S(P,N,b,x,K)},async pipe(w,_,b){let{channel:x,where:P}=Q(w,_);await I(b,x,P)},async revalidate(w,_,b={}){let x=r.get(w),P=`Palbase.gateways.to(${w?.name??String(w)}).revalidate`;if(!x)throw new TypeError(`${P}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=fa(x.g.pattern,_??{},b);if("problem"in N)throw new TypeError(`${P}: ${N.problem}`);await t.revalidate(N)},close(){for(let w of o.values())w.abort();o.clear()}}}function ya(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!an(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function wa(e){return Array.isArray(e)?"an array":an(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 ba=20,$t=256;function mr(e){let t="";for(let n of e.slice(0,ba)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=$t)break}return tn(t,$t)}function tn(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 nn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ie(t.event)>ve){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${ve} bytes`);return}try{JSON.stringify(t.payload)}catch(a){E.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=ha?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),ae.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,ga);try{await this.broadcast(s)}catch(o){E.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),E.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as on,createHmac as ka,createPublicKey as Tr,timingSafeEqual as va,verify as $r}from"node:crypto";function vd(e){let t=D(e,Me);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 Er(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let i=D(o,Me),u=s.get(i.name);if(u)throw new TypeError(`@Webhook "${i.name}" is declared by ${u.cls.name} and by ${o.name}: /webhooks/${i.name} is one endpoint`);let m=`@Webhook "${i.name}" (${o.name})`,g=n[i.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${m} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=Ta(i,g)}catch(H){a.push(`${m}: ${i.secret.env} ${H.message}`)}let S=t(o),I=new Map(i.events.map(({event:H,fn:z})=>[H,{name:`${o.name}.${z}`,call:(te,ee)=>S[z](te,ee)}]));s.set(i.name,{name:i.name,cls:o,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:I})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
3
|
- ${a.join(`
|
|
4
4
|
- `)}`);return s}function Sr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var He=1024,br=1024*He;function Ta(e,t){if(e.signature)return xe(void 0,e.signature.header,1/0,ja(e.signature,t));switch(e.provider){case"stripe":return xe("stripe","stripe-signature",512*He,Sa(t));case"github":return xe("github","x-hub-signature-256",25*br,_a(t));case"slack":return xe("slack","x-slack-signature",64*He,xa(t));case"discord":return xe("discord","x-signature-ed25519",64*He,Oa(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*He),check:Aa(t)};case"sendgrid":return xe("sendgrid","x-twilio-email-event-webhook-signature",br,Pa(t));case"livekit":return xe("livekit","authorization",512*He,Ca(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function xe(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??_r(e,s)}}function _r(e,t){let n=dn(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:xr(e,t.headers,r),event:r,...$a(e,t,r)}}function xr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Oe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Ar(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 Oe(n,"EventType");case"livekit":return Oe(n,"event");default:return Oe(n,"type")}}function $a(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Oe(n,"id"));case"slack":return r(Oe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${Or(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Oe(s,"sg_event_id")||void 0)}:{};default:return{}}}var Ea=300;function Sa(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let u of r.split(",")){let m=u.indexOf("=");if(m<=0)continue;let g=u.slice(0,m).trim(),k=u.slice(m+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(g==="v1"){let S=pe(k,"hex");if(!S)return"malformed_signature";a.push(S)}}let o=nt(s);if(o===void 0||a.length===0)return"malformed_signature";if(rt(o,n))return"stale_timestamp";let i=Ge("sha256",e,`${s}.`,t.body);return a.some(u=>Te(u,i))?void 0:"signature_mismatch"}}function _a(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?pe(n.slice(7),"hex"):void 0;return r?Te(r,Ge("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function xa(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=nt(s),o=r.startsWith("v0=")?pe(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":rt(a,n)?"stale_timestamp":Te(o,Ge("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function Oa(e){let t=pe(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=Tr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,i=nt(o),u=pe(a,"hex");return i===void 0||!u||u.byteLength!==64?"malformed_signature":rt(i,s)?"stale_timestamp":$r(null,Rr(o,r.body),n,u)?void 0:"signature_mismatch"}}var Ra=1e3;function Aa(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=pe(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",i;if(a!==null){if(!Te(Buffer.from(a.toLowerCase()),Buffer.from(on("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let I=1;for(let te of t.body)if(te===38&&++I>Ra)return"malformed_signature";let H=new Map;for(let[te,ee]of new URLSearchParams(dn(t.body))){let se=H.get(te);se||H.set(te,se=new Set),se.add(ee)}let z=[];for(let te of[...H.keys()].sort()){let ee=[...H.get(te)].sort();for(let se of ee)o+=te+se;z.push([te,ee.length===1?ee[0]:ee])}i=Object.fromEntries(z)}let u=s.protocol==="https:"?"443":"80",m=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||u}${s.pathname}${s.search}`;if(![m,g].some(I=>Te(r,Ge("sha1",e,I,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),S=k?{id:`${k}:${Or(`${m}
|
|
5
5
|
${o}`)}`}:{};return i?{type:xr("twilio",t.headers,i),event:i,...S}:{..._r("twilio",t),...S}}}function Pa(e){let t;try{let n=pe(e,"base64");if(!n)throw new Error;t=Tr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=nt(a),i=pe(s.trim(),"base64");return o===void 0||!i?"malformed_signature":rt(o,r)?"stale_timestamp":$r("sha256",Rr(a,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var kr=60;function Ca(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=vr(pe(s[0],"base64url")),o=pe(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Te(o,Ge("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=vr(pe(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+kr||typeof i.nbf=="number"&&n<i.nbf-kr)return"stale_timestamp";let u=typeof i.sha256=="string"?pe(i.sha256,"base64"):void 0;return u&&Te(u,on("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function ja(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let i="";if(n.includes("{ts}")){i=s.headers.get(e.timestampHeader)?.trim()??"";let m=nt(i);if(m===void 0)return"malformed_signature";if(rt(m,a))return"stale_timestamp"}let u=pe(o.trim(),e.encoding);return u?Te(u,Ge(r,t,...n.map(m=>m==="{body}"?s.body:m==="{ts}"?i:m)))?void 0:"signature_mismatch":"malformed_signature"}}var Ma=new TextEncoder;function Ge(e,t,...n){let r=ka(e,t);for(let s of n)r.update(s);return r.digest()}function Or(e){return on("sha256").update(e).digest("hex")}function Rr(e,t){return Buffer.concat([Ma.encode(e),t])}function Te(e,t){return e.byteLength===t.byteLength&&va(e,t)}var Da={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 pe(e,t){return Da[t].test(e)?Buffer.from(e,t):void 0}function nt(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function rt(e,t){return Math.abs(t-e)>Ea}function dn(e){return new TextDecoder().decode(e)}function vr(e){if(e)try{return JSON.parse(dn(e))}catch{return}}function Ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oe(e,t){let n=Ar(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,a){super(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
2
|
-
import{b as v}from"./WYUC5N2T.js";import{a as F}from"./S4GBHZOR.js";import{a as P,b as R,c as x,d as O,e as j,f as M,g as C,h as L,i as U,j as K,k as N,l as $}from"./KXY2SF4N.js";import{a as I,b as D}from"./BAOQMZPI.js";import{b as S,d as w}from"./7JE4KOPN.js";var ce=/^pb_[a-z0-9]+_s/;function E(n){if(F())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"||!ce.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=D(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??I),t=K.client(e);return{ai:P.client(e),analytics:R.client(e),auth:x.client(e),cache:O.client(e),fields:new v({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:j.client(e),machines:M.client(e),notify:C.client(e),purchases:L.client(e),realtime:U.client(e),secrets:t,storage:N.client(e),stores:$.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,le=/^[0-9]{1,12}$/,fe=/^[0-9a-f]{64}$/,W=8,he=/^whsec_[0-9A-Za-z]{32,}$/,pe=1024*1024;async function B(n){if(typeof n.secret!="string"||!he.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await H(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(V(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!ke(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 H(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=V(n.body),{t,v1:r}=z(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,be(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let d of r)we(o,me(d))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function z(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 d=a.indexOf("=");if(d<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,d).trim(),i=a.slice(d+1).trim();if(c==="t"){if(s!==void 0||!le.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!fe.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 ye(n,e,t={}){let r=await ge(n,t.maxBytes??pe);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ge(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 d=new Uint8Array(a),c=0;for(let i of o)d.set(i,c),c+=i.byteLength;return d}function V(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 me(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 we(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 be(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function ke(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 J=60,Se=60,ve=8*1024,Ee=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 G(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 q(n){let e=G(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 b=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ee){this.max=e}spend(e,t){if(t>=e.until)throw new u("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 u("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 _e(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 Y(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function X(n,e,t,r){let s=ae=>{throw new u("proof",`the DPoP proof is not taken: ${ae}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>ve)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 d=q(a[0]),c=q(a[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let i=d.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 _e(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=G(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"?Y(c.htu):void 0,y=Y(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let se=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-se)>J)return s("it was not made within a minute of now");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==oe)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 ie=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:ie,until:(c.iat+J+Se)*1e3+1}}var u=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"}},Te=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Ae(n){return async e=>{let t=w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof S&&r.status===401&&!Te.has(r.code))return!1;throw new g("a session's standing could not be told",{cause: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}}},Z=60,Pe=16*1024,Re=10*6e4,xe=5e4,Q=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 b;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>Pe)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=ee(r[0]),o=ee(r[1]);if(!s||!o)throw new u("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Q(a))throw new u("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==a)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${a}`);let i=ne(r[2]);if(!i)throw new u("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 u("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new u("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 u("bound","the token is bound to a key it does not name (cnf.jkt)");y=await X(e,h.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new u("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:je(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("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:te(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 d=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:d,until:d+this.standingTtlMs}),this.standings.size>xe&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new u("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 u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+Z<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-Z>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("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 u("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+Re;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"||!Q(a))continue;let d=T[a];if(o.kty!==d.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,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Me(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function te(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 Oe.test(s)?`${r}://${s}${e.pathname}`:""}var Oe=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function je(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 Me(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function ne(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 ee(n){let e=ne(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 Ce(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 k=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 Le(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:d}=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}:{},...d!==void 0?{metadata:d}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new k(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*Ue(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 Ke=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Ne=/^(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 re(n){return!Ke.test(n)||Ne.test(n)||/_PROXY$/i.test(n)}var $e=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function Ie(n){return $e.test(n)}async function De(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}}),d=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(re(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:i.sort()}}export{E as a,f as b,B as c,H as d,z as e,ye as f,u as g,g as h,Ae as i,A as j,te as k,Ce as l,k as m,Le as n,Ue as o,re as p,Ie as q,De as r};
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as v}from"./XOPSQEWX.js";import{a as F}from"./SI2TXLYT.js";import{a as P,b as R,c as x,d as O,e as j,f as M,g as C,h as L,i as U,j as K,k as N,l as $}from"./4NC6D3AY.js";import{a as I,b as D}from"./FIWWCA6S.js";import{b as S,d as w}from"./5FJNJOWL.js";var ce=/^pb_[a-z0-9]+_s/;function E(n){if(F())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"||!ce.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=D(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??I),t=K.client(e);return{ai:P.client(e),analytics:R.client(e),auth:x.client(e),cache:O.client(e),fields:new v({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:j.client(e),machines:M.client(e),notify:C.client(e),purchases:L.client(e),realtime:U.client(e),secrets:t,storage:N.client(e),stores:$.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,le=/^[0-9]{1,12}$/,fe=/^[0-9a-f]{64}$/,W=8,he=/^whsec_[0-9A-Za-z]{32,}$/,pe=1024*1024;async function B(n){if(typeof n.secret!="string"||!he.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await H(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(V(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!ke(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 H(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=V(n.body),{t,v1:r}=z(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,be(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let d of r)we(o,me(d))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function z(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 d=a.indexOf("=");if(d<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,d).trim(),i=a.slice(d+1).trim();if(c==="t"){if(s!==void 0||!le.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!fe.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 ye(n,e,t={}){let r=await ge(n,t.maxBytes??pe);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ge(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 d=new Uint8Array(a),c=0;for(let i of o)d.set(i,c),c+=i.byteLength;return d}function V(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 me(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 we(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 be(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function ke(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 J=60,Se=60,ve=8*1024,Ee=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 G(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 q(n){let e=G(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 b=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ee){this.max=e}spend(e,t){if(t>=e.until)throw new u("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 u("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 _e(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 Y(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function X(n,e,t,r){let s=ae=>{throw new u("proof",`the DPoP proof is not taken: ${ae}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>ve)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 d=q(a[0]),c=q(a[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let i=d.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 _e(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=G(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"?Y(c.htu):void 0,y=Y(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let se=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-se)>J)return s("it was not made within a minute of now");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==oe)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 ie=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:ie,until:(c.iat+J+Se)*1e3+1}}var u=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"}},Te=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Ae(n){return async e=>{let t=w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof S&&r.status===401&&!Te.has(r.code))return!1;throw new g("a session's standing could not be told",{cause: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}}},Z=60,Pe=16*1024,Re=10*6e4,xe=5e4,Q=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 b;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>Pe)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=ee(r[0]),o=ee(r[1]);if(!s||!o)throw new u("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Q(a))throw new u("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==a)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${a}`);let i=ne(r[2]);if(!i)throw new u("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 u("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new u("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 u("bound","the token is bound to a key it does not name (cnf.jkt)");y=await X(e,h.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new u("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:je(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("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:te(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 d=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:d,until:d+this.standingTtlMs}),this.standings.size>xe&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new u("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 u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+Z<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-Z>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("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 u("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+Re;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"||!Q(a))continue;let d=T[a];if(o.kty!==d.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,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Me(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function te(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 Oe.test(s)?`${r}://${s}${e.pathname}`:""}var Oe=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function je(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 Me(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function ne(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 ee(n){let e=ne(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 Ce(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 k=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 Le(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:d}=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}:{},...d!==void 0?{metadata:d}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new k(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*Ue(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 Ke=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Ne=/^(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 re(n){return!Ke.test(n)||Ne.test(n)||/_PROXY$/i.test(n)}var $e=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function Ie(n){return $e.test(n)}async function De(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}}),d=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(re(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:i.sort()}}export{E as a,f as b,B as c,H as d,z as e,ye as f,u as g,g as h,Ae as i,A as j,te as k,Ce as l,k as m,Le as n,Ue as o,re as p,Ie as q,De as r};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
2
|
-
import{a as d,b as u}from"./
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as d,b as u}from"./5FJNJOWL.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof u)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new u({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function h(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=d(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{h as a,_ as b,b as c,l as d,v as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
2
|
-
import{c as D,g as b,l as O,m as _,s as F}from"./5D7BAVO5.js";import{b as w}from"./7JE4KOPN.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.11.0"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as D,g as b,l as O,m as _,s as F}from"./6FV2T52H.js";import{b as w}from"./5FJNJOWL.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.11.2"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
|