palbase 0.37.0 → 0.37.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{KC64EJP4.js → 4Y47I6LA.js} +2 -2
- package/dist/chunks/{WBBBK7KR.js → 5HYKOPCW.js} +2 -2
- package/dist/chunks/{IVZQOIXW.js → 72CHRRHY.js} +1 -1
- package/dist/chunks/{PJP7TT3V.js → A6LIFQOQ.js} +3 -3
- package/dist/chunks/{ML2FPPCL.js → AF3XUGHY.js} +2 -2
- package/dist/chunks/{EIGFU7MO.js → C4ENQSIX.js} +1 -1
- package/dist/chunks/{VK6ALHIT.js → CHXCVOON.js} +1 -1
- package/dist/chunks/{BWQXLDGG.js → GEZH3OTX.js} +2 -2
- package/dist/chunks/{ZSJDQ34E.js → HMDMAILZ.js} +1 -1
- package/dist/chunks/{SRFAWNOD.js → IOVYIATC.js} +1 -1
- package/dist/chunks/{JHRMDLGF.js → JCHW52YV.js} +2 -2
- package/dist/chunks/{5IDPIZGR.js → L3S7O5FQ.js} +2 -2
- package/dist/chunks/{PBYDJFD3.js → LANEQ73A.js} +2 -2
- package/dist/chunks/{FVWB6QLP.js → NFFQO2UC.js} +2 -2
- package/dist/chunks/{TPHZCHLV.js → P5EW3DTQ.js} +2 -2
- package/dist/chunks/{RQBRUINN.js → QK2S67K3.js} +2 -2
- package/dist/chunks/{T64GKIOS.js → RVRPBQ4W.js} +2 -2
- package/dist/chunks/{SNCOLU4O.js → SEECU52P.js} +2 -2
- package/dist/chunks/{BJB4ODEW.js → UBQK5O7J.js} +1 -1
- package/dist/chunks/{3NCYWZCH.js → VAPNSTWC.js} +2 -2
- package/dist/chunks/{YIHRINWP.js → YLLZC52Q.js} +1 -1
- package/dist/chunks/{22UYQWHM.js → YQQHL67Y.js} +2 -2
- package/dist/chunks/{2HWKGNH2.js → ZDENVL2U.js} +2 -2
- package/dist/cli.js +15 -15
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/internal/src/messaging/store.d.ts +2 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
2
|
-
import{a,b,c,d,e,f}from"../chunks/
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f}from"../chunks/JCHW52YV.js";import"../chunks/QK2S67K3.js";import"../chunks/HMDMAILZ.js";import"../chunks/L3S7O5FQ.js";import"../chunks/LANEQ73A.js";import"../chunks/4Y47I6LA.js";import"../chunks/CHXCVOON.js";import"../chunks/72CHRRHY.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
|
package/dist/backend/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
2
|
-
import{ia as w,ma as h}from"../chunks/
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ia as w,ma as h}from"../chunks/P5EW3DTQ.js";import"../chunks/ZDENVL2U.js";import"../chunks/NFFQO2UC.js";import"../chunks/JCHW52YV.js";import"../chunks/QK2S67K3.js";import"../chunks/YQQHL67Y.js";import"../chunks/UBQK5O7J.js";import"../chunks/YLLZC52Q.js";import"../chunks/HMDMAILZ.js";import"../chunks/L3S7O5FQ.js";import"../chunks/LANEQ73A.js";import"../chunks/4Y47I6LA.js";import"../chunks/CHXCVOON.js";import"../chunks/72CHRRHY.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
|
package/dist/backend/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
2
|
-
import{$ as $t,A as ut,B as F,C as pt,D as ht,E as ft,F as mt,G as gt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as xt,S as Rt,T as _t,U as Ot,V as Ct,W as Bt,X as Ft,Y as se,Z as Mt,_ as It,a as X,aa as Lt,b as Z,ba as Dt,c as ee,ca as Ut,d as qe,da as jt,e as We,ea as Nt,f as Ke,fa as qt,g as Ve,ga as M,h as Ge,ha as Gt,i as ze,ia as I,j as He,ja as G,k as Ye,ka as zt,l as Je,la as Ht,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as rt,s as st,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/TPHZCHLV.js";import{a as Wt,b as Kt}from"../chunks/2HWKGNH2.js";import{a as ae}from"../chunks/EIGFU7MO.js";import{a as _,b as te,c as re,f as g,g as V,h as d,j as ne,k as Vt}from"../chunks/FVWB6QLP.js";import"../chunks/JHRMDLGF.js";import"../chunks/RQBRUINN.js";import{d as R,j as je,k as Ne,l as Y,m as B,t as J,u as Q}from"../chunks/22UYQWHM.js";import"../chunks/BJB4ODEW.js";import"../chunks/YIHRINWP.js";import"../chunks/ZSJDQ34E.js";import{p as Ue}from"../chunks/5IDPIZGR.js";import"../chunks/PBYDJFD3.js";import{b as E,c as K}from"../chunks/KC64EJP4.js";import"../chunks/VK6ALHIT.js";import"../chunks/IVZQOIXW.js";import"reflect-metadata";import{existsSync as z,writeFileSync as Rr,writeSync as _r}from"node:fs";import{createServer as Or}from"node:http";import{dirname as T,join as H,resolve as _e}from"node:path";import{Readable as Cr}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,$=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Jt,this.shutdownMs=r.shutdownMs??Yt,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as er,bunDriver as tr,createDatabase as rr,envBlock as sr,createSearchWorker as nr,cutOff as ar,forgetUserIn as or,MigrationOpen as ir,MigrationRefused as lr,Migrator as de,renewingBunPool as oe,VersionNotMigrated as cr}from"palgres";import{toModel as ue}from"palgres/dsl";var dr=["start","complete","rollback","plan","status","types"],ur=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function pe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!dr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function he(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function D(t){return ue(he(t))}function pr(t){return t.tables.some(e=>e.search!==void 0)}function U(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function fe(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function hr(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var ie=5;function me(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=oe(()=>new r.SQL({url:n,prepare:!1,max:s})),i=oe(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:tr(a,i),poolSize:s,close:async()=>{await a.close({timeout:ie}),await i.close({timeout:ie})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await O(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await O("types",sr(r,{module:"palbase/backend/env"}),e),0}async function ye(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!ur.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=me(t,fe(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=D(t),u=new de(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let m=new URL(s);m.pathname=`/${f}`;let y=a(m.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>fr(e)});if(r==="plan"){let f=await u.plan(l);return await O(r,f),f.refusals.length>0?1:0}if(r==="status")return await O(r,await u.status()),0;let h=r==="start"?await mr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await O(r,h),0}catch(l){return l instanceof lr?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):ar(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??le(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${le(l)}`),1)}finally{await i.close().catch(()=>{})}}async function fr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=R({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function mr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof ir)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function O(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as $t,A as ut,B as F,C as pt,D as ht,E as ft,F as mt,G as gt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as xt,S as Rt,T as _t,U as Ot,V as Ct,W as Bt,X as Ft,Y as se,Z as Mt,_ as It,a as X,aa as Lt,b as Z,ba as Dt,c as ee,ca as Ut,d as qe,da as jt,e as We,ea as Nt,f as Ke,fa as qt,g as Ve,ga as M,h as Ge,ha as Gt,i as ze,ia as I,j as He,ja as G,k as Ye,ka as zt,l as Je,la as Ht,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as rt,s as st,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/P5EW3DTQ.js";import{a as Wt,b as Kt}from"../chunks/ZDENVL2U.js";import{a as ae}from"../chunks/C4ENQSIX.js";import{a as _,b as te,c as re,f as g,g as V,h as d,j as ne,k as Vt}from"../chunks/NFFQO2UC.js";import"../chunks/JCHW52YV.js";import"../chunks/QK2S67K3.js";import{d as R,j as je,k as Ne,l as Y,m as B,t as J,u as Q}from"../chunks/YQQHL67Y.js";import"../chunks/UBQK5O7J.js";import"../chunks/YLLZC52Q.js";import"../chunks/HMDMAILZ.js";import{p as Ue}from"../chunks/L3S7O5FQ.js";import"../chunks/LANEQ73A.js";import{b as E,c as K}from"../chunks/4Y47I6LA.js";import"../chunks/CHXCVOON.js";import"../chunks/72CHRRHY.js";import"reflect-metadata";import{existsSync as z,writeFileSync as Rr,writeSync as _r}from"node:fs";import{createServer as Or}from"node:http";import{dirname as T,join as H,resolve as _e}from"node:path";import{Readable as Cr}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,$=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Jt,this.shutdownMs=r.shutdownMs??Yt,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as er,bunDriver as tr,createDatabase as rr,envBlock as sr,createSearchWorker as nr,cutOff as ar,forgetUserIn as or,MigrationOpen as ir,MigrationRefused as lr,Migrator as de,renewingBunPool as oe,VersionNotMigrated as cr}from"palgres";import{toModel as ue}from"palgres/dsl";var dr=["start","complete","rollback","plan","status","types"],ur=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function pe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!dr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function he(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function D(t){return ue(he(t))}function pr(t){return t.tables.some(e=>e.search!==void 0)}function U(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function fe(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function hr(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var ie=5;function me(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=oe(()=>new r.SQL({url:n,prepare:!1,max:s})),i=oe(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:tr(a,i),poolSize:s,close:async()=>{await a.close({timeout:ie}),await i.close({timeout:ie})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await O(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await O("types",sr(r,{module:"palbase/backend/env"}),e),0}async function ye(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!ur.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=me(t,fe(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=D(t),u=new de(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let m=new URL(s);m.pathname=`/${f}`;let y=a(m.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>fr(e)});if(r==="plan"){let f=await u.plan(l);return await O(r,f),f.refusals.length>0?1:0}if(r==="status")return await O(r,await u.status()),0;let h=r==="start"?await mr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await O(r,h),0}catch(l){return l instanceof lr?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):ar(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??le(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${le(l)}`),1)}finally{await i.close().catch(()=>{})}}async function fr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=R({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function mr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof ir)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function O(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,s))}function le(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
4
|
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function br(t,e){try{return await new de(t).plan(e)}catch{return}}var ce="palbase.idempotency_keys.response_body";function yr(t,e){let r=null,s=!1,n=async()=>{let o=e.currentKey();if(!(s||o===r)){s=!0;try{let c=await t.reseal();r=o;let l=c.reduce((u,h)=>u+h.resealed,0);l>0&&d.info(`[palbase] fields: ${l} value(s) sealed again with key ${o}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${o} stopped; tried again in a minute`,{error:c})}finally{s=!1}}},a=setTimeout(n,1e4),i=setInterval(n,6e4);for(let o of[a,i])o.unref?.();return()=>{clearTimeout(a),clearInterval(i)}}var L=class extends Error{digest;plan;constructor(e,r){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...r?wr(r):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function wr(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let r of t.changes)e.push(` + ${r}`);for(let r of t.refusals)e.push(` \u2717 ${r}`);return e}var Pr=8e4;async function we(t,e,r,s){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=he(t),i=ue(a),o=me(t,fe(e))(n);try{let c=!1,l=p=>{c||(c=!0,d.warn(`[palbase] database: not answering yet (${p instanceof Error?p.message:String(p)}) \u2014 waiting for it, as one waking does`))},u=await er(o.engine,i,{waitMs:s.onPlatform?Pr:0,onUnreachable:l}).catch(async p=>{throw s.onPlatform||!(p instanceof cr)?p:new L(p.digest,await br(o.pool,i))}),h=Zt("sha256",r).update("palgres page cursor").digest("hex"),f=t.embed??s.embed,m=s.fields,y=await rr({sql:o.engine,schemas:a,binding:u,cursorSecret:h,admission:hr(o.poolSize),embed:f,log:p=>d.warn(`[palbase] ${p}`),fields:async()=>(await m.load(),m)}),S=m.loaded?yr(y,m):()=>{},b=pr(i)?nr({sql:o.engine,embed:f,log:p=>d.info(`[palbase] ${p}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:(p,k)=>or({attempt:v=>k.$attempt(v)},u,i,p),...b?{search:b}:{},keptAnswers:{seal:p=>m.loaded?m.encrypt(ce,p):p,open:async p=>m.isEncrypted(p)?(m.loaded||await m.load(),m.decrypt(ce,p)):p},close:async()=>{S(),m.close(),await o.close()}}}catch(c){throw await o.close(),c}}function Sr(t){let e=Buffer.from(t,"base64"),r=new Array(e.byteLength/4);for(let s=0;s<r.length;s++)r[s]=e.readFloatLE(s*4);return r}function Pe(t){return async({texts:e,model:r,dimensions:s})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:r,dimensions:s}});return{model:n.model,vectors:n.vectors.map(Sr)}}}var vr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Se(t,e,r){let s=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&s.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&s.push("palbase.url / PALBASE_URL is the project origin alone")}catch{s.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let i=t.projectId??e.PALBASE_PROJECT_ID??"";vr.test(i)||s.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&s.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let l=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(c!==void 0||l!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(l??"")&&s.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),s.length>0)throw new Error(`[palbase] the app cannot start:
|
|
@@ -9,4 +9,4 @@ ${s.join(`
|
|
|
9
9
|
`)}
|
|
10
10
|
`}function ke(t,e,r=kr){let s=Buffer.from(e,"utf8"),n=new Int32Array(new SharedArrayBuffer(4));for(let a=0;a<s.length;)try{a+=r(t,s,a,s.length-a)}catch(i){if(i.code!=="EAGAIN")throw i;Atomics.wait(n,0,0,5)}}var Ee=2e4,Te=5e3,Br=15e3,Fr="/_palbase/health";function Mr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=F(s,X);return n?n.providers.some(a=>F(a,Z)!==void 0&&F(a,ee)===void 0)||n.imports.some(r):!1};return t.some(r)}var Ir={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=pe(s);if(n!==void 0){let w=n==="types"?await be(e.db):e.db?await ye(e.db,s,n):await ge(n);throw process.exit(w),new j(w)}let a=s.PALBASE_CONTRACT_OUT;if(a){let w;try{await Re(xe(s)),w=await $r(r,e,s)}catch(A){throw _r(2,`[palbase] the contract: ${A instanceof Error?A.message:String(A)}
|
|
11
11
|
`),process.exit(1),new C}throw a==="/dev/stdout"?ke(1,Ae(w)):Rr(a,`${w}
|
|
12
|
-
`),process.exit(0),new C}let i=xe(s),o=await Re(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),ne(o?void 0:i);let c=e.db?D(e.db):void 0,l=await Q({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Mr(r)||c!==void 0&&U(c),h=Se(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=R({url:h.url,secretKey:h.secretKey}),m=e.port??Number(s.PORT??"8080");if(!Number.isInteger(m)||m<0||m>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await we(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&U(y.model)?{"user.deleted":[w=>Lr(y,w)]}:void 0,b=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new $(f.analytics),k=()=>I({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:Y({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:jr(e.cors,s.PALBASE_WEB_ORIGINS),platform:b,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),v=k(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await v.start();break}catch(A){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:A}),A;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:A}),await new Promise(De=>setTimeout(De,W)),W*=2,v=k()}return Dr(v,f,m,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function xe(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=T(_e(e));for(;!z(H(r,"package.json"))&&T(r)!==r;)r=T(r);return z(H(r,"package.json"))?r:process.cwd()}async function Re(t){try{return await ae(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=_e(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=T(s);for(;!z(H(n,"package.json"))&&T(n)!==n;)n=T(n);let{analyzeProject:a}=await import("../chunks/T64GKIOS.js"),{routeContracts:i}=await import("../chunks/ML2FPPCL.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=I({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:R({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&U(D(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var C=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Lr(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r,V.$asService());d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Dr(t,e,r,s,n,a){let i,o={on:!1},c=(b,p)=>new URL(b.url).pathname===Fr&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,p),l=Or((b,p)=>{Ur(c,b,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((b,p)=>{l.once("error",p),l.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=b=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(v=>l.close(()=>v()));l.closeIdleConnections();let k=setTimeout(()=>l.closeAllConnections(),b);await p,clearTimeout(k),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(Ee),m=!1,y=()=>{if(m){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}m=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+Br);b.unref(),f().then(()=>{clearTimeout(b),process.exit(0)},p=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let p=setTimeout(()=>process.exit(1),Te+1e3);h(Te).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let m of f)i.append(h,m);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Cr.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function jr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>G(o)),a=s.filter(o=>!G(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Js,boolean as Qs,check as Xs,date as Zs,defineSchema as en,defineTable as tn,enumType as rn,foreignKey as sn,index as nn,integer as an,jsonb as on,numeric as ln,ownedByUser as cn,policy as dn,raw as un,sqlType as pn,text as hn,timestamp as fn,userRef as mn,uuid as gn}from"palgres/dsl";import{increment as yn,now as wn}from"palgres";function x(t){if(t instanceof E)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return x(r)}}var Nr=_("Secrets",{async get(t){if(J(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),qr=100,Wr=1e3,Kr=168*3600,Vr={s:1,m:60,h:3600,d:86400};function Gr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Vr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof E&&i.code==="invalid_path_parameter"?new E({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${g.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Oe(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function zr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof E&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:x(a)}},async download(e){try{let r=await g.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return x(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Gr(r?.expiresIn);return s===void 0||s<1||s>Kr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>g.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??qr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Wr,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=l.data.next_cursor,!i)break}}catch(c){return x(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await g.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return x(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Hr={bucket:zr},Ce=t=>te("Storage",t,Hr),Yr={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},Jr=_("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>g.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>g.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await g.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return x(c)}return{data:{message_ids:a},error:null,status:i}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Me=t=>t==="override"?"user":t,Qr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Le(){return re.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Le();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Ie={setOverrideForUser:(t,e,r)=>P(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Me(s.source)})),setOverridesForUser:(t,e)=>P(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Me(r.source)})),clearAllOverridesForUser:t=>P(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Xr=_("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Be(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Fe(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Fe(s);return{name:r,enabled:Be(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Qr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Le();return r?Ie.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Ie}}),Zr=_("Realtime",{broadcast(t,e,r){return P(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as xn}from"zod";export{at as AttestedDevice,Ne as AuthUnavailable,At as Authorize,It as BadRequest,Ye as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,nt as Client,$t as Conflict,C as ContractRunEnded,qe as Controller,dt as Cron,V as Database,Lt as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,Xr as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,We as Get,Qe as Headers,Dt as HttpError,it as Injectable,d as Log,Gt as MAX_BODY_BYTES,j as MigrationRunEnded,lt as Module,Ut as NotFound,Jr as Notifications,ct as On,Et as OnConnect,Tt as OnDisconnect,xt as OnEmpty,kt as OnFirst,et as OptionalUser,Ct as PalError,g as Palbase,E as PalbaseError,Ir as PalbaseFactory,Xe as Param,Ge as Patch,Ke as Post,Ve as Put,He as Query,Je as QueryParams,Zr as Realtime,tt as Req,rt as RequestId,ot as Resolve,L as SchemaNotPushed,Nr as Secrets,jt as SerializationFailure,Yr as Storage,Rt as Subscribe,mt as Task,ft as TaskFailure,gt as Tasks,bt as TestUserTemplate,je as TokenError,B as TokenVerifier,Nt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Ze as User,ut as Webhook,Js as bigint,Qs as boolean,Xs as check,I as createApp,Zs as date,Mt as defineError,en as defineSchema,tn as defineTable,Kt as encrypt,Wt as encrypted,rn as enumType,sn as foreignKey,pt as getRegisteredControllers,ht as getRoutes,_t as getWebhookManifest,yn as increment,nn as index,an as integer,on as jsonb,wn as now,ln as numeric,cn as ownedByUser,dn as policy,un as raw,pn as sqlType,Vt as t,hn as text,fn as timestamp,mn as userRef,gn as uuid,xn as z};
|
|
12
|
+
`),process.exit(0),new C}let i=xe(s),o=await Re(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),ne(o?void 0:i);let c=e.db?D(e.db):void 0,l=await Q({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Mr(r)||c!==void 0&&U(c),h=Se(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=R({url:h.url,secretKey:h.secretKey}),m=e.port??Number(s.PORT??"8080");if(!Number.isInteger(m)||m<0||m>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await we(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&U(y.model)?{"user.deleted":[w=>Lr(y,w)]}:void 0,b=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new $(f.analytics),k=()=>I({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:Y({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:jr(e.cors,s.PALBASE_WEB_ORIGINS),platform:b,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),v=k(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await v.start();break}catch(A){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:A}),A;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:A}),await new Promise(De=>setTimeout(De,W)),W*=2,v=k()}return Dr(v,f,m,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function xe(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=T(_e(e));for(;!z(H(r,"package.json"))&&T(r)!==r;)r=T(r);return z(H(r,"package.json"))?r:process.cwd()}async function Re(t){try{return await ae(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=_e(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=T(s);for(;!z(H(n,"package.json"))&&T(n)!==n;)n=T(n);let{analyzeProject:a}=await import("../chunks/RVRPBQ4W.js"),{routeContracts:i}=await import("../chunks/AF3XUGHY.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=I({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:R({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&U(D(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var C=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Lr(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r,V.$asService());d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Dr(t,e,r,s,n,a){let i,o={on:!1},c=(b,p)=>new URL(b.url).pathname===Fr&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,p),l=Or((b,p)=>{Ur(c,b,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((b,p)=>{l.once("error",p),l.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=b=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(v=>l.close(()=>v()));l.closeIdleConnections();let k=setTimeout(()=>l.closeAllConnections(),b);await p,clearTimeout(k),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(Ee),m=!1,y=()=>{if(m){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}m=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+Br);b.unref(),f().then(()=>{clearTimeout(b),process.exit(0)},p=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let p=setTimeout(()=>process.exit(1),Te+1e3);h(Te).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let m of f)i.append(h,m);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Cr.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function jr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>G(o)),a=s.filter(o=>!G(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Js,boolean as Qs,check as Xs,date as Zs,defineSchema as en,defineTable as tn,enumType as rn,foreignKey as sn,index as nn,integer as an,jsonb as on,numeric as ln,ownedByUser as cn,policy as dn,raw as un,sqlType as pn,text as hn,timestamp as fn,userRef as mn,uuid as gn}from"palgres/dsl";import{increment as yn,now as wn}from"palgres";function x(t){if(t instanceof E)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return x(r)}}var Nr=_("Secrets",{async get(t){if(J(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),qr=100,Wr=1e3,Kr=168*3600,Vr={s:1,m:60,h:3600,d:86400};function Gr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Vr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof E&&i.code==="invalid_path_parameter"?new E({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${g.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Oe(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function zr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof E&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:x(a)}},async download(e){try{let r=await g.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return x(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Gr(r?.expiresIn);return s===void 0||s<1||s>Kr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>g.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??qr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Wr,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=l.data.next_cursor,!i)break}}catch(c){return x(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await g.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return x(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Hr={bucket:zr},Ce=t=>te("Storage",t,Hr),Yr={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},Jr=_("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>g.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>g.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await g.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return x(c)}return{data:{message_ids:a},error:null,status:i}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Me=t=>t==="override"?"user":t,Qr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Le(){return re.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Le();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Ie={setOverrideForUser:(t,e,r)=>P(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Me(s.source)})),setOverridesForUser:(t,e)=>P(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Me(r.source)})),clearAllOverridesForUser:t=>P(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Xr=_("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Be(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Fe(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Fe(s);return{name:r,enabled:Be(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Qr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Le();return r?Ie.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Ie}}),Zr=_("Realtime",{broadcast(t,e,r){return P(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as xn}from"zod";export{at as AttestedDevice,Ne as AuthUnavailable,At as Authorize,It as BadRequest,Ye as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,nt as Client,$t as Conflict,C as ContractRunEnded,qe as Controller,dt as Cron,V as Database,Lt as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,Xr as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,We as Get,Qe as Headers,Dt as HttpError,it as Injectable,d as Log,Gt as MAX_BODY_BYTES,j as MigrationRunEnded,lt as Module,Ut as NotFound,Jr as Notifications,ct as On,Et as OnConnect,Tt as OnDisconnect,xt as OnEmpty,kt as OnFirst,et as OptionalUser,Ct as PalError,g as Palbase,E as PalbaseError,Ir as PalbaseFactory,Xe as Param,Ge as Patch,Ke as Post,Ve as Put,He as Query,Je as QueryParams,Zr as Realtime,tt as Req,rt as RequestId,ot as Resolve,L as SchemaNotPushed,Nr as Secrets,jt as SerializationFailure,Yr as Storage,Rt as Subscribe,mt as Task,ft as TaskFailure,gt as Tasks,bt as TestUserTemplate,je as TokenError,B as TokenVerifier,Nt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Ze as User,ut as Webhook,Js as bigint,Qs as boolean,Xs as check,I as createApp,Zs as date,Mt as defineError,en as defineSchema,tn as defineTable,Kt as encrypt,Wt as encrypted,rn as enumType,sn as foreignKey,pt as getRegisteredControllers,ht as getRoutes,_t as getWebhookManifest,yn as increment,nn as index,an as integer,on as jsonb,wn as now,ln as numeric,cn as ownedByUser,dn as policy,un as raw,pn as sqlType,Vt as t,hn as text,fn as timestamp,mn as userRef,gn as uuid,xn as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
2
|
-
import{a as u}from"../chunks/
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u}from"../chunks/C4ENQSIX.js";import{c as p,i as c}from"../chunks/NFFQO2UC.js";import"../chunks/JCHW52YV.js";import{b as l,c as g,d as f,e as y}from"../chunks/VAPNSTWC.js";import"../chunks/QK2S67K3.js";import"../chunks/UBQK5O7J.js";import"../chunks/HMDMAILZ.js";import"../chunks/L3S7O5FQ.js";import"../chunks/LANEQ73A.js";import"../chunks/4Y47I6LA.js";import"../chunks/CHXCVOON.js";import"../chunks/72CHRRHY.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
2
|
-
import{a as g,b}from"./
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,b}from"./CHXCVOON.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,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
2
|
-
import{p as R,t as k,u as H}from"./
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{p as R,t as k,u as H}from"./IOVYIATC.js";var N=40,V=`
|
|
3
3
|
:host{display:contents}
|
|
4
4
|
.pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
|
|
5
5
|
.pm-modal::backdrop,.pm-full::backdrop{background:transparent}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.37.
|
|
1
|
+
/*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|