palbase 0.47.0 → 0.47.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/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +8 -8
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{6ZLGGFVO.js → 25P2SZXG.js} +2 -2
- package/dist/chunks/{GFEZR5PZ.js → 3KGKMKHP.js} +2 -2
- package/dist/chunks/{W2UIFG2K.js → 4ZIV6DRV.js} +1 -1
- package/dist/chunks/{DG5OM7OE.js → 5VL5SBYY.js} +2 -2
- package/dist/chunks/{VK4RPW5V.js → 6QZOMJZD.js} +2 -2
- package/dist/chunks/{F6OQEGNQ.js → BMLS34GG.js} +2 -2
- package/dist/chunks/{ZPAMHNWK.js → BZ3UWVAE.js} +1 -1
- package/dist/chunks/{ZUCLHMCN.js → DDWWN5GR.js} +2 -2
- package/dist/chunks/{QMC5FETR.js → IVULOJ4X.js} +2 -2
- package/dist/chunks/{XK24H3DU.js → IWKPXNQI.js} +2 -2
- package/dist/chunks/{7F44AWRP.js → LBAO4ATA.js} +2 -2
- package/dist/chunks/{QOEHX5GR.js → LKLBWDJ4.js} +1 -1
- package/dist/chunks/{JNWRXHQW.js → M5NO46CY.js} +2 -2
- package/dist/chunks/{KQYLME2O.js → Q5OG7ZS5.js} +2 -2
- package/dist/chunks/{TEOG7F4X.js → R6SVF3Q6.js} +1 -1
- package/dist/chunks/{OIHDSNG5.js → TL3NBGBL.js} +1 -1
- package/dist/chunks/{LVGB4GZA.js → TPQLHLA3.js} +2 -2
- package/dist/chunks/{3GMO7PBT.js → TY64APAC.js} +2 -2
- package/dist/chunks/{6X2RHXFE.js → V2H26EAT.js} +2 -2
- package/dist/chunks/{XQT5FV33.js → VWJMRXQJ.js} +2 -2
- package/dist/chunks/{4WNQ74NR.js → XMH2U63C.js} +1 -1
- package/dist/chunks/{6XUYDPJ4.js → XXVAFTAU.js} +2 -2
- package/dist/chunks/{FKF4XTJV.js → ZK2IPLYN.js} +1 -1
- package/dist/cli.js +3 -3
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/backend/src/database.d.ts +22 -3
- package/types/internal/src/modules/machines.d.ts +3 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.47.
|
|
2
|
-
import{e as tt,g as st,h as it}from"./QMC5FETR.js";import{h as nt}from"./KQYLME2O.js";import{a as et}from"./3GMO7PBT.js";import{r as Ye,t as Qe,u as Ze}from"./OIHDSNG5.js";import{b as H,c as $,e as Be,f as Je,i as _e,j as V,k as ze}from"./6ZLGGFVO.js";import{a as Xe,b as B}from"./XK24H3DU.js";import{b,d as K}from"./DG5OM7OE.js";function Qt(r){let e=r,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var C=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function rt(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function at(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(r);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let n=s();if(!n)throw new Error("no storage");n.setItem(r,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(i){let n=globalThis;if(typeof n.addEventListener!="function")return()=>{};let a=o=>{(o.key===r||o.key===null)&&i()};return n.addEventListener("storage",a),()=>n.removeEventListener?.("storage",a)}}}function Pe(r){try{let e=r.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var Zt=6e4,es=15e3;function ts(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var X=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??es,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(n=>{this.current=n}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,n={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??Pe(e.access_token),user:s??i?.user};return this.current=n,await this.store.save(n),this.emit(t,n),n}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>Zt)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=ts(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new C("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new C("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",Qt(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new C("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new C("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,n)=>{t=setTimeout(()=>n(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var Te=class{state="closed";refusal;logSeq;joinRef=null;refusals=0;retry=null;listeners=new Map;closers=new Set;joiners=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}onJoined(e){return this.joiners.add(e),()=>this.joiners.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t,e&&(this.refusals=0);let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`));if(e)for(let i of[...this.joiners])try{i()}catch{}}closed(e){this.state="closed",this.joinRef=null,this.retry&&clearTimeout(this.retry),this.retry=null,this.refusals=0;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},Y=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Te(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed");this.lastJoin.clear()}async tokenChanged(){if(this.askRefusedAgain(),!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}askRefusedAgain(){for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,this.askAgain(e))}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>this.settle(e,!1,{reason:t instanceof Error?t.message:String(t)}))}settle(e,t,s){e.settled(t,s),t||this.askAgainLater(e)}askAgainLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=J(setTimeout(()=>{e.retry=null,this.askAgain(e)},s))}askAgain(e){this.reconnectTimer||this.channels.get(e.name)!==e||e.state!=="refused"||this.join(e)}leave(e){e.retry&&clearTimeout(e.retry),e.retry=null,e.state==="joined"&&(this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),this.lastJoin.get(e.name)===e&&this.lastJoin.delete(e.name)),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let n=this.nextRef(),a=JSON.stringify([e.joinRef,n,e.topic,t,s]),o=this.awaitReply(n);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,n)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>n(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"||i.state==="refused"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(n=>(n.state==="refused"&&(n.state="joining"),n.state==="joining"));this.open().then(()=>Promise.all(i.map(n=>this.sendJoin(n)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken();if(this.channels.get(e.name)!==e||e.state!=="joining")return;let s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),n={broadcast:{self:!1}};e.logSeq!==void 0&&(n.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(s,e.topic,"phx_join",{access_token:t,config:n},s);let{status:a,response:o}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{}));return}this.settle(e,a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,n,a]=t,o=typeof a=="object"&&a!==null?a:{};if(n==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let l=[...this.channels.values()].find(d=>d.topic===i);if(l){if(n==="phx_close"){l.state="closed";return}if(n==="phx_error"){l.state="joining",J(setTimeout(()=>this.channels.get(l.name)===l&&l.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(l),1e3));return}l.deliver(n,o)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(r){return r.unref?.(),r}var O="X-Palbase-Installation-Secret",Z="X-Palbase-Installation",lt=new WeakMap;function A(r){return lt.get(r)}var dt=new WeakSet;function ct(r){return dt.has(r)}var ss=/^[A-Za-z0-9_-]{43}$/,Q=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=ot()?.getItem(t);i&&ss.test(i)&&(s=i)}catch{}if(!s){dt.add(this),s=ht(crypto.getRandomValues(new Uint8Array(32)));try{ot()?.setItem(t,s)}catch{}}lt.set(this,s),this.id=is(s)}};function is(r){return ht(rs(new TextEncoder().encode(r)).subarray(0,16))}function ot(){try{return globalThis.localStorage}catch{return}}function ht(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var ns=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),I=(r,e)=>r>>>e|r<<32-e;function rs(r){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((r.length+9)/64)*64);t.set(r),t[r.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(r.length/536870912)),s.setUint32(t.length-4,r.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let v=I(i[g-15],7)^I(i[g-15],18)^i[g-15]>>>3,_=I(i[g-2],17)^I(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+v+i[g-7]+_|0}let[l,d,c,f,u,S,m,h]=e;for(let g=0;g<64;g++){let v=h+(I(u,6)^I(u,11)^I(u,25))+(u&S^~u&m)+ns[g]+i[g]|0,_=(I(l,2)^I(l,13)^I(l,22))+(l&d^l&c^d&c)|0;h=m,m=S,S=u,u=f+v|0,f=c,c=d,d=l,l=v+_|0}e[0]+=l,e[1]+=d,e[2]+=c,e[3]+=f,e[4]+=u,e[5]+=S,e[6]+=m,e[7]+=h}let n=new Uint8Array(32),a=new DataView(n.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return n}var os=30*6e4,ut=1e3,ls=100,ds=60*1024,ee=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function q(){try{return globalThis.localStorage}catch{return}}var se=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,n,a,o={}){this.session=s,this.consent=i;let l={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[Z]:n.id}}:c)};this.api=H.client(l);let d={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=H.client(d),this.closingApi=H.client({send:c=>l.send({...c,keepalive:!0})}),this.closingPerfApi=H.client({send:c=>d.send({...c,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,f)=>{f!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(xe),this.reset()):c==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),n=this.readOnce(),a=n?.session===i?n.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=q()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{q()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${F(t.pathname)}`:"");if(!i)return;let n=e.referrer??gs(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...n?{referrer:n}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{q()?.removeItem(this.anonKey),q()?.removeItem(this.sessionKey),q()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(xe)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(us((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},n=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",n),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",n)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=ut&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=ut&&this.samples.shift();let n={row_id:ee(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...n,distinct_id:this.distinctId()}:xe(n)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,ls);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>ds;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=q();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${ee()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${ee()}`,this.memoryAnon}sessionId(e){let t=q(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<os?{id:s.id,last:e}:{id:`ses_${ee()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let l=`${e.location.origin}${F(e.location.pathname)}`;setTimeout(()=>this.page({url:l}),0)},i=e.history,n=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{n(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=n,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let a=performance.now(),o=i instanceof Request?i:void 0,l=(n?.method??o?.method??"GET").toUpperCase(),d;try{d=new URL(o?.url??String(i),e.location.href)}catch{d=void 0}let c=!!d&&d.pathname.startsWith("/analytics/")||ps(n?.headers??o?.headers);try{let f=await t(i,n);return d&&!c&&this.sample("network",`${l} ${d.origin}${F(d.pathname)}`,performance.now()-a,{attrs:{status:String(f.status)},...f.headers.get("x-request-id")?{request_id:f.headers.get("x-request-id")}:{}}),f}catch(f){throw d&&!c&&this.sample("network",`${l} ${d.origin}${F(d.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),f}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function xe(r){let{distinct_id:e,request_id:t,...s}=r;return s}var cs=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,hs=r=>r.entryType==="event"||r.entryType==="first-input";function te(r,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:r,buffered:!0}),t}catch{return}}function us(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[te("largest-contentful-paint",d=>{for(let c of d)e=Math.max(e,c.startTime)}),te("layout-shift",d=>{for(let c of d)cs(c)&&!c.hadRecentInput&&(t+=c.value)}),te("event",d=>{for(let c of d)hs(c)&&(s=Math.max(s,c.duration))}),te("paint",d=>{for(let c of d)c.name==="first-contentful-paint"&&r("FCP",c.startTime)})],n=performance.getEntriesByType("navigation")[0];n&&n.responseStart>0&&r("TTFB",n.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},l=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",l),()=>{o(),document.removeEventListener("visibilitychange",l);for(let d of i)d?.disconnect()}}function ps(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var fs=/^[a-z][a-z0-9_-]{0,31}$/;function F(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return fs.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(n=>n.length<=16)?s:":id"}).join("/")}function gs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${F(e.pathname)}`}catch{return F(r.split(/[?#]/,1)[0]??"")}}var _t=/^custom\.[a-z0-9_]{1,48}$/,ms=/^[a-z][a-z0-9_]{0,63}$/,pt=r=>ms.test(r)||_t.test(r),vs=50,ft=[5e3,3e4,12e4,6e5],ys=100,ne=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[l,d]of Object.entries(t.start??{})){if(!pt(l))throw new TypeError(`consent.start: ${JSON.stringify(l)} is not a consent key (a platform key, or custom.<name>)`);if(d!=="granted"&&d!=="denied")throw new TypeError(`consent.start.${l} is granted or denied`)}for(let l of t.customKeys??[])if(!_t.test(l))throw new TypeError(`consent.customKeys: ${JSON.stringify(l)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>ct(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},n={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...n,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...n,unsent:s.unsent.filter(l=>l.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((l,d)=>{this.engaged&&(l==="SIGNED_IN"&&d?this.signedIn(d):(l==="SIGNED_OUT"||l==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",l=>{(l.key===this.storeKey||l.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(P(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=vt(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||P(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!pt(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,n=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(n),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(l=>l.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(l=>l.ads).map(l=>l.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(l=>{let d=this.kept.choices[l];return a&&n.has(l)&&d?.last_denied_at!==void 0&&Date.parse(d.last_denied_at)>o.getTime()?!1:!d||d.state==="unset"?!0:this.textVersion!==void 0&&d.source==="app"&&d.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[O]:A(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),n={};for(let h of e.choices)n[h.key]={state:h.state,source:h.source,chosen_at:h.chosen_at,...h.text_version!==void 0?{text_version:h.text_version}:{},...h.last_denied_at!==void 0?{last_denied_at:h.last_denied_at}:{}};let a=s.filter(h=>n[h.key]?.state!==h.state||Date.parse(n[h.key]?.chosen_at??"")!==Date.parse(h.chosen_at)).map(h=>D(h.key,h)),l=P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,h])=>h.provisional).map(([h,g])=>D(h,g)):[];if(a.length+l.length>0&&(this.kept={...this.kept,void:N([...this.kept.void??[],...a,...l])}),t===null&&this.kept.resetAt!==void 0)for(let[h,g]of Object.entries(n))Date.parse(g.chosen_at)<this.kept.resetAt&&delete n[h];let d=new Set(Object.entries(n).map(([h,g])=>D(h,g))),c=(this.kept.void??[]).filter(h=>d.has(h));c.length>0&&(this.kept={...this.kept,unvoid:N([...this.kept.unvoid??[],...c])});let f=Pt(this.kept),u;if(P(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))u=n;else{u={};for(let h of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let g=this.kept.choices[h],v=g&&!g.provisional&&!f.has(D(h,g))?g:void 0,_=n[h],M=_&&(!v||Date.parse(_.chosen_at)>=Date.parse(v.chosen_at))?_:v;M&&(u[h]=M)}}for(let h of this.kept.unsent){if(h.user!==null&&h.user!==t||h.user===null&&h.device!==void 0&&h.device!==this.installation.id||h.user===null&&t!==null)continue;let g=u[h.key];g&&Date.parse(g.chosen_at)>Date.parse(h.chosen_at)||(u[h.key]=gt(h,g))}let{install:S,...m}=this.kept;this.kept={...m,whose:t,...t===null?{install:this.installation.id}:{},choices:u,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=N([...this.kept.void??[],...s.map(l=>D(l.key,l))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let l of s){if(this.kept.unsent.some(c=>c.key===l.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(l.chosen_at)))continue;let d=o[l.key];o[l.key]={state:"denied",source:"app",chosen_at:l.chosen_at,...d?.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:n},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=P(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Tt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:gt(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.session.snapshot()?.userId??null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!bt(i))throw i}if(this.kept.link===e){let{link:i,...n}=this.kept;this.kept=n,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch{return(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let n=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...n.source==="gpc"?{source:"gpc"}:{},...n.text_version!==void 0?{text_version:n.text_version}:{},choices:i.map(l=>({key:l.key,state:l.state,chosen_at:l.chosen_at}))}})).data}catch(l){if(!bt(l))throw l;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(d=>i.some(c=>wt(c,d))?{...d,alone:!0}:d)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(l=>!i.some(d=>wt(d,l))),done:N([...this.kept.done??[],...i.map(re)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let a of t)if(!n.has(a.key)&&(n.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===vs)))break;return i}retryLater(){if(this.retryTimer)return;let e=ft[Math.min(this.retries,ft.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,l]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...l.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{}};let n=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!n(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:N([...this.kept.done??[],...a.map(re)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",n=>{n.event==="changed"&&this.changed(s,Ce(n.payload))}),t.on("state_snapshot",n=>this.held(s,Ce(St(n.entries)))),t.on("state_diff",n=>this.held(s,Ce(St(n.set))))];s.off=()=>i.forEach(n=>n()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(n=>n.key===e&&n.ads))return!1;let t=vt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[P(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||P(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(P(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[P(this.kept)]:Date.parse(i)}},this.commit(n),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let n of[...this.listeners])try{n(s,i)}catch{}}}load(){let e;try{e=kt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Ss(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=mt(e,this.kept,"theirs",this.holder()),P(e)===P(this.kept)&&yt(this.kept)!==yt(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=mt(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{kt()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function gt(r,e){let t=r.state==="denied"?r.chosen_at:e?.last_denied_at;return{state:r.state,source:r.source,chosen_at:r.chosen_at,...r.text_version!==void 0?{text_version:r.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function D(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Pt(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var ie={denied:2,unset:1,granted:0};function ws(r,e,t,s){let i=e&&!s.has(D(r,e))?e:void 0,n=t&&!s.has(D(r,t))?t:void 0;if(!i||!n)return i??n;let a=Date.parse(i.chosen_at),o=Date.parse(n.chosen_at);return a!==o?a>o?i:n:ie[i.state]!==ie[n.state]?ie[i.state]>ie[n.state]?i:n:i.provisional?n:i}function bs(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function mt(r,e,t,s){let i=N([...r.void??[],...e.void??[]]),n=N([...r.unvoid??[],...e.unvoid??[]]),a=Pt({void:i,unvoid:n}),o={},l,d={...r.gpc};for(let[v,_]of Object.entries(e.gpc??{}))d[v]=Math.max(d[v]??0,_);let c;if(P(r)===P(e)){l=e;for(let v of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let _=ws(v,r.choices[v],e.choices[v],a);_&&(o[v]=_)}c=bs(r.unknown,e.unknown)}else{l=P(e)===s?e:P(r)===s?r:t==="ours"?e:r;for(let[v,_]of Object.entries(l.choices))a.has(D(v,_))||(o[v]=_);c=l.unknown}let f=N([...r.done??[],...e.done??[]]),u=Tt([...r.unsent,...e.unsent]).filter(v=>!f.includes(re(v))),S=t==="ours"?e:r,m=t==="ours"?r:e,h=S.region??m.region,g=S.keys??m.keys;return{whose:l.whose??null,...l.whose==null&&l.install!==void 0?{install:l.install}:{},...l.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&P(r)===P(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:l.whose==null&&l.resetAt!==void 0?{resetAt:l.resetAt}:{},choices:o,unsent:u,...f.length>0?{done:f}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...S.link!==void 0?{link:S.link}:{},...h?{region:h}:{},...Object.keys(d).length>0?{gpc:d}:{},...g?{keys:g}:{},...c?{unknown:c}:{}}}function re(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function vt(r,e){let t=r.choices[e];if(!t||r.whose!=null||r.resetAt===void 0||Date.parse(t.chosen_at)>=r.resetAt)return t}function P(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function N(r){return[...new Set(r)].slice(-ys)}function yt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Tt(r){let e=new Map;for(let t of r){let s=re(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var ks=new Set(["granted","denied","unset"]);function Ss(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,l)=>{if(typeof o!="object"||o===null)return!1;let d=o;return ks.has(d.state)&&typeof d.chosen_at=="string"&&(!l||typeof d.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=r,n=o=>o===void 0||Array.isArray(o)&&o.every(l=>typeof l=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&a}function wt(r,e){return r.key===e.key&&r.user===e.user&&r.state===e.state&&r.source===e.source&&r.chosen_at===e.chosen_at}function bt(r){return r instanceof b&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function kt(){try{return globalThis.localStorage}catch{return}}function St(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Ce(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var _s=`
|
|
1
|
+
/*! palbase 0.47.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{e as tt,g as st,h as it}from"./IVULOJ4X.js";import{h as nt}from"./Q5OG7ZS5.js";import{a as et}from"./TY64APAC.js";import{r as Ye,t as Qe,u as Ze}from"./TL3NBGBL.js";import{b as H,c as $,e as Be,f as Je,i as _e,j as V,k as ze}from"./25P2SZXG.js";import{a as Xe,b as B}from"./IWKPXNQI.js";import{b,d as K}from"./5VL5SBYY.js";function Qt(r){let e=r,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var C=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function rt(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function at(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(r);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let n=s();if(!n)throw new Error("no storage");n.setItem(r,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(i){let n=globalThis;if(typeof n.addEventListener!="function")return()=>{};let a=o=>{(o.key===r||o.key===null)&&i()};return n.addEventListener("storage",a),()=>n.removeEventListener?.("storage",a)}}}function Pe(r){try{let e=r.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var Zt=6e4,es=15e3;function ts(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var X=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??es,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(n=>{this.current=n}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,n={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??Pe(e.access_token),user:s??i?.user};return this.current=n,await this.store.save(n),this.emit(t,n),n}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>Zt)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=ts(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new C("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new C("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",Qt(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new C("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new C("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,n)=>{t=setTimeout(()=>n(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var Te=class{state="closed";refusal;logSeq;joinRef=null;refusals=0;retry=null;listeners=new Map;closers=new Set;joiners=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}onJoined(e){return this.joiners.add(e),()=>this.joiners.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t,e&&(this.refusals=0);let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`));if(e)for(let i of[...this.joiners])try{i()}catch{}}closed(e){this.state="closed",this.joinRef=null,this.retry&&clearTimeout(this.retry),this.retry=null,this.refusals=0;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},Y=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Te(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed");this.lastJoin.clear()}async tokenChanged(){if(this.askRefusedAgain(),!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}askRefusedAgain(){for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,this.askAgain(e))}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>this.settle(e,!1,{reason:t instanceof Error?t.message:String(t)}))}settle(e,t,s){e.settled(t,s),t||this.askAgainLater(e)}askAgainLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=J(setTimeout(()=>{e.retry=null,this.askAgain(e)},s))}askAgain(e){this.reconnectTimer||this.channels.get(e.name)!==e||e.state!=="refused"||this.join(e)}leave(e){e.retry&&clearTimeout(e.retry),e.retry=null,e.state==="joined"&&(this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),this.lastJoin.get(e.name)===e&&this.lastJoin.delete(e.name)),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let n=this.nextRef(),a=JSON.stringify([e.joinRef,n,e.topic,t,s]),o=this.awaitReply(n);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,n)=>{let a=new e(t);this.ws=a,a.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>n(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"||i.state==="refused"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(n=>(n.state==="refused"&&(n.state="joining"),n.state==="joining"));this.open().then(()=>Promise.all(i.map(n=>this.sendJoin(n)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken();if(this.channels.get(e.name)!==e||e.state!=="joining")return;let s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),n={broadcast:{self:!1}};e.logSeq!==void 0&&(n.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(s,e.topic,"phx_join",{access_token:t,config:n},s);let{status:a,response:o}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),a==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{}));return}this.settle(e,a==="ok",o)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,n,a]=t,o=typeof a=="object"&&a!==null?a:{};if(n==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(o.status),o.response??{});return}let l=[...this.channels.values()].find(d=>d.topic===i);if(l){if(n==="phx_close"){l.state="closed";return}if(n==="phx_error"){l.state="joining",J(setTimeout(()=>this.channels.get(l.name)===l&&l.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(l),1e3));return}l.deliver(n,o)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(r){return r.unref?.(),r}var O="X-Palbase-Installation-Secret",Z="X-Palbase-Installation",lt=new WeakMap;function A(r){return lt.get(r)}var dt=new WeakSet;function ct(r){return dt.has(r)}var ss=/^[A-Za-z0-9_-]{43}$/,Q=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=ot()?.getItem(t);i&&ss.test(i)&&(s=i)}catch{}if(!s){dt.add(this),s=ht(crypto.getRandomValues(new Uint8Array(32)));try{ot()?.setItem(t,s)}catch{}}lt.set(this,s),this.id=is(s)}};function is(r){return ht(rs(new TextEncoder().encode(r)).subarray(0,16))}function ot(){try{return globalThis.localStorage}catch{return}}function ht(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var ns=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),I=(r,e)=>r>>>e|r<<32-e;function rs(r){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((r.length+9)/64)*64);t.set(r),t[r.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(r.length/536870912)),s.setUint32(t.length-4,r.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let v=I(i[g-15],7)^I(i[g-15],18)^i[g-15]>>>3,_=I(i[g-2],17)^I(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+v+i[g-7]+_|0}let[l,d,c,f,u,S,m,h]=e;for(let g=0;g<64;g++){let v=h+(I(u,6)^I(u,11)^I(u,25))+(u&S^~u&m)+ns[g]+i[g]|0,_=(I(l,2)^I(l,13)^I(l,22))+(l&d^l&c^d&c)|0;h=m,m=S,S=u,u=f+v|0,f=c,c=d,d=l,l=v+_|0}e[0]+=l,e[1]+=d,e[2]+=c,e[3]+=f,e[4]+=u,e[5]+=S,e[6]+=m,e[7]+=h}let n=new Uint8Array(32),a=new DataView(n.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return n}var os=30*6e4,ut=1e3,ls=100,ds=60*1024,ee=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function q(){try{return globalThis.localStorage}catch{return}}var se=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,n,a,o={}){this.session=s,this.consent=i;let l={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[Z]:n.id}}:c)};this.api=H.client(l);let d={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=H.client(d),this.closingApi=H.client({send:c=>l.send({...c,keepalive:!0})}),this.closingPerfApi=H.client({send:c=>d.send({...c,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,f)=>{f!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(xe),this.reset()):c==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),n=this.readOnce(),a=n?.session===i?n.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=q()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{q()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${F(t.pathname)}`:"");if(!i)return;let n=e.referrer??gs(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...n?{referrer:n}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{q()?.removeItem(this.anonKey),q()?.removeItem(this.sessionKey),q()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map(xe)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(us((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},n=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",n),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",n)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=ut&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=ut&&this.samples.shift();let n={row_id:ee(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...n,distinct_id:this.distinctId()}:xe(n)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,ls);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>ds;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=q();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${ee()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${ee()}`,this.memoryAnon}sessionId(e){let t=q(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<os?{id:s.id,last:e}:{id:`ses_${ee()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let o=`${e.location.origin}${e.location.pathname}`;if(o===t)return;t=o;let l=`${e.location.origin}${F(e.location.pathname)}`;setTimeout(()=>this.page({url:l}),0)},i=e.history,n=i.pushState.bind(i),a=i.replaceState.bind(i);return i.pushState=(...o)=>{n(...o),s()},i.replaceState=(...o)=>{a(...o),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=n,i.replaceState=a,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let a=performance.now(),o=i instanceof Request?i:void 0,l=(n?.method??o?.method??"GET").toUpperCase(),d;try{d=new URL(o?.url??String(i),e.location.href)}catch{d=void 0}let c=!!d&&d.pathname.startsWith("/analytics/")||ps(n?.headers??o?.headers);try{let f=await t(i,n);return d&&!c&&this.sample("network",`${l} ${d.origin}${F(d.pathname)}`,performance.now()-a,{attrs:{status:String(f.status)},...f.headers.get("x-request-id")?{request_id:f.headers.get("x-request-id")}:{}}),f}catch(f){throw d&&!c&&this.sample("network",`${l} ${d.origin}${F(d.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),f}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function xe(r){let{distinct_id:e,request_id:t,...s}=r;return s}var cs=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,hs=r=>r.entryType==="event"||r.entryType==="first-input";function te(r,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:r,buffered:!0}),t}catch{return}}function us(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[te("largest-contentful-paint",d=>{for(let c of d)e=Math.max(e,c.startTime)}),te("layout-shift",d=>{for(let c of d)cs(c)&&!c.hadRecentInput&&(t+=c.value)}),te("event",d=>{for(let c of d)hs(c)&&(s=Math.max(s,c.duration))}),te("paint",d=>{for(let c of d)c.name==="first-contentful-paint"&&r("FCP",c.startTime)})],n=performance.getEntriesByType("navigation")[0];n&&n.responseStart>0&&r("TTFB",n.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},l=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",l),()=>{o(),document.removeEventListener("visibilitychange",l);for(let d of i)d?.disconnect()}}function ps(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var fs=/^[a-z][a-z0-9_-]{0,31}$/;function F(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return fs.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(n=>n.length<=16)?s:":id"}).join("/")}function gs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${F(e.pathname)}`}catch{return F(r.split(/[?#]/,1)[0]??"")}}var _t=/^custom\.[a-z0-9_]{1,48}$/,ms=/^[a-z][a-z0-9_]{0,63}$/,pt=r=>ms.test(r)||_t.test(r),vs=50,ft=[5e3,3e4,12e4,6e5],ys=100,ne=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[l,d]of Object.entries(t.start??{})){if(!pt(l))throw new TypeError(`consent.start: ${JSON.stringify(l)} is not a consent key (a platform key, or custom.<name>)`);if(d!=="granted"&&d!=="denied")throw new TypeError(`consent.start.${l} is granted or denied`)}for(let l of t.customKeys??[])if(!_t.test(l))throw new TypeError(`consent.customKeys: ${JSON.stringify(l)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>ct(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},n={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...n,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...n,unsent:s.unsent.filter(l=>l.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((l,d)=>{this.engaged&&(l==="SIGNED_IN"&&d?this.signedIn(d):(l==="SIGNED_OUT"||l==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",l=>{(l.key===this.storeKey||l.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(P(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=vt(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||P(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!pt(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,n=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(n),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(l=>l.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(l=>l.ads).map(l=>l.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(l=>{let d=this.kept.choices[l];return a&&n.has(l)&&d?.last_denied_at!==void 0&&Date.parse(d.last_denied_at)>o.getTime()?!1:!d||d.state==="unset"?!0:this.textVersion!==void 0&&d.source==="app"&&d.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[O]:A(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),n={};for(let h of e.choices)n[h.key]={state:h.state,source:h.source,chosen_at:h.chosen_at,...h.text_version!==void 0?{text_version:h.text_version}:{},...h.last_denied_at!==void 0?{last_denied_at:h.last_denied_at}:{}};let a=s.filter(h=>n[h.key]?.state!==h.state||Date.parse(n[h.key]?.chosen_at??"")!==Date.parse(h.chosen_at)).map(h=>D(h.key,h)),l=P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,h])=>h.provisional).map(([h,g])=>D(h,g)):[];if(a.length+l.length>0&&(this.kept={...this.kept,void:N([...this.kept.void??[],...a,...l])}),t===null&&this.kept.resetAt!==void 0)for(let[h,g]of Object.entries(n))Date.parse(g.chosen_at)<this.kept.resetAt&&delete n[h];let d=new Set(Object.entries(n).map(([h,g])=>D(h,g))),c=(this.kept.void??[]).filter(h=>d.has(h));c.length>0&&(this.kept={...this.kept,unvoid:N([...this.kept.unvoid??[],...c])});let f=Pt(this.kept),u;if(P(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))u=n;else{u={};for(let h of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let g=this.kept.choices[h],v=g&&!g.provisional&&!f.has(D(h,g))?g:void 0,_=n[h],M=_&&(!v||Date.parse(_.chosen_at)>=Date.parse(v.chosen_at))?_:v;M&&(u[h]=M)}}for(let h of this.kept.unsent){if(h.user!==null&&h.user!==t||h.user===null&&h.device!==void 0&&h.device!==this.installation.id||h.user===null&&t!==null)continue;let g=u[h.key];g&&Date.parse(g.chosen_at)>Date.parse(h.chosen_at)||(u[h.key]=gt(h,g))}let{install:S,...m}=this.kept;this.kept={...m,whose:t,...t===null?{install:this.installation.id}:{},choices:u,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=N([...this.kept.void??[],...s.map(l=>D(l.key,l))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let l of s){if(this.kept.unsent.some(c=>c.key===l.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(l.chosen_at)))continue;let d=o[l.key];o[l.key]={state:"denied",source:"app",chosen_at:l.chosen_at,...d?.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:n},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=P(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Tt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:gt(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.session.snapshot()?.userId??null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!bt(i))throw i}if(this.kept.link===e){let{link:i,...n}=this.kept;this.kept=n,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch{return(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let n=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...n.source==="gpc"?{source:"gpc"}:{},...n.text_version!==void 0?{text_version:n.text_version}:{},choices:i.map(l=>({key:l.key,state:l.state,chosen_at:l.chosen_at}))}})).data}catch(l){if(!bt(l))throw l;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(d=>i.some(c=>wt(c,d))?{...d,alone:!0}:d)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(l=>!i.some(d=>wt(d,l))),done:N([...this.kept.done??[],...i.map(re)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||(a.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let a of t)if(!n.has(a.key)&&(n.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===vs)))break;return i}retryLater(){if(this.retryTimer)return;let e=ft[Math.min(this.retries,ft.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&(o.device??this.installation.id)===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,l]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...l.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{}};let n=o=>o.user===null&&(o.device??this.installation.id)===this.installation.id,a=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!n(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:N([...this.kept.done??[],...a.map(re)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",n=>{n.event==="changed"&&this.changed(s,Ce(n.payload))}),t.on("state_snapshot",n=>this.held(s,Ce(St(n.entries)))),t.on("state_diff",n=>this.held(s,Ce(St(n.set))))];s.off=()=>i.forEach(n=>n()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(n=>n.key===e&&n.ads))return!1;let t=vt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[P(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||P(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(P(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[P(this.kept)]:Date.parse(i)}},this.commit(n),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let n of[...this.listeners])try{n(s,i)}catch{}}}load(){let e;try{e=kt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Ss(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=mt(e,this.kept,"theirs",this.holder()),P(e)===P(this.kept)&&yt(this.kept)!==yt(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=mt(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{kt()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function gt(r,e){let t=r.state==="denied"?r.chosen_at:e?.last_denied_at;return{state:r.state,source:r.source,chosen_at:r.chosen_at,...r.text_version!==void 0?{text_version:r.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function D(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Pt(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var ie={denied:2,unset:1,granted:0};function ws(r,e,t,s){let i=e&&!s.has(D(r,e))?e:void 0,n=t&&!s.has(D(r,t))?t:void 0;if(!i||!n)return i??n;let a=Date.parse(i.chosen_at),o=Date.parse(n.chosen_at);return a!==o?a>o?i:n:ie[i.state]!==ie[n.state]?ie[i.state]>ie[n.state]?i:n:i.provisional?n:i}function bs(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function mt(r,e,t,s){let i=N([...r.void??[],...e.void??[]]),n=N([...r.unvoid??[],...e.unvoid??[]]),a=Pt({void:i,unvoid:n}),o={},l,d={...r.gpc};for(let[v,_]of Object.entries(e.gpc??{}))d[v]=Math.max(d[v]??0,_);let c;if(P(r)===P(e)){l=e;for(let v of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let _=ws(v,r.choices[v],e.choices[v],a);_&&(o[v]=_)}c=bs(r.unknown,e.unknown)}else{l=P(e)===s?e:P(r)===s?r:t==="ours"?e:r;for(let[v,_]of Object.entries(l.choices))a.has(D(v,_))||(o[v]=_);c=l.unknown}let f=N([...r.done??[],...e.done??[]]),u=Tt([...r.unsent,...e.unsent]).filter(v=>!f.includes(re(v))),S=t==="ours"?e:r,m=t==="ours"?r:e,h=S.region??m.region,g=S.keys??m.keys;return{whose:l.whose??null,...l.whose==null&&l.install!==void 0?{install:l.install}:{},...l.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&P(r)===P(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:l.whose==null&&l.resetAt!==void 0?{resetAt:l.resetAt}:{},choices:o,unsent:u,...f.length>0?{done:f}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...S.link!==void 0?{link:S.link}:{},...h?{region:h}:{},...Object.keys(d).length>0?{gpc:d}:{},...g?{keys:g}:{},...c?{unknown:c}:{}}}function re(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function vt(r,e){let t=r.choices[e];if(!t||r.whose!=null||r.resetAt===void 0||Date.parse(t.chosen_at)>=r.resetAt)return t}function P(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function N(r){return[...new Set(r)].slice(-ys)}function yt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Tt(r){let e=new Map;for(let t of r){let s=re(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var ks=new Set(["granted","denied","unset"]);function Ss(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,l)=>{if(typeof o!="object"||o===null)return!1;let d=o;return ks.has(d.state)&&typeof d.chosen_at=="string"&&(!l||typeof d.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=r,n=o=>o===void 0||Array.isArray(o)&&o.every(l=>typeof l=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&a}function wt(r,e){return r.key===e.key&&r.user===e.user&&r.state===e.state&&r.source===e.source&&r.chosen_at===e.chosen_at}function bt(r){return r instanceof b&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function kt(){try{return globalThis.localStorage}catch{return}}function St(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Ce(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var _s=`
|
|
3
3
|
:host{display:block;color-scheme:light dark;font:15px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
4
4
|
.list{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none}
|
|
5
5
|
.item{position:relative;display:flex;gap:12px;align-items:flex-start;padding:12px 40px 12px 12px;border-radius:12px;background:var(--bg);color:var(--fg);cursor:pointer;outline:none}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.47.
|
|
2
|
-
import{a as j,c as Ee,d as Pe,e as Re}from"./
|
|
1
|
+
/*! palbase 0.47.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as j,c as Ee,d as Pe,e as Re}from"./XXVAFTAU.js";import{a as Ce}from"./ZK2IPLYN.js";import{a as Ae}from"./25P2SZXG.js";import{a as xe,b as ve,c as _e}from"./IWKPXNQI.js";import{b as P,d as Se}from"./5VL5SBYY.js";async function*Ie(e,t={}){let o=e.getReader(),s=new TextDecoder,i="",d="",l=[],u,r=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:a}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=s.decode(a,{stream:!0});for(let c=i.indexOf(`
|
|
3
3
|
`);c>=0;c=i.indexOf(`
|
|
4
4
|
`)){let g=i.slice(0,i[c-1]==="\r"?c-1:c);i=i.slice(c+1),g===""?(d!==""&&(yield u===void 0?{event:d,data:l.join(`
|
|
5
5
|
`)}:{event:d,data:l.join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.47.
|
|
1
|
+
/*! palbase 0.47.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.47.
|
|
2
|
-
import{a as u,b as d}from"./
|
|
1
|
+
/*! palbase 0.47.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u,b as d}from"./5VL5SBYY.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project has no paid rights now to pay for Palbase's models (it is on Free, at its month's limit, or its payment account has an unpaid charge): move it to Pay as you go (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof d)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new d({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=u(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.47.
|
|
1
|
+
/*! palbase 0.47.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! palbase 0.47.
|
|
2
|
+
/*! palbase 0.47.1 — Palbase SDK License (see LICENSE) */
|
|
3
3
|
var Ww=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Ww(e,n,{get:t[n],enumerable:!0})};import{parseArgs as Tv}from"node:util";var Fw=Symbol.for("palbase.data"),Jw=globalThis,Id=Jw[Fw]??=new WeakSet;function Vw(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Ya(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||Id.has(n)||Vw(n))){Id.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var Hw="X-PoW-Challenge-ID",Yw="X-PoW-Nonce";function Dd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:s,difficulty:a}=t.challenge;return typeof n!="string"||typeof s!="string"||typeof a!="number"||!Number.isInteger(a)||a<0?null:{id:n,prefix:s,difficulty:a}}function Xw(e){return 8*2**e}var ds;async function Zw(){if(ds)return ds;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let s=(await import("node:crypto")).createHash;if(typeof s=="function")return ds=a=>new Uint8Array(s("sha256").update(a).digest()),ds}catch{}let t=new TextEncoder;return ds=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),ds}function Qw(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var ev=4096,tv=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function xd(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await Zw(),s=Xw(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<s;i++){if(i%ev===0&&i>0){if(await tv(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>a)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let r=n(e.prefix+i),o=r instanceof Uint8Array?r:await r;if(Qw(o)>=e.difficulty)return{[Hw]:e.id,[Yw]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var C=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="PalbaseError",this.op=t.op,this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.retryAfter=t.retryAfter,this.body=t.body}};function c(e,t,n){let s=String(n);if(s===""||s==="."||s==="..")throw new C({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var nv=new Set(["apikey","authorization"]),sv=64*1024;function Jr(e){let t=Xa(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(i,r)=>{let o=rv(t,i),l=new Headers;for(let[y,w]of Object.entries(i.headers??{}))w!=null&&!nv.has(y.toLowerCase())&&l.set(y,String(w));for(let[y,w]of Object.entries(r))l.set(y,w);await ov(i,e.credentials,l),l.has("accept")||l.set("accept","application/json");let d={method:i.method,headers:l,redirect:"manual",signal:i.signal,...i.keepalive?{keepalive:!0}:{}};i.body&&i.body.value!==void 0&&(l.set("content-type",i.body.contentType),d.body=lv(i.body.kind,i.body.value),ps(d.body)||(d.duplex="half"));let p;try{p=i.onUploadProgress&&e.xmlHttpRequest?await av(e.xmlHttpRequest,i.op,o,d,i.onUploadProgress):await n(o,d)}catch(y){throw i.signal?.aborted||y instanceof C?y:new C({op:i.op,status:0,code:"network_error",message:`${i.op}: the request did not reach ${t.origin}`,cause:y})}let u=i.answers[p.status]??(i.ownResponse&&p.status>=200&&p.status<300?"raw":void 0);if(u===void 0)throw p.status>=200&&p.status<300?(await p.body?.cancel(),new C({op:i.op,status:p.status,code:"undeclared_answer",message:`${i.op}: the server answered ${p.status}, which its contract does not declare; the request may have taken effect`})):await pv(i.op,p);let g;switch(u){case"json":try{g=Ya(await p.json())}catch(y){throw new C({op:i.op,status:p.status,code:"invalid_json",message:`${i.op}: the answer is not JSON`,cause:y})}break;case"raw":g=p;break;default:await p.body?.cancel(),g=void 0}return{status:p.status,data:g,headers:p.headers}};return{async send(i){try{return await a(i,{})}catch(r){let o=s&&r instanceof C&&r.status===403?Dd(r.body):null,l=i.body?.value;if(!o||i.body?.kind==="raw"&&!ps(l))throw r;let d=r,p;try{p=await xd(o,{signal:i.signal})}catch(u){throw i.signal?.aborted?u:new C({op:i.op,status:403,code:"pow_unsolved",message:`${i.op}: ${u instanceof Error?u.message:String(u)}`,requestId:d.requestId,body:d.body,cause:u})}return a(i,p)}}}}function av(e,t,n,s,a){return new Promise((i,r)=>{let o=s.signal;if(o?.aborted)return r(o.reason);let l=new e,d=()=>l.abort();o?.addEventListener("abort",d,{once:!0});let p=u=>{o?.removeEventListener("abort",d),u()};l.open(s.method??"GET",n.href),l.responseType="arraybuffer",new Headers(s.headers).forEach((u,g)=>l.setRequestHeader(g,u)),l.upload&&(l.upload.onprogress=u=>{u.lengthComputable&&a(u.loaded,u.total)}),l.onload=()=>p(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){r(new C({op:t,status:0,code:"undeclared_redirect",message:`${t}: the server redirected; the answer is another address's, and was not read`}));return}if(l.status<200||l.status>599)return r(new TypeError(`${t}: answered ${l.status}`));let u=l.status===204||l.status===205||l.status===304;i(new Response(u?null:l.response,{status:l.status,statusText:l.statusText,headers:iv(l.getAllResponseHeaders())}))}),l.onerror=()=>p(()=>r(new TypeError(`${t}: the request failed`))),l.onabort=()=>p(()=>r(o?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function iv(e){let t=new Headers;for(let n of e.split(/\r?\n/)){let s=n.indexOf(":");if(!(s<=0))try{t.append(n.slice(0,s).trim(),n.slice(s+1).trim())}catch{}}return t}function Xa(e){let t;try{t=new URL(e)}catch{throw new TypeError(`baseUrl ${JSON.stringify(e)} is not an absolute URL`)}let n=t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${t.origin}`);if(t.username||t.password||t.search||t.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(t.pathname!=="/"&&t.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return t}function rv(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new C({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path ${JSON.stringify(t.path)} is not absolute`});let n=new URL(t.path+dv(t.query),e);if(n.origin!==e.origin)throw new C({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function ov(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(r=>r.includes("userJWT"))?await t.accessToken?.():void 0,a=r=>{switch(r){case"ApiKeyAuth":return!!(t.publishableKey??t.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(t.secretKey??t.token);case"PalbaseBearer":return!!t.token;case"userJWT":return!!s&&!t.token;default:return!1}},i=e.auth.filter(r=>r.every(a)).reduce((r,o)=>r===void 0||o.length>r.length?o:r,void 0);if(!i)throw new C({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(r=>r.length===0?"nothing":r.join(" + ")).join(" | ")}`});for(let r of i)r==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(r==="SecretKeyAuth"||r==="AdminAuth"||r==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):r==="SecretKeyAuth"||r==="AdminAuth"?n.set("apikey",t.secretKey):r==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function lv(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))Vr(n,s,a);return n}case"raw":return t}}function ps(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function dv(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))Vr(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function Vr(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)Vr(e,t,s);return}if(n instanceof Date){e.append(t,n.toISOString());return}e.append(t,typeof n=="object"?JSON.stringify(n):String(n))}}async function pv(e,t){let n=await uv(t,sv).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=cv(s)?s:void 0,i=Number(t.headers.get("retry-after")),r=t.status>=300&&t.status<400;return new C({op:e,status:t.status,code:a?.error??(r?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(r?`${e}: the server redirected (${t.status}); the request was not followed, its credentials stay here`:`${e}: ${t.status} ${t.statusText}`.trim()),requestId:a?.request_id??t.headers.get("x-request-id")??void 0,retryAfter:a?.retry_after??(Number.isFinite(i)&&i>0?i:void 0),body:s})}async function uv(e,t){if(!e.body)return"";let n=e.body.getReader(),s=[],a=0;for(;a<t;){let{done:o,value:l}=await n.read();if(o)break;s.push(l),a+=l.byteLength}await n.cancel().catch(()=>{});let i=new Uint8Array(Math.min(a,t)),r=0;for(let o of s){let l=Math.min(o.byteLength,i.byteLength-r);if(i.set(o.subarray(0,l),r),r+=l,r>=i.byteLength)break}return new TextDecoder().decode(i)}function cv(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var Za={project:{type:"string",short:"P",value:"project",description:"the project (name or id; org/project when the name is in two organizations)"},env:{type:"string",short:"E",value:"env",description:"the project's environment (slug or ref)"},json:{type:"boolean",description:"print the answer as JSON"},"non-interactive":{type:"boolean",description:"never ask: refuse what would need a question"},yes:{type:"boolean",short:"y",description:"confirm a change to a production environment without asking"},debug:{type:"boolean",description:"print each request the command sends"},help:{type:"boolean",short:"h",description:"show help"}};var f=class extends Error{exitCode;hint;code;reported;constructor(t,n,s={}){super(n),this.name="CliError",this.code=t,this.hint=s.hint,this.exitCode=s.exitCode??1,this.reported=s.reported??!1}};function m(e,t){return new f("usage",e,{hint:t,exitCode:2})}var Qa=class{io;json;constructor(t,n){this.io=t,this.json=n}result(t,n){this.json?this.io.stdout(`${JSON.stringify(t,null,2)}
|
|
4
4
|
`):n()}line(t=""){this.io.stdout(`${N(t)}
|
|
5
5
|
`)}note(t){this.io.stderr(`${N(t)}
|
|
@@ -9,7 +9,7 @@ var Ww=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Ww(e,n,{get:t[n],enum
|
|
|
9
9
|
`);let r;try{r=await this.io.fetch(t,{method:n.method,headers:{...n.headers,...a},body:n.body,signal:n.signal,...s?{}:{duplex:"half"},redirect:"manual"})}catch(l){throw n.signal?.aborted?l:new f("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${r.status} ${r.headers.get("x-request-id")??""}
|
|
10
10
|
`),r.status!==503||!s||i>=Pv||!$v.has(await Xr(r)??""))return r;await r.body?.cancel();let o=Number(r.headers.get("retry-after")??"");await this.io.sleep((Number.isFinite(o)&&o>0?Math.min(o,30):1)*1e3)}}async exchange(t,n,s){let a=await this.token(),i=await this.send(t,n,s,a.value);if(i.status===401&&a.renewable){let r=await this.renew(await this.currentSession());i=await this.send(t,n,s,r.access_token)}return{res:i,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let i=await s.text(),r=i===""?void 0:Av(i);if(s.ok)return r;let o=r??{};throw s.status===401?o.error==="token_not_for_machines"?Qd(new URL(this.cloud.studioApi).host):a?us():this.tokenRefused("Studio"):new C({op:`${t} ${n}`,status:s.status,code:o.error??`http_${s.status}`,message:o.error_description??`Studio answered ${s.status}`,requestId:o.request_id??s.headers.get("x-request-id")??void 0,body:r})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new f("token_refused",`${t} refused PALBASE_TOKEN, an environment's token: it ended (a few hours at most), it was revoked, or what minted it no longer holds`,{hint:"mint another: palbase env:tokens:create --scope <scope> (an admin), or with the environment's secret key (Studio's POST /environments/{ref}/tokens)"}):(this.io.env.PALBASE_TOKEN??"").startsWith("pbu_")?new f("token_refused",`${t} refused PALBASE_TOKEN, an account token: it was revoked, it ended, or, in this organization, the one who made it left it`,{hint:"its maker makes a new one: palbase account:tokens:create <name>"}):new f("token_refused",`${t} refused PALBASE_TOKEN: it was revoked, it ended, or the one who made it no longer holds its role`,{hint:"an admin makes a new one: palbase tokens:create <name>"})}async token(){let t=this.io.env.PALBASE_TOKEN;return t&&t!==""?{value:t,renewable:!1}:{value:(await this.currentSession()).access_token,renewable:!0}}async renew(t){let n=await Hd(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let i=`${this.cloud.studioApi}${Sv}${n}`;this.debug&&this.io.stderr(`> ${t} ${i}
|
|
11
11
|
`);try{let r=await this.io.fetch(i,{method:t,headers:{...a===void 0?{}:{authorization:`Bearer ${a}`},accept:"application/json",...s===void 0?{}:{"content-type":"application/json"}},body:s===void 0?void 0:JSON.stringify(s),redirect:"manual"});return this.debug&&this.io.stderr(`< ${r.status} ${r.headers.get("x-request-id")??""}
|
|
12
|
-
`),r}catch(r){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${r instanceof Error?r.message:String(r)}`)}}};function Qd(e){return new f("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function Xr(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Av(e){try{return JSON.parse(e)}catch{return e}}var ep={version:"0.47.
|
|
12
|
+
`),r}catch(r){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${r instanceof Error?r.message:String(r)}`)}}};function Qd(e){return new f("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function Xr(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Av(e){try{return JSON.parse(e)}catch{return e}}var ep={version:"0.47.1"};var ai=ep.version;async function ip(e,t,n){let s=new Map(n.map(r=>[r.name,r])),a=e.includes("--json"),i=e.includes("--debug");try{let{name:r,at:o}=Ev(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${ai}
|
|
13
13
|
`),0):(t.stdout(ap(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(r==="help"){let S=e[o+1],$=S===void 0?void 0:s.get(S);if(S!==void 0&&!$)throw tp(S,n);return t.stdout($?sp($):ap(n)),0}let l=s.get(r);if(!l)throw tp(r,n);let d=[...e.slice(0,o),...e.slice(o+1)];if(d.includes("--help")||d.includes("-h"))return t.stdout(sp(l)),0;let{flags:p,positionals:u}=Cv(l,d),g=l.args??{min:0,max:0};if(u.length<g.min)throw m(`${l.name} needs ${g.min===1?"an argument":`${g.min} arguments`}`,Qr(l));if(u.length>g.max)throw m(`${l.name} takes ${g.max===0?"no argument":`at most ${g.max}`}: ${JSON.stringify(u.slice(g.max))} is left over`,Qr(l));let y={project:p.project,env:p.env,json:p.json===!0,nonInteractive:p["non-interactive"]===!0,yes:p.yes===!0,debug:p.debug===!0},w=Bd(t.env),_=new ei(Fd(t.configDir,w)),P={io:t,state:_,out:new Qa(t,y.json),global:y,args:u,flags:p,interactive:t.interactive&&!y.nonInteractive,cloud:w,studio:new si(t,w,_,y.debug)};return await l.run(P)??0}catch(r){return jv(r,t,a,i)}}function Ev(e){let t=new Set;for(let[n,s]of Object.entries(Za))s.type==="string"&&(t.add(`--${n}`),s.short&&t.add(`-${s.short}`));for(let n=0;n<e.length;n++){let s=e[n];if(s==="--")return{at:-1};if(t.has(s)){n++;continue}if(!s.startsWith("-"))return{name:s,at:n}}return{at:-1}}function Cv(e,t){let n={...Za,...e.flags??{}},s={};for(let[a,i]of Object.entries(n))s[a]={type:i.type,...i.short?{short:i.short}:{},...i.multiple?{multiple:!0}:{}};try{let{values:a,positionals:i}=Tv({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:i}}catch(a){throw m(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function jv(e,t,n,s){let a="error",i,r,o=1,l;return e instanceof f?(a=e.code,i=e.message,r=e.hint,o=e.exitCode):e instanceof C?(a=e.code,i=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(i=`${e.op} refused PALBASE_TOKEN: ${e.message}`,r="this is the token's reach, fixed when it was minted: a person's yes does not change it \u2014 mint a token whose scopes name this call, or have a person run it signed in")):i=e instanceof Error?e.message:String(e),n&&e instanceof f&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:i,...r?{hint:r}:{},...l?{request_id:l}:{}},null,2)}
|
|
14
14
|
`),t.stderr(`error: ${N(i)}${l?` (request ${N(l)})`:""}
|
|
15
15
|
`),r&&t.stderr(` ${N(r)}
|
|
@@ -34,7 +34,7 @@ var Ww=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Ww(e,n,{get:t[n],enum
|
|
|
34
34
|
`)+1,s=t.slice(n,n+256);if(n>0&&s!==""){for(let a=e.indexOf(s);a>=0;a=e.indexOf(s,a+1))if(t.startsWith(e.slice(a),n))return t.slice(n+e.length-a)}return t}function kk(e){return e.pull_request?` (preview of #${e.pull_request})`:e.branch?` (preview of ${e.branch})`:""}async function Sk(e,t,n,s){let a=n.name,i=!1,r=()=>{},o=new Promise(u=>r=u),l=()=>{i=!0,r()},d=async()=>(await Promise.race([e.io.sleep(2e3),o]),i),p=u=>(e.out.note(u?`Stopped following: the build ${u} goes on (palbase hosting:builds ${u} --site ${a} --wait follows it, hosting:builds:cancel ${u} --site ${a} cancels it).`:`Stopped following: the build goes on (palbase hosting:builds --site ${a}).`),130);process.once("SIGINT",l);try{let u;for(let _=0;;_++){let{builds:P}=await h(e,t,"GET",`/sites/${de(a)}/builds`);if(u=P.find(S=>!s.has(S.id)&&!S.pull_request&&!S.branch)?.id,u)break;if(_===60)throw new f("build_not_queued",`no build of ${a} was queued in 2 minutes`,{hint:`palbase hosting:builds --site ${a}`});if(await d())return p()}let g="",y="",w="";for(let _=0;;_++){let P=await h(e,t,"GET",`/sites/${de(a)}/builds/${x("the build",u)}`),S=`build ${P.id.slice(0,8)} (${P.commit.slice(0,7)}): ${P.state}`;if(S!==g&&e.out.note(` ${S}`),g=S,P.log&&!e.global.json){let $=w+_k(y,P.log),R=$.lastIndexOf(`
|
|
35
35
|
`)+1;e.io.stdout(N($.slice(0,R))),w=$.slice(R),y=P.log}if(P.state!=="queued"&&P.state!=="building")return w!==""&&e.io.stdout(`${N(w)}
|
|
36
36
|
`),e.out.result({site:a,url:n.url,build:P},()=>e.out.line(P.state==="succeeded"?`${a} serves the build of ${P.commit.slice(0,7)}: ${n.url}`:`The build ${P.state}${P.reason?`: ${P.reason}`:""} \u2014 ${a} serves what it served.`)),P.state==="succeeded"?0:1;if(_===900)throw new f("timeout",`the build ${u} was still ${P.state} after 30 minutes; it goes on`,{hint:`palbase hosting:builds ${u} --site ${a} --wait`});if(await d())return p(u)}}finally{process.removeListener("SIGINT",l)}}var $k={name:"hosting:build",summary:"build a site's branch head now and serve it, as a push does \u2014 following the build to its end, its log as it grows",usage:"[--site <name>] [--no-wait]",details:["It ends as the build does: 0 once the site serves it (its address printed), 1 when it failed or was cancelled \u2014 the site serves what it served.","Ctrl-C stops following it, not the build: hosting:builds:cancel cancels it.",te("site")],flags:{...ot,"no-wait":{type:"boolean",description:"ask for the build and end: hosting:builds follows it"}},scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,kt(e),e.flags.site!==void 0);await v(e,t,`build ${n} from the head of its branch`);let a=e.flags["no-wait"]!==!0?new Set((await h(e,t,"GET",`/sites/${de(n)}/builds`)).builds.map(r=>r.id)):void 0,i=await h(e,t,"POST",`/sites/${de(n)}/builds`);if(a)return Sk(e,t,i,a);e.out.result(i,()=>e.out.line(`${i.name}: a build of ${i.source?.branch??"its branch"}'s head is on its way (palbase hosting:builds --site ${i.name}).`))}},Pk={name:"hosting:previews",summary:"a site's previews \u2014 its pull requests' and its other branches' \u2014 newest first: where each answers, and whether it is built",usage:"[--site <name>]",details:["A branch's preview answers at <name>-git-<branch>-<ref> from its first push while the site previews, until the branch is deleted or a month passes with no push.",te("site")],flags:ot,scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,kt(e),e.flags.site!==void 0),{previews:s,branches:a=[]}=await h(e,t,"GET",`/sites/${de(n)}/previews`);e.out.result({previews:s,branches:a},()=>{(s.length>0||a.length===0)&&Fo(e,s,`${n} has no preview: a site built from GitHub previews its pull requests and its other branches with hosting:sites:update ${n} --previews.`);for(let i of a)e.out.line(`branch ${i.branch} ${i.state} ${i.commit.slice(0,7)} ${i.url}`)})}},Ak={name:"hosting:previews:links",summary:"a site's share links that have not ended: each opens its protected previews to whoever holds it \u2014 never their tokens",usage:"[--site <name>]",details:[te("site")],flags:ot,scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,kt(e),e.flags.site!==void 0),{links:s}=await h(e,t,"GET",`/sites/${de(n)}/previews/links`);e.out.result({links:s},()=>{s.length===0&&e.out.line(`${n} has no share link: palbase hosting:previews:link --site ${n} makes one.`),e.out.table(s,[{header:"link",value:a=>a.id},{header:"name",value:a=>a.name},{header:"made by",value:a=>a.made_by},{header:"ends",value:a=>a.expires_at}])})}},Rk={name:"hosting:previews:link",summary:"make a share link of a site's protected previews: whoever holds it opens any of them, for 1 to 30 days",usage:"[--site <name>] [--name <name>] [--days <1-30>]",details:["Its token is printed this once: add ?_palbase_pass=<token> to any preview's address and the preview opens \u2014 for a reviewer, a client, a test run. hosting:previews:unlink closes the previews to it at once.","A site has 20 at most.",te("site")],flags:{...ot,name:{type:"string",value:"name",description:"what it is for, as the links are listed: who holds it (64 at most)"},days:{type:"string",value:"days",description:"how many days it opens the previews, 1 to 30 (default: 7)"}},scope:"environment",async run(e){let t=e.flags.days===void 0?void 0:Number(e.flags.days);if(t!==void 0&&(!Number.isInteger(t)||t<1||t>30))throw m("--days is a whole number of days, 1 to 30");let n=e.flags.name;if(n!==void 0&&n.length>64)throw m("a link's --name is 64 characters at most");let{t:s,site:{name:a}}=await rt(e,kt(e),e.flags.site!==void 0);await v(e,s,`make a share link that opens ${a}'s previews to whoever holds it${t!==void 0?`, for ${t} days`:""}`);let i=await h(e,s,"POST",`/sites/${de(a)}/previews/links`,{...n!==void 0?{name:n}:{},...t!==void 0?{days:t}:{}});e.out.result(i,()=>{e.out.line(`Made the share link ${i.id}${i.name?` (${i.name})`:""}: it opens ${a}'s previews until ${i.expires_at}. Its token:`),e.out.line(` ${i.token??""}`),e.out.line(`Add ?_palbase_pass=<token> to any preview's address (palbase hosting:previews --site ${a} lists them). It is shown this once; palbase hosting:previews:unlink ${i.id} --site ${a} closes the previews to it.`)})}},Tk={name:"hosting:previews:unlink",summary:"delete a share link: the site's previews close to it at once",usage:"<link id> [--site <name>]",details:[te("site")],args:{min:1,max:1},flags:ot,scope:"environment",async run(e){let{t,site:{name:n}}=await rt(e,kt(e),e.flags.site!==void 0);await v(e,t,`delete the share link ${e.args[0]} of ${n}'s previews`),await h(e,t,"DELETE",`/sites/${de(n)}/previews/links/${x("the link's id",e.args[0])}`),e.out.result({deleted:e.args[0]},()=>e.out.line(`Deleted the share link ${e.args[0]}: ${n}'s previews are closed to it.`))}},Ek={name:"hosting:previews:pass",summary:"an address that opens one of a site's protected previews in your browser, as you: for 12 hours",usage:"<preview url> [--site <name>]",details:["The address is the preview's, with a pass of yours in its query: opened in a browser, the preview keeps it in a cookie of its own and opens for 12 hours. A team member's alone \u2014 share links (hosting:previews:link) are for others.",te("site")],args:{min:1,max:1},flags:ot,scope:"environment",async run(e){let t;try{t=new URL(e.args[0])}catch{throw m(`${JSON.stringify(e.args[0])} is not an address: a preview's, as hosting:previews lists it`)}if(t.protocol!=="https:")throw m("a preview's address is https://\u2026");let{t:n,site:{name:s}}=await rt(e,kt(e),e.flags.site!==void 0),a=await h(e,n,"POST",`/sites/${de(s)}/previews/pass`,{to:t.href});e.out.result(a,()=>{e.out.line(a.url),e.out.note(`Open it in your browser: it opens the preview, as you, until ${a.expires_at}.`)})}},Ck=zo("site","hosting",Ci,ot),jk=Wo("site","hosting",Ci,ot),Ok=Vo("site","hosting",Ci,ot),Mk=Jo("site","hosting",Ci,ot),Xc=[ck,hk,mk,gk,fk,yk,bk,wk,vk,$k,Ok,...Mk,Pk,jk,Ak,Rk,Tk,Ek,...Ck];function Qc(e){return`its last push (${A(e.commit.slice(0,7))}) did not roll out \u2014 ${A(ks(e.reason))}`}function Lk(e){let t=`${e.running_version} serving`;if(e.version!==e.running_version){let s={waiting:"waiting to roll out",not_up:"not up",given_up:"given up on",migration:"held by its database migration",stopped:"not up (the machine is stopped)",failed:"not up (the machine cannot run)",no_room:"waiting for room in the cluster"}[e.state_reason_kind??""]??(e.state_reason?"not up":"rolling out");t+=`, ${e.version} ${s}`}return`${t}${e.build?` (build ${e.build.id}, ${e.build.commit.slice(0,7)})`:""}`}function Oi(e){return e.state_reason_kind==="no_room"?`${e.state}, waiting for room`:e.state}function ks(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t!=="").join(" \xB7 ")}function Ik(e){let t=e.openapi_path?`, from ${e.openapi_path}`:"";switch(e.contract_state){case"refused":return`refused: ${(e.contract_error??"its app wrote none").split(/\r?\n/).filter(s=>s.trim()!=="").map(A).join(`
|
|
37
|
-
${" ".repeat(15)}`)}${t}`;case"none":return`none: its app serves none${t}`}return`${e.contract_digest?`sha256:${e.contract_digest.slice(0,12)}\u2026`:"none read"}${t}`}var Dk=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;async function U(e,t,n,s,a,i){return(await _e(e.studio,t.env_ref,n,s,a,i)).body}function ne(e){if(!Dk.test(e))throw m(`${JSON.stringify(e)} is not a name: lowercase letters, digits and dashes, starting with a letter`);return encodeURIComponent(e)}async function ue(e,t){let n=await pn(e),s=n.t,{body:a,etag:i}=await _e(e.studio,s.env_ref,"GET",`/machines/${ne(t??await Nk(e,n))}`);return await On(e,n,a,()=>xk(e,s),`the machine ${a.name}`),{t:await Ln(e,s,a.environment,`the machine ${a.name}`),name:a.name,machine:a,etag:i}}async function xk(e,t){return oa(async n=>{let s=await U(e,t,"GET",`/machines?limit=100${n?`&cursor=${encodeURIComponent(n)}`:""}`);return{items:s.machines,next:s.next_cursor}})}async function eh(e,t,n){return oa(async s=>{let a=await U(e,t,"GET",ci(e,t,`/${n}?limit=100${s?`&cursor=${encodeURIComponent(s)}`:""}`));return{items:a[n],next:a.next_cursor}})}async function Nk(e,t){let{machines:n}=await U(e,t.t,"GET",ui(t,"/machines?limit=100"));if(n.length===1)return n[0].name;let s=await cs(e.io,e.io.cwd),a=s?.repository?n.filter(r=>r.source.repository.toLowerCase()===s.repository?.toLowerCase()&&(r.source.path??"")===s.path):[];if(a.length===1)return a[0].name;let i=t.by==="fallback"?"the project":`the environment ${t.t.env_slug}`;throw n.length===0?new f("no_machine",`${i} has no machine yet`,{hint:"make one with palbase machines:create"}):m("which machine? name it",`${i}'s machines: ${n.map(r=>r.name).join(", ")}`)}var Mi=async e=>{let{t,name:n}=await ue(e,e.flags.machine);return{t,path:`/machines/${ne(n)}`}},Ge={machine:{type:"string",value:"name",description:"the machine (default: the only one of the environment chosen here or -E's, the project's only one when neither says, or this directory's)"}},qk="Named by none, it is the only machine of the environment chosen for this directory or named by -E \u2014 never one bound elsewhere \u2014 else, when neither says, the project's only one; or the one this directory's code is built into.",ye=[te("machine"),qk];function th(e){let t=e.price_micros_per_hour;if(t===void 0)return e.free?"free":"";if(e.free)return`free, then $${(t/1e6).toFixed(3)} an hour`;let n=Math.round(t*730/1e4),s=n%100===0;return`$${(n/100).toLocaleString("en-US",{minimumFractionDigits:s?0:2,maximumFractionDigits:s?0:2})} a month${e.sleeps?" awake":""}`}function Kk(e){let t=`${(e.storage_bytes/1e9).toFixed(0)} GB`;return e.storage_adjustable?`${t}, or what you say (up to ${(e.max_storage_gb??4e3).toLocaleString("en-US")})`:t}function Gk(e){return`$${(e/1e6).toFixed(2)}`}function nh(e){return e>=1024&&e%1024===0?`${e/1024} GiB`:`${e} MiB`}function ji(e){return e<1e9?`${Number((e/1e6).toFixed(1)).toLocaleString("en-US")} MB`:`${Number((e/1e9).toFixed(2)).toLocaleString("en-US")} GB`}var sh={name:"machines:sizes",summary:"the machine sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await b(e),{sizes:n}=await U(e,t,"GET","/machines/sizes");e.out.result({sizes:n},()=>e.out.table(n,[{header:"size",value:s=>s.name},{header:"cpu",value:s=>`${s.vcpu} vCPU`},{header:"memory",value:s=>nh(s.memory_mib)},{header:"sleeps",value:s=>s.sleeps?"when idle":"never"},{header:"price",value:s=>th(s)},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},ah={name:"databases:sizes",summary:"the database sizes, and which of them this environment may open now",details:["A size that never sleeps holds the storage its database says \u2014 databases:create --storage, 1 GB or a multiple of 5, up to 4,000 \u2014 or the size's own: its price is its CPU and memory, and its storage is billed beside it by the GB-month past its first GB. free and hobby hold their size's."],scope:"environment",async run(e){let t=await b(e),{sizes:n}=await U(e,t,"GET","/databases/sizes");e.out.result({sizes:n},()=>{e.out.table(n,[{header:"size",value:a=>a.name},{header:"cpu",value:a=>`${a.vcpu} vCPU`},{header:"memory",value:a=>nh(a.memory_mib)},{header:"storage",value:a=>Kk(a)},{header:"sleeps",value:a=>a.sleeps?`when idle${a.awake_hours_per_month?`, ${a.awake_hours_per_month} h awake a month`:""}`:"never"},{header:"price",value:a=>`${th(a)}${a.storage_adjustable&&a.price_micros_per_hour!==void 0?" + storage":""}`},{header:"open",value:a=>a.available?"yes":`no \u2014 ${a.reason??""}`}]);let s=n.find(a=>a.storage_adjustable&&a.storage_price_micros_per_gb_month!==void 0);s&&(e.out.line(),e.out.line(`Storage: ${Gk(s.storage_price_micros_per_gb_month)} a GB-month past each database's first GB \u2014 what databases:create --storage says (1 GB or a multiple of 5), or the size's; it grows, never shrinks (databases:update --storage, --storage-autoscaling).`))})}},ih={name:"machines:list",summary:"the project's machines, each with the environment it is bound to: size, state, the version serving, address",usage:"[-E <env>]",details:["A project's machines are the project's: each is bound to one of its environments, whose settings, secrets and modules it takes, and the list is every environment's you reach. -E lists that environment's alone, as an environment's own token does."],scope:"environment",async run(e){let t=await jn(e),[n,s]=await Promise.all([eh(e,t,"machines"),hs(e.studio,t)]);e.out.result({machines:n},()=>{n.length===0&&e.out.line("No machine yet: palbase machines:create makes one from the code in this directory."),e.out.table(n,[{header:"name",value:a=>a.name},{header:"env",value:a=>`${Ft(s,a.environment)}${a.moving_to?` \u2192 ${Ft(s,a.moving_to)}`:""}`},{header:"size",value:a=>`${a.size}${a.autoscaling?` \xD7${a.replicas}\u2013${a.autoscaling.max_replicas}`:a.replicas>1?` \xD7${a.replicas}`:""}`},{header:"state",value:a=>Oi(a)},{header:"version",value:a=>a.running_version===a.version?`${a.version}`:`${a.running_version} \u2192 ${a.version}`},{header:"source",value:a=>`${a.source.repository}@${a.source.branch}${a.source.path?`/${a.source.path}`:""}`},{header:"url",value:a=>a.url}])})}},rh={name:"machines:move",summary:"bind a machine to another environment of the project: it starts there with that environment's settings, secrets and modules",usage:"<name> --to <env>",details:["The machine starts in the new environment at the version it serves, and what ran where it left answers until it is up there: no request goes unanswered. Its address names the new environment (<name>-<its ref>), and the one it had keeps working, for good.","Its domains of its own move with it and answer throughout. Its pull requests' previews are closed: a new push opens them in the new environment. The database it is given stays where it is kept, given to it across environments (databases:move moves a database).","It moves out of the environment it is bound to; -E picks it where two environments hold its name.","It needs the admin role in both environments, and the new environment room for it."],args:{min:1,max:1},flags:{to:{type:"string",value:"env",description:"the environment of the project it moves to (its slug)"}},scope:"environment",async run(e){let t=e.flags.to;if(typeof t!="string"||t==="")throw m("--to names the environment of the project it moves to");let{t:n,name:s}=await ue(e,e.args[0]),a=await la(e,n,t);await v(e,n,`move the machine ${s} out of this environment, into ${a.slug}`),await v(e,ie(a),`move the machine ${s} into this environment: it starts here with this environment's settings, secrets and modules`);let i=await U(e,n,"POST",`/machines/${ne(s)}/move`,{environment:a.ref});e.out.result(i,()=>e.out.line(`${i.name} moves to ${a.slug}: it starts there in a moment (palbase machines:get ${i.name}).`))}},oh={name:"machines:get",summary:"a machine of the project in full: the environment it is bound to, its source, size, database and the build serving",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,machine:n}=await ue(e,e.args[0]);e.out.result(n,()=>{e.out.line(`${n.name} \u2014 ${Oi(n)}${n.state_reason?` (${n.state_reason})`:""}`),e.out.line(` bound to ${t.env_slug}${n.moving_to?`, moving to ${n.moving_to.name||n.moving_to.ref}`:""}`),e.out.line(` url ${n.url}`),e.out.line(` source ${n.source.repository} @ ${n.source.branch}${n.source.path?`, ${n.source.path}`:""}${n.source.context?` (context ${n.source.context})`:""}`),e.out.line(` size ${n.size} \xD7 ${n.replicas}, port ${n.port}${n.health_path?`, health ${n.health_path}`:""}`),n.autoscaling&&e.out.line(` scaling ${Uk(n.replicas,n.autoscaling)}`),e.out.line(` version ${Lk(n)}`),n.failed_build&&e.out.line(` last push ${A(`${n.failed_build.commit.slice(0,7)} ${n.failed_build.state}: ${ks(n.failed_build.reason)}`)} (palbase machines:builds:log ${A(n.failed_build.id)} --machine ${n.name})`),e.out.line(` contract ${Ik(n)}`),e.out.line(` database ${n.database?.name?`${n.database.name}${n.database.migrations?", its migrations run before each release":""}`:"none"}`),e.out.line(` secrets ${n.secrets?`the ${n.secrets} secrets`:"none"}`),e.out.line(` tests ${n.test_command?`${n.test_command}${n.test_users?.length?`, as ${n.test_users.join(", ")}`:""} \u2014 run on each build before it rolls out`:"none"}`),e.out.line(` env ${Object.keys(n.env).length===0?"none":Object.keys(n.env).sort().join(", ")}`)})}},lh={repo:{type:"string",value:"owner/name",description:"the GitHub repository (default: this checkout's origin)"},branch:{type:"string",value:"branch",description:"the branch whose pushes are built and rolled out (default: the one checked out)"},path:{type:"string",value:"dir",description:"the directory built, from the repository's root (default: this directory's place in it)"},context:{type:"string",value:"dir",description:'what the build is given above --path (a monorepo: ".")'},size:{type:"string",value:"size",description:"its size (palbase machines:sizes lists them)"},replicas:{type:"string",value:"n",description:"how many copies run, 1 to 100 (one on Free), over two nodes at least and never all on one \u2014 with --max-replicas, the fewest its load runs (2 at least)"},"max-replicas":{type:"string",value:"n",description:"scale its copies by its load, up to n (2 to 100; Pay as you go): as many run as keep each near --cpu-percent and --memory-percent of its size"},"cpu-percent":{type:"string",value:"p",description:"with --max-replicas: the share of a copy's processor it is kept near, 10 to 95 (a copy is added above it)"},"memory-percent":{type:"string",value:"p",description:"with --max-replicas: the share of a copy's memory it is kept near, 10 to 95"},"no-autoscaling":{type:"boolean",description:"stop scaling it by its load: it runs --replicas (or the fewest it ran) always"},port:{type:"string",value:"port",description:"the port it listens on (it also finds it in PORT)"},"always-on":{type:"boolean",description:"keep it awake: never put to sleep when idle (a project on Pay as you go pays its every hour; on Free a shared machine sleeps when idle)"},"no-always-on":{type:"boolean",description:"let it sleep when idle again"},...wa,health:{type:"string",value:"path",description:"where it answers 2xx while well; a release that does not is not rolled out"},"openapi-path":{type:"string",value:"path",description:`where its app serves its OpenAPI contract, when it is not a Palbase backend (apps:sync makes its client from it); "" for a Palbase backend's own`},db:{type:"string",value:"database",description:'a database of the project it is given, whichever environment keeps it (PALBASE_DB_URL); "" for none'},migrations:{type:"boolean",description:"run the database's migrations before each release (a Palbase backend's)"},secrets:{type:"string",value:"production|development",description:'the secrets it is started with, by name; "" for none'},var:{type:"string",multiple:!0,value:"K=V",description:"a setting it is started with (repeat it); secrets go in secrets:set"},"test-command":{type:"string",value:"command",description:'what each new build runs before it takes traffic, in its image, against the new version itself once its migration has run (bun test, npm test); a failure fails the build and the machine runs what it ran; "" for none'},"test-users":{type:"string",value:"names",description:'the test users each test run makes for its tests (api.signInAs), comma-separated; "" for none'}};function dh(e,t){e.flags["test-command"]!==void 0&&(t.test_command=e.flags["test-command"]),e.flags["test-users"]!==void 0&&(t.test_users=ko(e.flags["test-users"]))}function ph(e){if(!e)return;let t={};for(let n of e){let s=n.indexOf("=");if(s<=0)throw m(`a setting is K=V, not ${JSON.stringify(n)}`);t[n.slice(0,s)]=n.slice(s+1)}return t}function uh(e){let t=ut(e.flags["max-replicas"],"max-replicas"),n=ut(e.flags["cpu-percent"],"cpu-percent"),s=ut(e.flags["memory-percent"],"memory-percent");if(e.flags["no-autoscaling"]===!0){if(t!==void 0||n!==void 0||s!==void 0)throw m("--no-autoscaling stops scaling it: give it alone, not with --max-replicas, --cpu-percent or --memory-percent");return null}if(t===void 0){if(n!==void 0||s!==void 0)throw m("--cpu-percent and --memory-percent go with --max-replicas: the most copies its load may run");return}if(n===void 0&&s===void 0)throw m("with --max-replicas give --cpu-percent, --memory-percent or both: what a copy is kept near");return{max_replicas:t,...n!==void 0?{cpu_percent:n}:{},...s!==void 0?{memory_percent:s}:{}}}function Uk(e,t){let n=[t.cpu_percent?`processor ${t.cpu_percent}%`:"",t.memory_percent?`memory ${t.memory_percent}%`:""].filter(s=>s!=="").join(" and ");return`${e}\u2013${t.max_replicas} copies by its load: ${n} of its size`}function ut(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw m(`--${t} is a whole number`);return n}async function ch(e,t){let{sizes:n}=await U(e,t,"GET","/machines/sizes"),s=n.find(a=>a.available)?.name;if(!s)throw new f("no_size_open","no machine size is open to this environment",{hint:"palbase machines:sizes says why"});return s}function hh(e,t,n){return{...e?{name:e}:{},source:{repository:t.repository,branch:t.branch,...t.path!==""?{path:t.path}:{},...t.context?{context:t.context}:{}},size:n}}var mh={name:"machines:create",summary:"make a machine of the project from the code in this directory, bound to one of its environments and built on every push to its branch",usage:"[name] [-E <env>] [--size <size>] [--db <database> --migrations] [--repo --branch --path --context] \u2026",details:["Run in a checkout, it reads the repository from origin, the branch from HEAD and the directory from where you are; flags say otherwise.",`${In} It takes that environment's settings, secrets and modules.`,"The first build starts at once; --wait follows it until the machine serves, and prints its address.","The environment needs its GitHub link first: palbase github:connect."],args:{min:0,max:1},flags:{...lh,wait:{type:"boolean",description:"follow the first build until the machine serves"}},scope:"environment",async run(e){let t=await Mn(e),n=await cs(e.io,e.io.cwd),s=e.flags.repo??n?.repository,a=e.flags.branch??n?.branch;if(!s)throw m("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!a)throw m("which branch? none is checked out here","pass --branch <branch>");let i=e.flags.size??await ch(e,t),r=e.flags.path??n?.path??"",o=hh(e.args[0],{repository:s,branch:a,path:r,context:e.flags.context},i),l=ut(e.flags.replicas,"replicas"),d=ut(e.flags.port,"port");l!==void 0&&(o.replicas=l),d!==void 0&&(o.port=d),e.flags["always-on"]===!0&&(o.always_on=!0),e.flags["no-always-on"]===!0&&(o.always_on=!1);let p=uh(e);p!==void 0&&(o.autoscaling=p),_a(e,o),e.flags.health!==void 0&&(o.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(o.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(o.secrets=e.flags.secrets);let u=ph(e.flags.var);if(u&&(o.env=u),e.flags.db!==void 0)o.database={name:e.flags.db,migrations:e.flags.migrations===!0};else if(e.flags.migrations===!0)throw m("--migrations goes with --db <database>");dh(e,o),await v(e,t,`make a machine from ${s}@${a}${r?`/${r}`:""} (${i})`);let g=await U(e,t,"POST","/machines",o);e.flags.wait===!0&&(g=await zk(e,t,g.name)),e.out.result(g,()=>e.out.line(`Made the machine ${g.name} (${g.size}) \u2014 ${g.state}; it answers at ${g.url}`))}},gh={name:"machines:update",summary:"change a machine of the project, in the environment it is bound to: the change rolls out as a new version beside the one serving",usage:"[name] [--size \u2026] [--replicas \u2026] [--db \u2026] [--repo --branch --path --context] \u2026",details:ye,args:{min:0,max:1},flags:lh,scope:"environment",async run(e){let{t,name:n,machine:s}=await ue(e,e.args[0]),a={};(e.flags.repo!==void 0||e.flags.branch!==void 0||e.flags.path!==void 0||e.flags.context!==void 0)&&(a.source={repository:e.flags.repo??s.source.repository,branch:e.flags.branch??s.source.branch,path:e.flags.path??s.source.path??"",context:e.flags.context??s.source.context??""}),e.flags.size!==void 0&&(a.size=e.flags.size);let i=ut(e.flags.replicas,"replicas"),r=ut(e.flags.port,"port");i!==void 0&&(a.replicas=i),r!==void 0&&(a.port=r),e.flags["always-on"]===!0&&(a.always_on=!0),e.flags["no-always-on"]===!0&&(a.always_on=!1);let o=uh(e);if(o!==void 0&&(a.autoscaling=o),_a(e,a),e.flags.health!==void 0&&(a.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(a.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(a.secrets=e.flags.secrets),e.flags.var!==void 0)throw m("machines:update leaves the settings as they are: machines:env:set and machines:env:unset change them");if(e.flags.db!==void 0&&(a.database={name:e.flags.db,migrations:e.flags.migrations===!0}),dh(e,a),Object.keys(a).length===0)throw m("nothing to change: give a flag","palbase help machines:update");await v(e,t,`change the machine ${n}: ${Object.keys(a).join(", ")}`);let l=await U(e,t,"PATCH",`/machines/${ne(n)}`,a);e.out.result(l,()=>e.out.line(`${l.name}: version ${l.version} rolls out beside ${l.running_version}.`))}},fh={name:"machines:env:list",summary:"what a machine of the project is started with, and where each comes from (the platform, the machine, its secrets)",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,machine:n}=await ue(e,e.args[0]),s=n.secrets?await U(e,t,"GET",`/secrets/${x("the machine's secret set",n.secrets)}`).then(r=>(r.items??r.secrets??[]).map(o=>o.name),()=>[]):[],a=["PORT","PALBASE_URL","PALBASE_PROJECT_ID","PALBASE_REPLICAS","PALBASE_PLATFORM_SECRET","PALBASE_SECRET_KEY","PALBASE_WEBHOOK_SECRET",...n.database?.name?["PALBASE_DB_URL","PALBASE_DB_CONNECTIONS"]:[]],i=a.map(r=>({name:r,from:"platform",note:s.includes(r)||r in n.env?`in place of the ${r} set by hand`:""}));for(let r of Object.keys(n.env).sort())a.includes(r)||i.push({name:r,from:"machine",note:s.includes(r)?`shadows the secret ${r}`:""});for(let r of s.sort())a.includes(r)||r in n.env||i.push({name:r,from:`secrets (${n.secrets})`,note:""});e.out.result({machine:n.name,env:i},()=>e.out.table(i,[{header:"name",value:r=>r.name},{header:"from",value:r=>r.from},{header:"",value:r=>r.note}]))}};async function yh(e,t){let{t:n,name:s,machine:a,etag:i}=await ue(e,e.flags.machine),r={body:a,etag:i};for(let o=1;;o++){o>1&&(r=await _e(e.studio,n.env_ref,"GET",`/machines/${ne(s)}`));let l={...r.body.env},d=t(l);if(o===1){if(r.body.secrets){let p=await U(e,n,"GET",`/secrets/${x("the machine's secret set",r.body.secrets)}`).catch(()=>({items:[]}));for(let u of Object.keys(l))(p.items??[]).some(g=>g.name===u)&&e.out.warn(`${u} in the machine's env shadows the secret of that name`)}await v(e,n,`${d.join(", ")} on the machine ${s}`)}try{let p=await U(e,n,"PATCH",`/machines/${ne(s)}`,{env:l},r.etag?{"if-match":r.etag}:void 0);e.out.result({machine:p.name,env:Object.keys(p.env).sort()},()=>e.out.line(`${p.name}: version ${p.version} rolls out with it.`));return}catch(p){if(!(p instanceof C&&p.status===412)||o===3)throw p;e.out.note(`${s} changed meanwhile: making the change again on what it is now\u2026`)}}}var bh={name:"machines:env:set",summary:"set settings a machine of the project is started with (not secrets: secrets:set keeps those)",usage:"K=V\u2026 [--machine <name>]",details:ye,args:{min:1,max:50},flags:Ge,scope:"environment",async run(e){let t=ph(e.args);await yh(e,n=>(Object.assign(n,t),Object.keys(t).map(s=>`set ${s}`)))}},wh={name:"machines:env:unset",summary:"take settings away from what a machine of the project is started with",usage:"K\u2026 [--machine <name>]",details:ye,args:{min:1,max:50},flags:Ge,scope:"environment",async run(e){await yh(e,t=>{for(let n of e.args){if(!(n in t))throw new f("no_such_setting",`the machine is not started with ${n}`);delete t[n]}return e.args.map(n=>`unset ${n}`)})}},vh={name:"machines:builds",summary:"a machine's builds, newest first",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),{builds:s}=await U(e,t,"GET",`/machines/${ne(n)}/builds?limit=20`);e.out.result({builds:s},()=>e.out.table(s,[{header:"build",value:a=>a.id},{header:"commit",value:a=>a.commit.slice(0,7)},{header:"state",value:a=>`${a.state}${a.running?" (serving)":""}${a.reason?` \u2014 ${ks(a.reason)}`:""}`},{header:"message",value:a=>a.message.split(`
|
|
37
|
+
${" ".repeat(15)}`)}${t}`;case"none":return`none: its app serves none${t}`}return`${e.contract_digest?`sha256:${e.contract_digest.slice(0,12)}\u2026`:"none read"}${t}`}var Dk=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;async function U(e,t,n,s,a,i){return(await _e(e.studio,t.env_ref,n,s,a,i)).body}function ne(e){if(!Dk.test(e))throw m(`${JSON.stringify(e)} is not a name: lowercase letters, digits and dashes, starting with a letter`);return encodeURIComponent(e)}async function ue(e,t){let n=await pn(e),s=n.t,{body:a,etag:i}=await _e(e.studio,s.env_ref,"GET",`/machines/${ne(t??await Nk(e,n))}`);return await On(e,n,a,()=>xk(e,s),`the machine ${a.name}`),{t:await Ln(e,s,a.environment,`the machine ${a.name}`),name:a.name,machine:a,etag:i}}async function xk(e,t){return oa(async n=>{let s=await U(e,t,"GET",`/machines?limit=100${n?`&cursor=${encodeURIComponent(n)}`:""}`);return{items:s.machines,next:s.next_cursor}})}async function eh(e,t,n){return oa(async s=>{let a=await U(e,t,"GET",ci(e,t,`/${n}?limit=100${s?`&cursor=${encodeURIComponent(s)}`:""}`));return{items:a[n],next:a.next_cursor}})}async function Nk(e,t){let{machines:n}=await U(e,t.t,"GET",ui(t,"/machines?limit=100"));if(n.length===1)return n[0].name;let s=await cs(e.io,e.io.cwd),a=s?.repository?n.filter(r=>r.source.repository.toLowerCase()===s.repository?.toLowerCase()&&(r.source.path??"")===s.path):[];if(a.length===1)return a[0].name;let i=t.by==="fallback"?"the project":`the environment ${t.t.env_slug}`;throw n.length===0?new f("no_machine",`${i} has no machine yet`,{hint:"make one with palbase machines:create"}):m("which machine? name it",`${i}'s machines: ${n.map(r=>r.name).join(", ")}`)}var Mi=async e=>{let{t,name:n}=await ue(e,e.flags.machine);return{t,path:`/machines/${ne(n)}`}},Ge={machine:{type:"string",value:"name",description:"the machine (default: the only one of the environment chosen here or -E's, the project's only one when neither says, or this directory's)"}},qk="Named by none, it is the only machine of the environment chosen for this directory or named by -E \u2014 never one bound elsewhere \u2014 else, when neither says, the project's only one; or the one this directory's code is built into.",ye=[te("machine"),qk];function th(e){let t=e.price_micros_per_hour;if(t===void 0)return e.free?"free":"";if(e.free)return`free, then $${(t/1e6).toFixed(3)} an hour`;let n=Math.round(t*730/1e4),s=n%100===0;return`$${(n/100).toLocaleString("en-US",{minimumFractionDigits:s?0:2,maximumFractionDigits:s?0:2})} a month${e.sleeps?" awake":""}`}function Kk(e){let t=`${(e.storage_bytes/1e9).toFixed(0)} GB`;return e.storage_adjustable?`${t}, or what you say (up to ${(e.max_storage_gb??4e3).toLocaleString("en-US")})`:t}function Gk(e){return`$${(e/1e6).toFixed(2)}`}function nh(e){return e>=1024&&e%1024===0?`${e/1024} GiB`:`${e} MiB`}function ji(e){return e<1e9?`${Number((e/1e6).toFixed(1)).toLocaleString("en-US")} MB`:`${Number((e/1e9).toFixed(2)).toLocaleString("en-US")} GB`}var sh={name:"machines:sizes",summary:"the machine sizes, and which of them this environment may open now",scope:"environment",async run(e){let t=await b(e),{sizes:n}=await U(e,t,"GET","/machines/sizes");e.out.result({sizes:n},()=>e.out.table(n,[{header:"size",value:s=>s.name},{header:"cpu",value:s=>`${s.vcpu} vCPU`},{header:"memory",value:s=>nh(s.memory_mib)},{header:"sleeps",value:s=>s.sleeps?"when idle":"never"},{header:"price",value:s=>th(s)},{header:"open",value:s=>s.available?"yes":`no \u2014 ${s.reason??""}`}]))}},ah={name:"databases:sizes",summary:"the database sizes, and which of them this environment may open now",details:["A size that never sleeps holds the storage its database says \u2014 databases:create --storage, 1 GB or a multiple of 5, up to 4,000 \u2014 or the size's own: its price is its CPU and memory, and its storage is billed beside it by the GB-month past its first GB. free and hobby hold their size's."],scope:"environment",async run(e){let t=await b(e),{sizes:n}=await U(e,t,"GET","/databases/sizes");e.out.result({sizes:n},()=>{e.out.table(n,[{header:"size",value:a=>a.name},{header:"cpu",value:a=>`${a.vcpu} vCPU`},{header:"memory",value:a=>nh(a.memory_mib)},{header:"storage",value:a=>Kk(a)},{header:"sleeps",value:a=>a.sleeps?`when idle${a.awake_hours_per_month?`, ${a.awake_hours_per_month} h awake a month`:""}`:"never"},{header:"price",value:a=>`${th(a)}${a.storage_adjustable&&a.price_micros_per_hour!==void 0?" + storage":""}`},{header:"open",value:a=>a.available?"yes":`no \u2014 ${a.reason??""}`}]);let s=n.find(a=>a.storage_adjustable&&a.storage_price_micros_per_gb_month!==void 0);s&&(e.out.line(),e.out.line(`Storage: ${Gk(s.storage_price_micros_per_gb_month)} a GB-month past each database's first GB \u2014 what databases:create --storage says (1 GB or a multiple of 5), or the size's; it grows, never shrinks (databases:update --storage, --storage-autoscaling).`))})}},ih={name:"machines:list",summary:"the project's machines, each with the environment it is bound to: size, state, the version serving, address",usage:"[-E <env>]",details:["A project's machines are the project's: each is bound to one of its environments, whose settings, secrets and modules it takes, and the list is every environment's you reach. -E lists that environment's alone, as an environment's own token does."],scope:"environment",async run(e){let t=await jn(e),[n,s]=await Promise.all([eh(e,t,"machines"),hs(e.studio,t)]);e.out.result({machines:n},()=>{n.length===0&&e.out.line("No machine yet: palbase machines:create makes one from the code in this directory."),e.out.table(n,[{header:"name",value:a=>a.name},{header:"env",value:a=>`${Ft(s,a.environment)}${a.moving_to?` \u2192 ${Ft(s,a.moving_to)}`:""}`},{header:"size",value:a=>`${a.size}${a.autoscaling?` \xD7${a.replicas}\u2013${a.autoscaling.max_replicas}`:a.replicas>1?` \xD7${a.replicas}`:""}`},{header:"state",value:a=>Oi(a)},{header:"version",value:a=>a.running_version===a.version?`${a.version}`:`${a.running_version} \u2192 ${a.version}`},{header:"source",value:a=>`${a.source.repository}@${a.source.branch}${a.source.path?`/${a.source.path}`:""}`},{header:"url",value:a=>a.url}])})}},rh={name:"machines:move",summary:"bind a machine to another environment of the project: it starts there with that environment's settings, secrets and modules",usage:"<name> --to <env>",details:["The machine starts in the new environment at the version it serves, and what ran where it left answers until it is up there: no request goes unanswered. Its address names the new environment (<name>-<its ref>), and the one it had keeps working, for good.","Its domains of its own move with it and answer throughout. Its pull requests' previews are closed: a new push opens them in the new environment. The database it is given stays where it is kept, given to it across environments (databases:move moves a database).","It moves out of the environment it is bound to; -E picks it where two environments hold its name.","It needs the admin role in both environments, and the new environment room for it."],args:{min:1,max:1},flags:{to:{type:"string",value:"env",description:"the environment of the project it moves to (its slug)"}},scope:"environment",async run(e){let t=e.flags.to;if(typeof t!="string"||t==="")throw m("--to names the environment of the project it moves to");let{t:n,name:s}=await ue(e,e.args[0]),a=await la(e,n,t);await v(e,n,`move the machine ${s} out of this environment, into ${a.slug}`),await v(e,ie(a),`move the machine ${s} into this environment: it starts here with this environment's settings, secrets and modules`);let i=await U(e,n,"POST",`/machines/${ne(s)}/move`,{environment:a.ref});e.out.result(i,()=>e.out.line(`${i.name} moves to ${a.slug}: it starts there in a moment (palbase machines:get ${i.name}).`))}},oh={name:"machines:get",summary:"a machine of the project in full: the environment it is bound to, its source, size, database and the build serving",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,machine:n}=await ue(e,e.args[0]);e.out.result(n,()=>{e.out.line(`${n.name} \u2014 ${Oi(n)}${n.state_reason?` (${n.state_reason})`:""}`),e.out.line(` bound to ${t.env_slug}${n.moving_to?`, moving to ${n.moving_to.name||n.moving_to.ref}`:""}`),e.out.line(` url ${n.url}`),e.out.line(` source ${n.source.repository} @ ${n.source.branch}${n.source.path?`, ${n.source.path}`:""}${n.source.context?` (context ${n.source.context})`:""}`),e.out.line(` size ${n.size} \xD7 ${n.replicas}, port ${n.port}${n.health_path?`, health ${n.health_path}`:""}`),n.autoscaling&&e.out.line(` scaling ${Uk(n.replicas,n.autoscaling)}`),e.out.line(` version ${Lk(n)}`),n.failed_build&&e.out.line(` last push ${A(`${n.failed_build.commit.slice(0,7)} ${n.failed_build.state}: ${ks(n.failed_build.reason)}`)} (palbase machines:builds:log ${A(n.failed_build.id)} --machine ${n.name})`),e.out.line(` contract ${Ik(n)}`),e.out.line(` database ${n.database?.name?`${n.database.name}${n.database.migrations?", its migrations run before each release":""}`:"none"}`),e.out.line(` secrets ${n.secrets?`the ${n.secrets} secrets`:"none"}`),e.out.line(` tests ${n.test_command?`${n.test_command}${n.test_users?.length?`, as ${n.test_users.join(", ")}`:""} \u2014 run on each build before it rolls out`:"none"}`),e.out.line(` env ${Object.keys(n.env).length===0?"none":Object.keys(n.env).sort().join(", ")}`)})}},lh={repo:{type:"string",value:"owner/name",description:"the GitHub repository (default: this checkout's origin)"},branch:{type:"string",value:"branch",description:"the branch whose pushes are built and rolled out (default: the one checked out)"},path:{type:"string",value:"dir",description:"the directory built, from the repository's root (default: this directory's place in it)"},context:{type:"string",value:"dir",description:'what the build is given above --path (a monorepo: ".")'},size:{type:"string",value:"size",description:"its size (palbase machines:sizes lists them)"},replicas:{type:"string",value:"n",description:"how many copies run, 1 to 100 (one on Free), over two nodes at least and never all on one \u2014 with --max-replicas, the fewest its load runs (2 at least)"},"max-replicas":{type:"string",value:"n",description:"scale its copies by its load, up to n (2 to 100; Pay as you go): as many run as keep each near --cpu-percent and --memory-percent of its size"},"cpu-percent":{type:"string",value:"p",description:"with --max-replicas: the share of a copy's processor it is kept near, 10 to 95 (a copy is added above it)"},"memory-percent":{type:"string",value:"p",description:"with --max-replicas: the share of a copy's memory it is kept near, 10 to 95"},"no-autoscaling":{type:"boolean",description:"stop scaling it by its load: it runs --replicas (or the fewest it ran) always"},port:{type:"string",value:"port",description:"the port it listens on (it also finds it in PORT)"},"always-on":{type:"boolean",description:"keep it awake: never put to sleep when idle (a project on Pay as you go pays its every hour; on Free a shared machine sleeps when idle)"},"no-always-on":{type:"boolean",description:"let it sleep when idle again"},...wa,health:{type:"string",value:"path",description:"where it answers 2xx while well; a release that does not is not rolled out"},"openapi-path":{type:"string",value:"path",description:`where its app serves its OpenAPI contract, when it is not a Palbase backend (apps:sync makes its client from it); "" for a Palbase backend's own`},db:{type:"string",value:"database",description:'a database of the project it is given, whichever environment keeps it (PALBASE_DB_URL); "" for none'},migrations:{type:"boolean",description:"run the database's migrations before each release (a Palbase backend's)"},secrets:{type:"string",value:"production|development",description:'the secrets it is started with, by name; "" for none'},var:{type:"string",multiple:!0,value:"K=V",description:"a setting it is started with (repeat it); secrets go in secrets:set"},"test-command":{type:"string",value:"command",description:'what each new build runs before it takes traffic, in its image, against the new version itself once its migration has run (bun test, npm test); a failure fails the build and the machine runs what it ran; "" for none'},"test-users":{type:"string",value:"names",description:'the test users each test run makes for its tests (api.signInAs), comma-separated; "" for none'}};function dh(e,t){e.flags["test-command"]!==void 0&&(t.test_command=e.flags["test-command"]),e.flags["test-users"]!==void 0&&(t.test_users=ko(e.flags["test-users"]))}function ph(e){if(!e)return;let t={};for(let n of e){let s=n.indexOf("=");if(s<=0)throw m(`a setting is K=V, not ${JSON.stringify(n)}`);t[n.slice(0,s)]=n.slice(s+1)}return t}function uh(e,t){let n=ut(e.flags["max-replicas"],"max-replicas"),s=ut(e.flags["cpu-percent"],"cpu-percent"),a=ut(e.flags["memory-percent"],"memory-percent");if(e.flags["no-autoscaling"]===!0){if(n!==void 0||s!==void 0||a!==void 0)throw m("--no-autoscaling stops scaling it: give it alone, not with --max-replicas, --cpu-percent or --memory-percent");return null}if(n===void 0&&s===void 0&&a===void 0)return;let i=n??t?.max_replicas;if(i===void 0)throw m("--cpu-percent and --memory-percent go with --max-replicas: the most copies its load may run");let r=s??t?.cpu_percent,o=a??t?.memory_percent;if(r===void 0&&o===void 0)throw m("with --max-replicas give --cpu-percent, --memory-percent or both: what a copy is kept near");return{max_replicas:i,...r!==void 0?{cpu_percent:r}:{},...o!==void 0?{memory_percent:o}:{}}}function Uk(e,t){let n=[t.cpu_percent?`processor ${t.cpu_percent}%`:"",t.memory_percent?`memory ${t.memory_percent}%`:""].filter(s=>s!=="").join(" and ");return`${e}\u2013${t.max_replicas} copies by its load: ${n} of its size`}function ut(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw m(`--${t} is a whole number`);return n}async function ch(e,t){let{sizes:n}=await U(e,t,"GET","/machines/sizes"),s=n.find(a=>a.available)?.name;if(!s)throw new f("no_size_open","no machine size is open to this environment",{hint:"palbase machines:sizes says why"});return s}function hh(e,t,n){return{...e?{name:e}:{},source:{repository:t.repository,branch:t.branch,...t.path!==""?{path:t.path}:{},...t.context?{context:t.context}:{}},size:n}}var mh={name:"machines:create",summary:"make a machine of the project from the code in this directory, bound to one of its environments and built on every push to its branch",usage:"[name] [-E <env>] [--size <size>] [--db <database> --migrations] [--repo --branch --path --context] \u2026",details:["Run in a checkout, it reads the repository from origin, the branch from HEAD and the directory from where you are; flags say otherwise.",`${In} It takes that environment's settings, secrets and modules.`,"The first build starts at once; --wait follows it until the machine serves, and prints its address.","The environment needs its GitHub link first: palbase github:connect."],args:{min:0,max:1},flags:{...lh,wait:{type:"boolean",description:"follow the first build until the machine serves"}},scope:"environment",async run(e){let t=await Mn(e),n=await cs(e.io,e.io.cwd),s=e.flags.repo??n?.repository,a=e.flags.branch??n?.branch;if(!s)throw m("which repository? this directory's origin is not a GitHub repository","pass --repo owner/name");if(!a)throw m("which branch? none is checked out here","pass --branch <branch>");let i=e.flags.size??await ch(e,t),r=e.flags.path??n?.path??"",o=hh(e.args[0],{repository:s,branch:a,path:r,context:e.flags.context},i),l=ut(e.flags.replicas,"replicas"),d=ut(e.flags.port,"port");l!==void 0&&(o.replicas=l),d!==void 0&&(o.port=d),e.flags["always-on"]===!0&&(o.always_on=!0),e.flags["no-always-on"]===!0&&(o.always_on=!1);let p=uh(e);p!==void 0&&(o.autoscaling=p),_a(e,o),e.flags.health!==void 0&&(o.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(o.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(o.secrets=e.flags.secrets);let u=ph(e.flags.var);if(u&&(o.env=u),e.flags.db!==void 0)o.database={name:e.flags.db,migrations:e.flags.migrations===!0};else if(e.flags.migrations===!0)throw m("--migrations goes with --db <database>");dh(e,o),await v(e,t,`make a machine from ${s}@${a}${r?`/${r}`:""} (${i})`);let g=await U(e,t,"POST","/machines",o);e.flags.wait===!0&&(g=await zk(e,t,g.name)),e.out.result(g,()=>e.out.line(`Made the machine ${g.name} (${g.size}) \u2014 ${g.state}; it answers at ${g.url}`))}},gh={name:"machines:update",summary:"change a machine of the project, in the environment it is bound to: the change rolls out as a new version beside the one serving",usage:"[name] [--size \u2026] [--replicas \u2026] [--db \u2026] [--repo --branch --path --context] \u2026",details:ye,args:{min:0,max:1},flags:lh,scope:"environment",async run(e){let{t,name:n,machine:s}=await ue(e,e.args[0]),a={};(e.flags.repo!==void 0||e.flags.branch!==void 0||e.flags.path!==void 0||e.flags.context!==void 0)&&(a.source={repository:e.flags.repo??s.source.repository,branch:e.flags.branch??s.source.branch,path:e.flags.path??s.source.path??"",context:e.flags.context??s.source.context??""}),e.flags.size!==void 0&&(a.size=e.flags.size);let i=ut(e.flags.replicas,"replicas"),r=ut(e.flags.port,"port");i!==void 0&&(a.replicas=i),r!==void 0&&(a.port=r),e.flags["always-on"]===!0&&(a.always_on=!0),e.flags["no-always-on"]===!0&&(a.always_on=!1);let o=uh(e,s.autoscaling);if(o!==void 0&&(a.autoscaling=o),_a(e,a),e.flags.health!==void 0&&(a.health_path=e.flags.health),e.flags["openapi-path"]!==void 0&&(a.openapi_path=e.flags["openapi-path"]),e.flags.secrets!==void 0&&(a.secrets=e.flags.secrets),e.flags.var!==void 0)throw m("machines:update leaves the settings as they are: machines:env:set and machines:env:unset change them");if(e.flags.db!==void 0&&(a.database={name:e.flags.db,migrations:e.flags.migrations===!0}),dh(e,a),Object.keys(a).length===0)throw m("nothing to change: give a flag","palbase help machines:update");await v(e,t,`change the machine ${n}: ${Object.keys(a).join(", ")}`);let l=await U(e,t,"PATCH",`/machines/${ne(n)}`,a);e.out.result(l,()=>e.out.line(`${l.name}: version ${l.version} rolls out beside ${l.running_version}.`))}},fh={name:"machines:env:list",summary:"what a machine of the project is started with, and where each comes from (the platform, the machine, its secrets)",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,machine:n}=await ue(e,e.args[0]),s=n.secrets?await U(e,t,"GET",`/secrets/${x("the machine's secret set",n.secrets)}`).then(r=>(r.items??r.secrets??[]).map(o=>o.name),()=>[]):[],a=["PORT","PALBASE_URL","PALBASE_PROJECT_ID","PALBASE_REPLICAS","PALBASE_PLATFORM_SECRET","PALBASE_SECRET_KEY","PALBASE_WEBHOOK_SECRET",...n.database?.name?["PALBASE_DB_URL","PALBASE_DB_CONNECTIONS","PALBASE_DB_POOLED_URL","PALBASE_DB_POOLED_CONNECTIONS"]:[]],i=a.map(r=>({name:r,from:"platform",note:s.includes(r)||r in n.env?`in place of the ${r} set by hand`:""}));for(let r of Object.keys(n.env).sort())a.includes(r)||i.push({name:r,from:"machine",note:s.includes(r)?`shadows the secret ${r}`:""});for(let r of s.sort())a.includes(r)||r in n.env||i.push({name:r,from:`secrets (${n.secrets})`,note:""});e.out.result({machine:n.name,env:i},()=>e.out.table(i,[{header:"name",value:r=>r.name},{header:"from",value:r=>r.from},{header:"",value:r=>r.note}]))}};async function yh(e,t){let{t:n,name:s,machine:a,etag:i}=await ue(e,e.flags.machine),r={body:a,etag:i};for(let o=1;;o++){o>1&&(r=await _e(e.studio,n.env_ref,"GET",`/machines/${ne(s)}`));let l={...r.body.env},d=t(l);if(o===1){if(r.body.secrets){let p=await U(e,n,"GET",`/secrets/${x("the machine's secret set",r.body.secrets)}`).catch(()=>({items:[]}));for(let u of Object.keys(l))(p.items??[]).some(g=>g.name===u)&&e.out.warn(`${u} in the machine's env shadows the secret of that name`)}await v(e,n,`${d.join(", ")} on the machine ${s}`)}try{let p=await U(e,n,"PATCH",`/machines/${ne(s)}`,{env:l},r.etag?{"if-match":r.etag}:void 0);e.out.result({machine:p.name,env:Object.keys(p.env).sort()},()=>e.out.line(`${p.name}: version ${p.version} rolls out with it.`));return}catch(p){if(!(p instanceof C&&p.status===412)||o===3)throw p;e.out.note(`${s} changed meanwhile: making the change again on what it is now\u2026`)}}}var bh={name:"machines:env:set",summary:"set settings a machine of the project is started with (not secrets: secrets:set keeps those)",usage:"K=V\u2026 [--machine <name>]",details:ye,args:{min:1,max:50},flags:Ge,scope:"environment",async run(e){let t=ph(e.args);await yh(e,n=>(Object.assign(n,t),Object.keys(t).map(s=>`set ${s}`)))}},wh={name:"machines:env:unset",summary:"take settings away from what a machine of the project is started with",usage:"K\u2026 [--machine <name>]",details:ye,args:{min:1,max:50},flags:Ge,scope:"environment",async run(e){await yh(e,t=>{for(let n of e.args){if(!(n in t))throw new f("no_such_setting",`the machine is not started with ${n}`);delete t[n]}return e.args.map(n=>`unset ${n}`)})}},vh={name:"machines:builds",summary:"a machine's builds, newest first",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),{builds:s}=await U(e,t,"GET",`/machines/${ne(n)}/builds?limit=20`);e.out.result({builds:s},()=>e.out.table(s,[{header:"build",value:a=>a.id},{header:"commit",value:a=>a.commit.slice(0,7)},{header:"state",value:a=>`${a.state}${a.running?" (serving)":""}${a.reason?` \u2014 ${ks(a.reason)}`:""}`},{header:"message",value:a=>a.message.split(`
|
|
38
38
|
`)[0].slice(0,60)},{header:"created",value:a=>a.created_at}]))}},_h={name:"machines:previews",summary:"a machine's pull request previews, newest first: each a machine of its own while its pull request is open",usage:"[name]",details:ye,args:{min:0,max:1},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),{previews:s}=await U(e,t,"GET",`/machines/${ne(n)}/previews`);e.out.result({previews:s},()=>Fo(e,s,`${n} has no preview: machines:update ${n} --previews previews its pull requests (in a preview environment).`))}},kh=zo("machine","machines",Mi,Ge),Sh=Wo("machine","machines",Mi,Ge),$h=Vo("machine","machines",Mi,Ge),Ph=Jo("machine","machines",Mi,Ge),Ah={name:"machines:previews:open",summary:"open a machine's pull request preview again \u2014 one closed after 3 days with no push, or refused \u2014 at the pull request's head",usage:"<pull request> [--machine <name>]",details:["Its machine is made again and built at the pull request's head; a machine that runs its database's migrations has its preview given a new, empty database of its own, migrated by the preview's release.","A preview that is open goes on as it is, and its 3 days start again. A fork's, under fork protection, opens at a head an admin authorized (previews:authorize).",...ye],args:{min:1,max:1},flags:Ge,scope:"environment",async run(e){let t=Number(e.args[0].replace(/^#/,""));if(!Number.isInteger(t)||t<=0)throw m("the pull request is its number: 12, or #12");let{t:n,name:s}=await ue(e,e.flags.machine),a=await U(e,n,"POST",`/machines/${ne(s)}/previews/${t}/open`);e.out.result(a,()=>e.out.line(`#${t}: its preview is being built at ${a.commit.slice(0,7)} (palbase machines:previews ${s}).`))}},Rh={name:"machines:builds:log",summary:"a build's log (the newest build's when none is named)",usage:"[build] [--machine <name>]",details:ye,args:{min:0,max:1},flags:Ge,scope:"environment",async run(e){let{t,name:n}=await ue(e,e.flags.machine),s=e.args[0];if(!s){let{builds:r}=await U(e,t,"GET",`/machines/${ne(n)}/builds?limit=1`);if(r.length===0)throw new f("no_build",`${n} has no build yet`);s=r[0].id}let a;try{a=await U(e,t,"GET",`/machines/${ne(n)}/builds/${x("the build's id",s)}/log`)}catch(r){if(!(r instanceof C))throw r;if(r.code==="log_not_ready"){e.out.result({build:s,started:!1,log:""},()=>e.out.note(`The build ${s} has not started yet: its log is there once it has (palbase machines:builds ${n}).`));return}if(r.code==="no_log"){let o=await U(e,t,"GET",`/machines/${ne(n)}/builds/${x("the build's id",s)}`);throw new f("no_log",`the build ${s} ended before it ran, so it has no log: ${o.state}${o.reason?` \u2014 ${ks(o.reason)}`:""}`)}throw r}let i=typeof a=="string"?a:a==null?"":JSON.stringify(a);e.out.result({build:s,log:i},()=>{if(i==="")e.out.note(`The build ${s} has written no log yet (palbase machines:builds ${n}).`);else for(let r of i.split(`
|
|
39
39
|
`))e.out.line(r)})}},Th={name:"machines:logs",summary:"a machine's log: the last hour, or since a time; -f follows what it writes next",usage:"[name] [-f] [--since <time>] [--lines <n>] [--search <text>]",details:["Besides the machine's own lines: its migration runs' (migration), and what a build printed while its tests ran against it (test) \u2014 the error it answered a test with, and that request's id: palbase machines:logs <name> --search <request_id>.",...ye],args:{min:0,max:1},flags:{follow:{type:"boolean",short:"f",description:"keep printing what the machine writes"},since:{type:"string",value:"time",description:"from when: an RFC 3339 time, or 10m, 2h, 1d ago"},lines:{type:"string",value:"n",description:"how many lines at most (default 200)"},search:{type:"string",value:"text",description:"only the lines that hold this text"}},scope:"environment",async run(e){let{t,name:n}=await ue(e,e.args[0]),s=ut(e.flags.lines,"lines")??200,a=e.flags.since?Wk(e.flags.since,e.io.now()):void 0,i=e.flags.search,r=new Set,o=async d=>{let p=new URLSearchParams({lines:String(s),order:d,...a?{since:a}:{},...i?{q:i}:{}}),u=await U(e,t,"GET",`/machines/${ne(n)}/logs?${p}`),g=u!==null&&typeof u=="object"?[u]:String(u??"").split(`
|
|
40
40
|
`).filter(y=>y.trim()!=="").map(y=>JSON.parse(y));return d==="desc"?g.reverse():g},l=d=>{for(let p of d)r.has(p.id)||(r.add(p.id),e.global.json?e.io.stdout(`${JSON.stringify(p)}
|