palbase 0.73.0 → 0.73.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- 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/{DIQMCEMJ.js → 2TKZTIMD.js} +2 -2
- package/dist/chunks/{YMIK6HLK.js → 3KCV4F4F.js} +2 -2
- package/dist/chunks/{PAQCJT7M.js → 4E4ABCSD.js} +2 -2
- package/dist/chunks/{IICQMY2Z.js → 5N5GHLUU.js} +2 -2
- package/dist/chunks/{EKOEK6LR.js → 5N6QKGPA.js} +2 -2
- package/dist/chunks/{MVKZWEHL.js → AXANFT2A.js} +2 -2
- package/dist/chunks/{P36C47FS.js → DNSLYLU6.js} +1 -1
- package/dist/chunks/{3DUDNEMM.js → GTKPHG5F.js} +2 -2
- package/dist/chunks/{757A6AR6.js → GWWU2FJ7.js} +2 -2
- package/dist/chunks/{PEQZDT6P.js → HRWVZ4PC.js} +2 -2
- package/dist/chunks/{LCDNCPQW.js → HYPCFC4K.js} +1 -1
- package/dist/chunks/{P4NZ4NZD.js → IVJOWYRE.js} +2 -2
- package/dist/chunks/{5OOA4R4H.js → MB7MHOQO.js} +1 -1
- package/dist/chunks/{VEL7X2G3.js → MFSC4OJV.js} +2 -2
- package/dist/chunks/{76W5ZO2L.js → SEICTPQP.js} +2 -2
- package/dist/chunks/{JG4V6LNY.js → SQNAPFXW.js} +2 -2
- package/dist/chunks/{4XSSQAES.js → SS2RVI27.js} +1 -1
- package/dist/chunks/{UFP6GLLW.js → TR2IPX2A.js} +2 -2
- package/dist/chunks/{25HECIZY.js → U3H6HER3.js} +1 -1
- package/dist/chunks/{SRN7N2WX.js → UOJVMV42.js} +2 -2
- package/dist/chunks/{SMECWMF7.js → UXHNXE3J.js} +2 -2
- package/dist/chunks/{CY6KUFZW.js → VCL3SAQL.js} +2 -2
- package/dist/chunks/{J7ZNBBRN.js → W2KD2I4Q.js} +1 -1
- package/dist/chunks/{J7Z2PYL4.js → YU3GFTZV.js} +1 -1
- package/dist/cli.js +8 -8
- 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
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.73.
|
|
2
|
-
import{c as hr,d as gr,e as nn,f as yr,g as wr}from"./757A6AR6.js";import{a as Rt,c as ne,d as pr,e as mr,f as be,h as _,i as br}from"./PAQCJT7M.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"./76W5ZO2L.js";import{a as Et,b as or,n as ir}from"./J7Z2PYL4.js";import{b as ie}from"./PEQZDT6P.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.73.1 — Palbase SDK License (see LICENSE) */
|
|
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:
|
|
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.73.
|
|
2
|
-
import{b as d,m as k}from"./
|
|
1
|
+
/*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as d,m as k}from"./YU3GFTZV.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.73.
|
|
2
|
-
import{a as g,b}from"./
|
|
1
|
+
/*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,b}from"./W2KD2I4Q.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.73.
|
|
1
|
+
/*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
import{lstat as E,mkdir as k,readdir as b,readFile as j,rename as F,rm as J,writeFile as R}from"node:fs/promises";import{join as $}from"node:path";var o="palbase/strings",g="_meta.json",m=3,S=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function w(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function O(r,t){try{return JSON.parse(r)}catch(n){throw new Error(`${t} is not JSON: ${n.message}`)}}async function M(r){let t=$(r,o);try{if(!(await E(t)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let n=new Map;for(let e of await b(t,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);n.set(e.name,await j($(t,e.name),"utf8"))}return n.size===0?void 0:n}async function N(r){let t=await M(r);if(t===void 0)return;let n=t.get(g);if(n===void 0)throw new Error(`${o}/${g} is missing: it names the source language, and without it the language files are not a table`);let e=O(n,`${o}/${g}`);if(!S(e))throw new Error(`${o}/${g}: not a JSON object`);let c=e.version;if(c!==m)throw new Error(`${o}/${g}: version ${JSON.stringify(c)} is not one this reads (${m})`);let s=e.source;if(typeof s!="string"||w(s)!==s)throw new Error(`${o}/${g}: source ${JSON.stringify(s)} is not a language tag as it is written (${w(String(s))??"en, en-US, zh-Hans"})`);let f=new Map;for(let u of[...t.keys()].sort()){if(u===g)continue;let i=u.slice(0,-5),a=`${o}/${u}`,l=w(i);if(l===void 0)throw new Error(`${a}: ${JSON.stringify(i)} is not a language tag`);if(l!==i)throw new Error(`${a}: the language is written ${l} \u2014 name the file ${l}.json`);if(i===s)throw new Error(`${a}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${a}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let d=O(t.get(u),a);if(!S(d))throw new Error(`${a}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[p,y]of Object.entries(d)){if(typeof y!="string")throw new Error(`${a}: the translation of ${JSON.stringify(p)} is not a string`);h.set(p,y)}f.set(i,h)}return{format:c,source:s,languages:f}}async function P(r){let t=await N(r);if(t===void 0)return;let n={};Object.setPrototypeOf(n,null);for(let[e,c]of t.languages)for(let[s,f]of c)Object.hasOwn(n,s)||(n[s]={},Object.setPrototypeOf(n[s],null)),n[s][e]=f;return{source:t.source,locales:[t.source,...t.languages.keys()],strings:n}}export{P as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.73.
|
|
2
|
-
import{n as w}from"./SMECWMF7.js";import{b as c}from"./PEQZDT6P.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.73.1 — Palbase SDK License (see LICENSE) */
|
|
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,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.73.
|
|
1
|
+
/*! palbase 0.73.1 — 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.73.
|
|
2
|
-
import{a as d,b as u}from"./PEQZDT6P.js";var g={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project has no paid rights now to pay for Palbase's models (it is on Free, at its month's limit, or its payment account has an unpaid charge): move it to Pay as you go (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,client_handoff_disabled:()=>"app users may not hand off chats in this project: enable allow_client_handoff in AI settings, or trigger the handoff from your server",superseded:()=>"this chat has already moved to a newer execution target generation",machine_not_found:()=>"the target machine is not enrolled in this project's runner pools",harness_unavailable:()=>"the requested ACP CLI harness is not ready on the target machine",handoff_requires_idle:()=>"a turn is currently running in this chat: pass when: 'after_turn' or when: 'now' to hand off"},c=new WeakSet;function f(t){if(!(t instanceof u)||c.has(t))return t;let n=g[t.code];if(!n)return t;let i=new u({op:t.op,status:t.status,code:t.code,message:`${n(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return c.add(i),i}function m(t){return t.catch(n=>{throw f(n)})}function h(t){if(typeof t!="object"||t===null)return;let n=t,i=n.data;if(typeof n.type!="string"||typeof i!="object"||i===null||Array.isArray(i))return;let e=d(i),s=typeof n.id=="number"&&Number.isSafeInteger(n.id)?n.id:0;switch(n.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:s,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let r={...e,type:"turn",seq:s};return r.waiting??=null,r.error??=null,r}case"text":{let r=e.offset;return typeof e.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"text",response_id:e.response_id,offset:r,text:typeof e.text=="string"?e.text:""}}case"reset":{let r=e.offset;return typeof e.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"reset",response_id:e.response_id,offset:r}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let r=e.omitted_bytes;return{...e,type:"tool",seq:s,omittedBytes:typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:s}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let r=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:s,response_id:e.response_id,run_id:r,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:s,response_id:e.response_id,run_id:r,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:r,...a}=e;return{...a,type:"goal",seq:s,...typeof r=="number"?{turn:r}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let r=e.items.filter(o=>typeof o=="object"&&o!==null&&(o.role==="user"||o.role==="assistant")&&typeof o.text=="string"),a=e.forked_from;return{type:"history",forked_from:a&&typeof a.chat_id=="string"?a:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:r}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:s,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:s,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};case"session.handed_off":return typeof e.to_target!="object"||e.to_target===null||typeof e.generation!="number"?void 0:{type:"session.handed_off",seq:s,chat_id:typeof e.chat_id=="string"?e.chat_id:"",generation:e.generation,...typeof e.from_target=="object"&&e.from_target!==null?{from_target:e.from_target}:{},to_target:e.to_target,reason:typeof e.reason=="string"?e.reason:"",workspace_seq:typeof e.workspace_seq=="number"?e.workspace_seq:0};case"session.machine_status":return typeof e.status!="string"?void 0:{type:"session.machine_status",seq:s,chat_id:typeof e.chat_id=="string"?e.chat_id:"",machine_id:typeof e.machine_id=="string"?e.machine_id:"",status:e.status,...e.failover_at===null||typeof e.failover_at=="string"?{failover_at:e.failover_at}:{}};case"context.offloaded":return{type:"context.offloaded",seq:s,call_id:typeof e.call_id=="string"?e.call_id:"",...typeof e.storage=="string"?{storage:e.storage}:{},...typeof e.ref=="string"?{ref:e.ref}:{},...typeof e.original_bytes=="number"?{original_bytes:e.original_bytes}:{},...typeof e.stub_bytes=="number"?{stub_bytes:e.stub_bytes}:{}};case"context.compacted":return{type:"context.compacted",seq:s,...typeof e.format=="string"?{format:e.format}:{},...typeof e.messages_compacted=="number"?{messages_compacted:e.messages_compacted}:{},...typeof e.tokens_before=="number"?{tokens_before:e.tokens_before}:{},...typeof e.tokens_after=="number"?{tokens_after:e.tokens_after}:{},...typeof e.preserved_attachments_count=="number"?{preserved_attachments_count:e.preserved_attachments_count}:{},...typeof e.project_directives_count=="number"?{project_directives_count:e.project_directives_count}:{},...typeof e.cache_friendly=="boolean"?{cache_friendly:e.cache_friendly}:{}};default:return}}function y(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let n=d(t);if(!(typeof n.chat_id!="string"||n.chat_id===""||typeof n.run_status!="string"||typeof n.target_generation!="number")&&!(typeof n.target_summary!="object"||n.target_summary===null))return{chat_id:n.chat_id,run_status:n.run_status,...typeof n.active_run_id=="string"&&n.active_run_id!==""?{active_run_id:n.active_run_id}:{},...typeof n.workspace_id=="string"&&n.workspace_id!==""?{workspace_id:n.workspace_id}:{},target_generation:n.target_generation,target_summary:n.target_summary,updated_at:typeof n.updated_at=="string"?n.updated_at:""}}function v(t){let n=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n+=1:e<2048?n+=2:e>=55296&&e<=56319&&i+1<t.length&&(t.charCodeAt(i+1)&64512)===56320?(n+=4,i++):n+=3}return n}function p(t,n){if(n<=0)return 0;let i=0;for(let e=0;e<t.length;e++){let s=t.charCodeAt(e),r=3,a=1;if(s<128?r=1:s<2048?r=2:s>=55296&&s<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(r=4,a=2),i+=r,i>=n)return e+a;e+=a-1}return t.length}function w(t,n){return t.slice(p(t,n))}export{m as a,h as b,y as c,v as d,p as e,w as f};
|
|
1
|
+
/*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as d,b as u}from"./HRWVZ4PC.js";var g={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project has no paid rights now to pay for Palbase's models (it is on Free, at its month's limit, or its payment account has an unpaid charge): move it to Pay as you go (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,client_handoff_disabled:()=>"app users may not hand off chats in this project: enable allow_client_handoff in AI settings, or trigger the handoff from your server",superseded:()=>"this chat has already moved to a newer execution target generation",machine_not_found:()=>"the target machine is not enrolled in this project's runner pools",harness_unavailable:()=>"the requested ACP CLI harness is not ready on the target machine",handoff_requires_idle:()=>"a turn is currently running in this chat: pass when: 'after_turn' or when: 'now' to hand off"},c=new WeakSet;function f(t){if(!(t instanceof u)||c.has(t))return t;let n=g[t.code];if(!n)return t;let i=new u({op:t.op,status:t.status,code:t.code,message:`${n(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return c.add(i),i}function m(t){return t.catch(n=>{throw f(n)})}function h(t){if(typeof t!="object"||t===null)return;let n=t,i=n.data;if(typeof n.type!="string"||typeof i!="object"||i===null||Array.isArray(i))return;let e=d(i),s=typeof n.id=="number"&&Number.isSafeInteger(n.id)?n.id:0;switch(n.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:s,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let r={...e,type:"turn",seq:s};return r.waiting??=null,r.error??=null,r}case"text":{let r=e.offset;return typeof e.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"text",response_id:e.response_id,offset:r,text:typeof e.text=="string"?e.text:""}}case"reset":{let r=e.offset;return typeof e.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"reset",response_id:e.response_id,offset:r}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let r=e.omitted_bytes;return{...e,type:"tool",seq:s,omittedBytes:typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:s}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let r=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:s,response_id:e.response_id,run_id:r,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:s,response_id:e.response_id,run_id:r,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:r,...a}=e;return{...a,type:"goal",seq:s,...typeof r=="number"?{turn:r}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let r=e.items.filter(o=>typeof o=="object"&&o!==null&&(o.role==="user"||o.role==="assistant")&&typeof o.text=="string"),a=e.forked_from;return{type:"history",forked_from:a&&typeof a.chat_id=="string"?a:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:r}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:s,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:s,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};case"session.handed_off":return typeof e.to_target!="object"||e.to_target===null||typeof e.generation!="number"?void 0:{type:"session.handed_off",seq:s,chat_id:typeof e.chat_id=="string"?e.chat_id:"",generation:e.generation,...typeof e.from_target=="object"&&e.from_target!==null?{from_target:e.from_target}:{},to_target:e.to_target,reason:typeof e.reason=="string"?e.reason:"",workspace_seq:typeof e.workspace_seq=="number"?e.workspace_seq:0};case"session.machine_status":return typeof e.status!="string"?void 0:{type:"session.machine_status",seq:s,chat_id:typeof e.chat_id=="string"?e.chat_id:"",machine_id:typeof e.machine_id=="string"?e.machine_id:"",status:e.status,...e.failover_at===null||typeof e.failover_at=="string"?{failover_at:e.failover_at}:{}};case"context.offloaded":return{type:"context.offloaded",seq:s,call_id:typeof e.call_id=="string"?e.call_id:"",...typeof e.storage=="string"?{storage:e.storage}:{},...typeof e.ref=="string"?{ref:e.ref}:{},...typeof e.original_bytes=="number"?{original_bytes:e.original_bytes}:{},...typeof e.stub_bytes=="number"?{stub_bytes:e.stub_bytes}:{}};case"context.compacted":return{type:"context.compacted",seq:s,...typeof e.format=="string"?{format:e.format}:{},...typeof e.messages_compacted=="number"?{messages_compacted:e.messages_compacted}:{},...typeof e.tokens_before=="number"?{tokens_before:e.tokens_before}:{},...typeof e.tokens_after=="number"?{tokens_after:e.tokens_after}:{},...typeof e.preserved_attachments_count=="number"?{preserved_attachments_count:e.preserved_attachments_count}:{},...typeof e.project_directives_count=="number"?{project_directives_count:e.project_directives_count}:{},...typeof e.cache_friendly=="boolean"?{cache_friendly:e.cache_friendly}:{}};default:return}}function y(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let n=d(t);if(!(typeof n.chat_id!="string"||n.chat_id===""||typeof n.run_status!="string"||typeof n.target_generation!="number")&&!(typeof n.target_summary!="object"||n.target_summary===null))return{chat_id:n.chat_id,run_status:n.run_status,...typeof n.active_run_id=="string"&&n.active_run_id!==""?{active_run_id:n.active_run_id}:{},...typeof n.workspace_id=="string"&&n.workspace_id!==""?{workspace_id:n.workspace_id}:{},target_generation:n.target_generation,target_summary:n.target_summary,updated_at:typeof n.updated_at=="string"?n.updated_at:""}}function v(t){let n=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n+=1:e<2048?n+=2:e>=55296&&e<=56319&&i+1<t.length&&(t.charCodeAt(i+1)&64512)===56320?(n+=4,i++):n+=3}return n}function p(t,n){if(n<=0)return 0;let i=0;for(let e=0;e<t.length;e++){let s=t.charCodeAt(e),r=3,a=1;if(s<128?r=1:s<2048?r=2:s>=55296&&s<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(r=4,a=2),i+=r,i>=n)return e+a;e+=a-1}return t.length}function w(t,n){return t.slice(p(t,n))}export{m as a,h as b,y as c,v as d,p as e,w as f};
|