palbase 0.68.0 → 0.69.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai-sdk/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{2ZHSNWVZ.js → 37KUGTKN.js} +2 -2
- package/dist/chunks/{UJLFALKX.js → BCSBO6QR.js} +2 -2
- package/dist/chunks/BZYYDYLF.js +2 -0
- package/dist/chunks/{22GRHCVI.js → CD2TYINV.js} +1 -1
- package/dist/chunks/{J7WJF7F4.js → CE6XFRSZ.js} +2 -2
- package/dist/chunks/{XJLAH42O.js → CPTZEOT3.js} +1 -1
- package/dist/chunks/CRK2KWFW.js +18 -0
- package/dist/chunks/{D6EUPFUR.js → D6ZVNWQ2.js} +2 -2
- package/dist/chunks/{4YV35XDP.js → EZW67SHF.js} +2 -2
- package/dist/chunks/{QQUIM4VK.js → F7WQUODK.js} +2 -2
- package/dist/chunks/{OWLXCD3D.js → FQEGZTR3.js} +1 -1
- package/dist/chunks/{QFZ4GCJH.js → ICNSKNUT.js} +2 -2
- package/dist/chunks/{YCDAV3WO.js → JFVOERVR.js} +2 -2
- package/dist/chunks/{622BI7EV.js → KOX5W2ID.js} +1 -1
- package/dist/chunks/{LUUXXMXH.js → LQF6CVJR.js} +1 -1
- package/dist/chunks/{EJAGO6ZV.js → OA2EJLJ2.js} +2 -2
- package/dist/chunks/{IZWB7FGX.js → OE772CLE.js} +2 -2
- package/dist/chunks/{3OP3YJ63.js → OZM5TI3D.js} +4 -3
- package/dist/chunks/{EGWQ3EJE.js → P234HHKR.js} +2 -2
- package/dist/chunks/{PP7MW4OT.js → PM3BWYB5.js} +1 -1
- package/dist/chunks/TXOMPE5N.js +13 -0
- package/dist/chunks/{F4B6ELAN.js → XK7JQGKM.js} +2 -2
- package/dist/chunks/{7SGTDHXJ.js → Y4FKEIZV.js} +2 -2
- package/dist/chunks/{XU4G5W72.js → YGIYMCYC.js} +1 -1
- package/dist/cli.js +227 -227
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/payments-ui.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/ai.d.ts +22 -0
- package/types/ai/src/chats.d.ts +65 -15
- package/types/ai/src/index.d.ts +4 -1
- package/types/ai/src/templates.d.ts +76 -0
- package/types/ai/src/workflows.d.ts +201 -0
- package/types/cloud/src/generated/project.d.ts +2 -2
- package/types/internal/src/modules/ai.d.ts +2242 -674
- package/types/internal/src/modules/calls.d.ts +297 -0
- package/types/internal/src/modules/events.d.ts +2 -2
- package/types/web/src/client.d.ts +3 -0
- package/types/web/src/index.d.ts +1 -0
- package/types/web/src/templates.d.ts +75 -0
- package/types/web/src/voice.d.ts +4 -1
- package/dist/chunks/5ZXXBM6L.js +0 -18
- package/dist/chunks/65QZXK2S.js +0 -2
- package/dist/chunks/MVY4K43S.js +0 -13
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.69.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f,g}from"../chunks/CRK2KWFW.js";import"../chunks/D6ZVNWQ2.js";import"../chunks/FQEGZTR3.js";import"../chunks/BZYYDYLF.js";import"../chunks/CE6XFRSZ.js";import"../chunks/ICNSKNUT.js";import"../chunks/CPTZEOT3.js";import"../chunks/YGIYMCYC.js";export{f as AIResponseError,b as AISchemaError,d as ToolError,e as WorkflowParkedError,g as createAI,a as partial,c as prepare};
|
package/dist/ai-sdk/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"../chunks/
|
|
1
|
+
/*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"../chunks/YGIYMCYC.js";function M(s){return typeof process<"u"&&process.env?process.env[s]??"":""}function j(s){let a=(s??M("PALBASE_URL")).trim().replace(/\/+$/,"");if(!a)throw new Error("@palbase/ai-sdk: url or PALBASE_URL is required");return a.endsWith("/ai/v1")?a:`${a}/ai/v1`}function N(s){let a=(s??M("PALBASE_SECRET_KEY")).trim();if(!a)throw new Error("@palbase/ai-sdk: apiKey or PALBASE_SECRET_KEY is required");return a}function x(s,a,t){let u={apikey:s,Authorization:`Bearer ${s}`,"Content-Type":"application/json",...a};return t?.sessionId&&(u["X-Palbase-Session-Id"]=t.sessionId),t?.agent&&(u["X-Palbase-Agent"]=t.agent),t?.userId&&(u["X-Palbase-User-Id"]=t.userId),t?.workspaceId&&(u["X-Palbase-Workspace-Id"]=t.workspaceId),t?.fallbacks?.length&&(u["X-Palbase-Fallbacks"]=t.fallbacks.join(",")),u}function I(s){let a=[];for(let t of s){if(typeof t.content=="string"){a.push({role:t.role,content:t.content});continue}if(t.role==="tool"){for(let g of t.content)a.push({role:"tool",tool_call_id:g.toolCallId??"",content:typeof g.output=="string"?g.output:JSON.stringify(g.output??"")});continue}let u=[],k=[];for(let g of t.content)g.type==="text"&&g.text&&u.push(g.text),g.type==="tool-call"&&k.push({id:g.toolCallId??"",type:"function",function:{name:g.toolName??"",arguments:typeof g.input=="string"?g.input:JSON.stringify(g.input??{})}});let T={role:t.role,content:u.join(`
|
|
3
3
|
`)};k.length>0&&(T.tool_calls=k),a.push(T)}return a}function R(s){switch(s){case"stop":return"stop";case"length":return"length";case"tool_calls":return"tool-calls";case"error":return"error";default:return"unknown"}}function L(s={}){let a=j(s.url),t=N(s.apiKey),u=s.fetch??globalThis.fetch,k=(l,c)=>({specificationVersion:"v2",provider:"palbase",modelId:l,async doGenerate(e){let n={model:l,messages:I(e.prompt),stream:!1};e.maxOutputTokens!==void 0&&(n.max_tokens=e.maxOutputTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.top_p=e.topP),e.tools?.length&&(n.tools=e.tools.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema??{type:"object",properties:{}}}})));let o=await u(`${a}/chat/completions`,{method:"POST",headers:x(t,{...s.headers,...e.headers},c),body:JSON.stringify(n),signal:e.abortSignal});if(!o.ok)throw new Error(`Palbase AI HTTP ${o.status}: ${await o.text()}`);let d=await o.json(),r=d.choices?.[0],p=[];r?.message?.content&&p.push({type:"text",text:r.message.content});for(let i of r?.message?.tool_calls??[])p.push({type:"tool-call",toolCallId:i.id,toolName:i.function.name,input:i.function.arguments});let m=d.usage?.prompt_tokens??0,f=d.usage?.completion_tokens??0;return{content:p,finishReason:R(r?.finish_reason),usage:{inputTokens:m,outputTokens:f,totalTokens:d.usage?.total_tokens??m+f},warnings:[]}},async doStream(e){let n={model:l,messages:I(e.prompt),stream:!0,stream_options:{include_usage:!0}};e.maxOutputTokens!==void 0&&(n.max_tokens=e.maxOutputTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.top_p=e.topP),e.tools?.length&&(n.tools=e.tools.map(b=>({type:"function",function:{name:b.name,description:b.description,parameters:b.inputSchema??{type:"object",properties:{}}}})));let o=await u(`${a}/chat/completions`,{method:"POST",headers:x(t,{...s.headers,...e.headers},c),body:JSON.stringify(n),signal:e.abortSignal});if(!o.ok||!o.body)throw new Error(`Palbase AI stream HTTP ${o.status}: ${await o.text()}`);let d=o.body.getReader(),r=new TextDecoder,p="",m="stop",f={inputTokens:0,outputTokens:0,totalTokens:0},i=new Map;return{stream:new ReadableStream({async pull(b){for(;;){let v=p.indexOf(`
|
|
4
4
|
`);if(v>=0){let S=p.slice(0,v).trim();if(p=p.slice(v+1),!S.startsWith("data:"))continue;let A=S.slice(5).trim();if(A==="[DONE]"){for(let P of i.values())b.enqueue({type:"tool-call",toolCallId:P.id,toolName:P.name,input:P.args});i.clear(),b.enqueue({type:"finish",finishReason:m,usage:f}),b.close();return}try{let P=JSON.parse(A);if(P.usage){let h=P.usage.prompt_tokens??0,y=P.usage.completion_tokens??0;f={inputTokens:h,outputTokens:y,totalTokens:P.usage.total_tokens??h+y}}for(let h of P.choices??[]){h.finish_reason&&(m=R(h.finish_reason)),h.delta?.content&&b.enqueue({type:"text-delta",id:P.id??"text_0",delta:h.delta.content});for(let y of h.delta?.tool_calls??[]){let _=i.get(y.index)??{id:"",name:"",args:""};y.id&&(_.id=y.id),y.function?.name&&(_.name=y.function.name),y.function?.arguments&&(_.args+=y.function.arguments),i.set(y.index,_)}}}catch{}continue}let{value:$,done:C}=await d.read();if(C){for(let S of i.values())b.enqueue({type:"tool-call",toolCallId:S.id,toolName:S.name,input:S.args});b.enqueue({type:"finish",finishReason:m,usage:f}),b.close();return}p+=r.decode($,{stream:!0})}}})}}}),T=l=>({specificationVersion:"v2",provider:"palbase",modelId:l,maxEmbeddingsPerCall:1024,async doEmbed({values:c,abortSignal:e}){let n=await u(`${a}/embeddings`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,input:c}),signal:e});if(!n.ok)throw new Error(`Palbase AI embeddings HTTP ${n.status}: ${await n.text()}`);let o=await n.json();return{embeddings:(o.data??[]).map(d=>d.embedding),usage:{tokens:o.usage?.prompt_tokens??o.usage?.total_tokens??0}}}}),g=l=>({specificationVersion:"v2",provider:"palbase",modelId:l,async doGenerate({prompt:c,n:e=1,size:n,abortSignal:o}){let d=await u(`${a}/images/generations`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,prompt:c,n:e,size:n,response_format:"b64_json"}),signal:o});if(!d.ok)throw new Error(`Palbase AI images HTTP ${d.status}: ${await d.text()}`);return{images:((await d.json()).data??[]).map(p=>p.b64_json??p.url??""),warnings:[]}}}),E=l=>({specificationVersion:"v1",provider:"palbase",modelId:l,async doGenerate({audio:c,mediaType:e,language:n,diarization:o,abortSignal:d}){let r=new FormData;r.set("model",l),n&&r.set("language",n),o&&r.set("diarization","true"),r.set("file",new Blob([new Uint8Array(c)],{type:e}),"audio.wav");let p=x(t,s.headers);delete p["Content-Type"];let m=await u(`${a}/audio/transcriptions`,{method:"POST",headers:p,body:r,signal:d});if(!m.ok)throw new Error(`Palbase AI transcription HTTP ${m.status}: ${await m.text()}`);let f=await m.json();return{text:f.text,language:f.language,durationInSeconds:f.duration_seconds,segments:(f.segments??[]).map(i=>({speaker:i.speaker,startSecond:i.start,endSecond:i.end,text:i.text}))}}}),O=l=>({specificationVersion:"v1",provider:"palbase",modelId:l,async doGenerate({text:c,voice:e,outputFormat:n,speed:o,abortSignal:d}){let r=await u(`${a}/audio/speech`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,input:c,voice:e,response_format:n??"mp3",speed:o}),signal:d});if(!r.ok)throw new Error(`Palbase AI speech HTTP ${r.status}: ${await r.text()}`);return{audio:new Uint8Array(await r.arrayBuffer()),mediaType:r.headers.get("content-type")??"audio/mpeg"}}}),w=((l,c)=>k(l,c));return w.languageModel=k,w.textEmbeddingModel=T,w.image=g,w.transcription=E,w.speech=O,w}export{L as createPalbase};
|
package/dist/backend/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{ha as w,la as h}from"../chunks/
|
|
1
|
+
/*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ha as w,la as h}from"../chunks/P234HHKR.js";import"../chunks/XK7JQGKM.js";import"../chunks/EZW67SHF.js";import"../chunks/CRK2KWFW.js";import"../chunks/D6ZVNWQ2.js";import"../chunks/JFVOERVR.js";import"../chunks/KOX5W2ID.js";import"../chunks/FQEGZTR3.js";import"../chunks/BZYYDYLF.js";import"../chunks/LQF6CVJR.js";import"../chunks/CE6XFRSZ.js";import"../chunks/ICNSKNUT.js";import"../chunks/CPTZEOT3.js";import"../chunks/YGIYMCYC.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.
|
|
1
|
+
/*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{$ as It,A as I,B as ut,C as pt,D as ft,E as ht,F as gt,G as bt,H as mt,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 Rt,R as _t,S as xt,T as Ot,U as Tt,V as Ct,W as Bt,X as ne,Y as Ft,Z as Lt,_ as $t,a as Z,aa as Mt,b as ee,ba as Dt,c as te,ca as Ut,d as qe,da as jt,e as Ke,ea as Nt,f as We,fa as M,g as Ve,ga as Vt,h as Ge,ha as D,i as ze,ia as G,j as He,ja as Gt,k as Ye,ka as zt,l as Je,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as st,s as rt,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/EGWQ3EJE.js";import{a as qt,b as Kt}from"../chunks/F4B6ELAN.js";import{a as oe}from"../chunks/PP7MW4OT.js";import{a as C,b as se,c as re,f as b,g as V,h as d,j as ae,k as Wt}from"../chunks/4YV35XDP.js";import"../chunks/5ZXXBM6L.js";import"../chunks/D6EUPFUR.js";import{d as T,j as je,k as Ne,l as J,m as $,y as Q,z as X}from"../chunks/YCDAV3WO.js";import"../chunks/622BI7EV.js";import"../chunks/OWLXCD3D.js";import{r as Ue}from"../chunks/65QZXK2S.js";import"../chunks/LUUXXMXH.js";import"../chunks/J7WJF7F4.js";import{b as _,c as W}from"../chunks/QFZ4GCJH.js";import"../chunks/XJLAH42O.js";import"../chunks/XU4G5W72.js";import"reflect-metadata";import{existsSync as H,writeFileSync as Is,writeSync as Ms}from"node:fs";import{createServer as Ds}from"node:http";import{dirname as x,join as Y,resolve as Oe}from"node:path";import{Readable as Us}from"node:stream";var Ht=2e3,Yt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Qt=512,U=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,s={}){this.sink=e,this.linesPerSecond=s.linesPerSecond??10,this.batchSize=Math.min(100,s.batchSize??100),this.flushMs=s.flushMs??2e3,this.maxPending=s.maxPending??2e3,this.sendMs=s.sendMs??Yt,this.shutdownMs=s.shutdownMs??Ht,this.now=s.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,s,r=new Promise(a=>s=a),n=setTimeout(()=>{e=!0,s()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,s=(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`))),s>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${s} dropped`)}log(e){let s=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(s-this.refilled)/1e3*this.linesPerSecond),this.refilled=s,this.unlogged>0&&s-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=s),this.tokens<1){this.unlogged===0&&(this.unloggedSince=s),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[r](`${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:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Qt),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),s=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let n=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await s.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${i}); ${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 Xt}from"node:crypto";import{readFileSync as Zt}from"node:fs";import{bind as es,bunDriver as ts,createDatabase as ss,pooledBinding as rs,sayRunning as ns,envBlock as as,createSearchWorker as os,cutOff as is,forgetUserIn as ls,MigrationOpen as cs,MigrationRefused as ds,Migrator as ue,renewingBunPool as ie,VersionNotMigrated as us}from"palgres";import{toModel as ps}from"palgres/dsl";var fs=["start","complete","rollback","plan","status","types"],hs=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function pe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!fs.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function fe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let s of e)if(s.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 he(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Zt(e,"utf8")}catch(s){throw new Error(`[palbase] db.access: ${e.href} could not be read (${s instanceof Error?s.message:String(s)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=he(t);return ps(fe(t),e===void 0?{}:{access:e})}function gs(t){return t.tables.some(e=>e.search!==void 0)}function N(t){return t.access!==void 0||t.tables.some(e=>!e.ignored&&e.columns.some(s=>s.user!==void 0&&!s.ignored))}function ge(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let s=Number(e);if(!Number.isSafeInteger(s)||s<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 s}function bs(t,e){if(t.url!==void 0||t.driver!==void 0)return;let s=e.PALBASE_DB_POOLED_URL;return s===void 0||s===""?void 0:s}function ms(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let s=Number(e);if(!Number.isSafeInteger(s)||s<4)throw new Error(`[palbase] PALBASE_DB_POOLED_CONNECTIONS is how many pooled connections the app keeps open, 4 at least \u2014 not ${e}`);return s}var ys=2,ws=5e3;async function Ps(t,e,s=ws){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let n=r,a=!1,l=!1,i=async()=>{if(n!==void 0)try{await n.unsafe("SELECT 1");return}catch{n.release(),n=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(u){throw o.release(),u}a?o.release():n=o},c=setInterval(()=>{l||a||(l=!0,i().catch(o=>d.warn(`[palbase] database: the session that says this version runs could not be opened again (${o instanceof Error?o.message:String(o)}) \u2014 tried again in ${s/1e3} s`)).finally(()=>{l=!1}))},s);return c.unref?.(),{stop(){a=!0,clearInterval(c),n?.release(),n=void 0}}}function Ss(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 le=5;function z(t,e){if(t.driver)return t.driver;let s=globalThis.Bun;if(!s)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 r=e-1;return n=>{let a=ie(()=>new s.SQL({url:n,prepare:!1,max:r})),l=ie(()=>new s.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(i,c)=>a.unsafe(i,c),begin:i=>a.current.begin(i)},engine:ts(a,l),poolSize:r,close:async()=>{await a.close({timeout:le}),await l.close({timeout:le})}}}}async function be(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function me(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let s=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=he(t);return await B("types",as(s,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function ye(t,e,s){let r=e.PALBASE_DB_OWNER_URL;if(!r)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(!hs.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=z(t,ge(e)),l=a(r),i,c=o=>d.error(`[palbase] migrate ${s}: ${o}`);try{let o=F(t),u=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),d.info(f)},shadow:f=>{let w=new URL(r);w.pathname=`/${f}`;let m=a(w.toString());return{reserve:()=>m.pool.reserve(),end:()=>m.close()}},openedBy:n,fields:()=>vs(e)});if(s==="plan"){let f=await u.plan(o);return await B(s,f),f.refusals.length>0?1:0}if(s==="status")return await B(s,await u.status()),0;let p=s==="start"?await As(u,o,n):s==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${s}: done`,{result:p}),await B(s,p),0}catch(o){return o instanceof ds?(d.error(`[palbase] migrate ${s}: refused`,{refusals:o.refusals}),c(`refused \u2014 ${o.refusals.join("; ")}`),1):is(o)?(d.error(`[palbase] migrate ${s}: cut off; run again, it goes on from where it stopped`,{error:o}),c(`cut off \u2014 ${i??ce(o)}`),75):(d.error(`[palbase] migrate ${s}: failed`,{error:o}),c(`failed \u2014 ${ce(o)}`),1)}finally{await l.close().catch(()=>{})}}async function vs(t){let e=t.PALBASE_URL,s=t.PALBASE_SECRET_KEY;if(!e||!s)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 r=T({url:e,secretKey:s}).fields;return await r.load(),r.close(),r}async function As(t,e,s){try{return await t.start(e)}catch(r){if(!(r instanceof cs)||s!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return d.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var ks=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,s=ks){return new Promise(r=>s(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
1
|
+
/*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as It,A as I,B as ut,C as pt,D as ft,E as ht,F as gt,G as bt,H as mt,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 Rt,R as _t,S as xt,T as Ot,U as Tt,V as Ct,W as Bt,X as ne,Y as Ft,Z as Lt,_ as $t,a as Z,aa as Mt,b as ee,ba as Dt,c as te,ca as Ut,d as qe,da as jt,e as Ke,ea as Nt,f as We,fa as M,g as Ve,ga as Vt,h as Ge,ha as D,i as ze,ia as G,j as He,ja as Gt,k as Ye,ka as zt,l as Je,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as st,s as rt,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/P234HHKR.js";import{a as qt,b as Kt}from"../chunks/XK7JQGKM.js";import{a as oe}from"../chunks/PM3BWYB5.js";import{a as C,b as se,c as re,f as b,g as V,h as d,j as ae,k as Wt}from"../chunks/EZW67SHF.js";import"../chunks/CRK2KWFW.js";import"../chunks/D6ZVNWQ2.js";import{d as T,j as je,k as Ne,l as J,m as $,y as Q,z as X}from"../chunks/JFVOERVR.js";import"../chunks/KOX5W2ID.js";import"../chunks/FQEGZTR3.js";import{r as Ue}from"../chunks/BZYYDYLF.js";import"../chunks/LQF6CVJR.js";import"../chunks/CE6XFRSZ.js";import{b as _,c as W}from"../chunks/ICNSKNUT.js";import"../chunks/CPTZEOT3.js";import"../chunks/YGIYMCYC.js";import"reflect-metadata";import{existsSync as H,writeFileSync as Is,writeSync as Ms}from"node:fs";import{createServer as Ds}from"node:http";import{dirname as x,join as Y,resolve as Oe}from"node:path";import{Readable as Us}from"node:stream";var Ht=2e3,Yt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Qt=512,U=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,s={}){this.sink=e,this.linesPerSecond=s.linesPerSecond??10,this.batchSize=Math.min(100,s.batchSize??100),this.flushMs=s.flushMs??2e3,this.maxPending=s.maxPending??2e3,this.sendMs=s.sendMs??Yt,this.shutdownMs=s.shutdownMs??Ht,this.now=s.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,s,r=new Promise(a=>s=a),n=setTimeout(()=>{e=!0,s()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,s=(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`))),s>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${s} dropped`)}log(e){let s=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(s-this.refilled)/1e3*this.linesPerSecond),this.refilled=s,this.unlogged>0&&s-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=s),this.tokens<1){this.unlogged===0&&(this.unloggedSince=s),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[r](`${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:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Qt),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),s=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let n=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await s.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${i}); ${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 Xt}from"node:crypto";import{readFileSync as Zt}from"node:fs";import{bind as es,bunDriver as ts,createDatabase as ss,pooledBinding as rs,sayRunning as ns,envBlock as as,createSearchWorker as os,cutOff as is,forgetUserIn as ls,MigrationOpen as cs,MigrationRefused as ds,Migrator as ue,renewingBunPool as ie,VersionNotMigrated as us}from"palgres";import{toModel as ps}from"palgres/dsl";var fs=["start","complete","rollback","plan","status","types"],hs=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function pe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!fs.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function fe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let s of e)if(s.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 he(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Zt(e,"utf8")}catch(s){throw new Error(`[palbase] db.access: ${e.href} could not be read (${s instanceof Error?s.message:String(s)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=he(t);return ps(fe(t),e===void 0?{}:{access:e})}function gs(t){return t.tables.some(e=>e.search!==void 0)}function N(t){return t.access!==void 0||t.tables.some(e=>!e.ignored&&e.columns.some(s=>s.user!==void 0&&!s.ignored))}function ge(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let s=Number(e);if(!Number.isSafeInteger(s)||s<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 s}function bs(t,e){if(t.url!==void 0||t.driver!==void 0)return;let s=e.PALBASE_DB_POOLED_URL;return s===void 0||s===""?void 0:s}function ms(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let s=Number(e);if(!Number.isSafeInteger(s)||s<4)throw new Error(`[palbase] PALBASE_DB_POOLED_CONNECTIONS is how many pooled connections the app keeps open, 4 at least \u2014 not ${e}`);return s}var ys=2,ws=5e3;async function Ps(t,e,s=ws){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let n=r,a=!1,l=!1,i=async()=>{if(n!==void 0)try{await n.unsafe("SELECT 1");return}catch{n.release(),n=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(u){throw o.release(),u}a?o.release():n=o},c=setInterval(()=>{l||a||(l=!0,i().catch(o=>d.warn(`[palbase] database: the session that says this version runs could not be opened again (${o instanceof Error?o.message:String(o)}) \u2014 tried again in ${s/1e3} s`)).finally(()=>{l=!1}))},s);return c.unref?.(),{stop(){a=!0,clearInterval(c),n?.release(),n=void 0}}}function Ss(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 le=5;function z(t,e){if(t.driver)return t.driver;let s=globalThis.Bun;if(!s)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 r=e-1;return n=>{let a=ie(()=>new s.SQL({url:n,prepare:!1,max:r})),l=ie(()=>new s.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(i,c)=>a.unsafe(i,c),begin:i=>a.current.begin(i)},engine:ts(a,l),poolSize:r,close:async()=>{await a.close({timeout:le}),await l.close({timeout:le})}}}}async function be(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function me(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let s=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=he(t);return await B("types",as(s,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function ye(t,e,s){let r=e.PALBASE_DB_OWNER_URL;if(!r)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(!hs.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=z(t,ge(e)),l=a(r),i,c=o=>d.error(`[palbase] migrate ${s}: ${o}`);try{let o=F(t),u=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),d.info(f)},shadow:f=>{let w=new URL(r);w.pathname=`/${f}`;let m=a(w.toString());return{reserve:()=>m.pool.reserve(),end:()=>m.close()}},openedBy:n,fields:()=>vs(e)});if(s==="plan"){let f=await u.plan(o);return await B(s,f),f.refusals.length>0?1:0}if(s==="status")return await B(s,await u.status()),0;let p=s==="start"?await As(u,o,n):s==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${s}: done`,{result:p}),await B(s,p),0}catch(o){return o instanceof ds?(d.error(`[palbase] migrate ${s}: refused`,{refusals:o.refusals}),c(`refused \u2014 ${o.refusals.join("; ")}`),1):is(o)?(d.error(`[palbase] migrate ${s}: cut off; run again, it goes on from where it stopped`,{error:o}),c(`cut off \u2014 ${i??ce(o)}`),75):(d.error(`[palbase] migrate ${s}: failed`,{error:o}),c(`failed \u2014 ${ce(o)}`),1)}finally{await l.close().catch(()=>{})}}async function vs(t){let e=t.PALBASE_URL,s=t.PALBASE_SECRET_KEY;if(!e||!s)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 r=T({url:e,secretKey:s}).fields;return await r.load(),r.close(),r}async function As(t,e,s){try{return await t.start(e)}catch(r){if(!(r instanceof cs)||s!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return d.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var ks=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,s=ks){return new Promise(r=>s(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,r))}function ce(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
4
|
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function Es(t,e){try{return await new ue(t).plan(e)}catch{return}}var de="palbase.idempotency_keys.response_body";function Rs(t,e){let s=null,r=!1,n=async()=>{let i=e.currentKey();if(!(r||i===s)){r=!0;try{let c=await t.reseal();s=i;let o=c.reduce((u,p)=>u+p.resealed,0);o>0&&d.info(`[palbase] fields: ${o} value(s) sealed again with key ${i}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${i} stopped; tried again in a minute`,{error:c})}finally{r=!1}}},a=setTimeout(n,1e4),l=setInterval(n,6e4);for(let i of[a,l])i.unref?.();return()=>{clearTimeout(a),clearInterval(l)}}var j=class extends Error{digest;plan;constructor(e,s){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>)`,...s?_s(s):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=s}};function _s(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 s of t.changes)e.push(` + ${s}`);for(let s of t.refusals)e.push(` \u2717 ${s}`);return e}var xs=8e4;async function we(t,e,s,r){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=fe(t),l=F(t),i=bs(t,e),c=z(t,i===void 0?ge(e):ys)(n),o,u;try{let p=!1,f=g=>{p||(p=!0,d.warn(`[palbase] database: not answering yet (${g instanceof Error?g.message:String(g)}) \u2014 waiting for it, as one waking does`))},w=await es(c.engine,l,{waitMs:r.onPlatform?xs:0,onUnreachable:f}).catch(async g=>{throw r.onPlatform||!(g instanceof us)?g:new j(g.digest,await Es(c.pool,l))});i!==void 0&&(u=await Ps(c.pool,ns(w)),o=z(t,ms(e))(i));let m=o??c,A=Xt("sha256",s).update("palgres page cursor").digest("hex"),y=t.embed??r.embed,h=r.fields,k=await ss({sql:m.engine,schemas:a,binding:o===void 0?w:rs(w),...o===void 0?{}:{prepare:!1},cursorSecret:A,admission:Ss(m.poolSize),embed:y,log:g=>d.warn(`[palbase] ${g}`),fields:async()=>(await h.load(),h)}),E=h.loaded?Rs(k,h):()=>{},R=gs(l)?os({sql:m.engine,embed:y,log:g=>d.info(`[palbase] ${g}`)}):void 0;return{model:l,binding:w,app:k,requests:t.requests??"caller",forget:(g,P)=>ls({attempt:v=>P.$attempt(v)},w,l,g),...R?{search:R}:{},keptAnswers:{seal:g=>h.loaded?h.encrypt(de,g):g,open:async g=>h.isEncrypted(g)?(h.loaded||await h.load(),h.decrypt(de,g)):g},close:async()=>{E(),h.close(),await o?.close(),u?.stop(),await c.close()}}}catch(p){throw await o?.close().catch(()=>{}),u?.stop(),await c.close(),p}}function Os(t){let e=Buffer.from(t,"base64"),s=new Array(e.byteLength/4);for(let r=0;r<s.length;r++)s[r]=e.readFloatLE(r*4);return s}function Pe(t){return async({texts:e,model:s,dimensions:r})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:s,dimensions:r}});return{model:n.model,vectors:n.vectors.map(Os)}}}var Ts=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Se(t,e,s){let r=[],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"&&r.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&r.push("palbase.url / PALBASE_URL is the project origin alone")}catch{r.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let l=t.projectId??e.PALBASE_PROJECT_ID??"";Ts.test(l)||r.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let i=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(i)||r.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)&&r.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 o=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(s.needsWebhookSecret&&(c!==void 0||o!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(o??"")&&r.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"),r.length>0)throw new Error(`[palbase] the app cannot start:
|
|
@@ -9,4 +9,4 @@ ${r.join(`
|
|
|
9
9
|
`)}
|
|
10
10
|
`}async function ke(t,e,s=Bs){let r=Buffer.from(e,"utf8");for(let n=0;n<r.length;)try{n+=s(t,r,n,r.length-n)}catch(a){if(a.code!=="EAGAIN")throw a;await new Promise(l=>setTimeout(l,5))}}var Ee=2e4,Re=5e3,js=15e3,Ns="/_palbase/health";function qs(t){let e=new Set,s=r=>{if(e.has(r))return!1;e.add(r);let n=I(r,Z);return n?n.providers.some(a=>I(a,ee)!==void 0&&I(a,te)===void 0)||n.imports.some(s):!1};return t.some(s)}var Ks={async create(t,e={}){let s=Array.isArray(t)?t:[t],r=e.env??process.env,n=pe(r);if(n!==void 0){let P=n==="types"?await me(e.db):e.db?await ye(e.db,r,n):await be(n);throw process.exit(P),new q(P)}let a=r.PALBASE_CONTRACT_OUT;if(a){let P;try{await xe(_e(r)),P=await Ws(s,e,r)}catch(v){throw Ms(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
|
|
11
11
|
`),process.exit(1),new L}throw a==="/dev/stdout"?await ke(1,Ae(P)):Is(a,`${P}
|
|
12
|
-
`),process.exit(0),new L}let l=_e(r),i=await xe(l);i&&d.info(`[palbase] strings: ${i.source} and ${i.locales.length-1} other language(s), ${Object.keys(i.strings).length} sentence(s), from ${l}/palbase/strings`),ae(i?void 0:l);let c=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&d.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let u=qs(s)||c!==void 0&&N(c),p=Se(e.palbase??{},r,{needsWebhookSecret:u});u&&p.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=T({url:p.url,secretKey:p.secretKey}),w=e.port??Number(r.PORT??"8080");if(!Number.isInteger(w)||w<0||w>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let m=e.db?await we(e.db,r,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;m&&d.info(`[palbase] database: version ${m.binding.version}`);let A=m&&N(m.model)?{"user.deleted":[P=>Vs(m,P)]}:void 0,y=p.platformSecret===void 0?void 0:{secret:p.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),k=()=>D({modules:s,verifier:new $({issuer:p.url,projectId:p.projectId,standing:J({url:p.url,secretKey:p.secretKey})}),server:f,webhookSecret:p.webhookSecret,env:r,projectId:p.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Hs(e.cors,r.PALBASE_WEB_ORIGINS),platform:y,events:A,database:m&&{app:m.app,requests:m.requests,keptAnswers:m.keptAnswers},strings:i}),E=k(),R=e.boot?.attempts??5,g=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(v){if(P>=R)throw d.error(`[palbase] the app did not start after ${R} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${P} of ${R}); trying again in ${g} ms`,{error:v}),await new Promise(De=>setTimeout(De,g)),g*=2,E=k()}return Gs(E,f,w,e.host??"0.0.0.0",e.exitOnFatal??!0,m)}};function _e(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let s=x(Oe(e));for(;!H(Y(s,"package.json"))&&x(s)!==s;)s=x(s);return H(Y(s,"package.json"))?s:process.cwd()}async function xe(t){try{return await oe(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Ws(t,e,s){let r=Oe(s.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=x(r);for(;!H(Y(n,"package.json"))&&x(n)!==n;)n=x(n);let{analyzeProject:a}=await import("../chunks/IZWB7FGX.js"),{routeContracts:l}=await import("../chunks/7SGTDHXJ.js"),i=a(n,r);for(let u of i.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",o=D({modules:t,verifier:new $({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:T({url:c,secretKey:"pb_contract_s"}),env:s,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 l(i.routes),errors:ne()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var L=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},q=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Vs(t,e){let s=e.data?.user_id;if(typeof s!="string"||s==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(s,V.$asService());d.info(`[palbase] user ${s} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them${r.relationships===void 0?"":`, ${r.relationships} relationship(s) of the access schema taken back`}`)}async function Gs(t,e,s,r,n,a){let l,i={on:!1},c=(y,h)=>new URL(y.url).pathname===Ns&&y.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(y,h),o=Ds((y,h)=>{zs(c,y,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((y,h)=>{o.once("error",h),o.listen(s,r,()=>y())})}catch(y){throw await t.stop(),await a?.close(),y}let u=o.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=y=>l??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let k=setTimeout(()=>o.closeAllConnections(),y);await h,clearTimeout(k),process.off("SIGINT",m),process.off("uncaughtException",A),process.off("unhandledRejection",A);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",m)}})(),f=()=>p(Ee),w=!1,m=()=>{if(w){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}w=!0;let y=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+js);y.unref(),f().then(()=>{clearTimeout(y),process.exit(0)},h=>{clearTimeout(y),d.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},A=y=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:y});let h=setTimeout(()=>process.exit(1),Re+1e3);p(Re).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",m),process.once("SIGINT",m),n&&(process.on("uncaughtException",A),process.on("unhandledRejection",A)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function zs(t,e,s,r){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{s.statusCode=400,s.end();return}let l=new Headers;for(let[p,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let w of f)l.append(p,w);else l.set(p,f);let i=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;s.on("close",()=>{s.writableFinished||c.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Us.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(o,{remoteAddress:e.socket.remoteAddress,target:n});if(s.statusCode=u.status,u.headers.forEach((p,f)=>s.setHeader(f,p)),r.on&&s.setHeader("connection","close"),u.body)for await(let p of u.body)s.write(p);s.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),s.headersSent||(s.statusCode=500),s.end()}}function Hs(t,e,s=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let n=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&s(`[palbase] the project's web origins ${a.map(i=>JSON.stringify(i)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let l=[...new Set([...t?.origins??[],...n])];return l.length===0?t:{...t,origins:l}}import{bigint as an,boolean as on,check as ln,date as cn,defineSchema as dn,defineTable as un,enumType as pn,foreignKey as fn,index as hn,integer as gn,jsonb as bn,numeric as mn,ownedByUser as yn,policy as wn,raw as Pn,sqlType as Sn,text as vn,timestamp as An,userRef as kn,uuid as En}from"palgres/dsl";import{AccessRefused as _n}from"palgres";import{increment as On,now as Tn}from"palgres";function O(t){if(t instanceof _)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function S(t,e){try{let s=await t();return{data:await e(s.data),error:null,status:s.status}}catch(s){return O(s)}}var Ys=C("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Js=100,Qs=1e3,Xs=168*3600,Zs={s:1,m:60,h:3600,d:86400};function er(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let s=0;for(let[,r,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))s+=Math.round(Number(r)*Zs[n]*1e3);return Math.ceil(s/1e3)}function Ie(t,e,s){let r="getPublicUrl",n;try{n=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof _&&l.code==="invalid_path_parameter"?new _({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):l}let a=`${b.url}/storage/public/${W(r,"bucket",t)}/${n}`;return s?`${a}?variant=${encodeURIComponent(s)}`:a}function Te(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,Ie(t.bucket,t.path,e)]))}}function tr(t){return{async upload(e,s,r){let n=r?.contentType??(s instanceof Blob&&s.type!==""?s.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:s,contentType:n});return{data:Te(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}:O(a)}},async download(e){try{let s=await b.storage.getObject({path:{bucket:t,path:e}});if(s.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=s.data;try{return{data:await r.blob(),error:null,status:s.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(s){return O(s)}},getPublicUrl(e,s){return Ie(t,e,s?.variant)},async createSignedUrl(e,s){let r=er(s?.expiresIn);return r===void 0||r<1||r>Xs?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(s?.expiresIn)})`},status:400}:S(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,s){let r=s?.limit??Js,n=s?.offset??0;if(!Number.isInteger(r)||r<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=[],l,i=200;try{for(;a.length<r;){let c=Math.max(1,Math.min(Qs,n+r-a.length)),o=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...l?{cursor:l}:{}}});i=o.status;for(let u of o.data.objects)n>0?n--:a.length<r&&a.push(Te(u));if(l=o.data.next_cursor,!l)break}}catch(c){return O(c)}return{data:a,error:null,status:i}},async remove(e){let s=[];for(let r of e){try{await b.storage.deleteObject({path:{bucket:t,path:r}})}catch(n){return O(n)}s.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:s,error:null,status:200}},move(e,s){return S(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})},copy(e,s){return S(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})}}}var sr={bucket:tr},Ce=t=>se("Storage",t,sr),rr={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},nr=C("Notifications",{push:{send(t){let{to:e,...s}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return S(()=>b.notify.sendPush({body:{...s,to:r}}),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:s,...r}=t,n={...r,...s!==void 0?{template:s}:{}};if(!Array.isArray(e))return S(()=>b.notify.sendEmail({body:{...n,to:e}}),i=>({...i.message_id!==void 0?{message_id:i.message_id}:{},...i.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let i of e)try{let c=await b.notify.sendEmail({body:{...n,to:i}});l=c.status,a.push(c.data.message_id??null)}catch(c){return O(c)}return{data:{message_ids:a},error:null,status:l}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Le=t=>t==="override"?"user":t,ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Me(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:Me();return S(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),s=>s.values??{})}var $e={setOverrideForUser:(t,e,s)=>S(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:s}}),r=>({key:r.key,value:r.value,source:Le(r.source)})),setOverridesForUser:(t,e)=>S(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),s=>({values:s.values??{}})),clearOverrideForUser:(t,e)=>S(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),s=>({key:s.key,value:s.value,source:Le(s.source)})),clearAllOverridesForUser:t=>S(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>S(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},or=C("Flags",{async isEnabled(t,e){let s=r=>(d.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?s(`${r.error.code}: ${r.error.message}`):Be(r.data[t])}catch(r){return s(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let s=await K(e);return s.error?{data:null,error:s.error,status:s.status}:{data:Fe(s.data[t]),error:null,status:s.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([s,r])=>{let n=Fe(r);return{name:s,enabled:Be(r),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,s){let r,n=!1,a;s!==void 0?(r=e,n=!0,a=s):ar(e)?a=e:e!==void 0&&(r=e,n=!0);let l=await K(a);if(l.error)return n?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?r??null:i,error:null,status:l.status}},async setOverride(t,e){let s=Me();return s?$e.setOverrideForUser(s,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 $e}}),ir=C("Realtime",{broadcast(t,e,s){return S(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:s??{}}]}}),()=>{})},state:{set(t,e,s){return S(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:s}]}}),()=>{})},clear(t,e){return S(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as Dn}from"zod";export{_n as AccessRefused,nt as AttestedDevice,Ne as AuthUnavailable,vt as Authorize,Lt as BadRequest,Ye as Body,Gt as CACHE_MAX_TTL,zt as Cache,wt as ChatPart,rt as Client,$t as Conflict,L as ContractRunEnded,qe as Controller,ct as Cron,V as Database,It as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,or as Flags,Bt as Forbidden,St as Gateway,Pt as GatewayRefusal,Ke as Get,Qe as Headers,Mt as HttpError,ot as Injectable,d as Log,Vt as MAX_BODY_BYTES,q as MigrationRunEnded,it as Module,Dt as NotFound,nr as Notifications,lt as On,kt as OnConnect,Et as OnDisconnect,Rt as OnEmpty,At as OnFirst,et as OptionalUser,Tt as PalError,b as Palbase,_ as PalbaseError,Ks as PalbaseFactory,Xe as Param,Ge as Patch,We as Post,Ve as Put,He as Query,Je as QueryParams,ir as Realtime,tt as Req,st as RequestId,at as Resolve,j as SchemaNotPushed,Ys as Secrets,Ut as SerializationFailure,rr as Storage,_t as Subscribe,ht as Task,ft as TaskFailure,gt as Tasks,bt as TestUserTemplate,je as TokenError,$ as TokenVerifier,jt as TooManyRequests,Ct as Unauthorized,Nt as UniqueViolation,mt as Upload,yt as UploadedObject,Ze as User,dt as Webhook,an as bigint,on as boolean,ln as check,D as createApp,cn as date,Ft as defineError,dn as defineSchema,un as defineTable,Kt as encrypt,qt as encrypted,pn as enumType,fn as foreignKey,ut as getRegisteredControllers,pt as getRoutes,xt as getWebhookManifest,On as increment,hn as index,gn as integer,bn as jsonb,Tn as now,mn as numeric,yn as ownedByUser,wn as policy,Pn as raw,Sn as sqlType,Wt as t,vn as text,An as timestamp,kn as userRef,En as uuid,Dn as z};
|
|
12
|
+
`),process.exit(0),new L}let l=_e(r),i=await xe(l);i&&d.info(`[palbase] strings: ${i.source} and ${i.locales.length-1} other language(s), ${Object.keys(i.strings).length} sentence(s), from ${l}/palbase/strings`),ae(i?void 0:l);let c=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&d.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let u=qs(s)||c!==void 0&&N(c),p=Se(e.palbase??{},r,{needsWebhookSecret:u});u&&p.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=T({url:p.url,secretKey:p.secretKey}),w=e.port??Number(r.PORT??"8080");if(!Number.isInteger(w)||w<0||w>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let m=e.db?await we(e.db,r,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;m&&d.info(`[palbase] database: version ${m.binding.version}`);let A=m&&N(m.model)?{"user.deleted":[P=>Vs(m,P)]}:void 0,y=p.platformSecret===void 0?void 0:{secret:p.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),k=()=>D({modules:s,verifier:new $({issuer:p.url,projectId:p.projectId,standing:J({url:p.url,secretKey:p.secretKey})}),server:f,webhookSecret:p.webhookSecret,env:r,projectId:p.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Hs(e.cors,r.PALBASE_WEB_ORIGINS),platform:y,events:A,database:m&&{app:m.app,requests:m.requests,keptAnswers:m.keptAnswers},strings:i}),E=k(),R=e.boot?.attempts??5,g=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(v){if(P>=R)throw d.error(`[palbase] the app did not start after ${R} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${P} of ${R}); trying again in ${g} ms`,{error:v}),await new Promise(De=>setTimeout(De,g)),g*=2,E=k()}return Gs(E,f,w,e.host??"0.0.0.0",e.exitOnFatal??!0,m)}};function _e(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let s=x(Oe(e));for(;!H(Y(s,"package.json"))&&x(s)!==s;)s=x(s);return H(Y(s,"package.json"))?s:process.cwd()}async function xe(t){try{return await oe(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Ws(t,e,s){let r=Oe(s.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=x(r);for(;!H(Y(n,"package.json"))&&x(n)!==n;)n=x(n);let{analyzeProject:a}=await import("../chunks/OE772CLE.js"),{routeContracts:l}=await import("../chunks/Y4FKEIZV.js"),i=a(n,r);for(let u of i.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",o=D({modules:t,verifier:new $({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:T({url:c,secretKey:"pb_contract_s"}),env:s,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 l(i.routes),errors:ne()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var L=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},q=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Vs(t,e){let s=e.data?.user_id;if(typeof s!="string"||s==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(s,V.$asService());d.info(`[palbase] user ${s} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them${r.relationships===void 0?"":`, ${r.relationships} relationship(s) of the access schema taken back`}`)}async function Gs(t,e,s,r,n,a){let l,i={on:!1},c=(y,h)=>new URL(y.url).pathname===Ns&&y.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(y,h),o=Ds((y,h)=>{zs(c,y,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((y,h)=>{o.once("error",h),o.listen(s,r,()=>y())})}catch(y){throw await t.stop(),await a?.close(),y}let u=o.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=y=>l??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let k=setTimeout(()=>o.closeAllConnections(),y);await h,clearTimeout(k),process.off("SIGINT",m),process.off("uncaughtException",A),process.off("unhandledRejection",A);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",m)}})(),f=()=>p(Ee),w=!1,m=()=>{if(w){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}w=!0;let y=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+js);y.unref(),f().then(()=>{clearTimeout(y),process.exit(0)},h=>{clearTimeout(y),d.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},A=y=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:y});let h=setTimeout(()=>process.exit(1),Re+1e3);p(Re).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",m),process.once("SIGINT",m),n&&(process.on("uncaughtException",A),process.on("unhandledRejection",A)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function zs(t,e,s,r){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{s.statusCode=400,s.end();return}let l=new Headers;for(let[p,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let w of f)l.append(p,w);else l.set(p,f);let i=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;s.on("close",()=>{s.writableFinished||c.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Us.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(o,{remoteAddress:e.socket.remoteAddress,target:n});if(s.statusCode=u.status,u.headers.forEach((p,f)=>s.setHeader(f,p)),r.on&&s.setHeader("connection","close"),u.body)for await(let p of u.body)s.write(p);s.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),s.headersSent||(s.statusCode=500),s.end()}}function Hs(t,e,s=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let n=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&s(`[palbase] the project's web origins ${a.map(i=>JSON.stringify(i)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let l=[...new Set([...t?.origins??[],...n])];return l.length===0?t:{...t,origins:l}}import{bigint as an,boolean as on,check as ln,date as cn,defineSchema as dn,defineTable as un,enumType as pn,foreignKey as fn,index as hn,integer as gn,jsonb as bn,numeric as mn,ownedByUser as yn,policy as wn,raw as Pn,sqlType as Sn,text as vn,timestamp as An,userRef as kn,uuid as En}from"palgres/dsl";import{AccessRefused as _n}from"palgres";import{increment as On,now as Tn}from"palgres";function O(t){if(t instanceof _)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function S(t,e){try{let s=await t();return{data:await e(s.data),error:null,status:s.status}}catch(s){return O(s)}}var Ys=C("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Js=100,Qs=1e3,Xs=168*3600,Zs={s:1,m:60,h:3600,d:86400};function er(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let s=0;for(let[,r,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))s+=Math.round(Number(r)*Zs[n]*1e3);return Math.ceil(s/1e3)}function Ie(t,e,s){let r="getPublicUrl",n;try{n=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof _&&l.code==="invalid_path_parameter"?new _({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):l}let a=`${b.url}/storage/public/${W(r,"bucket",t)}/${n}`;return s?`${a}?variant=${encodeURIComponent(s)}`:a}function Te(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,Ie(t.bucket,t.path,e)]))}}function tr(t){return{async upload(e,s,r){let n=r?.contentType??(s instanceof Blob&&s.type!==""?s.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:s,contentType:n});return{data:Te(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}:O(a)}},async download(e){try{let s=await b.storage.getObject({path:{bucket:t,path:e}});if(s.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=s.data;try{return{data:await r.blob(),error:null,status:s.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(s){return O(s)}},getPublicUrl(e,s){return Ie(t,e,s?.variant)},async createSignedUrl(e,s){let r=er(s?.expiresIn);return r===void 0||r<1||r>Xs?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(s?.expiresIn)})`},status:400}:S(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,s){let r=s?.limit??Js,n=s?.offset??0;if(!Number.isInteger(r)||r<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=[],l,i=200;try{for(;a.length<r;){let c=Math.max(1,Math.min(Qs,n+r-a.length)),o=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...l?{cursor:l}:{}}});i=o.status;for(let u of o.data.objects)n>0?n--:a.length<r&&a.push(Te(u));if(l=o.data.next_cursor,!l)break}}catch(c){return O(c)}return{data:a,error:null,status:i}},async remove(e){let s=[];for(let r of e){try{await b.storage.deleteObject({path:{bucket:t,path:r}})}catch(n){return O(n)}s.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:s,error:null,status:200}},move(e,s){return S(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})},copy(e,s){return S(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})}}}var sr={bucket:tr},Ce=t=>se("Storage",t,sr),rr={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},nr=C("Notifications",{push:{send(t){let{to:e,...s}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return S(()=>b.notify.sendPush({body:{...s,to:r}}),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:s,...r}=t,n={...r,...s!==void 0?{template:s}:{}};if(!Array.isArray(e))return S(()=>b.notify.sendEmail({body:{...n,to:e}}),i=>({...i.message_id!==void 0?{message_id:i.message_id}:{},...i.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let i of e)try{let c=await b.notify.sendEmail({body:{...n,to:i}});l=c.status,a.push(c.data.message_id??null)}catch(c){return O(c)}return{data:{message_ids:a},error:null,status:l}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Le=t=>t==="override"?"user":t,ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Me(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:Me();return S(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),s=>s.values??{})}var $e={setOverrideForUser:(t,e,s)=>S(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:s}}),r=>({key:r.key,value:r.value,source:Le(r.source)})),setOverridesForUser:(t,e)=>S(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),s=>({values:s.values??{}})),clearOverrideForUser:(t,e)=>S(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),s=>({key:s.key,value:s.value,source:Le(s.source)})),clearAllOverridesForUser:t=>S(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>S(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},or=C("Flags",{async isEnabled(t,e){let s=r=>(d.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?s(`${r.error.code}: ${r.error.message}`):Be(r.data[t])}catch(r){return s(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let s=await K(e);return s.error?{data:null,error:s.error,status:s.status}:{data:Fe(s.data[t]),error:null,status:s.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([s,r])=>{let n=Fe(r);return{name:s,enabled:Be(r),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,s){let r,n=!1,a;s!==void 0?(r=e,n=!0,a=s):ar(e)?a=e:e!==void 0&&(r=e,n=!0);let l=await K(a);if(l.error)return n?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?r??null:i,error:null,status:l.status}},async setOverride(t,e){let s=Me();return s?$e.setOverrideForUser(s,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 $e}}),ir=C("Realtime",{broadcast(t,e,s){return S(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:s??{}}]}}),()=>{})},state:{set(t,e,s){return S(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:s}]}}),()=>{})},clear(t,e){return S(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as Dn}from"zod";export{_n as AccessRefused,nt as AttestedDevice,Ne as AuthUnavailable,vt as Authorize,Lt as BadRequest,Ye as Body,Gt as CACHE_MAX_TTL,zt as Cache,wt as ChatPart,rt as Client,$t as Conflict,L as ContractRunEnded,qe as Controller,ct as Cron,V as Database,It as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,or as Flags,Bt as Forbidden,St as Gateway,Pt as GatewayRefusal,Ke as Get,Qe as Headers,Mt as HttpError,ot as Injectable,d as Log,Vt as MAX_BODY_BYTES,q as MigrationRunEnded,it as Module,Dt as NotFound,nr as Notifications,lt as On,kt as OnConnect,Et as OnDisconnect,Rt as OnEmpty,At as OnFirst,et as OptionalUser,Tt as PalError,b as Palbase,_ as PalbaseError,Ks as PalbaseFactory,Xe as Param,Ge as Patch,We as Post,Ve as Put,He as Query,Je as QueryParams,ir as Realtime,tt as Req,st as RequestId,at as Resolve,j as SchemaNotPushed,Ys as Secrets,Ut as SerializationFailure,rr as Storage,_t as Subscribe,ht as Task,ft as TaskFailure,gt as Tasks,bt as TestUserTemplate,je as TokenError,$ as TokenVerifier,jt as TooManyRequests,Ct as Unauthorized,Nt as UniqueViolation,mt as Upload,yt as UploadedObject,Ze as User,dt as Webhook,an as bigint,on as boolean,ln as check,D as createApp,cn as date,Ft as defineError,dn as defineSchema,un as defineTable,Kt as encrypt,qt as encrypted,pn as enumType,fn as foreignKey,ut as getRegisteredControllers,pt as getRoutes,xt as getWebhookManifest,On as increment,hn as index,gn as integer,bn as jsonb,Tn as now,mn as numeric,yn as ownedByUser,wn as policy,Pn as raw,Sn as sqlType,Wt as t,vn as text,An as timestamp,kn as userRef,En as uuid,Dn as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as l,c as g,d as f,e as m}from"../chunks/
|
|
1
|
+
/*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as l,c as g,d as f,e as m}from"../chunks/37KUGTKN.js";import{a as u}from"../chunks/PM3BWYB5.js";import{c,i as p}from"../chunks/EZW67SHF.js";import"../chunks/CRK2KWFW.js";import"../chunks/D6ZVNWQ2.js";import"../chunks/KOX5W2ID.js";import"../chunks/FQEGZTR3.js";import"../chunks/BZYYDYLF.js";import"../chunks/CE6XFRSZ.js";import"../chunks/ICNSKNUT.js";import"../chunks/CPTZEOT3.js";import"../chunks/YGIYMCYC.js";import"reflect-metadata";import{randomUUID as y}from"node:crypto";import{createFakeClient as w,typedDatabase as h}from"palgres/testing";function b(s,t,e){if(e?.acceptLanguage!==void 0&&e.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:n,...o}=s,a=e?.strings;return c.run({requestId:`test_${y()}`,database:n===void 0?void 0:d(n),services:o,...a!==void 0?{strings:a,locales:p(e?.acceptLanguage??null,a.source),usedLocales:[]}:{}},t)}function T(){let s=new Map,t=new Map,e=[],n=a=>{if(s.has(a))return s.get(a);if(t.has(a))return t.get(a);if(e.includes(a)){let r=[...e.slice(e.indexOf(a)),a].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${r.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}e.push(a);try{let r=Reflect.getMetadata("design:paramtypes",a)??[],i=new a(...r.map(n));return t.set(a,i),i}finally{e.pop()}},o={with(a,r){return s.set(a,r),o},get:a=>n(a)};return o}var k="a database in memory keeps rows, not relationships, and answers no access question \u2014 give it the schema (fakeDatabase({ access: <the schema file's text> })), or test what asks Database.$access against Postgres; the schema itself is held to its expectations with `palbase access:test`";function d(s){let t=s.access;return h(s,t===void 0?{unanswered:k}:{access:t.names,via:t.via,as:"authenticated"})}function v(s={}){let t=w(s);return{db:d(t),raw:t,queries:t.queries,seed:(e,n)=>t.seed(e,n),inserted:e=>t.inserted(e),updated:e=>t.updated(e),deleted:e=>t.deleted(e),signedInAs(e){if(!t.access)throw new TypeError("fakeDatabase().signedInAs: this database was made without an access schema \u2014 fakeDatabase({ access: <the schema file's text> })");t.access.signedInAs(e)}}}export{l as TestApiError,m as api,g as createTestApi,v as fakeDatabase,T as isolated,u as loadStringsTable,f as testRun,b as withServices};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b}from"./
|
|
1
|
+
/*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b}from"./KOX5W2ID.js";import{a as k,b as A}from"./CPTZEOT3.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as O,g as w,l as F,m as _,s as D}from"./22GRHCVI.js";import{b as h}from"./QFZ4GCJH.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=j(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var X={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function U(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.68.0"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let u=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var Y={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function G(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:Y,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
|
|
1
|
+
/*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as O,g as w,l as F,m as _,s as D}from"./CD2TYINV.js";import{b as h}from"./ICNSKNUT.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=j(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var X={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function U(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.69.1"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let u=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var Y={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function G(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:Y,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
|