palbase 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +9 -9
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/5VTGMNPL.js +20 -0
- package/dist/chunks/{ZBOJEH7K.js → BO5KR2EQ.js} +2 -2
- package/dist/chunks/{PJVWGUIT.js → BRBCWPR3.js} +1 -1
- package/dist/chunks/DB3SIBKB.js +2 -0
- package/dist/chunks/EGNEXFTZ.js +2 -0
- package/dist/chunks/{HEXIIGWS.js → FZ3MQOVA.js} +2 -2
- package/dist/chunks/{SU7BP6VF.js → JSJVV43D.js} +1 -1
- package/dist/chunks/K6RRNI23.js +4 -0
- package/dist/chunks/{KDSWK3XW.js → KDWDPSL2.js} +1 -1
- package/dist/chunks/P4Z5E6ZI.js +2 -0
- package/dist/chunks/PDOHT46N.js +2 -0
- package/dist/chunks/PGPQGKH2.js +18 -0
- package/dist/chunks/{G3BK7L3J.js → RBA6V3UO.js} +2 -2
- package/dist/chunks/{X3MTLJRV.js → RO5Y5YU4.js} +1 -1
- package/dist/chunks/{BKVU4I5R.js → TUGRIOFX.js} +2 -2
- package/dist/chunks/WEI32SAJ.js +13 -0
- package/dist/chunks/{5ZJCEQV5.js → WINBISC2.js} +3 -3
- package/dist/chunks/Z5JVQNAZ.js +2 -0
- package/dist/cli.js +121 -120
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/ai.d.ts +44 -15
- package/types/ai/src/chats.d.ts +442 -12
- package/types/ai/src/index.d.ts +4 -4
- package/types/ai/src/tools.d.ts +158 -21
- package/types/backend/src/bootstrap.d.ts +8 -0
- package/types/backend/src/container.d.ts +9 -0
- package/types/backend/src/database.d.ts +17 -2
- package/types/backend/src/engine.d.ts +2 -0
- package/types/backend/src/gateways.d.ts +19 -0
- package/types/backend/src/index.d.ts +1 -0
- package/types/backend/src/runtime.d.ts +12 -0
- package/types/backend/src/testing/unit.d.ts +3 -1
- package/types/internal/src/chat.d.ts +168 -3
- package/types/internal/src/modules/ai.d.ts +1305 -57
- package/types/internal/src/modules/auth.d.ts +14 -2
- package/types/internal/src/modules/events.d.ts +2 -2
- package/types/internal/src/modules/machines.d.ts +57 -1
- package/types/internal/src/modules/notify.d.ts +6 -6
- package/types/internal/src/modules/purchases.d.ts +357 -13
- package/types/internal/src/modules/realtime.d.ts +36 -0
- package/types/internal/src/modules/stores.d.ts +259 -22
- package/types/internal/src/transport.d.ts +5 -0
- package/types/server/src/auth/jwt.d.ts +1 -6
- package/types/web/src/auth.d.ts +15 -4
- package/types/web/src/backends.d.ts +1 -1
- package/types/web/src/chat.d.ts +215 -4
- package/types/web/src/client.d.ts +28 -0
- package/types/web/src/gateways.d.ts +4 -3
- package/types/web/src/index.d.ts +3 -2
- package/types/web/src/session.d.ts +11 -1
- package/types/web/src/voice.d.ts +36 -0
- package/dist/chunks/3ALGILOX.js +0 -2
- package/dist/chunks/AIIKXCWN.js +0 -2
- package/dist/chunks/ELEE7XO2.js +0 -18
- package/dist/chunks/G7E26S3Y.js +0 -13
- package/dist/chunks/H2EPK74V.js +0 -20
- package/dist/chunks/JS3TTUHS.js +0 -2
- package/dist/chunks/L3NTI4AZ.js +0 -2
- package/dist/chunks/LEBVOSG6.js +0 -4
- package/dist/chunks/OIA7KLRW.js +0 -2
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a,b,c,d,e,f}from"../chunks/
|
|
1
|
+
/*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f}from"../chunks/PGPQGKH2.js";import"../chunks/P4Z5E6ZI.js";import"../chunks/KDWDPSL2.js";import"../chunks/EGNEXFTZ.js";import"../chunks/BO5KR2EQ.js";import"../chunks/PDOHT46N.js";import"../chunks/RO5Y5YU4.js";import"../chunks/JSJVV43D.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.
|
|
2
|
-
import{ga as h,
|
|
1
|
+
/*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ga as h,ka as d}from"../chunks/5VTGMNPL.js";import"../chunks/K6RRNI23.js";import"../chunks/Z5JVQNAZ.js";import"../chunks/PGPQGKH2.js";import"../chunks/P4Z5E6ZI.js";import"../chunks/KDWDPSL2.js";import"../chunks/EGNEXFTZ.js";import"../chunks/BO5KR2EQ.js";import"../chunks/PDOHT46N.js";import"../chunks/RO5Y5YU4.js";import"../chunks/JSJVV43D.js";import{binding as R,createDatabase as v}from"palgres";var b=new WeakMap;function q(l,e,n){if(!n?.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=n.schemas,s=b.get(l);s||b.set(l,s=new Map);let r=s.get(u);r||s.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",f=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},g=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(g);i||(i=v({sql:l,schemas:u,binding:R(0,!0),roles:f}),r.set(g,i));let w=JSON.parse(e.claimsJson),m=i.then(a=>a.request({role:o,claims:w},{diagnostics:n.diagnostics,signal:n.signal})),y=a=>new Proxy(()=>{},{apply:async(t,D,c)=>{let p=(await m).client;return a(p).apply(p,c)}});return{client:new Proxy({},{get(a,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:y(p=>p.asService()[c])}):y(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async a=>(await m).rollback(a)}}export{h as createApp,q as createRequestDatabase,d as makeMemoryCache};
|
package/dist/backend/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{$ as
|
|
3
|
-
|
|
4
|
-
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function
|
|
5
|
-
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function
|
|
1
|
+
/*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as $t,A as B,B as ct,C as dt,D as pt,E as ht,F as gt,G as bt,H as ft,I as mt,J as yt,K as wt,L as Pt,M as St,N as vt,O as At,P as kt,Q as Et,R as xt,S as Rt,T as _t,U as Ot,V as Tt,W as re,X as Ct,Y as Bt,Z as Ft,_ as Mt,a as Q,aa as It,b as X,ba as Lt,c as Z,ca as Dt,d as je,da as Ut,e as Ne,ea as F,f as qe,fa as Nt,g as We,ga as M,h as Ve,ha as G,i as Ge,ia as qt,j as Ke,ja as Wt,k as ze,l as He,m as Ye,n as Je,o as Qe,p as Xe,q as Ze,r as et,s as tt,t as rt,u as st,v as nt,w as at,x as ot,y as it,z as lt}from"../chunks/5VTGMNPL.js";import{a as ne}from"../chunks/BRBCWPR3.js";import{a as R,b as ee,c as te,f as g,g as ut,h as c,j as se,k as jt}from"../chunks/K6RRNI23.js";import{a as V,g as De,h as Ue,i as H,j as C,q as Y,r as J}from"../chunks/Z5JVQNAZ.js";import"../chunks/PGPQGKH2.js";import"../chunks/P4Z5E6ZI.js";import"../chunks/KDWDPSL2.js";import{m as Le}from"../chunks/EGNEXFTZ.js";import"../chunks/BO5KR2EQ.js";import{b as A,c as W}from"../chunks/PDOHT46N.js";import"../chunks/RO5Y5YU4.js";import"../chunks/JSJVV43D.js";import"reflect-metadata";import{existsSync as K,writeFileSync as Sr,writeSync as vr}from"node:fs";import{createServer as Ar}from"node:http";import{dirname as k,join as z,resolve as Re}from"node:path";import{Readable as kr}from"node:stream";var Vt=2e3,Gt=1e4,Kt=/^[A-Za-z0-9_-]{1,64}$/,zt=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??Gt,this.shutdownMs=r.shutdownMs??Vt,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&&c.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&&(c.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;c[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:Kt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,zt),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"),d=a.retryAfter;this.pausedUntil=this.now()+(typeof d=="number"&&d>0?d*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),c.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 Ht}from"node:crypto";import{bind as Yt,bunDriver as Jt,createDatabase as Qt,envBlock as Xt,createSearchWorker as Zt,cutOff as er,forgetUser as tr,MigrationOpen as rr,MigrationRefused as sr,Migrator as le,renewingBunPool as ae,VersionNotMigrated as nr}from"palgres";import{toModel as ce}from"palgres/dsl";var ar=["start","complete","rollback","plan","status","types"],or=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!ar.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function ue(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===F.name)throw new Error(`[palbase] db.schemas: the ${F.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,F]}function L(t){return ce(ue(t))}function ir(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function pe(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 lr(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 oe=5;function he(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=ae(()=>new r.SQL({url:n,prepare:!1,max:s})),i=ae(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,d)=>a.unsafe(o,d),begin:o=>a.current.begin(o)},engine:Jt(a,i),poolSize:s,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(c.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await _(t,{state:"none"}),0):(c.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return c.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 _("types",Xt(r,{module:"palbase/backend/env"}),e),0}async function fe(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return c.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(!or.test(n))return c.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=he(t,pe(e)),i=a(s),o,d=l=>c.error(`[palbase] migrate ${r}: ${l}`);try{let l=L(t),u=new le(i.pool,{log:h=>{/ is held by others | held by writers/.test(h)&&(o=h.trim()),c.info(h)},shadow:h=>{let y=new URL(s);y.pathname=`/${h}`;let b=a(y.toString());return{reserve:()=>b.pool.reserve(),end:()=>b.close()}},openedBy:n});if(r==="plan"){let h=await u.plan(l);return await _(r,h),h.refusals.length>0?1:0}if(r==="status")return await _(r,await u.status()),0;let p=r==="start"?await cr(u,l,n):r==="complete"?await u.complete():await u.rollback();return c.info(`[palbase] migrate ${r}: done`,{result:p}),await _(r,p),0}catch(l){return l instanceof sr?(c.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),d(`refused \u2014 ${l.refusals.join("; ")}`),1):er(l)?(c.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),d(`cut off \u2014 ${o??ie(l)}`),75):(c.error(`[palbase] migrate ${r}: failed`,{error:l}),d(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function cr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof rr)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return c.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 dr=(t,e)=>{process.stdout.write(t,()=>e())};function _(t,e,r=dr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
|
+
`,s))}function ie(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
|
+
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function ur(t,e){try{return await new le(t).plan(e)}catch{return}}var I=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?pr(r):[" palbase db:plan says what it would change"]].join(`
|
|
5
|
+
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function pr(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 hr=8e4;async function me(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=ue(t),i=ce(a),o=he(t,pe(e))(n);try{let d=!1,l=f=>{d||(d=!0,c.warn(`[palbase] database: not answering yet (${f instanceof Error?f.message:String(f)}) \u2014 waiting for it, as one waking does`))},u=await Yt(o.engine,i,{waitMs:s.onPlatform?hr:0,onUnreachable:l}).catch(async f=>{throw s.onPlatform||!(f instanceof nr)?f:new I(f.digest,await ur(o.pool,i))}),p=Ht("sha256",r).update("palgres page cursor").digest("hex"),h=t.embed??s.embed,y=await Qt({sql:o.engine,schemas:a,binding:u,cursorSecret:p,admission:lr(o.poolSize),embed:h,log:f=>c.warn(`[palbase] ${f}`)}),b=ir(i)?Zt({sql:o.engine,embed:h,log:f=>c.info(`[palbase] ${f}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:f=>tr(o.engine,u,i,f),...b?{search:b}:{},close:()=>o.close()}}catch(d){throw await o.close(),d}}function gr(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 ye(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(gr)}}}var br=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function we(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??"";br.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 d=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;d!==void 0&&!/^[0-9a-f]{64}$/.test(d)&&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&&(d!==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:
|
|
6
6
|
- ${s.join(`
|
|
7
|
-
- `)}`);return{url:a,projectId:i,secretKey:o,webhookSecret:r.needsWebhookSecret?l:void 0,platformSecret:
|
|
7
|
+
- `)}`);return{url:a,projectId:i,secretKey:o,webhookSecret:r.needsWebhookSecret?l:void 0,platformSecret:d}}import{createHash as fr}from"node:crypto";import{writeSync as mr}from"node:fs";import{gzipSync as yr}from"node:zlib";var wr="palbase-contract-v1 begin",Pr="palbase-contract-v1 end",Pe=76;function Se(t){let e=Buffer.from(t,"utf8"),r=yr(e).toString("base64"),s=[`${wr} ${fr("sha256").update(e).digest("hex")} ${e.length}`];for(let n=0;n<r.length;n+=Pe)s.push(r.slice(n,n+Pe));return s.push(Pr),`
|
|
8
8
|
${s.join(`
|
|
9
9
|
`)}
|
|
10
|
-
`}function
|
|
11
|
-
`),process.exit(1),new
|
|
12
|
-
`),process.exit(0),new x}let i=ve(s),o=await ke(i);o&&u.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),te(o?void 0:i);let c=e.db?L(e.db):void 0,l=await H({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&u.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&&u.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 d=vr(r)||c!==void 0&&U(c),p=fe(e.palbase??{},s,{needsWebhookSecret:d});d&&p.webhookSecret===void 0&&u.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 h=V({url:p.url,secretKey:p.secretKey}),y=e.port??Number(s.PORT??"8080");if(!Number.isInteger(y)||y<0||y>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let g=e.db?await be(e.db,s,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:ge(h)}):void 0;g&&u.info(`[palbase] database: version ${g.binding.version}`);let f=g&&U(g.model)?{"user.deleted":[w=>Er(g,w)]}:void 0,m=p.platformSecret===void 0?void 0:{secret:p.platformSecret},S=e.requestTelemetry===!1?void 0:new M(h.analytics),T=()=>F({modules:r,verifier:new O({issuer:p.url,projectId:p.projectId,standing:K({url:p.url,secretKey:p.secretKey})}),server:h,webhookSecret:p.webhookSecret,env:s,projectId:p.projectId,telemetry:S,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,platform:m,events:f,database:g&&{app:g.app,requests:g.requests},strings:o}),E=T(),N=e.boot?.attempts??5,q=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await E.start();break}catch(v){if(w>=N)throw u.error(`[palbase] the app did not start after ${N} attempts`,{error:v}),v;u.warn(`[palbase] the app did not start (attempt ${w} of ${N}); trying again in ${q} ms`,{error:v}),await new Promise(Fe=>setTimeout(Fe,q)),q*=2,E=T()}return Rr(E,h,y,e.host??"0.0.0.0",e.exitOnFatal??!0,g)}};function ve(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=k(Ae(e));for(;!W(G(r,"package.json"))&&k(r)!==r;)r=k(r);return W(G(r,"package.json"))?r:process.cwd()}async function ke(t){try{return await re(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Ar(t,e,r){let s=Ae(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=k(s);for(;!W(G(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/HEXIIGWS.js"),{routeContracts:i}=await import("../chunks/BKVU4I5R.js"),o=a(n,s);for(let d of o.warnings)u.warn(`[palbase] the contract: ${d}`);let c="https://contract.palbase.invalid",l=F({modules:t,verifier:new O({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:V({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:ee()},events:e.db&&U(L(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract(),null,2)}var x=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},D=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Er(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);u.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Rr(t,e,r,s,n,a){let i,o={on:!1},c=(m,S)=>new URL(m.url).pathname===Sr&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,S),l=yr((m,S)=>{xr(c,m,S,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,S)=>{l.once("error",S),l.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let d=l.address().port;u.info(`[palbase] serving ${t.routes.length} route(s) on :${d}`,{routes:t.routes}),a?.search?.start();let p=m=>i??=(async()=>{u.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let S=new Promise(E=>l.close(()=>E()));l.closeIdleConnections();let T=setTimeout(()=>l.closeAllConnections(),m);await S,clearTimeout(T),process.off("SIGINT",g),process.off("uncaughtException",f),process.off("unhandledRejection",f);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",g)}})(),h=()=>p(Pe),y=!1,g=()=>{if(y){u.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}y=!0;let m=setTimeout(()=>{u.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Pe+Pr);m.unref(),h().then(()=>{clearTimeout(m),process.exit(0)},S=>{clearTimeout(m),u.error("[palbase] stopping failed; the process ends",{error:S}),process.exit(1)})},f=m=>{u.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let S=setTimeout(()=>process.exit(1),Se+1e3);p(Se).finally(()=>{clearTimeout(S),process.exit(1)})};return process.on("SIGTERM",g),process.once("SIGINT",g),n&&(process.on("uncaughtException",f),process.on("unhandledRejection",f)),{routes:t.routes,palbase:e,port:d,handle:c,close:h}}async function xr(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[p,h]of Object.entries(e.headers))if(h!==void 0)if(Array.isArray(h))for(let y of h)i.append(p,y);else i.set(p,h);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?wr.toWeb(e):void 0,duplex:"half",signal:c.signal}),d=await t(l,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=d.status,d.headers.forEach((p,h)=>r.setHeader(h,p)),s.on&&r.setHeader("connection","close"),d.body)for await(let p of d.body)r.write(p);r.end()}catch(n){u.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}import{bigint as Ms,boolean as Is,check as $s,date as Ls,defineSchema as Us,defineTable as Ds,enumType as js,foreignKey as Ns,index as qs,integer as Vs,jsonb as Ws,numeric as Gs,ownedByUser as Ks,policy as zs,raw as Hs,sqlType as Ys,text as Js,timestamp as Qs,userRef as Xs,uuid as Zs}from"palgres/dsl";import{increment as tn,now as rn}from"palgres";function A(t){if(t instanceof _)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 A(r)}}var Tr=R("Secrets",{async get(t){if(z(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),_r=100,Or=1e3,Cr=168*3600,Br={s:1,m:60,h:3600,d:86400};function Fr(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)*Br[n]*1e3);return Math.ceil(r/1e3)}function Ce(t,e,r){let s=`${b.url}/storage/public/${encodeURIComponent(t)}/${encodeURIComponent(e)}`;return r?`${s}?variant=${encodeURIComponent(r)}`:s}function Ee(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,Ce(t.bucket,t.path,e)]))}}function Mr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Ee(a.data),error:null,status:a.status}}catch(a){return a instanceof _&&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}:A(a)}},async download(e){try{let r=await b.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 A(r)}},getPublicUrl(e,r){return Ce(t,e,r?.variant)},async createSignedUrl(e,r){let s=Fr(r?.expiresIn);return s===void 0||s<1||s>Cr?{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(()=>b.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??_r,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(Or,n+s-a.length)),l=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let d of l.data.objects)n>0?n--:a.length<s&&a.push(Ee(d));if(i=l.data.next_cursor,!i)break}}catch(c){return A(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await b.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return A(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(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Ir={bucket:Mr},Re=t=>X("Storage",t,Ir),$r={bucket:t=>Re("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Re("buckets").bucket(e):void 0})},Lr=R("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(()=>b.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(()=>b.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 b.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return A(c)}return{data:{message_ids:a},error:null,status:i}}}}),xe=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Te=t=>typeof t=="string"?{name:t}:null,_e=t=>t==="override"?"user":"system",Ur=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&("userId"in t||"properties"in t);function Be(){return Z.getStore()?.userId}function j(t){let e=t&&"userId"in t?t.userId??void 0:Be();return P(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),r=>r.values??{})}var Oe={setOverrideForUser:(t,e,r)=>P(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:_e(s.source)})),setOverridesForUser:(t,e)=>P(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:_e(r.source)})),clearAllOverridesForUser:t=>P(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Dr=R("Flags",{async isEnabled(t,e){let r=s=>(u.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await j(e);return s.error?r(`${s.error.code}: ${s.error.message}`):xe(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await j(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Te(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await j(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Te(s);return{name:r,enabled:xe(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):Ur(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await j(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=Be();return r?Oe.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 Oe}}),jr=R("Realtime",{broadcast(t,e,r){return P(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as dn}from"zod";export{$e as AuthUnavailable,mt as Authorize,_t as BadRequest,We as Body,Dt as CACHE_MAX_TTL,jt as Cache,bt as ChatPart,Ze as Client,Ot as Conflict,x as ContractRunEnded,Le as Controller,nt as Cron,lt as Database,Ct as DeadlockDetected,qe as Delete,At as DiError,Me as EVENT_TYPES,Dr as Flags,xt as Forbidden,ft as Gateway,gt as GatewayRefusal,Ue as Get,Ke as Headers,Bt as HttpError,tt as Injectable,u as Log,Ut as MAX_BODY_BYTES,D as MigrationRunEnded,rt as Module,Ft as NotFound,Lr as Notifications,st as On,wt as OnConnect,Pt as OnDisconnect,St as OnEmpty,yt as OnFirst,Ye as OptionalUser,Et as PalError,b as Palbase,_ as PalbaseError,kr as PalbaseFactory,ze as Param,Ne as Patch,De as Post,je as Put,Ve as Query,Ge as QueryParams,jr as Realtime,Je as Req,Qe as RequestId,et as Resolve,$ as SchemaNotPushed,Tr as Secrets,Mt as SerializationFailure,$r as Storage,vt as Subscribe,ut as Task,ct as TaskFailure,dt as Tasks,Ie as TokenError,O as TokenVerifier,It as TooManyRequests,Xe as TraceId,Rt as Unauthorized,$t as UniqueViolation,pt as Upload,ht as UploadedObject,He as User,at as Webhook,Ms as bigint,Is as boolean,$s as check,F as createApp,Ls as date,Tt as defineError,Us as defineSchema,Ds as defineTable,js as enumType,Ns as foreignKey,ot as getRegisteredControllers,it as getRoutes,kt as getWebhookManifest,tn as increment,qs as index,Vs as integer,Ws as jsonb,rn as now,Gs as numeric,Ks as ownedByUser,zs as policy,Hs as raw,Ys as sqlType,Lt as t,Js as text,Qs as timestamp,Xs as userRef,Zs as uuid,dn as z};
|
|
10
|
+
`}function ve(t,e,r=mr){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 Ae=2e4,ke=5e3,Er=15e3,xr="/_palbase/health";function Rr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=B(s,Q);return n?n.providers.some(a=>B(a,X)!==void 0&&B(a,Z)===void 0)||n.imports.some(r):!1};return t.some(r)}var _r={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=de(s);if(n!==void 0){let w=n==="types"?await be(e.db):e.db?await fe(e.db,s,n):await ge(n);throw process.exit(w),new U(w)}let a=s.PALBASE_CONTRACT_OUT;if(a){let w;try{await xe(Ee(s)),w=await Or(r,e,s)}catch(v){throw vr(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
|
|
11
|
+
`),process.exit(1),new O}throw a==="/dev/stdout"?ve(1,Se(w)):Sr(a,`${w}
|
|
12
|
+
`),process.exit(0),new O}let i=Ee(s),o=await xe(i);o&&c.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),se(o?void 0:i);let d=e.db?L(e.db):void 0,l=await J({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&c.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&&c.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=Rr(r)||d!==void 0&&D(d),p=we(e.palbase??{},s,{needsWebhookSecret:u});u&&p.webhookSecret===void 0&&c.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 h=V({url:p.url,secretKey:p.secretKey}),y=e.port??Number(s.PORT??"8080");if(!Number.isInteger(y)||y<0||y>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let b=e.db?await me(e.db,s,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:ye(h)}):void 0;b&&c.info(`[palbase] database: version ${b.binding.version}`);let f=b&&D(b.model)?{"user.deleted":[w=>Tr(b,w)]}:void 0,m=p.platformSecret===void 0?void 0:{secret:p.platformSecret},S=e.requestTelemetry===!1?void 0:new $(h.analytics),T=()=>M({modules:r,verifier:new C({issuer:p.url,projectId:p.projectId,standing:H({url:p.url,secretKey:p.secretKey})}),server:h,webhookSecret:p.webhookSecret,env:s,projectId:p.projectId,telemetry:S,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Fr(e.cors,s.PALBASE_WEB_ORIGINS),platform:m,events:f,database:b&&{app:b.app,requests:b.requests},strings:o}),x=T(),N=e.boot?.attempts??5,q=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await x.start();break}catch(v){if(w>=N)throw c.error(`[palbase] the app did not start after ${N} attempts`,{error:v}),v;c.warn(`[palbase] the app did not start (attempt ${w} of ${N}); trying again in ${q} ms`,{error:v}),await new Promise(Ie=>setTimeout(Ie,q)),q*=2,x=T()}return Cr(x,h,y,e.host??"0.0.0.0",e.exitOnFatal??!0,b)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=k(Re(e));for(;!K(z(r,"package.json"))&&k(r)!==r;)r=k(r);return K(z(r,"package.json"))?r:process.cwd()}async function xe(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Or(t,e,r){let s=Re(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=k(s);for(;!K(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/FZ3MQOVA.js"),{routeContracts:i}=await import("../chunks/TUGRIOFX.js"),o=a(n,s);for(let u of o.warnings)c.warn(`[palbase] the contract: ${u}`);let d="https://contract.palbase.invalid",l=M({modules:t,verifier:new C({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:V({url:d,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:re()},events:e.db&&D(L(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},U=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Tr(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);c.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Cr(t,e,r,s,n,a){let i,o={on:!1},d=(m,S)=>new URL(m.url).pathname===xr&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,S),l=Ar((m,S)=>{Br(d,m,S,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,S)=>{l.once("error",S),l.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;c.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=m=>i??=(async()=>{c.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let S=new Promise(x=>l.close(()=>x()));l.closeIdleConnections();let T=setTimeout(()=>l.closeAllConnections(),m);await S,clearTimeout(T),process.off("SIGINT",b),process.off("uncaughtException",f),process.off("unhandledRejection",f);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",b)}})(),h=()=>p(Ae),y=!1,b=()=>{if(y){c.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}y=!0;let m=setTimeout(()=>{c.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ae+Er);m.unref(),h().then(()=>{clearTimeout(m),process.exit(0)},S=>{clearTimeout(m),c.error("[palbase] stopping failed; the process ends",{error:S}),process.exit(1)})},f=m=>{c.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let S=setTimeout(()=>process.exit(1),ke+1e3);p(ke).finally(()=>{clearTimeout(S),process.exit(1)})};return process.on("SIGTERM",b),process.once("SIGINT",b),n&&(process.on("uncaughtException",f),process.on("unhandledRejection",f)),{routes:t.routes,palbase:e,port:u,handle:d,close:h}}async function Br(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[p,h]of Object.entries(e.headers))if(h!==void 0)if(Array.isArray(h))for(let y of h)i.append(p,y);else i.set(p,h);let o=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;r.on("close",()=>{r.writableFinished||d.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?kr.toWeb(e):void 0,duplex:"half",signal:d.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((p,h)=>r.setHeader(h,p)),s.on&&r.setHeader("connection","close"),u.body)for await(let p of u.body)r.write(p);r.end()}catch(n){c.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function Fr(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 Ns,boolean as qs,check as Ws,date as Vs,defineSchema as Gs,defineTable as Ks,enumType as zs,foreignKey as Hs,index as Ys,integer as Js,jsonb as Qs,numeric as Xs,ownedByUser as Zs,policy as en,raw as tn,sqlType as rn,text as sn,timestamp as nn,userRef as an,uuid as on}from"palgres/dsl";import{increment as cn,now as dn}from"palgres";function E(t){if(t instanceof A)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 E(r)}}var Mr=R("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),$r=100,Ir=1e3,Lr=168*3600,Dr={s:1,m:60,h:3600,d:86400};function Ur(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)*Dr[n]*1e3);return Math.ceil(r/1e3)}function Me(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>W(s,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({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/${W(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function _e(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,Me(t.bucket,t.path,e)]))}}function jr(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:_e(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&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}:E(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 E(r)}},getPublicUrl(e,r){return Me(t,e,r?.variant)},async createSignedUrl(e,r){let s=Ur(r?.expiresIn);return s===void 0||s<1||s>Lr?{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??$r,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 d=Math.max(1,Math.min(Ir,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(_e(u));if(i=l.data.next_cursor,!i)break}}catch(d){return E(d)}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 E(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 Nr={bucket:jr},Oe=t=>ee("Storage",t,Nr),qr={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},Wr=R("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 d=await g.notify.sendEmail({body:{...n,to:o}});i=d.status,a.push(d.data.message_id??null)}catch(d){return E(d)}return{data:{message_ids:a},error:null,status:i}}}}),Te=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Ce=t=>typeof t=="string"?{name:t}:null,Be=t=>t==="override"?"user":"system",Vr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&("userId"in t||"properties"in t);function $e(){return te.getStore()?.userId}function j(t){let e=t&&"userId"in t?t.userId??void 0:$e();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Fe={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:Be(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:Be(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}))},Gr=R("Flags",{async isEnabled(t,e){let r=s=>(c.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await j(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Te(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await j(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Ce(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await j(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Ce(s);return{name:r,enabled:Te(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):Vr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await j(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=$e();return r?Fe.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 Fe}}),Kr=R("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 yn}from"zod";export{Ue as AuthUnavailable,Pt as Authorize,Bt as BadRequest,ze as Body,qt as CACHE_MAX_TTL,Wt as Cache,mt as ChatPart,rt as Client,Ft as Conflict,O as ContractRunEnded,je as Controller,it as Cron,ut as Database,Mt as DeadlockDetected,Ge as Delete,Rt as DiError,Le as EVENT_TYPES,Gr as Flags,Tt as Forbidden,wt as Gateway,yt as GatewayRefusal,Ne as Get,Ye as Headers,$t as HttpError,nt as Injectable,c as Log,Nt as MAX_BODY_BYTES,U as MigrationRunEnded,at as Module,It as NotFound,Wr as Notifications,ot as On,vt as OnConnect,At as OnDisconnect,kt as OnEmpty,St as OnFirst,Xe as OptionalUser,_t as PalError,g as Palbase,A as PalbaseError,_r as PalbaseFactory,Je as Param,Ve as Patch,qe as Post,We as Put,Ke as Query,He as QueryParams,Kr as Realtime,Ze as Req,et as RequestId,st as Resolve,I as SchemaNotPushed,Mr as Secrets,Lt as SerializationFailure,qr as Storage,Et as Subscribe,ht as Task,pt as TaskFailure,gt as Tasks,De as TokenError,C as TokenVerifier,Dt as TooManyRequests,tt as TraceId,Ot as Unauthorized,Ut as UniqueViolation,bt as Upload,ft as UploadedObject,Qe as User,lt as Webhook,Ns as bigint,qs as boolean,Ws as check,M as createApp,Vs as date,Ct as defineError,Gs as defineSchema,Ks as defineTable,zs as enumType,Hs as foreignKey,ct as getRegisteredControllers,dt as getRoutes,xt as getWebhookManifest,cn as increment,Ys as index,Js as integer,Qs as jsonb,dn as now,Xs as numeric,Zs as ownedByUser,en as policy,tn as raw,rn as sqlType,jt as t,sn as text,nn as timestamp,an as userRef,on as uuid,yn as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as l,b as g,c as f,d as
|
|
1
|
+
/*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as l,b as g,c as f,d as y}from"../chunks/RBA6V3UO.js";import{a as u}from"../chunks/BRBCWPR3.js";import{c as p,i as c}from"../chunks/K6RRNI23.js";import"../chunks/PGPQGKH2.js";import"../chunks/P4Z5E6ZI.js";import"../chunks/KDWDPSL2.js";import"../chunks/EGNEXFTZ.js";import"../chunks/BO5KR2EQ.js";import"../chunks/PDOHT46N.js";import"../chunks/RO5Y5YU4.js";import"../chunks/JSJVV43D.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};
|