palbase 0.40.2 → 0.41.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/{Z7RZBBBS.js → 2L2UBNP2.js} +2 -2
- package/dist/chunks/{KR3XSIAZ.js → 4LZMYSZA.js} +2 -2
- package/dist/chunks/{FDAOVX6B.js → 4YIEZ7GQ.js} +1 -1
- package/dist/chunks/{LO6DFZ7L.js → 5CV5NIXC.js} +2 -2
- package/dist/chunks/{OHNIWLO3.js → 5FC4ZZTY.js} +2 -2
- package/dist/chunks/{Q4VZ2BNE.js → BWWL27VF.js} +1 -1
- package/dist/chunks/{HDBPJPTI.js → DUBT7TA5.js} +2 -2
- package/dist/chunks/{D4KYGGQC.js → FXF4QMOQ.js} +2 -2
- package/dist/chunks/{CHQGN5YD.js → GFDEHWHB.js} +2 -2
- package/dist/chunks/{EJR46234.js → HAHKHE2Q.js} +2 -2
- package/dist/chunks/{4ONQGDDE.js → IRDLGXAB.js} +1 -1
- package/dist/chunks/{DFVKNPW7.js → JVDN7EOQ.js} +2 -2
- package/dist/chunks/{DN2MAZHA.js → K2BXR423.js} +2 -2
- package/dist/chunks/{LVX42GRN.js → KDQME6JZ.js} +2 -2
- package/dist/chunks/{7QY7ZMHT.js → LZSBQVXB.js} +2 -2
- package/dist/chunks/{HEHSHDUM.js → S7VKVW6I.js} +2 -2
- package/dist/chunks/{WH3G2H3E.js → ULKE62TM.js} +1 -1
- package/dist/chunks/{37C5IJBG.js → VEGFZICN.js} +2 -2
- package/dist/chunks/{ZTGSTF3B.js → X7T5ZRUE.js} +1 -1
- package/dist/chunks/{RCUVA3QW.js → XGLNNBME.js} +1 -1
- package/dist/chunks/{4ZMAF4YF.js → YGQVQEVB.js} +2 -2
- package/dist/chunks/{5QE5KFNR.js → YNE6YXJM.js} +2 -2
- package/dist/chunks/{Z5QBR46U.js → ZW4OIDTK.js} +1 -1
- package/dist/cli.js +139 -139
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.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
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as pr,d as mr,e as rn,f as hr,g as gr}from"./37C5IJBG.js";import{a as Pt,c as re,d as lr,e as fr,f as we,h as _,i as yr}from"./D4KYGGQC.js";import{a as or,e as dt,g as xt,h as ir,i as dr,j as Rt,k as Ot,n as cr,t as ur}from"./LVX42GRN.js";import{a as At,b as sr,n as ar}from"./4ONQGDDE.js";import{b as de}from"./5QE5KFNR.js";import"reflect-metadata";var sn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],wr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ct=/^\d+$/;function ya(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Ct.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let f=t,h=n;if(o!=="*")if(o.includes("-")){let y=o.indexOf("-"),k=o.slice(0,y),T=o.slice(y+1);if(!Ct.test(k)||!Ct.test(T)||Number(k)<t||Number(T)>n||Number(k)>Number(T))return;f=Number(k),h=Number(T)}else{if(!Ct.test(o)||Number(o)<t||Number(o)>n)return;f=Number(o),h=a===-1?f:n}for(let y=f;y<=h;y+=d)r.add(y)}return r}function br(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${wr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=ya(t[h],sn[h].lo,sn[h].hi);if(!y)return`${wr}; its ${sn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),f=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,f.setUTCDate(f.getUTCDate()+1)){if(!s.has(f.getUTCMonth()+1))continue;let y=r.has(f.getUTCDate()),k=a.has(f.getUTCDay());if(o||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var He=Symbol.for("palbase.backend.controller"),qe=Symbol.for("palbase.backend.routes"),on=Symbol.for("palbase.backend.params"),dn=Symbol.for("palbase.backend.injectable"),cn=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),ze=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ce(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var an=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[an]instanceof Set||(e[an]=new Set),e[an]}var Ge=new Set(["webhooks","_palbase"]);function md(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ce(n,He,()=>({basePath:e,options:t})),se().add(n)}}function Fe(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ce(r.constructor,qe,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var hd=Fe("GET"),gd=Fe("POST"),yd=Fe("PUT"),wd=Fe("PATCH"),bd=Fe("DELETE"),kd=Fe("QUERY");function ue(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ce(n.constructor,on,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function un(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var vd=e=>ue("body",{schema:un("Body",e)}),Td=e=>ue("query",{schema:un("QueryParams",e)}),$d=e=>ue("headers",e===void 0?{}:{schema:un("Headers",e)}),_d=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},Ed=()=>ue("user"),Sd=()=>ue("optionalUser"),Ad=()=>ue("req"),xd=()=>ue("requestId"),Rd=()=>ue("requestId"),Od=()=>ue("client"),Pd=()=>ue("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return ue("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{ce(e,dn,()=>!0),se().add(e)}}function jd(e){return t=>{ce(t,cn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Tr=/^[a-z]+(\.[a-z_]+)+$/,wa=/^[a-z][a-z0-9-]{1,62}$/,ln=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!wa.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!ln(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ce(r.constructor,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var fn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ba=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function kr(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!ba.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=br(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||kr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${kr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var vr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ka=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!ka.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!vr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${vr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&va(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Ce)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ce(t,ze,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function va(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,He)!==void 0)}function Id(e){return(D(e,qe)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Mt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var hn;function _r(e){hn=e}function pn(){if(!hn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return hn}var Ta=720*3600;function $a(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ta))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function _a(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Bd=Pt("Tasks",{async enqueue(e,t,n={}){return $a(n),pn().enqueue(_a(e),t===void 0?null:t,n)},async cancel(e,t={}){return pn().cancel(e,t.machine)},async get(e,t={}){return pn().get(e,t.machine)}}),mn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Er(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await we.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return mn(a.data,a.status===200)},async cancel(n,r){return mn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return mn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ea=1e4,Sa=36e5,$r=24*36e5,jt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new de({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new de({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new de({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let f of this.tasks.values())if(f.task===t&&f.key===r.key&&(f.finishedAt===void 0||this.now()-f.finishedAt<$r))return this.view(f,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new de({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new de({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ea*2**Math.min(t.attempt-1,16),Sa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=$r&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Dt="/_palbase/test-user-templates",Aa=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Aa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function Sr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Ar(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof de&&n.status===404)return!1;throw n}}var xa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function xr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,xa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var gn="/_palbase/storage/upload/authorize",Rr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Be(e){if(!Ra(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Or(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Pr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Nt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Oa=/^[a-z][a-z0-9-]{1,62}$/,Cr=1024,Pa=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Oa.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=Ca(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,f)=>{if(typeof d!="string"||f===void 0||typeof f.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ce(o.constructor,qe,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function tc(){return ue("uploadedObject")}function Ca(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Pa.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Mr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Mr(e){if(e===""||new TextEncoder().encode(e).byteLength>Cr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Ma(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ja(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ja(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function jr(e,t){let n=Ma(e,t);return Mr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Cr} bytes)`}}function Dr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Nr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Be(t.user);if(!o)return"user is { id?, session?, role }";let d=Or(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let f=Da(t.uploadedObject);return f?f.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:f,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Da(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:f,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||f!==void 0&&typeof f!="number"||h!==void 0&&typeof h!="string")&&!(!wn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...f!==void 0?{height:f}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Na}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),We=Symbol.for("palbase.backend.gatewayHooks"),Ur={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ua={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Ur),output:()=>structuredClone(Ur)}}},Fr=Symbol.for("palbase.backend.gatewayRefusal"),Lr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Fr,{value:!0})}},La=e=>typeof e=="object"&&e!==null&&e[Fr]===!0&&typeof e.reason=="string",Ke=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ia=6e4,Ha=86400,Ir=604800,Hr=65536,$e=255,qa=["roles:","flags:","messaging:","calls:","debug:"],za=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Je=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ga(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Je(e)>$e)return`a channel is ${$e} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=qa.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Br(e){if(typeof e!="string"||e==="")return"is a name";if(Je(e)>$e)return`is ${$e} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ga(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Fa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||za.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let T=Br(y);if(T)throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" ${T}`);if(!bn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let f=ce(a,We,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ua}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ia,hooks:{...f.hooks},messages:Object.assign(Object.create(null),f.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ce(a,Me,()=>h),se().add(a)}}function Fa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ha;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Ir)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Ir} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ba={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ba[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ce(n.constructor,We,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Br(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=ce(s.constructor,We,$n),f=d.messages[e];if(f!==void 0&&f.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${f.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ka(e){return D(e,Me)}function Ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Kr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Je(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Wa(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Kr(e,t):Va(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Va(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Za=1e4,Ya=1e3,Qa=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ye=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),qr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},zr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Jr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:S}of e){let m=Ka(b),$=a.get(m.name);if($!==void 0&&$!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let M=s.get(zr(m.pattern));if(M!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(zr(m.pattern),m.pattern);for(let[Z,Y]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof S[Y]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${Z} is ${Y}, which is no method of it`);let U={cls:b,instance:S,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,f=new Set,h=new vn(t.broadcast),y=b=>{let S=o.get(b);return S||(S=new AbortController,o.set(b,S)),S},k=(b,S)=>{S?.abort(),o.get(b)===S&&o.delete(b)},T=(b,S,m,$,M,U)=>{if(!Object.hasOwn(b.g.events,m)){_.warn(`[palbase] ${M}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){_.warn(`[palbase] ${M}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:S,event:m,payload:$??{},...U!==void 0?{conn_id:U}:{}},M)},F=async(b,S,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(S)};function N(b,S,m,$,M,U,Z){let Y=$?.signal??AbortSignal.abort(),L=`${b.cls.name} (${S})`;return{channel:S,params:Object.freeze({...m}),signal:Y,count:M,user:U,emit:(I,G)=>T(b,S,I,G,L,Z),pipe:I=>F(I,S,L),owner:{hold(I){re.exit(async()=>{try{await I(Y)}catch(G){Y.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(S,$)}}}function H(b){let{room:S,channel:m}=b;if(typeof S!="string"||typeof m!="string")return ye(400,"bad_request","A gateway's call names its pattern (room) and its channel");let $=n.get(S);return!$||!Ke($.g)?ye(404,"not_found",`This app serves no gateway "${S}"`):{entry:$,channel:m,params:Ja(S,m)}}let W=(b,S)=>ye(400,"bad_request",`"${S}" is not a channel of the gateway "${b}"`);async function z(b,S){let m=H(b);if("status"in m)return m;let{entry:$,channel:M,params:U}=m,Z={status:200,body:{subscribe:!1,publish:!1}};if(!U)return _.warn(`[palbase] ${$.cls.name}: realtime asked about "${M}", which is not a channel of the gateway "${$.g.pattern}"; the join is refused`),Z;let Y=Be(b.user),L=Y?.id;if(!L)return Z;if($.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}};if($.g.access==="owner")return U[Tn($.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}}:Z;let I=$.g.hooks.authorize;if(!I)return Z;let G,B;try{G=await t.run(Y,`${$.cls.name}.${I}`,S,async()=>$.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Xa(G)}catch(ne){if(t.isOutage(ne)||S?.aborted)throw ne;return _.error(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) failed; the join is refused`,{error:ne}),Z}return B==="malformed"?(_.warn(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) answered ${eo(G)}, which is no grant (true, { read, write } or null); the join is refused`),Z):{status:200,body:B}}async function ie(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=Be(b.user);if(!$?.id||typeof b.event!="string")return ye(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:kn(`gateway "${m.channel}" takes no message "${b.event}"`,Ut)}};let U=await M.schema["~standard"].validate(Na(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Gr(U.issues)}};let Z=y(m.channel),Y={...N(m.entry,m.channel,m.params,Z,0,{id:$.id}),payload:U.value},L=`${m.entry.cls.name}.${M.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run($,`${m.entry.cls.name}.${M.fn}`,S,async()=>m.entry.instance[M.fn](Y))}catch(B){if(t.isOutage(B))throw B;return La(B)?{status:200,body:{ok:!1,reason:kn(B.reason,Ut)}}:(S?.aborted||_.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(M.reply){let B=await M.reply["~standard"].validate(I);if(B.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Gr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Je(G)>Hr?(_.error(`[palbase] ${L} returned an ack of ${Je(G)} bytes, past ${Hr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function ge(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=b.event;if(typeof $!="string"||!Object.hasOwn(qr,$))return ye(400,"bad_request","A gateway's moment is first, join, leave or empty");let M=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(M===void 0)return ye(400,"bad_request","A gateway's moment says its count of members");let U=$==="join"||$==="leave",Z=U?Be(b.user):void 0,Y=U?b.connId:void 0;if(U&&(!Z?.id||typeof Y!="string"||Y===""))return ye(400,"bad_request",`A ${$} names its member: user and connId`);let L=`${$}\0${m.channel}\0${typeof Y=="string"?Y:""}`;if(U&&d.has(L))return{status:204};if(f.has(L))return ye(503,"in_progress","This moment of the gateway is being handled",5);f.add(L);try{let I=m.entry.g.hooks[qr[$]],G;if($==="empty"?(G=o.get(m.channel),k(m.channel,G)):G=$==="leave"?o.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,M,{id:Z?.id??""},$==="join"?Y:void 0);try{await t.run(Z,`${m.entry.cls.name}.${I}`,S,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return S?.aborted||_.error(`[palbase] ${m.entry.cls.name}.${I} (${$} of ${m.channel}) failed; realtime tells it again`,{error:ne}),ye(500,"handler_failed",`The gateway's ${$} could not be handled`)}}return U&&(d.add(L),d.size>Za&&d.delete(d.values().next().value)),{status:204}}finally{f.delete(L)}}function Se(b,S){let m=r.get(b),$=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${$}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let M=Kr(m.g.pattern,S??{});if(typeof M!="string")throw new TypeError(`${$}: ${M.problem}`);return{entry:m,channel:M,where:$}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,S,m){return _n(S)?b==="authorize"?z(S,m):b==="message"?ie(S,m):b==="lifecycle"?ge(S,m):ye(404,"not_found",`No gateway call ${JSON.stringify(b)}`):ye(400,"bad_request","A gateway's call is a JSON object")},emit(b,S,m,$){let{entry:M,channel:U,where:Z}=Se(b,S);T(M,U,m,$,Z)},async pipe(b,S,m){let{channel:$,where:M}=Se(b,S);await F(m,$,M)},async revalidate(b,S,m={}){let $=r.get(b),M=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!$)throw new TypeError(`${M}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Wa($.g.pattern,S??{},m);if("problem"in U)throw new TypeError(`${M}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Xa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function eo(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var to=20,Ut=256;function Gr(e){let t="";for(let n of e.slice(0,to)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ut)break}return kn(t,Ut)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Je(t.event)>$e){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ya?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),re.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,Qa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as no,createPublicKey as Yr,timingSafeEqual as ro,verify as Qr}from"node:crypto";function yc(e){let t=D(e,ze);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function Xr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,ze),f=s.get(d.name);if(f)throw new TypeError(`@Webhook "${d.name}" is declared by ${f.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=so(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let T=t(o),F=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${o.name}.${H}`,call:(W,z)=>T[H](W,z)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:F})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
1
|
+
/*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as pr,d as mr,e as rn,f as hr,g as gr}from"./VEGFZICN.js";import{a as Pt,c as re,d as lr,e as fr,f as we,h as _,i as yr}from"./FXF4QMOQ.js";import{a as or,e as dt,g as xt,h as ir,i as dr,j as Rt,k as Ot,n as cr,t as ur}from"./KDQME6JZ.js";import{a as At,b as sr,n as ar}from"./IRDLGXAB.js";import{b as de}from"./YNE6YXJM.js";import"reflect-metadata";var sn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],wr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ct=/^\d+$/;function ya(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Ct.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let f=t,h=n;if(o!=="*")if(o.includes("-")){let y=o.indexOf("-"),k=o.slice(0,y),T=o.slice(y+1);if(!Ct.test(k)||!Ct.test(T)||Number(k)<t||Number(T)>n||Number(k)>Number(T))return;f=Number(k),h=Number(T)}else{if(!Ct.test(o)||Number(o)<t||Number(o)>n)return;f=Number(o),h=a===-1?f:n}for(let y=f;y<=h;y+=d)r.add(y)}return r}function br(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${wr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=ya(t[h],sn[h].lo,sn[h].hi);if(!y)return`${wr}; its ${sn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),f=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,f.setUTCDate(f.getUTCDate()+1)){if(!s.has(f.getUTCMonth()+1))continue;let y=r.has(f.getUTCDate()),k=a.has(f.getUTCDay());if(o||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var He=Symbol.for("palbase.backend.controller"),qe=Symbol.for("palbase.backend.routes"),on=Symbol.for("palbase.backend.params"),dn=Symbol.for("palbase.backend.injectable"),cn=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),ze=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ce(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var an=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[an]instanceof Set||(e[an]=new Set),e[an]}var Ge=new Set(["webhooks","_palbase"]);function md(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ce(n,He,()=>({basePath:e,options:t})),se().add(n)}}function Fe(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ce(r.constructor,qe,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var hd=Fe("GET"),gd=Fe("POST"),yd=Fe("PUT"),wd=Fe("PATCH"),bd=Fe("DELETE"),kd=Fe("QUERY");function ue(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ce(n.constructor,on,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function un(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var vd=e=>ue("body",{schema:un("Body",e)}),Td=e=>ue("query",{schema:un("QueryParams",e)}),$d=e=>ue("headers",e===void 0?{}:{schema:un("Headers",e)}),_d=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},Ed=()=>ue("user"),Sd=()=>ue("optionalUser"),Ad=()=>ue("req"),xd=()=>ue("requestId"),Rd=()=>ue("requestId"),Od=()=>ue("client"),Pd=()=>ue("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return ue("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{ce(e,dn,()=>!0),se().add(e)}}function jd(e){return t=>{ce(t,cn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Tr=/^[a-z]+(\.[a-z_]+)+$/,wa=/^[a-z][a-z0-9-]{1,62}$/,ln=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!wa.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!ln(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ce(r.constructor,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var fn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ba=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function kr(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!ba.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=br(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||kr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${kr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var vr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ka=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!ka.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!vr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${vr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&va(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Ce)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ce(t,ze,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function va(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,He)!==void 0)}function Id(e){return(D(e,qe)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Mt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var hn;function _r(e){hn=e}function pn(){if(!hn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return hn}var Ta=720*3600;function $a(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ta))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function _a(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Bd=Pt("Tasks",{async enqueue(e,t,n={}){return $a(n),pn().enqueue(_a(e),t===void 0?null:t,n)},async cancel(e,t={}){return pn().cancel(e,t.machine)},async get(e,t={}){return pn().get(e,t.machine)}}),mn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Er(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await we.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return mn(a.data,a.status===200)},async cancel(n,r){return mn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return mn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ea=1e4,Sa=36e5,$r=24*36e5,jt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new de({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new de({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new de({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let f of this.tasks.values())if(f.task===t&&f.key===r.key&&(f.finishedAt===void 0||this.now()-f.finishedAt<$r))return this.view(f,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new de({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new de({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ea*2**Math.min(t.attempt-1,16),Sa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=$r&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Dt="/_palbase/test-user-templates",Aa=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Aa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function Sr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Ar(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof de&&n.status===404)return!1;throw n}}var xa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function xr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,xa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var gn="/_palbase/storage/upload/authorize",Rr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Be(e){if(!Ra(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Or(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Pr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Nt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Oa=/^[a-z][a-z0-9-]{1,62}$/,Cr=1024,Pa=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Oa.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=Ca(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,f)=>{if(typeof d!="string"||f===void 0||typeof f.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ce(o.constructor,qe,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function tc(){return ue("uploadedObject")}function Ca(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Pa.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Mr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Mr(e){if(e===""||new TextEncoder().encode(e).byteLength>Cr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Ma(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ja(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ja(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function jr(e,t){let n=Ma(e,t);return Mr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Cr} bytes)`}}function Dr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Nr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Be(t.user);if(!o)return"user is { id?, session?, role }";let d=Or(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let f=Da(t.uploadedObject);return f?f.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:f,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Da(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:f,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||f!==void 0&&typeof f!="number"||h!==void 0&&typeof h!="string")&&!(!wn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...f!==void 0?{height:f}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Na}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),We=Symbol.for("palbase.backend.gatewayHooks"),Ur={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ua={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Ur),output:()=>structuredClone(Ur)}}},Fr=Symbol.for("palbase.backend.gatewayRefusal"),Lr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Fr,{value:!0})}},La=e=>typeof e=="object"&&e!==null&&e[Fr]===!0&&typeof e.reason=="string",Ke=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ia=6e4,Ha=86400,Ir=604800,Hr=65536,$e=255,qa=["roles:","flags:","messaging:","calls:","debug:"],za=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Je=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ga(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Je(e)>$e)return`a channel is ${$e} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=qa.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Br(e){if(typeof e!="string"||e==="")return"is a name";if(Je(e)>$e)return`is ${$e} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ga(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Fa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||za.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let T=Br(y);if(T)throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" ${T}`);if(!bn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let f=ce(a,We,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ua}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ia,hooks:{...f.hooks},messages:Object.assign(Object.create(null),f.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ce(a,Me,()=>h),se().add(a)}}function Fa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ha;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Ir)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Ir} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ba={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ba[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ce(n.constructor,We,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Br(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=ce(s.constructor,We,$n),f=d.messages[e];if(f!==void 0&&f.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${f.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ka(e){return D(e,Me)}function Ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Kr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Je(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Wa(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Kr(e,t):Va(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Va(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Za=1e4,Ya=1e3,Qa=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ye=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),qr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},zr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Jr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:S}of e){let m=Ka(b),$=a.get(m.name);if($!==void 0&&$!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let M=s.get(zr(m.pattern));if(M!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(zr(m.pattern),m.pattern);for(let[Z,Y]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof S[Y]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${Z} is ${Y}, which is no method of it`);let U={cls:b,instance:S,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,f=new Set,h=new vn(t.broadcast),y=b=>{let S=o.get(b);return S||(S=new AbortController,o.set(b,S)),S},k=(b,S)=>{S?.abort(),o.get(b)===S&&o.delete(b)},T=(b,S,m,$,M,U)=>{if(!Object.hasOwn(b.g.events,m)){_.warn(`[palbase] ${M}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){_.warn(`[palbase] ${M}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:S,event:m,payload:$??{},...U!==void 0?{conn_id:U}:{}},M)},F=async(b,S,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(S)};function N(b,S,m,$,M,U,Z){let Y=$?.signal??AbortSignal.abort(),L=`${b.cls.name} (${S})`;return{channel:S,params:Object.freeze({...m}),signal:Y,count:M,user:U,emit:(I,G)=>T(b,S,I,G,L,Z),pipe:I=>F(I,S,L),owner:{hold(I){re.exit(async()=>{try{await I(Y)}catch(G){Y.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(S,$)}}}function H(b){let{room:S,channel:m}=b;if(typeof S!="string"||typeof m!="string")return ye(400,"bad_request","A gateway's call names its pattern (room) and its channel");let $=n.get(S);return!$||!Ke($.g)?ye(404,"not_found",`This app serves no gateway "${S}"`):{entry:$,channel:m,params:Ja(S,m)}}let W=(b,S)=>ye(400,"bad_request",`"${S}" is not a channel of the gateway "${b}"`);async function z(b,S){let m=H(b);if("status"in m)return m;let{entry:$,channel:M,params:U}=m,Z={status:200,body:{subscribe:!1,publish:!1}};if(!U)return _.warn(`[palbase] ${$.cls.name}: realtime asked about "${M}", which is not a channel of the gateway "${$.g.pattern}"; the join is refused`),Z;let Y=Be(b.user),L=Y?.id;if(!L)return Z;if($.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}};if($.g.access==="owner")return U[Tn($.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}}:Z;let I=$.g.hooks.authorize;if(!I)return Z;let G,B;try{G=await t.run(Y,`${$.cls.name}.${I}`,S,async()=>$.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Xa(G)}catch(ne){if(t.isOutage(ne)||S?.aborted)throw ne;return _.error(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) failed; the join is refused`,{error:ne}),Z}return B==="malformed"?(_.warn(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) answered ${eo(G)}, which is no grant (true, { read, write } or null); the join is refused`),Z):{status:200,body:B}}async function ie(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=Be(b.user);if(!$?.id||typeof b.event!="string")return ye(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:kn(`gateway "${m.channel}" takes no message "${b.event}"`,Ut)}};let U=await M.schema["~standard"].validate(Na(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Gr(U.issues)}};let Z=y(m.channel),Y={...N(m.entry,m.channel,m.params,Z,0,{id:$.id}),payload:U.value},L=`${m.entry.cls.name}.${M.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run($,`${m.entry.cls.name}.${M.fn}`,S,async()=>m.entry.instance[M.fn](Y))}catch(B){if(t.isOutage(B))throw B;return La(B)?{status:200,body:{ok:!1,reason:kn(B.reason,Ut)}}:(S?.aborted||_.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(M.reply){let B=await M.reply["~standard"].validate(I);if(B.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Gr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Je(G)>Hr?(_.error(`[palbase] ${L} returned an ack of ${Je(G)} bytes, past ${Hr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function ge(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=b.event;if(typeof $!="string"||!Object.hasOwn(qr,$))return ye(400,"bad_request","A gateway's moment is first, join, leave or empty");let M=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(M===void 0)return ye(400,"bad_request","A gateway's moment says its count of members");let U=$==="join"||$==="leave",Z=U?Be(b.user):void 0,Y=U?b.connId:void 0;if(U&&(!Z?.id||typeof Y!="string"||Y===""))return ye(400,"bad_request",`A ${$} names its member: user and connId`);let L=`${$}\0${m.channel}\0${typeof Y=="string"?Y:""}`;if(U&&d.has(L))return{status:204};if(f.has(L))return ye(503,"in_progress","This moment of the gateway is being handled",5);f.add(L);try{let I=m.entry.g.hooks[qr[$]],G;if($==="empty"?(G=o.get(m.channel),k(m.channel,G)):G=$==="leave"?o.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,M,{id:Z?.id??""},$==="join"?Y:void 0);try{await t.run(Z,`${m.entry.cls.name}.${I}`,S,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return S?.aborted||_.error(`[palbase] ${m.entry.cls.name}.${I} (${$} of ${m.channel}) failed; realtime tells it again`,{error:ne}),ye(500,"handler_failed",`The gateway's ${$} could not be handled`)}}return U&&(d.add(L),d.size>Za&&d.delete(d.values().next().value)),{status:204}}finally{f.delete(L)}}function Se(b,S){let m=r.get(b),$=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${$}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let M=Kr(m.g.pattern,S??{});if(typeof M!="string")throw new TypeError(`${$}: ${M.problem}`);return{entry:m,channel:M,where:$}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,S,m){return _n(S)?b==="authorize"?z(S,m):b==="message"?ie(S,m):b==="lifecycle"?ge(S,m):ye(404,"not_found",`No gateway call ${JSON.stringify(b)}`):ye(400,"bad_request","A gateway's call is a JSON object")},emit(b,S,m,$){let{entry:M,channel:U,where:Z}=Se(b,S);T(M,U,m,$,Z)},async pipe(b,S,m){let{channel:$,where:M}=Se(b,S);await F(m,$,M)},async revalidate(b,S,m={}){let $=r.get(b),M=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!$)throw new TypeError(`${M}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Wa($.g.pattern,S??{},m);if("problem"in U)throw new TypeError(`${M}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Xa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function eo(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var to=20,Ut=256;function Gr(e){let t="";for(let n of e.slice(0,to)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ut)break}return kn(t,Ut)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Je(t.event)>$e){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ya?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),re.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,Qa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as no,createPublicKey as Yr,timingSafeEqual as ro,verify as Qr}from"node:crypto";function yc(e){let t=D(e,ze);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function Xr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,ze),f=s.get(d.name);if(f)throw new TypeError(`@Webhook "${d.name}" is declared by ${f.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=so(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let T=t(o),F=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${o.name}.${H}`,call:(W,z)=>T[H](W,z)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:F})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
3
|
- ${a.join(`
|
|
4
4
|
- `)}`);return s}function es(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Wr=1024*Ve;function so(e,t){if(e.signature)return je(void 0,e.signature.header,1/0,go(e.signature,t));switch(e.provider){case"stripe":return je("stripe","stripe-signature",512*Ve,io(t));case"github":return je("github","x-hub-signature-256",25*Wr,co(t));case"slack":return je("slack","x-slack-signature",64*Ve,uo(t));case"discord":return je("discord","x-signature-ed25519",64*Ve,lo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:po(t)};case"sendgrid":return je("sendgrid","x-twilio-email-event-webhook-signature",Wr,mo(t));case"livekit":return je("livekit","authorization",512*Ve,ho(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function je(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??ts(e,s)}}function ts(e,t){let n=Sn(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:ns(e,t.headers,r),event:r,...ao(e,t,r)}}function ns(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=De(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=as(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return De(n,"EventType");case"livekit":return De(n,"event");default:return De(n,"type")}}function ao(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(De(n,"id"));case"slack":return r(De(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${rs(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>De(s,"sg_event_id")||void 0)}:{};default:return{}}}var oo=300;function io(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let f of r.split(",")){let h=f.indexOf("=");if(h<=0)continue;let y=f.slice(0,h).trim(),k=f.slice(h+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(y==="v1"){let T=me(k,"hex");if(!T)return"malformed_signature";a.push(T)}}let o=ut(s);if(o===void 0||a.length===0)return"malformed_signature";if(lt(o,n))return"stale_timestamp";let d=Ze("sha256",e,`${s}.`,t.body);return a.some(f=>_e(f,d))?void 0:"signature_mismatch"}}function co(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?_e(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function uo(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ut(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":lt(a,n)?"stale_timestamp":_e(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function lo(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=Yr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ut(o),f=me(a,"hex");return d===void 0||!f||f.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":Qr(null,ss(o,r.body),n,f)?void 0:"signature_mismatch"}}var fo=1e3;function po(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!_e(Buffer.from(a.toLowerCase()),Buffer.from(En("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let F=1;for(let W of t.body)if(W===38&&++F>fo)return"malformed_signature";let N=new Map;for(let[W,z]of new URLSearchParams(Sn(t.body))){let ie=N.get(W);ie||N.set(W,ie=new Set),ie.add(z)}let H=[];for(let W of[...N.keys()].sort()){let z=[...N.get(W)].sort();for(let ie of z)o+=W+ie;H.push([W,z.length===1?z[0]:z])}d=Object.fromEntries(H)}let f=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||f}${s.pathname}${s.search}`;if(![h,y].some(F=>_e(r,Ze("sha1",e,F,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),T=k?{id:`${k}:${rs(`${h}
|
|
5
5
|
${o}`)}`}:{};return d?{type:ns("twilio",t.headers,d),event:d,...T}:{...ts("twilio",t),...T}}}function mo(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=Yr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=ut(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":lt(o,r)?"stale_timestamp":Qr("sha256",ss(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Vr=60;function ho(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=Zr(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!_e(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Zr(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Vr||typeof d.nbf=="number"&&n<d.nbf-Vr)return"stale_timestamp";let f=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return f&&_e(f,En("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function go(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ut(d);if(h===void 0)return"malformed_signature";if(lt(h,a))return"stale_timestamp"}let f=me(o.trim(),e.encoding);return f?_e(f,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var yo=new TextEncoder;function Ze(e,t,...n){let r=no(e,t);for(let s of n)r.update(s);return r.digest()}function rs(e){return En("sha256").update(e).digest("hex")}function ss(e,t){return Buffer.concat([yo.encode(e),t])}function _e(e,t){return e.byteLength===t.byteLength&&ro(e,t)}var wo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return wo[t].test(e)?Buffer.from(e,t):void 0}function ut(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function lt(e,t){return Math.abs(t-e)>oo}function Sn(e){return new TextDecoder().decode(e)}function Zr(e){if(e)try{return JSON.parse(Sn(e))}catch{return}}function as(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(e,t){let n=as(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var V=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as R}from"./Z5QBR46U.js";import{a as m,c as G,d as X,e as Z,f as Q,h as ee,i as te,j as A,k as ne,l as re,o as P}from"./4ONQGDDE.js";import{a as se}from"./RCUVA3QW.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q,n as z,o as V}from"./4ZMAF4YF.js";import{a as J,b as Y}from"./HEHSHDUM.js";import{b as T,d as v}from"./5QE5KFNR.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Te=6e4,Ae=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Te),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=X(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await Z(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Ae-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=ee(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=Q(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await te(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof G?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ne(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await re(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Pe=/^pb_[a-z0-9]+_s/;function O(n){if(se())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"||!Pe.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=Y(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??J),t=q.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),calls:N.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:I.client(e),machines:F.client(e),messaging:D.client(e),notify:W.client(e),purchases:B.client(e),realtime:H.client(e),secrets:t,storage:z.client(e),stores:V.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},xe=300,Oe=/^[0-9]{1,12}$/,je=/^[0-9a-f]{64}$/,ie=8,Me=/^whsec_[0-9A-Za-z]{32,}$/,Ke=1024*1024;async function oe(n){if(typeof n.secret!="string"||!Me.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ae(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(de(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Ie(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ae(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=de(n.body),{t,v1:r}=ce(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Ne(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Le(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ce(n){let e=n.toleranceSeconds??xe;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 h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Oe.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!je.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ie)throw new h("malformed_signature",`Palbase-Signature carries at most ${ie} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("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:i}}async function Ue(n,e,t={}){let r=await Ce(n,t.maxBytes??Ke);return oe({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ce(n,e){let t=()=>new h("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(),i=[],o=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(o+=l.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(l)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function de(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 Le(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 $e(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 Ne(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Ie(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 ue=60,Fe=60,De=8*1024,We=1e5;function j(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 fe(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 le(n){let e=fe(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 E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=We){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,i]of t){if(i>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[i,o]of s)o>e||(s.delete(i),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 Be(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function he(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function pe(n,e,t,r){let s=_e=>{throw new u("proof",`the DPoP proof is not taken: ${_e}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>De)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=le(o[0]),c=le(o[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 a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Be(a.x,a.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:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=fe(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${o[0]}.${o[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 p=typeof c.htu=="string"?he(c.htu):void 0,g=he(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let ve=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-ve)>ue)return s("it was not made within a minute of now");let Se=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==Se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let Ee=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ee,until:(c.iat+ue+Fe)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},He=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function qe(n){return async e=>{let t=v({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 T&&r.status===401&&!He.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={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}}},ye=60,ze=16*1024,Ve=10*6e4,Je=5e4,ge=n=>typeof n=="string"&&Object.hasOwn(M,n),K=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 E;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>ze)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=me(r[0]),i=me(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!ge(o))throw new u("algorithm",`the token is signed with ${String(o)}; 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!==o)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=be(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,l).catch(()=>!1))throw new u("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==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 p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await pe(e,p.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,b.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Ge(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 i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:we(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Je&&this.standings.delete(this.standings.keys().next().value),o}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+ye<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ye>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+Ve;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}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(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!ge(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Xe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function we(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 Ye.test(s)?`${r}://${s}${e.pathname}`:""}var Ye=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Ge(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 Xe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function be(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 me(n){let e=be(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 Ze(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 _=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 Qe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,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:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),b}return await n.purchases.commitSpend({path:l}),y}async function*et(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 tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,nt=/^(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 ke(n){return!tt.test(n)||nt.test(n)||/_PROXY$/i.test(n)}var rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function st(n){return rt.test(n)}async function it(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 i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[l,y]of Object.entries(o.values)){if(ke(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,oe as f,ae as g,ce as h,Ue as i,u as j,w as k,qe as l,K as m,we as n,Ze as o,_ as p,Qe as q,et as r,ke as s,st as t,it as u};
|
|
1
|
+
/*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as R}from"./ZW4OIDTK.js";import{a as m,c as G,d as X,e as Z,f as Q,h as ee,i as te,j as A,k as ne,l as re,o as P}from"./IRDLGXAB.js";import{a as se}from"./XGLNNBME.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q,n as z,o as V}from"./YGQVQEVB.js";import{a as J,b as Y}from"./S7VKVW6I.js";import{b as T,d as v}from"./YNE6YXJM.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Te=6e4,Ae=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Te),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=X(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await Z(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Ae-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=ee(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=Q(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await te(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof G?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ne(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await re(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Pe=/^pb_[a-z0-9]+_s/;function O(n){if(se())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"||!Pe.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=Y(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??J),t=q.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),calls:N.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:I.client(e),machines:F.client(e),messaging:D.client(e),notify:W.client(e),purchases:B.client(e),realtime:H.client(e),secrets:t,storage:z.client(e),stores:V.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},xe=300,Oe=/^[0-9]{1,12}$/,je=/^[0-9a-f]{64}$/,ie=8,Me=/^whsec_[0-9A-Za-z]{32,}$/,Ke=1024*1024;async function oe(n){if(typeof n.secret!="string"||!Me.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ae(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(de(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Ie(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ae(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=de(n.body),{t,v1:r}=ce(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Ne(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Le(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ce(n){let e=n.toleranceSeconds??xe;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 h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Oe.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!je.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ie)throw new h("malformed_signature",`Palbase-Signature carries at most ${ie} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("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:i}}async function Ue(n,e,t={}){let r=await Ce(n,t.maxBytes??Ke);return oe({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ce(n,e){let t=()=>new h("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(),i=[],o=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(o+=l.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(l)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function de(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 Le(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 $e(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 Ne(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Ie(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 ue=60,Fe=60,De=8*1024,We=1e5;function j(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 fe(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 le(n){let e=fe(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 E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=We){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,i]of t){if(i>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[i,o]of s)o>e||(s.delete(i),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 Be(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function he(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function pe(n,e,t,r){let s=_e=>{throw new u("proof",`the DPoP proof is not taken: ${_e}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>De)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=le(o[0]),c=le(o[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 a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Be(a.x,a.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:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=fe(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${o[0]}.${o[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 p=typeof c.htu=="string"?he(c.htu):void 0,g=he(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let ve=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-ve)>ue)return s("it was not made within a minute of now");let Se=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==Se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let Ee=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ee,until:(c.iat+ue+Fe)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},He=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function qe(n){return async e=>{let t=v({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 T&&r.status===401&&!He.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={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}}},ye=60,ze=16*1024,Ve=10*6e4,Je=5e4,ge=n=>typeof n=="string"&&Object.hasOwn(M,n),K=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 E;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>ze)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=me(r[0]),i=me(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!ge(o))throw new u("algorithm",`the token is signed with ${String(o)}; 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!==o)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=be(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,l).catch(()=>!1))throw new u("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==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 p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await pe(e,p.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,b.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Ge(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 i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:we(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Je&&this.standings.delete(this.standings.keys().next().value),o}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+ye<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ye>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+Ve;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}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(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!ge(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Xe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function we(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 Ye.test(s)?`${r}://${s}${e.pathname}`:""}var Ye=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Ge(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 Xe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function be(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 me(n){let e=be(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 Ze(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 _=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 Qe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,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:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),b}return await n.purchases.commitSpend({path:l}),y}async function*et(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 tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,nt=/^(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 ke(n){return!tt.test(n)||nt.test(n)||/_PROXY$/i.test(n)}var rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function st(n){return rt.test(n)}async function it(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 i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[l,y]of Object.entries(o.values)){if(ke(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,oe as f,ae as g,ce as h,Ue as i,u as j,w as k,qe as l,K as m,we as n,Ze as o,_ as p,Qe as q,et as r,ke as s,st as t,it as u};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as D,g as b,l as O,m as _,s as F}from"./WH3G2H3E.js";import{b as w}from"./5QE5KFNR.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.40.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};
|
|
1
|
+
/*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as D,g as b,l as O,m as _,s as F}from"./ULKE62TM.js";import{b as w}from"./YNE6YXJM.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.41.1"};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,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as c,f as u}from"./
|
|
1
|
+
/*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as c,f as u}from"./YNE6YXJM.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),At=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let a={},l=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await l(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let w=_t(c.kind,new Uint8Array(g));if(w===void 0)return;let y=await Et(c,g,w,t);y&&(a[c.id]=y)}catch{}})),a}var C=(d,t,a=0)=>d.length>=a+t.length&&t.every((l,c)=>d[a+c]===l),W=d=>[...d].map(t=>t.charCodeAt(0));function _t(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,a,l){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:a}))};case"font":{let c=At(d.id),p=globalThis.FontFace,g=l.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),a=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){a=h;break}if(a<0)throw new Error("not a zip");let l=t.getUint16(a+10,!0),c=t.getUint32(a+16,!0),p=new Map,g=0;for(let h=0;h<l;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let w=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),_=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+_+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(w===0)p.set(x,O);else if(w===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function qe(d,t){let a=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",l="";for(let c=0;c<t.length;c+=32768)l+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${a};base64,${btoa(l)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let a=new TextDecoder().decode(t),l=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,_)=>{let P=c(_);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(a,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(l(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let _=c(v);_?y.setAttribute(m,qe(_,d.get(_))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let w=h.createElement("meta");return w.setAttribute("http-equiv","Content-Security-Policy"),w.setAttribute("content",$t),h.head.prepend(w),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,a)=>`M${d-a} ${t}a${a} ${a} 0 1 0 ${2*a} 0a${a} ${a} 0 1 0 ${-2*a} 0`,de={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[K(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",K(6,18,3),K(17,16,3)],people:[K(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var Be="http://www.w3.org/2000/svg";function pe(d,t,a){let l=d.createElementNS(Be,"svg");l.setAttribute("viewBox","0 0 24 24"),l.setAttribute("width",String(a)),l.setAttribute("height",String(a)),l.setAttribute("fill","none"),l.setAttribute("stroke","currentColor"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("aria-hidden","true"),l.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),l.append(p)}return l}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),X=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:X(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:X(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:X()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:X(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:X(!0),text:X(),color:j("")},feature:{icon:f(void 0,!0),text:X(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],G=(d,t)=>d??t;function It(d){let t="";for(let a of new TextEncoder().encode(d)){let l=String.fromCharCode(a);t+=/^[A-Za-z0-9._~-]$/.test(l)?l:`%${a.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),a=Math.floor(d%86400/3600),l=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(a)}:${p(l)}:${p(c)}`:a>0?`${a}:${p(l)}:${p(c)}`:`${p(l)}:${p(c)}`,days:String(t),hours:p(a),minutes:p(l),seconds:p(c)}}function fn(d){let t=[],a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer"])a(l[c]);for(let c of Object.keys(M(l.sheets)).sort())a(M(M(l.sheets)[c]).root);return t}function Ut(d){let t=new Map,a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer","sheets"])a(l[c]);return t}function gn(d,t){return _e(d,t).tree}function _e(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:a,...l}=t;return new ue("message",d,{...l,packages:{"":{...a}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,a,l){this.kind=t,this.d=a,this.opts=l,this.offers=Ut(a);let c={};for(let[y,m]of Object.entries(l.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=l.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let w=M(this.d.theme);this.palette=M(M(w.colors)[l.appearance]);for(let[y,m]of Object.entries(M(w.typography))){let v={};for(let[_,P]of Object.entries(this.objectFields("typography"))){let R=G(M(m)[_],P.def);R!=null&&(v[_]=R)}this.typography[y]=v}this.radii=M(w.radii),this.spacing=M(w.spacing)}open(t){let a=this.offers.get(t);return a!==void 0&&(this.opts.offers??[]).includes(a)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,a]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?a:"";let l={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(l.selected=a);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let w of Object.keys(g))h.includes(w)||delete g[w];l.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let w=this.component(M(h),g,"",!1);w&&(l[g]=w)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,w]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(w).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(w).title,this.packages[this.selected]);m!==null&&(p[h]=m)}l.sheets=g}return{tree:l,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,a){return this.opts.switches&&Object.hasOwn(this.opts.switches,a)?this.opts.switches[a]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,a){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[a];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",a="",l="",c="",p=(h,w)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${w}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;l===""&&(l=m),y.selected===!0&&a===""&&(a=m);break}case"switch":{let m=this.switchOn(y,w),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${w}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,w);t===""&&(t=m),I(y.tabs).forEach((v,_)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${w}.tabs[${_}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],w===""?m:`${w}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||a||l;return[t,g]}holds(t,a){let l=a||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(l)!==p)return!1;break;case"offer_open":if(this.open(l)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,a,l,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),l))return null;let p=String(t.type),g=l,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let w={type:p};this.paths.set(w,a),Q(t,"id")&&(w.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(w.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(w.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,w,a,g);case"switch":return this.switchOf(t,w,a,g,h);case"countdown":return this.countdown(t,w,a,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;w.package=v,this.open(v)&&(w.offer=this.offers.get(v));let _=this.component(M(t.content),`${a}.content`,v,h);return _?(w.content=_,w):null}case"package":w.product=t.product,w.plan=t.plan,w.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(w.offer=t.offer)}for(let[v,_]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(_.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${a}.${v}`,g,h);if(!x&&_.required)return null;x&&(w[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${a}.${v}[${O}]`,g,h);V&&x.push(V)}),w[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)w[v]=x;else if(_.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(_.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(w[v]=x);break}case"object":{if(R){let x=this.object(M(P),_.item,m);if(x===null&&_.required)return null;w[v]=x}else v==="indicator"&&(w[v]=this.object({},_.item,m));break}case"value":{let x=this.value(G(P,_.def),_);x!=null&&x!==""&&(w[v]=x);break}}}return p==="text"&&this.typeStyle(w),w}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let a=this.typography[t.size];for(let l of["font","weight","line_height","letter_spacing","text_style"])!Q(t,l)&&a?.[l]!==void 0&&a?.[l]!==null&&(t[l]=a[l]);t.size=a?.size??null}tabs(t,a,l,c){let p=this.tabShown(t,l);this.tabsShown[l]=p;let g=[];return I(t.tabs).forEach((h,w)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${l}.tabs[${w}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let _=this.component(M(y.content),`${l}.tabs[${w}].content`,c,!1);_&&(a.content=_)}}),a.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(a.bar=this.style(M(t.bar))),a}switchOf(t,a,l,c,p){let g=this.switchOn(t,l);this.switchesOn[l]=g,a.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(a.label=h),a.tint=this.color(String(G(t.tint,"accent")));let w=g?"on":"off",y=this.component(M(t[w]),`${l}.${w}`,c,p);return y&&(a.content=y),a}countdown(t,a,l,c,p){let g=M(t.target),h=this.opts.now??Date.now(),w;if(typeof g.after_open_seconds=="number"?w=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):w=Math.trunc((Date.parse(String(g.at))-h)/1e3),w>0){a.state="counting",a.remaining_seconds=w,this.countdowns[l]=w;let y=this.packages,m={};for(let[_,P]of Object.entries(y))m[_]={...P,...Vt(w)};this.packages=m;let v=this.component(M(t.counting),`${l}.counting`,c,p);return v&&(a.content=v),this.packages=y,a}if(a.state="ended",a.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${l}.ended`,c,p);y&&(a.content=y)}return a}item(t,a,l){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=a[p];if(g.kind==="text"){let w=this.text(h,l);if(w!==null)c[p]=w;else if(g.required)return null}else{let w=g.def,y=this.value(G(h,w),g);y!=null&&(Q(a,p)||w!=null&&w!=="")&&(c[p]=y)}}return c}object(t,a,l){if(a==="style")return this.style(t);let c=this.item(a,t,l)??{};if(a==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],l);if(g===null)return null;c[p]=g}return c}defaults(t,a){let l={};for(let[c,p]of Object.entries(a)){let g=G(t[c],p.def);g!=null&&g!==""&&(l[c]=g)}return l}style(t){let a={};for(let[l,c]of Object.entries(t)){let p=this.objectFields("style")[l];if(!p){a[l]=c;continue}switch(p.kind){case"edges":a[l]=this.sides(c,Nt,this.spacing);break;case"corners":a[l]=this.sides(c,Dt,this.radii);break;case"fill":a[l]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[w,y]of Object.entries(this.objectFields(p.item))){let m=G(g[w],y.def);m!=null&&m!==""&&(h[w]=this.value(m,y))}a[l]=h;break}default:a[l]=c}}return a}sides(t,a,l){let c={};for(let p of a){let g=typeof t=="object"&&t!==null?G(M(t)[p],0):t;c[p]=Ae(g,l)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let a=M(t),l=this.defaults(a,this.objectFields(Ft[String(a.type)]??""));return Array.isArray(a.stops)&&(l.stops=a.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),l}value(t,a){if(a.kind!=="value")return t;switch(a.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return Ae(t,this.spacing);case"radius":return Ae(t,this.radii);default:return t}}color(t){let a=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof a=="string"?a:t}text(t,a){let l;if(typeof t=="string")l=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;l=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return l=l.replace(Ye,(p,g)=>{let h=a&&Object.hasOwn(a,g)?a[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||l.trim()===""?null:l}};function qt(d,t){let a=!1,l=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(a=!0,""):It(g)});return a?null:l}function Ae(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
|
|
3
3
|
:host{display:block;height:100%}
|
|
4
4
|
.pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as d,m as k}from"./
|
|
1
|
+
/*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as d,m as k}from"./IRDLGXAB.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
import{lstat as j,mkdir as F,readdir as M,readFile as N,rename as J,rm as T,writeFile as v}from"node:fs/promises";import{join as E}from"node:path";var o="palbase/strings",f="_meta.json",p=3,y=2,$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function m(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function b(r,n){try{return JSON.parse(r)}catch(t){throw new Error(`${n} is not JSON: ${t.message}`)}}async function x(r){let n=E(r,o);try{if(!(await j(n)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let t=new Map;for(let e of await M(n,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);t.set(e.name,await N(E(n,e.name),"utf8"))}return t.size===0?void 0:t}async function R(r,n=[p,y]){let t=await x(r);if(t===void 0)return;let e=t.get(f);if(e===void 0)throw new Error(`${o}/${f} is missing: it names the source language, and without it the language files are not a table`);let u=b(e,`${o}/${f}`);if(!$(u))throw new Error(`${o}/${f}: not a JSON object`);let s=u.version;if(s===y&&!n.includes(y))throw new Error(`${o}/${f}: version 2 is the earlier format ({"value", "state"} for each sentence) \u2014 run \`npx palbase strings\` once, and it writes the table as version ${p}`);if(typeof s!="number"||!n.includes(s))throw new Error(`${o}/${f}: version ${JSON.stringify(s)} is not one this reads (${n.join(" or ")})`);let a=u.source;if(typeof a!="string"||m(a)!==a)throw new Error(`${o}/${f}: source ${JSON.stringify(a)} is not a language tag as it is written (${m(String(a))??"en, en-US, zh-Hans"})`);let S=new Map;for(let w of[...t.keys()].sort()){if(w===f)continue;let i=w.slice(0,-5),g=`${o}/${w}`,d=m(i);if(d===void 0)throw new Error(`${g}: ${JSON.stringify(i)} is not a language tag`);if(d!==i)throw new Error(`${g}: the language is written ${d} \u2014 name the file ${d}.json`);if(i===a)throw new Error(`${g}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${g}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let O=b(t.get(w),g);if(!$(O))throw new Error(`${g}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[l,c]of Object.entries(O))if(s===p){if(typeof c!="string")throw new Error(`${g}: the translation of ${JSON.stringify(l)} is not a string`);h.set(l,c)}else if(typeof c=="string")h.set(l,c);else{if(!$(c)||typeof c.value!="string")throw new Error(`${g}: key ${JSON.stringify(l)} is not {"value": string, "state": string}`);h.set(l,c.state==="missing"?"":c.value)}S.set(i,h)}return{format:s,source:a,languages:S}}async function A(r){let n=await R(r,[p]);if(n===void 0)return;let t={};Object.setPrototypeOf(t,null);for(let[e,u]of n.languages)for(let[s,a]of u)Object.hasOwn(t,s)||(t[s]={},Object.setPrototypeOf(t[s],null)),t[s][e]=a;return{source:n.source,locales:[n.source,...n.languages.keys()],strings:t}}export{A as a};
|