palbase 0.73.1 → 0.74.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai-sdk/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/4DNFXRTX.js +2 -0
- package/dist/chunks/{HYPCFC4K.js → 53XWB3UV.js} +1 -1
- package/dist/chunks/{W2KD2I4Q.js → 5NLCEWSD.js} +1 -1
- package/dist/chunks/{GTKPHG5F.js → 7HDSHHGM.js} +2 -2
- package/dist/chunks/{MB7MHOQO.js → AFO74GQQ.js} +1 -1
- package/dist/chunks/{IVJOWYRE.js → AKM627JB.js} +2 -2
- package/dist/chunks/{5N5GHLUU.js → BBXGUP7G.js} +2 -2
- package/dist/chunks/{5N6QKGPA.js → CVBLXV6M.js} +2 -2
- package/dist/chunks/{3KCV4F4F.js → DFIAGTHU.js} +2 -2
- package/dist/chunks/FKDQMWI7.js +23 -0
- package/dist/chunks/{GWWU2FJ7.js → FYZAVXD4.js} +2 -2
- package/dist/chunks/{DNSLYLU6.js → IIQ6QEL2.js} +1 -1
- package/dist/chunks/{U3H6HER3.js → IJBBBAXY.js} +1 -1
- package/dist/chunks/{2TKZTIMD.js → MKKBGO2H.js} +2 -2
- package/dist/chunks/OS567PDL.js +2 -0
- package/dist/chunks/{VCL3SAQL.js → PF52QMPW.js} +2 -2
- package/dist/chunks/{AXANFT2A.js → QJPQVLNV.js} +2 -2
- package/dist/chunks/{MFSC4OJV.js → RK4CTF2F.js} +2 -2
- package/dist/chunks/{SQNAPFXW.js → SS3YF6MP.js} +2 -2
- package/dist/chunks/{4E4ABCSD.js → U5LDOZB5.js} +2 -2
- package/dist/chunks/{YU3GFTZV.js → WNPRCDLR.js} +1 -1
- package/dist/chunks/{SS2RVI27.js → YDHRQOAN.js} +1 -1
- package/dist/chunks/{UOJVMV42.js → YOCX3MXN.js} +2 -2
- package/dist/chunks/{HRWVZ4PC.js → ZRNXABQJ.js} +2 -2
- package/dist/cli.js +162 -162
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- 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/payments-ui.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/cloud/src/generated/project.d.ts +1 -1
- package/types/internal/src/modules/commerce.d.ts +2810 -533
- package/types/internal/src/modules/events.d.ts +2 -2
- package/types/server/src/commerce.d.ts +172 -3
- package/types/server/src/index.d.ts +1 -1
- package/types/web/src/commerce.d.ts +460 -20
- package/types/web/src/index.d.ts +1 -1
- package/types/web/src/session.d.ts +15 -1
- package/types/web/src/ssr.d.ts +1 -1
- package/dist/chunks/SEICTPQP.js +0 -2
- package/dist/chunks/TR2IPX2A.js +0 -23
- package/dist/chunks/UXHNXE3J.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as hr,d as gr,e as nn,f as yr,g as wr}from"./GWWU2FJ7.js";import{a as Rt,c as ne,d as pr,e as mr,f as be,h as _,i as br}from"./4E4ABCSD.js";import{E as fr,a as dr,e as dt,g as St,h as cr,i as ur,j as At,k as xt,n as lr}from"./SEICTPQP.js";import{a as Et,b as or,n as ir}from"./YU3GFTZV.js";import{b as ie}from"./HRWVZ4PC.js";import"reflect-metadata";var rn=[{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}],kr="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)",Ot=/^\d+$/;function ba(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 g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function vr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${kr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ba(t[h],rn[h].lo,rn[h].hi);if(!g)return`${kr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var ze=new Set(["webhooks","_palbase"]);function hd(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&ze.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function Ge(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`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var gd=Ge("GET"),yd=Ge("POST"),wd=Ge("PUT"),bd=Ge("PATCH"),kd=Ge("DELETE"),vd=Ge("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(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 Td=e=>pe("body",{schema:cn("Body",e)}),$d=e=>pe("query",{schema:cn("QueryParams",e)}),_d=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Ed=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Sd=()=>pe("user"),Ad=()=>pe("optionalUser"),xd=()=>pe("req"),Rd=()=>pe("requestId"),Od=()=>pe("client"),Pd=()=>pe("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 pe("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{de(e,on,()=>!0),se().add(e)}}function jd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var _r=/^[a-z]+(\.[a-z_]+)+$/,ka=/^[a-z][a-z0-9-]{1,62}$/,un=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"||!ka.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(!un(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`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,va=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Tr(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(!va.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"||!ln.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=vr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Tr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Tr(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,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var $r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ta=/^[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(!Ta.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&&!$r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${$r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&$a(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,Me)??[];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)}de(t,Be,()=>({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 $a(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,qe)!==void 0)}function Id(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Gd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.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,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Sr(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var _a=720*3600;function Ea(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>_a))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 Sa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Fd=Rt("Tasks",{async enqueue(e,t,n={}){return Ea(n),fn().enqueue(Sa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(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 Ar(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 be.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 pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Aa=1e4,xa=36e5,Er=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Er))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),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(Aa*2**Math.min(t.attempt-1,16),xa),_.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>=Er&&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 Mt="/_palbase/test-user-templates",Ra=/^[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"||!Ra.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,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function xr(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 Rr(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Oa="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 Or(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Oa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Pr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Cr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Pa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Pa(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 Mr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function jr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ca=/^[a-z][a-z0-9-]{1,62}$/,Dr=1024,Ma=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`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ca.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" 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 s=ja(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function tc(){return pe("uploadedObject")}function ja(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Ma.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(!Nr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Nr(e){if(e===""||new TextEncoder().encode(e).byteLength>Dr)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 Da(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Na(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Na(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 Ur(e,t){let n=Da(e,t);return Nr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Dr} bytes)`}}function Lr(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 Ir(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=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=Mr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=Ua(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Ua(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as La}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),qr={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"]},Ia={"~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(qr),output:()=>structuredClone(qr)}}},Kr=Symbol.for("palbase.backend.gatewayRefusal"),Hr=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,Kr,{value:!0})}},qa=e=>typeof e=="object"&&e!==null&&e[Kr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ha=6e4,Ba=86400,Br=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Ga=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(" ")),Ke=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 Fa(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(Ke(e)>Se)return`a channel is ${Se} 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=za.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 Jr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} 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=Fa(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=Wa(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)||Ga.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[g,b]of Object.entries(d)){let k=Jr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!bn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,$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:Ia}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ha,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(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&&!We(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`);de(a,je,()=>h),se().add(a)}}function Wa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ba;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Br)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Br} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ka={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ka[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=de(n.constructor,Je,$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=Jr(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=de(s.constructor,Je,$n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ja(e){return D(e,je)}function Va(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 Vr(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 Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Za(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))?Vr(e,t):Ya(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 Ya(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 Qa=1e4,Xa=1e3,eo=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Gr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Fr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Zr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Ja(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Fr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Fr(f.pattern),f.pattern);for(let[z,J]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([L,N])=>[`message ${L}`,N.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${z} is ${J}, which is no method of it`);let I={cls:v,instance:E,g:f};n.set(f.pattern,I),r.set(v,I)}let o=new Map,d=new Set,l=new Set,h=new vn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,I)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...I!==void 0?{conn_id:I}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,I,z){let J=T?.signal??AbortSignal.abort(),L=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:J,count:R,user:I,emit:(N,G)=>k(v,E,N,G,L,z),pipe:N=>B(N,E,L),owner:{hold(N){ne.exit(async()=>{try{await N(J)}catch(G){J.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Va(E,f)}}let W=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function K(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:I}=f,z={status:200,body:{subscribe:!1,publish:!1}};if(!I)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),z;let J=Fe(v.user),L=J?.id;if(!L)return z;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return I[Tn(T.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:z;let N=T.g.hooks.authorize;if(!N)return z;let G,Q;try{G=await t.run(J,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:{id:L},params:Object.freeze({...I})})),Q=to(G)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),z}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${no(G)}, which is no grant (true, { read, write } or null); the join is refused`),z):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:kn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let I=await R.schema["~standard"].validate(La(v.payload??{}));if(I.issues)return{status:200,body:{ok:!1,reason:Wr(I.issues)}};let z=g(f.channel),J={...U(f.entry,f.channel,f.params,z,0,{id:T.id}),payload:I.value},L=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](J))}catch(Q){if(t.isOutage(Q))throw Q;return qa(Q)?{status:200,body:{ok:!1,reason:kn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${L} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Wr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let G;try{G=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Ke(G)>zr?(_.error(`[palbase] ${L} returned an ack of ${Ke(G)} bytes, past ${zr}; 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 he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Gr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let I=T==="join"||T==="leave",z=I?Fe(v.user):void 0,J=I?v.connId:void 0;if(I&&(!z?.id||typeof J!="string"||J===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let L=`${T}\0${f.channel}\0${typeof J=="string"?J:""}`;if(I&&d.has(L))return{status:204};if(l.has(L))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let N=f.entry.g.hooks[Gr[T]],G;if(T==="empty"?(G=o.get(f.channel),b(f.channel,G)):G=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,G,R,{id:z?.id??""},T==="join"?J:void 0);try{await t.run(z,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return I&&(d.add(L),d.size>Qa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Vr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return _n(E)?v==="authorize"?K(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:I,where:z}=ge(v,E);k(R,I,f,T,z)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let I=Za(T.g.pattern,E??{},f);if("problem"in I)throw new TypeError(`${R}: ${I.problem}`);let z=ne.getStore()?.saying;if(z){z.push(()=>{t.revalidate(I).catch(J=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:J}))});return}await t.revalidate(I)},close(){for(let v of o.values())v.abort();o.clear()}}}function to(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 no(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 ro=20,Dt=256;function Wr(e){let t="";for(let n of e.slice(0,ro)){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)>=Dt)break}return kn(t,Dt)}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===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=Xa?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,eo);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 so,createPublicKey as es,timingSafeEqual as ao,verify as ts}from"node:crypto";function yc(e){let t=D(e,Be);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 ns(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=oo(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(W,K)=>k[q](W,K)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
1
|
+
/*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as hr,d as gr,e as nn,f as yr,g as wr}from"./FYZAVXD4.js";import{a as Rt,c as ne,d as pr,e as mr,f as be,h as _,i as br}from"./U5LDOZB5.js";import{F as fr,a as dr,e as dt,g as St,h as cr,i as ur,j as At,k as xt,n as lr}from"./4DNFXRTX.js";import{a as Et,b as or,n as ir}from"./WNPRCDLR.js";import{b as ie}from"./ZRNXABQJ.js";import"reflect-metadata";var rn=[{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}],kr="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)",Ot=/^\d+$/;function ba(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 g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function vr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${kr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ba(t[h],rn[h].lo,rn[h].hi);if(!g)return`${kr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var ze=new Set(["webhooks","_palbase"]);function hd(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&ze.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function Ge(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`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var gd=Ge("GET"),yd=Ge("POST"),wd=Ge("PUT"),bd=Ge("PATCH"),kd=Ge("DELETE"),vd=Ge("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(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 Td=e=>pe("body",{schema:cn("Body",e)}),$d=e=>pe("query",{schema:cn("QueryParams",e)}),_d=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Ed=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Sd=()=>pe("user"),Ad=()=>pe("optionalUser"),xd=()=>pe("req"),Rd=()=>pe("requestId"),Od=()=>pe("client"),Pd=()=>pe("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 pe("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{de(e,on,()=>!0),se().add(e)}}function jd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var _r=/^[a-z]+(\.[a-z_]+)+$/,ka=/^[a-z][a-z0-9-]{1,62}$/,un=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"||!ka.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(!un(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`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,va=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Tr(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(!va.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"||!ln.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=vr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Tr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Tr(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,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var $r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ta=/^[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(!Ta.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&&!$r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${$r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&$a(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,Me)??[];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)}de(t,Be,()=>({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 $a(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,qe)!==void 0)}function Id(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Gd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.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,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Sr(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var _a=720*3600;function Ea(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>_a))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 Sa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Fd=Rt("Tasks",{async enqueue(e,t,n={}){return Ea(n),fn().enqueue(Sa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(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 Ar(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 be.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 pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Aa=1e4,xa=36e5,Er=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Er))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),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(Aa*2**Math.min(t.attempt-1,16),xa),_.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>=Er&&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 Mt="/_palbase/test-user-templates",Ra=/^[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"||!Ra.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,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function xr(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 Rr(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Oa="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 Or(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Oa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Pr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Cr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Pa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Pa(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 Mr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function jr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ca=/^[a-z][a-z0-9-]{1,62}$/,Dr=1024,Ma=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`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ca.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" 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 s=ja(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function tc(){return pe("uploadedObject")}function ja(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Ma.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(!Nr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Nr(e){if(e===""||new TextEncoder().encode(e).byteLength>Dr)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 Da(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Na(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Na(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 Ur(e,t){let n=Da(e,t);return Nr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Dr} bytes)`}}function Lr(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 Ir(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=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=Mr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=Ua(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Ua(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as La}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),qr={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"]},Ia={"~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(qr),output:()=>structuredClone(qr)}}},Kr=Symbol.for("palbase.backend.gatewayRefusal"),Hr=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,Kr,{value:!0})}},qa=e=>typeof e=="object"&&e!==null&&e[Kr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ha=6e4,Ba=86400,Br=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Ga=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(" ")),Ke=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 Fa(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(Ke(e)>Se)return`a channel is ${Se} 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=za.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 Jr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} 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=Fa(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=Wa(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)||Ga.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[g,b]of Object.entries(d)){let k=Jr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!bn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,$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:Ia}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ha,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(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&&!We(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`);de(a,je,()=>h),se().add(a)}}function Wa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ba;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Br)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Br} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ka={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ka[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=de(n.constructor,Je,$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=Jr(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=de(s.constructor,Je,$n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ja(e){return D(e,je)}function Va(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 Vr(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 Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Za(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))?Vr(e,t):Ya(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 Ya(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 Qa=1e4,Xa=1e3,eo=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Gr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Fr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Zr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Ja(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Fr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Fr(f.pattern),f.pattern);for(let[z,J]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([L,N])=>[`message ${L}`,N.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${z} is ${J}, which is no method of it`);let I={cls:v,instance:E,g:f};n.set(f.pattern,I),r.set(v,I)}let o=new Map,d=new Set,l=new Set,h=new vn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,I)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...I!==void 0?{conn_id:I}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,I,z){let J=T?.signal??AbortSignal.abort(),L=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:J,count:R,user:I,emit:(N,G)=>k(v,E,N,G,L,z),pipe:N=>B(N,E,L),owner:{hold(N){ne.exit(async()=>{try{await N(J)}catch(G){J.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Va(E,f)}}let W=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function K(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:I}=f,z={status:200,body:{subscribe:!1,publish:!1}};if(!I)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),z;let J=Fe(v.user),L=J?.id;if(!L)return z;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return I[Tn(T.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:z;let N=T.g.hooks.authorize;if(!N)return z;let G,Q;try{G=await t.run(J,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:{id:L},params:Object.freeze({...I})})),Q=to(G)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),z}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${no(G)}, which is no grant (true, { read, write } or null); the join is refused`),z):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:kn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let I=await R.schema["~standard"].validate(La(v.payload??{}));if(I.issues)return{status:200,body:{ok:!1,reason:Wr(I.issues)}};let z=g(f.channel),J={...U(f.entry,f.channel,f.params,z,0,{id:T.id}),payload:I.value},L=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](J))}catch(Q){if(t.isOutage(Q))throw Q;return qa(Q)?{status:200,body:{ok:!1,reason:kn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${L} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Wr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let G;try{G=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Ke(G)>zr?(_.error(`[palbase] ${L} returned an ack of ${Ke(G)} bytes, past ${zr}; 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 he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Gr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let I=T==="join"||T==="leave",z=I?Fe(v.user):void 0,J=I?v.connId:void 0;if(I&&(!z?.id||typeof J!="string"||J===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let L=`${T}\0${f.channel}\0${typeof J=="string"?J:""}`;if(I&&d.has(L))return{status:204};if(l.has(L))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let N=f.entry.g.hooks[Gr[T]],G;if(T==="empty"?(G=o.get(f.channel),b(f.channel,G)):G=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,G,R,{id:z?.id??""},T==="join"?J:void 0);try{await t.run(z,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return I&&(d.add(L),d.size>Qa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Vr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return _n(E)?v==="authorize"?K(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:I,where:z}=ge(v,E);k(R,I,f,T,z)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let I=Za(T.g.pattern,E??{},f);if("problem"in I)throw new TypeError(`${R}: ${I.problem}`);let z=ne.getStore()?.saying;if(z){z.push(()=>{t.revalidate(I).catch(J=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:J}))});return}await t.revalidate(I)},close(){for(let v of o.values())v.abort();o.clear()}}}function to(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 no(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 ro=20,Dt=256;function Wr(e){let t="";for(let n of e.slice(0,ro)){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)>=Dt)break}return kn(t,Dt)}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===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=Xa?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,eo);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 so,createPublicKey as es,timingSafeEqual as ao,verify as ts}from"node:crypto";function yc(e){let t=D(e,Be);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 ns(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=oo(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(W,K)=>k[q](W,K)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
3
|
- ${a.join(`
|
|
4
4
|
- `)}`);return s}function rs(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Yr=1024*Ve;function oo(e,t){if(e.signature)return De(void 0,e.signature.header,1/0,wo(e.signature,t));switch(e.provider){case"stripe":return De("stripe","stripe-signature",512*Ve,uo(t));case"github":return De("github","x-hub-signature-256",25*Yr,lo(t));case"slack":return De("slack","x-slack-signature",64*Ve,fo(t));case"discord":return De("discord","x-signature-ed25519",64*Ve,po(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:ho(t)};case"sendgrid":return De("sendgrid","x-twilio-email-event-webhook-signature",Yr,go(t));case"livekit":return De("livekit","authorization",512*Ve,yo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function De(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??ss(e,s)}}function ss(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:as(e,t.headers,r),event:r,...io(e,t,r)}}function as(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Ne(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=ds(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 Ne(n,"EventType");case"livekit":return Ne(n,"event");default:return Ne(n,"type")}}function io(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Ne(n,"id"));case"slack":return r(Ne(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${os(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Ne(s,"sg_event_id")||void 0)}:{};default:return{}}}var co=300;function uo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let l of r.split(",")){let h=l.indexOf("=");if(h<=0)continue;let g=l.slice(0,h).trim(),b=l.slice(h+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=b}else if(g==="v1"){let k=me(b,"hex");if(!k)return"malformed_signature";a.push(k)}}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(l=>Ae(l,d))?void 0:"signature_mismatch"}}function lo(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?Ae(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function fo(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":Ae(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function po(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=es({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),l=me(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":ts(null,is(o,r.body),n,l)?void 0:"signature_mismatch"}}var mo=1e3;function ho(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(!Ae(Buffer.from(a.toLowerCase()),Buffer.from(En("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let B=1;for(let W of t.body)if(W===38&&++B>mo)return"malformed_signature";let U=new Map;for(let[W,K]of new URLSearchParams(Sn(t.body))){let le=U.get(W);le||U.set(W,le=new Set),le.add(K)}let q=[];for(let W of[...U.keys()].sort()){let K=[...U.get(W)].sort();for(let le of K)o+=W+le;q.push([W,K.length===1?K[0]:K])}d=Object.fromEntries(q)}let l=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![h,g].some(B=>Ae(r,Ze("sha1",e,B,o))))return"signature_mismatch";let b=t.headers.get("i-twilio-idempotency-token"),k=b?{id:`${b}:${os(`${h}
|
|
5
5
|
${o}`)}`}:{};return d?{type:as("twilio",t.headers,d),event:d,...k}:{...ss("twilio",t),...k}}}function go(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=es({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":ts("sha256",is(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Qr=60;function yo(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=Xr(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Ae(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Xr(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Qr||typeof d.nbf=="number"&&n<d.nbf-Qr)return"stale_timestamp";let l=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return l&&Ae(l,En("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function wo(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 l=me(o.trim(),e.encoding);return l?Ae(l,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var bo=new TextEncoder;function Ze(e,t,...n){let r=so(e,t);for(let s of n)r.update(s);return r.digest()}function os(e){return En("sha256").update(e).digest("hex")}function is(e,t){return Buffer.concat([bo.encode(e),t])}function Ae(e,t){return e.byteLength===t.byteLength&&ao(e,t)}var ko={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 ko[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)>co}function Sn(e){return new TextDecoder().decode(e)}function Xr(e){if(e)try{return JSON.parse(Sn(e))}catch{return}}function ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,t){let n=ds(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var Y=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var s=class extends Error{code;constructor(t,e){super(e),this.name="FieldError",this.code=t}},f="pbe1.",g="pbl1.",k=6e4,p="[A-Za-z_][A-Za-z0-9_$]{0,62}",w=new RegExp(`^${p}\\.${p}(\\.${p})?$`);function v(o){return w.test(o)}var h=class{crypto;keys=new Map;lookupKey;timer;opts;now;constructor(t){this.opts=t,this.now=t.now??Date.now}get loaded(){return this.lookupKey!==void 0}async load(t){this.crypto??=await import("node:crypto"),this.take(await this.opts.fetch(t)),this.timer===void 0&&(this.timer=setInterval(()=>{this.opts.fetch().then(e=>this.take(e),()=>{})},k),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}take(t){let e=new Map;for(let r of t.keys)e.set(r.id,{id:r.id,key:Buffer.from(r.key,"base64url"),activatesAt:Date.parse(r.activates_at)});this.keys=e,this.lookupKey=Buffer.from(t.lookup,"base64url")}ready(){if(this.crypto===void 0||this.lookupKey===void 0)throw new s("not_loaded","the project's field keys are not loaded: await palbase.fields.load() at startup");return this.crypto}currentKey(){this.ready();let t;for(let e of this.keys.values())e.activatesAt<=this.now()&&(t===void 0||e.activatesAt>=t.activatesAt)&&(t=e);if(t===void 0)throw new s("unknown_key","the project has no field key in force");return t.id}encrypt(t,e){let r=this.ready();l(t);let n=this.currentKey(),i=r.randomBytes(12);return b(r,this.keys.get(n).key,i,n,t,e)}decrypt(t,e){let r=this.ready();if(l(t),!e.startsWith(f))throw new s("not_encrypted",`${t} holds a value that is not encrypted`);let n=e.slice(f.length),i=n.indexOf("."),a=i<0?n:n.slice(0,i),u=this.keys.get(a);if(u===void 0)throw new s("unknown_key",`${t} was sealed with field key ${a}, which this project does not hold`);let c=Buffer.from(n.slice(i+1),"base64url");if(i<0||c.length<28||c.toString("base64url")!==n.slice(i+1))throw new s("unopenable",`${t} holds a value that does not open here`);try{let d=r.createDecipheriv("aes-256-gcm",u.key,c.subarray(0,12));return d.setAAD(y(t)),d.setAuthTag(c.subarray(c.length-16)),Buffer.concat([d.update(c.subarray(12,c.length-16)),d.final()]).toString("utf8")}catch{throw new s("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(f)}lookup(t,e){let r=this.ready();return l(t),m(r,this.lookupKey,t,e)}};function l(o){if(!v(o))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(o)}`)}function y(o){return Buffer.from(`pbe1\0${o}`,"utf8")}function b(o,t,e,r,n,i){let a=o.createCipheriv("aes-256-gcm",t,e);a.setAAD(y(n));let u=Buffer.concat([e,a.update(i,"utf8"),a.final(),a.getAuthTag()]);return`${f}${r}.${u.toString("base64url")}`}function m(o,t,e,r){let n=o.createHmac("sha256",t);return n.update(`pbl1\0${e}\0`,"utf8"),n.update(r,"utf8"),`${g}${n.digest("base64url")}`}export{s as a,h as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{n as w}from"./UXHNXE3J.js";import{b as c}from"./HRWVZ4PC.js";var P=new Set(["succeeded","requires_capture","failed","canceled","expired"]);function S(o){return P.has(o)}var W=new Set(["payments.payment.succeeded","payments.payment.failed","payments.payment.canceled","payments.payment.requires_capture"]),E=new Set(["payments.wallet.balance_changed","payments.wallet.hold_changed"]);function T(o){if(typeof o!="object"||o===null)return null;let e=o;return e.source!=="palbase.payments"||typeof e.intent_id!="string"||e.intent_id.length===0||typeof e.status!="string"||e.status.length===0?null:{source:"palbase.payments",intent_id:e.intent_id,status:e.status,...typeof e.decline_code=="string"&&e.decline_code.length>0?{decline_code:e.decline_code}:{},...typeof e.return_url=="string"&&e.return_url.length>0?{return_url:e.return_url}:{}}}var A={insufficient_funds:"Insufficient funds on this card. Please try another payment method.",card_declined:"Your card was declined by the issuing bank.",do_not_honor:"Your bank declined this transaction. Please contact your bank or use another card.",expired_card:"This card has expired. Please use a valid card.",incorrect_cvc:"The security code (CVC/CVV) is incorrect.",incorrect_number:"The card number is invalid.",invalid_expiry:"The card expiration date is invalid.",authentication_required:"Additional 3D Secure verification is required by your bank.",three_ds_failed:"3D Secure verification failed or was canceled.",otp_invalid:"The verification code is incorrect. Please try again.",otp_expired:"The verification code has expired. Please request a new one.",fraud_suspected:"This transaction was declined for security reasons.",velocity_exceeded:"Too many failed payment attempts. Please wait a moment and try again.",limit_exceeded:"This transaction exceeds your card limit.",card_not_permitted:"This card is not enabled for online or international transactions.",processing_error:"A temporary payment processing error occurred. Please try again.",provider_unavailable:"The payment provider is temporarily unavailable. Please try again.",wallet_frozen:"This wallet is currently frozen and cannot be charged.",wallet_insufficient_balance:"Insufficient wallet balance for this payment."};function B(o){return o?A[o]??"Payment was declined. Please try another payment method.":"Payment could not be completed. Please try again."}var _=class{api;profile;methods;wallet;subscriptions;session;socket;ref;origin;walletListeners=new Set;walletWatch;walletFollowing;lastBalances;eventListeners=new Set;eventWatch;eventFollowing;constructor(e,t,i,s,d){this.api=w.client(e),this.session=t,this.socket=i,this.ref=s,this.origin=d,this.profile={get:async n=>(await this.api.getMyProfile({signal:n?.signal})).data,update:async(n,a)=>(await this.api.updateMyProfile({body:n,signal:a?.signal})).data},this.methods={list:async n=>(await this.api.listMyMethods({signal:n?.signal})).data.methods,add:async(n={})=>{let a={...n.channel!==void 0?{channel:n.channel}:{},...n.vault!==void 0?{vault:n.vault}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}};return(await this.api.addMyMethod({body:a,signal:n.signal})).data.next_action},remove:async(n,a)=>{await this.api.deleteMyMethod({path:{method_id:n},signal:a?.signal})}},this.wallet={balances:async n=>{let a=this.session.snapshot()?.userId,l=(await this.api.listMyWallets({signal:n?.signal})).data.balances;return this.walletWatch&&this.walletWatch.userId===a&&this.offerBalances(this.walletWatch,l),l},balance:async(n,a)=>(await this.wallet.balances(a)).find(u=>u.wallet_key===n),topUp:async n=>{let a={wallet_key:n.walletKey,amount:n.amount,...n.channel!==void 0?{channel:n.channel}:{},...n.methodId!==void 0?{method_id:n.methodId}:{},...n.saveMethod!==void 0?{save_method:n.saveMethod}:{},...n.useMasterpass!==void 0?{use_masterpass:n.useMasterpass}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}},l=n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:void 0;return(await this.api.topUpMyWallet({body:a,headers:l,signal:n.signal})).data},createSpendToken:async n=>{let a={wallet_key:n.walletKey,...n.maxAmount!==void 0?{max_amount:n.maxAmount}:{},...n.ttlSeconds!==void 0?{ttl_seconds:n.ttlSeconds}:{}};return(await this.api.createMySpendToken({body:a,signal:n.signal})).data},onChange:n=>this.onWalletChange(n)},this.subscriptions={list:async n=>(await this.api.listMySubscriptions({query:{limit:n?.limit,cursor:n?.cursor},signal:n?.signal})).data,cancel:async(n,a)=>(await this.api.cancelMySubscription({path:{subscription_id:n},signal:a?.signal})).data}}async capabilities(e={}){return(await this.api.getCapabilities({query:{...e.currency!==void 0?{currency:e.currency}:{},...e.channel!==void 0?{channel:e.channel}:{}},signal:e.signal})).data}async installments(e){let t={amount:e.amount,currency:e.currency,...e.bin!==void 0?{bin:e.bin}:{},...e.methodId!==void 0?{method_id:e.methodId}:{},...e.channel!==void 0?{channel:e.channel}:{}};return(await this.api.lookupInstallments({body:t,signal:e.signal})).data}async getIntent(e,t={}){return(await this.api.getIntent({path:{intent_id:e},query:t.clientSecret?{client_secret:t.clientSecret}:void 0,signal:t.signal})).data}async confirm(e,t={}){let i={...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.methodId!==void 0?{method_id:t.methodId}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{},...t.useMasterpass!==void 0?{use_masterpass:t.useMasterpass}:{},...t.phone!==void 0?{phone:t.phone}:{},...t.buyer!==void 0?{buyer:t.buyer}:{},...t.installments!==void 0?{installments:t.installments}:{},...t.providerOptions!==void 0?{provider_options:t.providerOptions}:{}},s=t.idempotencyKey?{"Idempotency-Key":t.idempotencyKey}:void 0;return(await this.api.confirmIntent({path:{intent_id:e},body:i,headers:s,signal:t.signal})).data}async submitOtp(e,t){let i={challenge_id:t.challengeId,otp:t.otp,...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{}};return(await this.api.submitIntentOtp({path:{intent_id:e},body:i,signal:t.signal})).data}async portal(e,t={}){let i={return_url:e,...t.channel!==void 0?{channel:t.channel}:{}};return(await this.api.createMyPortal({body:i,signal:t.signal})).data.url}async waitForIntent(e,t={}){let i=t.timeoutMs??3e5;if(t.signal?.aborted)throw t.signal.reason;return new Promise((s,d)=>{let n=!1,a=!1,l=!1,u=this.socket.channel(`payment_intent:${this.ref}:${e}`),h=()=>{v!==void 0&&clearTimeout(v),x(),u.leave(),y.removeEventListener?.("message",g),t.signal?.removeEventListener("abort",f)},I=r=>{n||(n=!0,h(),s(r))},p=r=>{n||(n=!0,h(),d(r))},m=async()=>{if(!n){if(a){l=!0;return}a=!0;try{for(;;){l=!1;try{let r=await this.getIntent(e,{clientSecret:t.clientSecret,signal:t.signal});if(S(r.status)){I(r);return}}catch(r){if(t.signal?.aborted){p(t.signal.reason);return}if(r instanceof c&&(r.status===401||r.status===403||r.status===404)){p(r);return}}if(n||!l)return}}finally{a=!1}}},x=u.on("broadcast",r=>{typeof r.event=="string"&&W.has(r.event)&&m()}),g=r=>{if(r.origin&&r.origin!=="null"&&r.origin!==this.origin)return;let b=T(r.data);b&&b.intent_id===e&&m()},f=()=>p(t.signal?.reason),y=globalThis;y.addEventListener?.("message",g),t.signal?.addEventListener("abort",f,{once:!0});let v=i>0?setTimeout(()=>{p(new c({op:"WaitForIntent",status:0,code:"payment_timeout",message:`timed out waiting for payment intent ${e}`}))},i):void 0;u.join().catch(()=>{}),m()})}async present(e,t={}){let i=t.clientSecret??e.client_secret,s=e.status!==void 0&&e.amount!==void 0?e:await this.getIntent(e.id,{clientSecret:i,signal:t.signal});for(let d=0;d<6;d++){if(S(s.status))return s;let n=s.next_action;if(!n||n.type==="none")return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal});if(n.type==="redirect"){if(!n.url)throw new c({op:"PresentIntent",status:0,code:"invalid_next_action",message:"redirect next_action is missing url"});if(t.onRedirect)await t.onRedirect(n.url,n);else{let a=globalThis.location;if(!a)throw new c({op:"PresentIntent",status:0,code:"redirect_unavailable",message:"provide onRedirect in non-browser environments"});a.assign(n.url)}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}if(n.type==="embed"){let a;if(t.onEmbed){let l=await t.onEmbed(n);typeof l=="function"&&(a=l)}else if(t.container)a=k(t.container,n);else throw new c({op:"PresentIntent",status:0,code:"embed_container_required",message:"provide container or onEmbed to present an embedded 3DS/checkout action"});try{return await this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}finally{a?.()}}if(n.type==="otp"||n.type==="masterpass"){if(!t.onOtp)throw new c({op:"PresentIntent",status:0,code:"otp_handler_required",message:"provide onOtp to complete an OTP or Masterpass verification step"});let a=n.challenge_id??"",l=await t.onOtp({intentId:s.id,challengeId:a,maskedPhone:n.masked_phone??n.masterpass?.phone,expiresAt:n.expires_at,masterpass:n.masterpass});if(l===null)throw new c({op:"PresentIntent",status:0,code:"payment_canceled",message:"verification canceled by customer"});let u=typeof l=="string"?l:l.otp,h=typeof l=="string"?void 0:l.saveMethod;s=await this.submitOtp(s.id,{challengeId:a,otp:u,clientSecret:i,saveMethod:h,signal:t.signal});continue}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}return this.getIntent(s.id,{clientSecret:i,signal:t.signal})}onEvent(e){return this.eventListeners.add(e),this.eventListeners.size===1&&this.startEvents(),()=>{this.eventListeners.delete(e)&&this.eventListeners.size===0&&this.stopEvents()}}onWalletChange(e){if(this.walletListeners.add(e),this.walletListeners.size===1)this.startWalletWatch();else if(this.lastBalances!==void 0){let t=this.lastBalances;queueMicrotask(()=>this.walletListeners.has(e)&&M(e,t))}return()=>{this.walletListeners.delete(e)&&this.walletListeners.size===0&&this.stopWalletWatch()}}startWalletWatch(){this.walletFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followWallet(t)}),this.session.session().then(e=>{this.walletFollowing&&!this.walletWatch&&this.lastBalances===void 0&&this.followWallet(e)})}stopWalletWatch(){this.walletFollowing?.(),this.walletFollowing=void 0,this.unfollowWallet(),this.lastBalances=void 0}followWallet(e){if(this.unfollowWallet(),!e){this.tellBalances(null);return}let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i={userId:e.userId,channel:t,off:()=>{},maxVersion:-1,reading:!1,wanted:!1},s=t.on("broadcast",d=>{typeof d.event=="string"&&E.has(d.event)&&this.walletChanged(i)});i.off=s,this.walletWatch=i,t.join().catch(()=>{}),this.readBalances(i)}unfollowWallet(){let e=this.walletWatch;e&&(this.walletWatch=void 0,e.off(),e.channel.leave())}walletChanged(e){this.walletWatch===e&&(e.reading?e.wanted=!0:this.readBalances(e))}async readBalances(e){e.reading=!0;try{for(;;){e.wanted=!1;try{let t=(await this.api.listMyWallets()).data.balances;if(this.walletWatch!==e)return;this.offerBalances(e,t)}catch{}if(this.walletWatch!==e||!e.wanted)return}}finally{e.reading=!1}}offerBalances(e,t){if(this.walletWatch!==e)return;let i=t.reduce((s,d)=>Math.max(s,d.version),0);e.maxVersion>=0&&i<e.maxVersion||(e.maxVersion=i,this.tellBalances(t))}tellBalances(e){if(!(this.lastBalances===null&&e===null)){this.lastBalances=e;for(let t of[...this.walletListeners])M(t,e)}}startEvents(){this.eventFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followEvents(t)}),this.session.session().then(e=>{this.eventFollowing&&!this.eventWatch&&this.followEvents(e)})}stopEvents(){this.eventFollowing?.(),this.eventFollowing=void 0,this.unfollowEvents()}followEvents(e){if(this.unfollowEvents(),!e)return;let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i=t.on("broadcast",s=>{if(typeof s.event!="string")return;let d={type:s.event,payload:s.payload};for(let n of[...this.eventListeners])try{n(d)}catch{}});this.eventWatch={userId:e.userId,channel:t,off:i},t.join().catch(()=>{})}unfollowEvents(){let e=this.eventWatch;e&&(this.eventWatch=void 0,e.off(),e.channel.leave())}};function k(o,e){let i=o.ownerDocument.createElement("iframe");return i.setAttribute("data-palbase-payments-frame",""),i.setAttribute("title","Secure Payment Verification"),i.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-top-navigation-by-user-activation"),i.style.width="100%",i.style.minHeight="480px",i.style.border="0",i.style.borderRadius="8px",i.style.background="#ffffff",e.html?i.srcdoc=e.html:e.url&&(i.src=e.url),o.replaceChildren(i),()=>{i.remove()}}function M(o,e){try{o(e)}catch{}}export{P as a,S as b,T as c,B as d,_ as e,k as f};
|
|
1
|
+
/*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{n as w}from"./OS567PDL.js";import{b as c}from"./ZRNXABQJ.js";var P=new Set(["succeeded","requires_capture","failed","canceled","expired"]);function S(o){return P.has(o)}var W=new Set(["payments.payment.succeeded","payments.payment.failed","payments.payment.canceled","payments.payment.requires_capture"]),E=new Set(["payments.wallet.balance_changed","payments.wallet.hold_changed"]);function T(o){if(typeof o!="object"||o===null)return null;let e=o;return e.source!=="palbase.payments"||typeof e.intent_id!="string"||e.intent_id.length===0||typeof e.status!="string"||e.status.length===0?null:{source:"palbase.payments",intent_id:e.intent_id,status:e.status,...typeof e.decline_code=="string"&&e.decline_code.length>0?{decline_code:e.decline_code}:{},...typeof e.return_url=="string"&&e.return_url.length>0?{return_url:e.return_url}:{}}}var A={insufficient_funds:"Insufficient funds on this card. Please try another payment method.",card_declined:"Your card was declined by the issuing bank.",do_not_honor:"Your bank declined this transaction. Please contact your bank or use another card.",expired_card:"This card has expired. Please use a valid card.",incorrect_cvc:"The security code (CVC/CVV) is incorrect.",incorrect_number:"The card number is invalid.",invalid_expiry:"The card expiration date is invalid.",authentication_required:"Additional 3D Secure verification is required by your bank.",three_ds_failed:"3D Secure verification failed or was canceled.",otp_invalid:"The verification code is incorrect. Please try again.",otp_expired:"The verification code has expired. Please request a new one.",fraud_suspected:"This transaction was declined for security reasons.",velocity_exceeded:"Too many failed payment attempts. Please wait a moment and try again.",limit_exceeded:"This transaction exceeds your card limit.",card_not_permitted:"This card is not enabled for online or international transactions.",processing_error:"A temporary payment processing error occurred. Please try again.",provider_unavailable:"The payment provider is temporarily unavailable. Please try again.",wallet_frozen:"This wallet is currently frozen and cannot be charged.",wallet_insufficient_balance:"Insufficient wallet balance for this payment."};function B(o){return o?A[o]??"Payment was declined. Please try another payment method.":"Payment could not be completed. Please try again."}var _=class{api;profile;methods;wallet;subscriptions;session;socket;ref;origin;walletListeners=new Set;walletWatch;walletFollowing;lastBalances;eventListeners=new Set;eventWatch;eventFollowing;constructor(e,t,i,s,d){this.api=w.client(e),this.session=t,this.socket=i,this.ref=s,this.origin=d,this.profile={get:async n=>(await this.api.getMyProfile({signal:n?.signal})).data,update:async(n,a)=>(await this.api.updateMyProfile({body:n,signal:a?.signal})).data},this.methods={list:async n=>(await this.api.listMyMethods({signal:n?.signal})).data.methods,add:async(n={})=>{let a={...n.channel!==void 0?{channel:n.channel}:{},...n.vault!==void 0?{vault:n.vault}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}};return(await this.api.addMyMethod({body:a,signal:n.signal})).data.next_action},remove:async(n,a)=>{await this.api.deleteMyMethod({path:{method_id:n},signal:a?.signal})}},this.wallet={balances:async n=>{let a=this.session.snapshot()?.userId,l=(await this.api.listMyWallets({signal:n?.signal})).data.balances;return this.walletWatch&&this.walletWatch.userId===a&&this.offerBalances(this.walletWatch,l),l},balance:async(n,a)=>(await this.wallet.balances(a)).find(u=>u.wallet_key===n),topUp:async n=>{let a={wallet_key:n.walletKey,amount:n.amount,...n.channel!==void 0?{channel:n.channel}:{},...n.methodId!==void 0?{method_id:n.methodId}:{},...n.saveMethod!==void 0?{save_method:n.saveMethod}:{},...n.useMasterpass!==void 0?{use_masterpass:n.useMasterpass}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}},l=n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:void 0;return(await this.api.topUpMyWallet({body:a,headers:l,signal:n.signal})).data},createSpendToken:async n=>{let a={wallet_key:n.walletKey,...n.maxAmount!==void 0?{max_amount:n.maxAmount}:{},...n.ttlSeconds!==void 0?{ttl_seconds:n.ttlSeconds}:{}};return(await this.api.createMySpendToken({body:a,signal:n.signal})).data},onChange:n=>this.onWalletChange(n)},this.subscriptions={list:async n=>(await this.api.listMySubscriptions({query:{limit:n?.limit,cursor:n?.cursor},signal:n?.signal})).data,cancel:async(n,a)=>(await this.api.cancelMySubscription({path:{subscription_id:n},signal:a?.signal})).data}}async capabilities(e={}){return(await this.api.getCapabilities({query:{...e.currency!==void 0?{currency:e.currency}:{},...e.channel!==void 0?{channel:e.channel}:{}},signal:e.signal})).data}async installments(e){let t={amount:e.amount,currency:e.currency,...e.bin!==void 0?{bin:e.bin}:{},...e.methodId!==void 0?{method_id:e.methodId}:{},...e.channel!==void 0?{channel:e.channel}:{}};return(await this.api.lookupInstallments({body:t,signal:e.signal})).data}async getIntent(e,t={}){return(await this.api.getIntent({path:{intent_id:e},query:t.clientSecret?{client_secret:t.clientSecret}:void 0,signal:t.signal})).data}async confirm(e,t={}){let i={...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.methodId!==void 0?{method_id:t.methodId}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{},...t.useMasterpass!==void 0?{use_masterpass:t.useMasterpass}:{},...t.phone!==void 0?{phone:t.phone}:{},...t.buyer!==void 0?{buyer:t.buyer}:{},...t.installments!==void 0?{installments:t.installments}:{},...t.providerOptions!==void 0?{provider_options:t.providerOptions}:{}},s=t.idempotencyKey?{"Idempotency-Key":t.idempotencyKey}:void 0;return(await this.api.confirmIntent({path:{intent_id:e},body:i,headers:s,signal:t.signal})).data}async submitOtp(e,t){let i={challenge_id:t.challengeId,otp:t.otp,...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{}};return(await this.api.submitIntentOtp({path:{intent_id:e},body:i,signal:t.signal})).data}async portal(e,t={}){let i={return_url:e,...t.channel!==void 0?{channel:t.channel}:{}};return(await this.api.createMyPortal({body:i,signal:t.signal})).data.url}async waitForIntent(e,t={}){let i=t.timeoutMs??3e5;if(t.signal?.aborted)throw t.signal.reason;return new Promise((s,d)=>{let n=!1,a=!1,l=!1,u=this.socket.channel(`payment_intent:${this.ref}:${e}`),h=()=>{v!==void 0&&clearTimeout(v),x(),u.leave(),y.removeEventListener?.("message",g),t.signal?.removeEventListener("abort",f)},I=r=>{n||(n=!0,h(),s(r))},p=r=>{n||(n=!0,h(),d(r))},m=async()=>{if(!n){if(a){l=!0;return}a=!0;try{for(;;){l=!1;try{let r=await this.getIntent(e,{clientSecret:t.clientSecret,signal:t.signal});if(S(r.status)){I(r);return}}catch(r){if(t.signal?.aborted){p(t.signal.reason);return}if(r instanceof c&&(r.status===401||r.status===403||r.status===404)){p(r);return}}if(n||!l)return}}finally{a=!1}}},x=u.on("broadcast",r=>{typeof r.event=="string"&&W.has(r.event)&&m()}),g=r=>{if(r.origin&&r.origin!=="null"&&r.origin!==this.origin)return;let b=T(r.data);b&&b.intent_id===e&&m()},f=()=>p(t.signal?.reason),y=globalThis;y.addEventListener?.("message",g),t.signal?.addEventListener("abort",f,{once:!0});let v=i>0?setTimeout(()=>{p(new c({op:"WaitForIntent",status:0,code:"payment_timeout",message:`timed out waiting for payment intent ${e}`}))},i):void 0;u.join().catch(()=>{}),m()})}async present(e,t={}){let i=t.clientSecret??e.client_secret,s=e.status!==void 0&&e.amount!==void 0?e:await this.getIntent(e.id,{clientSecret:i,signal:t.signal});for(let d=0;d<6;d++){if(S(s.status))return s;let n=s.next_action;if(!n||n.type==="none")return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal});if(n.type==="redirect"){if(!n.url)throw new c({op:"PresentIntent",status:0,code:"invalid_next_action",message:"redirect next_action is missing url"});if(t.onRedirect)await t.onRedirect(n.url,n);else{let a=globalThis.location;if(!a)throw new c({op:"PresentIntent",status:0,code:"redirect_unavailable",message:"provide onRedirect in non-browser environments"});a.assign(n.url)}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}if(n.type==="embed"){let a;if(t.onEmbed){let l=await t.onEmbed(n);typeof l=="function"&&(a=l)}else if(t.container)a=k(t.container,n);else throw new c({op:"PresentIntent",status:0,code:"embed_container_required",message:"provide container or onEmbed to present an embedded 3DS/checkout action"});try{return await this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}finally{a?.()}}if(n.type==="otp"||n.type==="masterpass"){if(!t.onOtp)throw new c({op:"PresentIntent",status:0,code:"otp_handler_required",message:"provide onOtp to complete an OTP or Masterpass verification step"});let a=n.challenge_id??"",l=await t.onOtp({intentId:s.id,challengeId:a,maskedPhone:n.masked_phone??n.masterpass?.phone,expiresAt:n.expires_at,masterpass:n.masterpass});if(l===null)throw new c({op:"PresentIntent",status:0,code:"payment_canceled",message:"verification canceled by customer"});let u=typeof l=="string"?l:l.otp,h=typeof l=="string"?void 0:l.saveMethod;s=await this.submitOtp(s.id,{challengeId:a,otp:u,clientSecret:i,saveMethod:h,signal:t.signal});continue}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}return this.getIntent(s.id,{clientSecret:i,signal:t.signal})}onEvent(e){return this.eventListeners.add(e),this.eventListeners.size===1&&this.startEvents(),()=>{this.eventListeners.delete(e)&&this.eventListeners.size===0&&this.stopEvents()}}onWalletChange(e){if(this.walletListeners.add(e),this.walletListeners.size===1)this.startWalletWatch();else if(this.lastBalances!==void 0){let t=this.lastBalances;queueMicrotask(()=>this.walletListeners.has(e)&&M(e,t))}return()=>{this.walletListeners.delete(e)&&this.walletListeners.size===0&&this.stopWalletWatch()}}startWalletWatch(){this.walletFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followWallet(t)}),this.session.session().then(e=>{this.walletFollowing&&!this.walletWatch&&this.lastBalances===void 0&&this.followWallet(e)})}stopWalletWatch(){this.walletFollowing?.(),this.walletFollowing=void 0,this.unfollowWallet(),this.lastBalances=void 0}followWallet(e){if(this.unfollowWallet(),!e){this.tellBalances(null);return}let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i={userId:e.userId,channel:t,off:()=>{},maxVersion:-1,reading:!1,wanted:!1},s=t.on("broadcast",d=>{typeof d.event=="string"&&E.has(d.event)&&this.walletChanged(i)});i.off=s,this.walletWatch=i,t.join().catch(()=>{}),this.readBalances(i)}unfollowWallet(){let e=this.walletWatch;e&&(this.walletWatch=void 0,e.off(),e.channel.leave())}walletChanged(e){this.walletWatch===e&&(e.reading?e.wanted=!0:this.readBalances(e))}async readBalances(e){e.reading=!0;try{for(;;){e.wanted=!1;try{let t=(await this.api.listMyWallets()).data.balances;if(this.walletWatch!==e)return;this.offerBalances(e,t)}catch{}if(this.walletWatch!==e||!e.wanted)return}}finally{e.reading=!1}}offerBalances(e,t){if(this.walletWatch!==e)return;let i=t.reduce((s,d)=>Math.max(s,d.version),0);e.maxVersion>=0&&i<e.maxVersion||(e.maxVersion=i,this.tellBalances(t))}tellBalances(e){if(!(this.lastBalances===null&&e===null)){this.lastBalances=e;for(let t of[...this.walletListeners])M(t,e)}}startEvents(){this.eventFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followEvents(t)}),this.session.session().then(e=>{this.eventFollowing&&!this.eventWatch&&this.followEvents(e)})}stopEvents(){this.eventFollowing?.(),this.eventFollowing=void 0,this.unfollowEvents()}followEvents(e){if(this.unfollowEvents(),!e)return;let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i=t.on("broadcast",s=>{if(typeof s.event!="string")return;let d={type:s.event,payload:s.payload};for(let n of[...this.eventListeners])try{n(d)}catch{}});this.eventWatch={userId:e.userId,channel:t,off:i},t.join().catch(()=>{})}unfollowEvents(){let e=this.eventWatch;e&&(this.eventWatch=void 0,e.off(),e.channel.leave())}};function k(o,e){let i=o.ownerDocument.createElement("iframe");return i.setAttribute("data-palbase-payments-frame",""),i.setAttribute("title","Secure Payment Verification"),i.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-top-navigation-by-user-activation"),i.style.width="100%",i.style.minHeight="480px",i.style.border="0",i.style.borderRadius="8px",i.style.background="#ffffff",e.html?i.srcdoc=e.html:e.url&&(i.src=e.url),o.replaceChildren(i),()=>{i.remove()}}function M(o,e){try{o(e)}catch{}}export{P as a,S as b,T as c,B as d,_ as e,k as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as O,g as w,l as F,m as _,s as D}from"./SS2RVI27.js";import{b as h}from"./HRWVZ4PC.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(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>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.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=j(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>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(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 E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(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 X={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 U(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=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(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.73.1"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(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 u=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(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(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 q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(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 Y={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 G(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:Y,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 $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.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?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={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":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,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 O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
|
|
1
|
+
/*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as O,g as w,l as F,m as _,s as D}from"./YDHRQOAN.js";import{b as h}from"./ZRNXABQJ.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(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>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.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=j(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>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(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 E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(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 X={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 U(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=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(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.74.0"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(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 u=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(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(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 q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(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 Y={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 G(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:Y,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 $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.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?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={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":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,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 O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b}from"./
|
|
1
|
+
/*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b}from"./AFO74GQQ.js";import{a as k,b as A}from"./5NLCEWSD.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as c,f as u}from"./
|
|
1
|
+
/*! palbase 0.74.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as c,f as u}from"./ZRNXABQJ.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};
|