palbase 0.76.0 → 0.78.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai-sdk/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/3I5XH3A3.js +13 -0
- package/dist/chunks/{MKVIRNSJ.js → 3X3ZT72M.js} +2 -2
- package/dist/chunks/{TGQGGUE6.js → 5H3UYFOC.js} +2 -2
- package/dist/chunks/5OBOVEK6.js +2 -0
- package/dist/chunks/{KEGVHELA.js → AKJC5WTU.js} +1 -1
- package/dist/chunks/{TUK6NH2Q.js → AMKY4SZU.js} +2 -2
- package/dist/chunks/B64J3E3T.js +2 -0
- package/dist/chunks/{5RNXCTOO.js → EFELMJMQ.js} +2 -2
- package/dist/chunks/{ZCMCYI2D.js → FOZVJW7G.js} +2 -2
- package/dist/chunks/{BRDO3ZPT.js → HHKRAOVG.js} +1 -1
- package/dist/chunks/{ISMWEEGW.js → HVRVTNMI.js} +1 -1
- package/dist/chunks/{SVWF7ABJ.js → JSRN4NOZ.js} +2 -2
- package/dist/chunks/{33XOVYAU.js → MA74JJUB.js} +4 -4
- package/dist/chunks/{UHN63FGH.js → MFWAOKLM.js} +2 -2
- package/dist/chunks/{PGQNRJ2C.js → NG4OMSEK.js} +2 -2
- package/dist/chunks/{5YJZAPY2.js → NQUAVRMC.js} +2 -2
- package/dist/chunks/{EXLA3A7O.js → Q3GH7I66.js} +2 -2
- package/dist/chunks/{3CN6HGTW.js → QL2UAO36.js} +1 -1
- package/dist/chunks/{DKYFIOWM.js → QOETZ4FB.js} +1 -1
- package/dist/chunks/RP2TPMXT.js +2 -0
- package/dist/chunks/S7C7NHZI.js +18 -0
- package/dist/chunks/{D6NOE76D.js → SHYJVOD2.js} +1 -1
- package/dist/chunks/{A3I7H7QN.js → VP3HFVV4.js} +1 -1
- package/dist/chunks/{UOW74IHY.js → XVJ3CMFN.js} +2 -2
- package/dist/chunks/{Q4UWBIJ6.js → YQQKZUVS.js} +2 -2
- package/dist/cli.js +243 -187
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/payments-ui.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/ai.d.ts +6 -2
- package/types/ai/src/chats.d.ts +29 -10
- package/types/ai/src/index.d.ts +2 -2
- package/types/ai/src/pools.d.ts +15 -24
- package/types/cloud/src/generated/project.d.ts +3 -3
- package/types/cloud/src/generated/studio.d.ts +4 -6
- package/types/internal/src/ai-machines.d.ts +120 -0
- package/types/internal/src/chat.d.ts +29 -1
- package/types/internal/src/modules/ai.d.ts +192 -79
- package/types/internal/src/modules/analytics.d.ts +5 -1
- package/types/internal/src/modules/auth.d.ts +3 -28
- package/types/internal/src/modules/commerce.d.ts +92 -13
- package/types/internal/src/modules/events.d.ts +2 -2
- package/types/internal/src/modules/iap.d.ts +2 -2
- package/types/internal/src/modules/journeys.d.ts +2 -2
- package/types/internal/src/modules/machines.d.ts +33 -33
- package/types/internal/src/modules/notify.d.ts +2 -2
- package/types/internal/src/modules/payments.d.ts +83 -14
- package/types/internal/src/modules/stores.d.ts +3 -3
- package/types/internal/src/modules/workspaces.d.ts +5 -5
- package/types/web/src/ai-machines.d.ts +76 -0
- package/types/web/src/chat.d.ts +21 -1
- package/types/web/src/index.d.ts +3 -1
- package/types/web/src/templates.d.ts +8 -0
- package/dist/chunks/2NEPN2ZZ.js +0 -2
- package/dist/chunks/3VGWTVKI.js +0 -2
- package/dist/chunks/ALT62XIG.js +0 -13
- package/dist/chunks/YRYPXVAJ.js +0 -18
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{e as _t}from"./ZCMCYI2D.js";import{e as wt,g as bt,h as St}from"./ALT62XIG.js";import{c as qe}from"./2NEPN2ZZ.js";import{h as kt}from"./5YJZAPY2.js";import{a as vt}from"./TUK6NH2Q.js";import{r as gt,t as mt,u as yt}from"./DKYFIOWM.js";import{b as Z,c as G,e as ct,f as ut,g as W,h as ht,i as pt,l as Ue,m as H}from"./3VGWTVKI.js";import{a as ft,b as ee}from"./SVWF7ABJ.js";import{b as w,d as $}from"./UOW74IHY.js";function Ss(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 T=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 Pt(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 Tt(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);return typeof s=="object"&&s!==null?s:{}}catch{return{}}}function je(r){let{sub:e}=Tt(r);return typeof e=="string"?e:""}function ks(r,e){let{iat:t,exp:s}=Tt(r);return typeof t!="number"||typeof s!="number"||!(s>t)?e:Math.min(e,(s-t)*1e3/2)}var _s=6e4,Rs=15e3;function Ps(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var ae=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??Rs,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??je(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>ks(e.accessToken,_s))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=Ps(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new T("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 T("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",Ss(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 T("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 T("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 Ke=class{state="closed";refusal;logSeq;joinRef=null;refusals=0;retry=null;asking=0;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{}}},oe=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;asks=0;epoch=0;wasOpen=!1;current="idle";statusListeners=new Set;reconnects=0;opts;constructor(e){this.opts=e}get status(){return this.current}onStatus(e){return this.statusListeners.add(e),()=>{this.statusListeners.delete(e)}}setStatus(e){if(this.current!==e){this.current=e;for(let t of[...this.statusListeners])try{t(e)}catch{}}}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Ke(e,this,t)),s}disconnect(){this.closedByUs=!0,this.wasOpen=!1,this.epoch++,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.attempts=0,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.asking=0,t.closed("the socket was closed");this.lastJoin.clear(),this.current!=="idle"&&this.setStatus("disconnected")}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(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.open().catch(()=>{}));for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,this.askAgain(e))}join(e){if(e.state="joining",this.ws?.readyState===1){this.sendJoin(e);return}this.reconnectTimer||this.open().catch(()=>{})}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=B(setTimeout(()=>{e.retry=null,this.askAgain(e)},s))}askAgain(e){this.reconnectTimer||this.channels.get(e.name)!==e||e.state!=="refused"||this.join(e)}joinWanted(){for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,e.state="joining"),e.state==="joining"&&this.sendJoin(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,this.current!=="reconnecting"&&this.setStatus("connecting");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;try{a=new e(t)}catch(o){this.setStatus("reconnecting");let d=o instanceof Error?o.message:String(o);for(let l of this.channels.values())l.state==="joining"&&this.settle(l,!1,{reason:d});n(o);return}this.ws=a,a.onopen=()=>{if(this.ws!==a){a.close(1e3),n(new Error("the socket was closed"));return}this.attempts=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wasOpen&&this.reconnects++,this.wasOpen=!0,this.startHeartbeat(),this.setStatus("connected"),this.joinWanted(),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,e.onmessage=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)return;if(![...this.channels.values()].some(i=>i.state==="joining"||i.state==="refused")){this.wasOpen=!1,this.setStatus("disconnected");return}if(this.setStatus("reconnecting"),this.reconnectTimer)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=B(setTimeout(()=>{this.reconnectTimer=null,this.open().catch(()=>{})},s))}async sendJoin(e){if(e.asking)return;let t=++this.asks;e.asking=t;try{await this.ask(e)}finally{e.asking===t&&(e.asking=0)}}async ask(e){let t=this.ws;if(t?.readyState!==1)return;let s=this.epoch,i;try{i=await this.opts.accessToken()}catch(c){s===this.epoch&&this.ws===t&&this.channels.get(e.name)===e&&e.state==="joining"&&this.settle(e,!1,{reason:c instanceof Error?c.message:String(c)});return}if(s!==this.epoch||this.channels.get(e.name)!==e||e.state!=="joining"||this.ws!==t||t.readyState!==1)return;let n=this.nextRef();e.joinRef=n;let a=this.awaitReply(n),o={broadcast:{self:!1}};e.logSeq!==void 0&&(o.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(n,e.topic,"phx_join",{access_token:i,config:o},n);let{status:d,response:l}=await a;if(!(d!=="ok"&&this.ws!==t)){if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),d==="ok"&&this.ws?.readyState===1&&this.push(n,e.topic,"phx_leave",{}));return}if(d==="timeout"){this.askOnLater(e);return}this.settle(e,d==="ok",l)}}askOnLater(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=B(setTimeout(()=>{e.retry=null,this.channels.get(e.name)===e&&e.state==="joining"&&this.ws?.readyState===1&&this.sendJoin(e)},s))}awaitReply(e){return new Promise(t=>{let s=B(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,o]=t,d=typeof o=="object"&&o!==null?o:{};if(a==="phx_reply"&&typeof i=="string"){if(i===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(i)?.(String(d.status),d.response??{});return}let l=[...this.channels.values()].find(c=>c.topic===n);if(l&&!((a==="phx_close"||a==="phx_error")&&typeof s=="string"&&l.joinRef!==null&&s!==l.joinRef)){if(a==="phx_close"){if(l.state!=="joined")return;l.state="refused",l.refusal={reason:"closed by the server"},this.askAgainLater(l);return}if(a==="phx_error"){l.state="joining",B(setTimeout(()=>this.channels.get(l.name)===l&&l.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(l),1e3));return}l.deliver(a,d)}}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=B(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null;let e=this.ws;e?.close(4e3),e&&this.dropped(e);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 B(r){return r.unref?.(),r}var O="X-Palbase-Installation-Secret",J="X-Palbase-Installation",xt=new WeakMap;function A(r){return xt.get(r)}var Mt=new WeakSet;function It(r){return Mt.has(r)}var Ts=/^[A-Za-z0-9_-]{43}$/,de=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Ct()?.getItem(t);i&&Ts.test(i)&&(s=i)}catch{}if(!s){Mt.add(this),s=Ot(crypto.getRandomValues(new Uint8Array(32)));try{Ct()?.setItem(t,s)}catch{}}xt.set(this,s),this.id=Cs(s)}};function Cs(r){return Ot(Ms(new TextEncoder().encode(r)).subarray(0,16))}function Ct(){try{return globalThis.localStorage}catch{return}}function Ot(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var xs=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]),L=(r,e)=>r>>>e|r<<32-e;function Ms(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 y=L(i[g-15],7)^L(i[g-15],18)^i[g-15]>>>3,R=L(i[g-2],17)^L(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+y+i[g-7]+R|0}let[d,l,c,h,p,b,f,u]=e;for(let g=0;g<64;g++){let y=u+(L(p,6)^L(p,11)^L(p,25))+(p&b^~p&f)+xs[g]+i[g]|0,R=(L(d,2)^L(d,13)^L(d,22))+(d&l^d&c^l&c)|0;u=f,f=b,b=p,p=h+y|0,h=c,c=l,l=d,d=y+R|0}e[0]+=d,e[1]+=l,e[2]+=c,e[3]+=h,e[4]+=p,e[5]+=b,e[6]+=f,e[7]+=u}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,At=1e3,As=100,Es=60*1024,le=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function V(){try{return globalThis.localStorage}catch{return}}var ue=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 d={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[J]:n.id}}:c)};this.api=Z.client(d);let l={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=Z.client(l),this.closingApi=Z.client({send:c=>d.send({...c,keepalive:!0})}),this.closingPerfApi=Z.client({send:c=>l.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,h)=>{h!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(Ve),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=V()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{V()?.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}${Q(t.pathname)}`:"");if(!i)return;let n=e.referrer??js(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{V()?.removeItem(this.anonKey),V()?.removeItem(this.sessionKey),V()?.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(Ve)):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(Ns((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>=At&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=At&&this.samples.shift();let n={row_id:le(),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()}:Ve(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,As);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>Es;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=V();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${le()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${le()}`,this.memoryAnon}sessionId(e){let t=V(),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_${le()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=!0,i,n=()=>{if(!s)return;let b=`${e.location.origin}${e.location.pathname}`;if(b===t)return;t=b;let f=`${e.location.origin}${Q(e.location.pathname)}`;i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,s&&this.page({url:f})},0)},a=e.history,o=a.pushState,d=Object.hasOwn(a,"pushState"),l=a.replaceState,c=Object.hasOwn(a,"replaceState"),h=(...b)=>{o.apply(a,b),n()},p=(...b)=>{l.apply(a,b),n()};return a.pushState=h,a.replaceState=p,e.addEventListener("popstate",n),n(),()=>{s=!1,i!==void 0&&(clearTimeout(i),i=void 0),a.pushState===h&&(d?a.pushState=o:delete a.pushState),a.replaceState===p&&(c?a.replaceState=l:delete a.replaceState),e.removeEventListener("popstate",n)}}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,d=(n?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let c=!!l&&l.pathname.startsWith("/analytics/")||Us(n?.headers??o?.headers);try{let h=await t(i,n);return l&&!c&&this.sample("network",`${d} ${l.origin}${Q(l.pathname)}`,performance.now()-a,{attrs:{status:String(h.status)},...h.headers.get("x-request-id")?{request_id:h.headers.get("x-request-id")}:{}}),h}catch(h){throw l&&!c&&this.sample("network",`${d} ${l.origin}${Q(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),h}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function Ve(r){let{distinct_id:e,request_id:t,...s}=r;return s}var Ls=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,Ds=r=>r.entryType==="event"||r.entryType==="first-input";function ce(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 Ns(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[ce("largest-contentful-paint",l=>{for(let c of l)e=Math.max(e,c.startTime)}),ce("layout-shift",l=>{for(let c of l)Ls(c)&&!c.hadRecentInput&&(t+=c.value)}),ce("event",l=>{for(let c of l)Ds(c)&&(s=Math.max(s,c.duration))}),ce("paint",l=>{for(let c of l)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))},d=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",d),()=>{o(),document.removeEventListener("visibilitychange",d);for(let l of i)l?.disconnect()}}function Us(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var qs=/^[a-z][a-z0-9_-]{0,31}$/;function Q(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return qs.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 js(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${Q(e.pathname)}`}catch{return Q(r.split(/[?#]/,1)[0]??"")}}var $t=/^custom\.[a-z0-9_]{1,48}$/,Ks=/^[a-z][a-z0-9_]{0,63}$/,Et=r=>Ks.test(r)||$t.test(r),Vs=50,Lt=[5e3,3e4,12e4,6e5],Fs=100,pe=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[d,l]of Object.entries(t.start??{})){if(!Et(d))throw new TypeError(`consent.start: ${JSON.stringify(d)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${d} is granted or denied`)}for(let d of t.customKeys??[])if(!$t.test(d))throw new TypeError(`consent.customKeys: ${JSON.stringify(d)} 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=()=>It(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(d=>d.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((d,l)=>{this.engaged&&(d==="SIGNED_IN"&&l?this.signedIn(l):(d==="SIGNED_OUT"||d==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",d=>{(d.key===this.storeKey||d.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=Ut(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(!Et(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(d=>d.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(d=>d.ads).map(d=>d.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(d=>{let l=this.kept.choices[d];return a&&n.has(d)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.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 u of e.choices)n[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>n[u.key]?.state!==u.state||Date.parse(n[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>N(u.key,u)),d=P(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>N(u,g)):[];if(a.length+d.length>0&&(this.kept={...this.kept,void:U([...this.kept.void??[],...a,...d])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(n))Date.parse(g.chosen_at)<this.kept.resetAt&&delete n[u];let l=new Set(Object.entries(n).map(([u,g])=>N(u,g))),c=(this.kept.void??[]).filter(u=>l.has(u));c.length>0&&(this.kept={...this.kept,unvoid:U([...this.kept.unvoid??[],...c])});let h=Gt(this.kept),p;if(P(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))p=n;else{p={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let g=this.kept.choices[u],y=g&&!g.provisional&&!h.has(N(u,g))?g:void 0,R=n[u],x=R&&(!y||Date.parse(R.chosen_at)>=Date.parse(y.chosen_at))?R:y;x&&(p[u]=x)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=p[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(p[u.key]=Dt(u,g))}let{install:b,...f}=this.kept;this.kept={...f,whose:t,...t===null?{install:this.installation.id}:{},choices:p,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=U([...this.kept.void??[],...s.map(d=>N(d.key,d))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let d of s){if(this.kept.unsent.some(c=>c.key===d.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(d.chosen_at)))continue;let l=o[d.key];o[d.key]={state:"denied",source:"app",chosen_at:d.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.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:Wt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Dt(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(!Kt(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(d=>({key:d.key,state:d.state,chosen_at:d.chosen_at}))}})).data}catch(d){if(!Kt(d))throw d;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(c=>jt(c,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(d=>!i.some(l=>jt(l,d))),done:U([...this.kept.done??[],...i.map(fe)])},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)),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=Lt[Math.min(this.retries,Lt.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).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,d]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...d.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{}};let n=o=>o.user===null&&o.device===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:U([...this.kept.done??[],...a.map(fe)]),...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,Fe(n.payload))}),t.on("state_snapshot",n=>this.held(s,Fe(Ft(n.entries)))),t.on("state_diff",n=>this.held(s,Fe(Ft(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=Ut(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=Vt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Hs(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=Nt(e,this.kept,"theirs",this.holder()),P(e)===P(this.kept)&&qt(this.kept)!==qt(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.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=Nt(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Vt()?.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 Dt(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 N(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Gt(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var he={denied:2,unset:1,granted:0};function $s(r,e,t,s){let i=e&&!s.has(N(r,e))?e:void 0,n=t&&!s.has(N(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:he[i.state]!==he[n.state]?he[i.state]>he[n.state]?i:n:i.provisional?n:i}function Gs(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function Nt(r,e,t,s){let i=U([...r.void??[],...e.void??[]]),n=U([...r.unvoid??[],...e.unvoid??[]]),a=Gt({void:i,unvoid:n}),o={},d,l={...r.gpc};for(let[y,R]of Object.entries(e.gpc??{}))l[y]=Math.max(l[y]??0,R);let c;if(P(r)===P(e)){d=e;for(let y of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let R=$s(y,r.choices[y],e.choices[y],a);R&&(o[y]=R)}c=Gs(r.unknown,e.unknown)}else{d=P(e)===s?e:P(r)===s?r:t==="ours"?e:r;for(let[y,R]of Object.entries(d.choices))a.has(N(y,R))||(o[y]=R);c=d.unknown}let h=U([...r.done??[],...e.done??[]]),p=Wt([...r.unsent,...e.unsent]).filter(y=>!h.includes(fe(y))),b=t==="ours"?e:r,f=t==="ours"?r:e,u=b.region??f.region,g=b.keys??f.keys;return{whose:d.whose??null,...d.whose==null&&d.install!==void 0?{install:d.install}:{},...d.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&P(r)===P(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:d.whose==null&&d.resetAt!==void 0?{resetAt:d.resetAt}:{},choices:o,unsent:p,...h.length>0?{done:h}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...b.link!==void 0?{link:b.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...c?{unknown:c}:{}}}function fe(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function Ut(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 U(r){return[...new Set(r)].slice(-Fs)}function qt(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 Wt(r){let e=new Map;for(let t of r){let s=fe(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 Ws=new Set(["granted","denied","unset"]);function Hs(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,d)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Ws.has(l.state)&&typeof l.chosen_at=="string"&&(!d||typeof l.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(d=>typeof d=="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 jt(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 Kt(r){return r instanceof w&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function Vt(){try{return globalThis.localStorage}catch{return}}function Ft(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Fe(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Bs=`
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as xt,c as Ke,d as Mt}from"./B64J3E3T.js";import{e as Ct}from"./FOZVJW7G.js";import{e as _t,g as Rt,h as Pt}from"./3I5XH3A3.js";import{c as je}from"./5OBOVEK6.js";import{h as Tt}from"./NQUAVRMC.js";import{a as kt}from"./AMKY4SZU.js";import{r as wt,t as bt,u as St}from"./QOETZ4FB.js";import{a as Ue,b as Z,c as W,e as ft,f as gt,g as G,h as mt,i as yt,l as qe,m as H}from"./RP2TPMXT.js";import{a as vt,b as ee}from"./JSRN4NOZ.js";import{b,d as $}from"./XVJ3CMFN.js";function Ms(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 P=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function It(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function Ot(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 At(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);return typeof s=="object"&&s!==null?s:{}}catch{return{}}}function Fe(r){let{sub:e}=At(r);return typeof e=="string"?e:""}function Is(r,e){let{iat:t,exp:s}=At(r);return typeof t!="number"||typeof s!="number"||!(s>t)?e:Math.min(e,(s-t)*1e3/2)}var Os=6e4,As=15e3;function Es(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var ae=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??As,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??Fe(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>Is(e.accessToken,Os))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=Es(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new P("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 P("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",Ms(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 P("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 P("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 Ve=class{state="closed";refusal;logSeq;joinRef=null;refusals=0;retry=null;asking=0;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{}}},oe=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;asks=0;epoch=0;wasOpen=!1;current="idle";statusListeners=new Set;reconnects=0;opts;constructor(e){this.opts=e}get status(){return this.current}onStatus(e){return this.statusListeners.add(e),()=>{this.statusListeners.delete(e)}}setStatus(e){if(this.current!==e){this.current=e;for(let t of[...this.statusListeners])try{t(e)}catch{}}}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Ve(e,this,t)),s}disconnect(){this.closedByUs=!0,this.wasOpen=!1,this.epoch++,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.attempts=0,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.asking=0,t.closed("the socket was closed");this.lastJoin.clear(),this.current!=="idle"&&this.setStatus("disconnected")}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(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.open().catch(()=>{}));for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,this.askAgain(e))}join(e){if(e.state="joining",this.ws?.readyState===1){this.sendJoin(e);return}this.reconnectTimer||this.open().catch(()=>{})}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=B(setTimeout(()=>{e.retry=null,this.askAgain(e)},s))}askAgain(e){this.reconnectTimer||this.channels.get(e.name)!==e||e.state!=="refused"||this.join(e)}joinWanted(){for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,e.state="joining"),e.state==="joining"&&this.sendJoin(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,this.current!=="reconnecting"&&this.setStatus("connecting");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;try{a=new e(t)}catch(o){this.setStatus("reconnecting");let d=o instanceof Error?o.message:String(o);for(let l of this.channels.values())l.state==="joining"&&this.settle(l,!1,{reason:d});n(o);return}this.ws=a,a.onopen=()=>{if(this.ws!==a){a.close(1e3),n(new Error("the socket was closed"));return}this.attempts=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wasOpen&&this.reconnects++,this.wasOpen=!0,this.startHeartbeat(),this.setStatus("connected"),this.joinWanted(),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,e.onmessage=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)return;if(![...this.channels.values()].some(i=>i.state==="joining"||i.state==="refused")){this.wasOpen=!1,this.setStatus("disconnected");return}if(this.setStatus("reconnecting"),this.reconnectTimer)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=B(setTimeout(()=>{this.reconnectTimer=null,this.open().catch(()=>{})},s))}async sendJoin(e){if(e.asking)return;let t=++this.asks;e.asking=t;try{await this.ask(e)}finally{e.asking===t&&(e.asking=0)}}async ask(e){let t=this.ws;if(t?.readyState!==1)return;let s=this.epoch,i;try{i=await this.opts.accessToken()}catch(c){s===this.epoch&&this.ws===t&&this.channels.get(e.name)===e&&e.state==="joining"&&this.settle(e,!1,{reason:c instanceof Error?c.message:String(c)});return}if(s!==this.epoch||this.channels.get(e.name)!==e||e.state!=="joining"||this.ws!==t||t.readyState!==1)return;let n=this.nextRef();e.joinRef=n;let a=this.awaitReply(n),o={broadcast:{self:!1}};e.logSeq!==void 0&&(o.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(n,e.topic,"phx_join",{access_token:i,config:o},n);let{status:d,response:l}=await a;if(!(d!=="ok"&&this.ws!==t)){if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),d==="ok"&&this.ws?.readyState===1&&this.push(n,e.topic,"phx_leave",{}));return}if(d==="timeout"){this.askOnLater(e);return}this.settle(e,d==="ok",l)}}askOnLater(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=B(setTimeout(()=>{e.retry=null,this.channels.get(e.name)===e&&e.state==="joining"&&this.ws?.readyState===1&&this.sendJoin(e)},s))}awaitReply(e){return new Promise(t=>{let s=B(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,o]=t,d=typeof o=="object"&&o!==null?o:{};if(a==="phx_reply"&&typeof i=="string"){if(i===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(i)?.(String(d.status),d.response??{});return}let l=[...this.channels.values()].find(c=>c.topic===n);if(l&&!((a==="phx_close"||a==="phx_error")&&typeof s=="string"&&l.joinRef!==null&&s!==l.joinRef)){if(a==="phx_close"){if(l.state!=="joined")return;l.state="refused",l.refusal={reason:"closed by the server"},this.askAgainLater(l);return}if(a==="phx_error"){l.state="joining",B(setTimeout(()=>this.channels.get(l.name)===l&&l.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(l),1e3));return}l.deliver(a,d)}}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=B(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null;let e=this.ws;e?.close(4e3),e&&this.dropped(e);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 B(r){return r.unref?.(),r}var O="X-Palbase-Installation-Secret",J="X-Palbase-Installation",Lt=new WeakMap;function A(r){return Lt.get(r)}var Dt=new WeakSet;function Nt(r){return Dt.has(r)}var Ls=/^[A-Za-z0-9_-]{43}$/,de=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Et()?.getItem(t);i&&Ls.test(i)&&(s=i)}catch{}if(!s){Dt.add(this),s=Ut(crypto.getRandomValues(new Uint8Array(32)));try{Et()?.setItem(t,s)}catch{}}Lt.set(this,s),this.id=Ds(s)}};function Ds(r){return Ut(Us(new TextEncoder().encode(r)).subarray(0,16))}function Et(){try{return globalThis.localStorage}catch{return}}function Ut(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]),L=(r,e)=>r>>>e|r<<32-e;function Us(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 y=L(i[g-15],7)^L(i[g-15],18)^i[g-15]>>>3,R=L(i[g-2],17)^L(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+y+i[g-7]+R|0}let[d,l,c,h,p,v,f,u]=e;for(let g=0;g<64;g++){let y=u+(L(p,6)^L(p,11)^L(p,25))+(p&v^~p&f)+Ns[g]+i[g]|0,R=(L(d,2)^L(d,13)^L(d,22))+(d&l^d&c^l&c)|0;u=f,f=v,v=p,p=h+y|0,h=c,c=l,l=d,d=y+R|0}e[0]+=d,e[1]+=l,e[2]+=c,e[3]+=h,e[4]+=p,e[5]+=v,e[6]+=f,e[7]+=u}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 qs=30*6e4,qt=1e3,js=100,Ks=60*1024,le=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function F(){try{return globalThis.localStorage}catch{return}}var ue=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 d={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[J]:n.id}}:c)};this.api=Z.client(d);let l={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=Z.client(l),this.closingApi=Z.client({send:c=>d.send({...c,keepalive:!0})}),this.closingPerfApi=Z.client({send:c=>l.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,h)=>{h!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map($e),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=F()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{F()?.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}${Q(t.pathname)}`:"");if(!i)return;let n=e.referrer??Hs(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{F()?.removeItem(this.anonKey),F()?.removeItem(this.sessionKey),F()?.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($e)):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($s((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>=qt&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=qt&&this.samples.shift();let n={row_id:le(),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()}:$e(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,js);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>Ks;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=F();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${le()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${le()}`,this.memoryAnon}sessionId(e){let t=F(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<qs?{id:s.id,last:e}:{id:`ses_${le()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=!0,i,n=()=>{if(!s)return;let v=`${e.location.origin}${e.location.pathname}`;if(v===t)return;t=v;let f=`${e.location.origin}${Q(e.location.pathname)}`;i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,s&&this.page({url:f})},0)},a=e.history,o=a.pushState,d=Object.hasOwn(a,"pushState"),l=a.replaceState,c=Object.hasOwn(a,"replaceState"),h=(...v)=>{o.apply(a,v),n()},p=(...v)=>{l.apply(a,v),n()};return a.pushState=h,a.replaceState=p,e.addEventListener("popstate",n),n(),()=>{s=!1,i!==void 0&&(clearTimeout(i),i=void 0),a.pushState===h&&(d?a.pushState=o:delete a.pushState),a.replaceState===p&&(c?a.replaceState=l:delete a.replaceState),e.removeEventListener("popstate",n)}}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,d=(n?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let c=!!l&&l.pathname.startsWith("/analytics/")||Ws(n?.headers??o?.headers);try{let h=await t(i,n);return l&&!c&&this.sample("network",`${d} ${l.origin}${Q(l.pathname)}`,performance.now()-a,{attrs:{status:String(h.status)},...h.headers.get("x-request-id")?{request_id:h.headers.get("x-request-id")}:{}}),h}catch(h){throw l&&!c&&this.sample("network",`${d} ${l.origin}${Q(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),h}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function $e(r){let{distinct_id:e,request_id:t,...s}=r;return s}var Fs=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,Vs=r=>r.entryType==="event"||r.entryType==="first-input";function ce(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 $s(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[ce("largest-contentful-paint",l=>{for(let c of l)e=Math.max(e,c.startTime)}),ce("layout-shift",l=>{for(let c of l)Fs(c)&&!c.hadRecentInput&&(t+=c.value)}),ce("event",l=>{for(let c of l)Vs(c)&&(s=Math.max(s,c.duration))}),ce("paint",l=>{for(let c of l)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))},d=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",d),()=>{o(),document.removeEventListener("visibilitychange",d);for(let l of i)l?.disconnect()}}function Ws(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var Gs=/^[a-z][a-z0-9_-]{0,31}$/;function Q(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Gs.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 Hs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${Q(e.pathname)}`}catch{return Q(r.split(/[?#]/,1)[0]??"")}}var zt=/^custom\.[a-z0-9_]{1,48}$/,Bs=/^[a-z][a-z0-9_]{0,63}$/,Kt=r=>Bs.test(r)||zt.test(r),Js=50,Ft=[5e3,3e4,12e4,6e5],Qs=100,pe=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[d,l]of Object.entries(t.start??{})){if(!Kt(d))throw new TypeError(`consent.start: ${JSON.stringify(d)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${d} is granted or denied`)}for(let d of t.customKeys??[])if(!zt.test(d))throw new TypeError(`consent.customKeys: ${JSON.stringify(d)} 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=()=>Nt(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(d=>d.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((d,l)=>{this.engaged&&(d==="SIGNED_IN"&&l?this.signedIn(l):(d==="SIGNED_OUT"||d==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",d=>{(d.key===this.storeKey||d.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(T(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Wt(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||T(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(!Kt(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(d=>d.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(d=>d.ads).map(d=>d.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(d=>{let l=this.kept.choices[d];return a&&n.has(d)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.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 u of e.choices)n[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>n[u.key]?.state!==u.state||Date.parse(n[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>N(u.key,u)),d=T(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>N(u,g)):[];if(a.length+d.length>0&&(this.kept={...this.kept,void:U([...this.kept.void??[],...a,...d])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(n))Date.parse(g.chosen_at)<this.kept.resetAt&&delete n[u];let l=new Set(Object.entries(n).map(([u,g])=>N(u,g))),c=(this.kept.void??[]).filter(u=>l.has(u));c.length>0&&(this.kept={...this.kept,unvoid:U([...this.kept.unvoid??[],...c])});let h=Xt(this.kept),p;if(T(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))p=n;else{p={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let g=this.kept.choices[u],y=g&&!g.provisional&&!h.has(N(u,g))?g:void 0,R=n[u],x=R&&(!y||Date.parse(R.chosen_at)>=Date.parse(y.chosen_at))?R:y;x&&(p[u]=x)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=p[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(p[u.key]=Vt(u,g))}let{install:v,...f}=this.kept;this.kept={...f,whose:t,...t===null?{install:this.installation.id}:{},choices:p,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&&T(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=U([...this.kept.void??[],...s.map(d=>N(d.key,d))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let d of s){if(this.kept.unsent.some(c=>c.key===d.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(d.chosen_at)))continue;let l=o[d.key];o[d.key]={state:"denied",source:"app",chosen_at:d.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.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=T(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Yt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Vt(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(d=>({key:d.key,state:d.state,chosen_at:d.chosen_at}))}})).data}catch(d){if(!Bt(d))throw d;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(c=>Ht(c,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(d=>!i.some(l=>Ht(l,d))),done:U([...this.kept.done??[],...i.map(fe)])},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)),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===Js)))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).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,d]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...d.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{}};let n=o=>o.user===null&&o.device===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:U([...this.kept.done??[],...a.map(fe)]),...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,We(n.payload))}),t.on("state_snapshot",n=>this.held(s,We(Qt(n.entries)))),t.on("state_diff",n=>this.held(s,We(Qt(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=Wt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[T(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||T(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(T(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,[T(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=Jt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Zs(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=$t(e,this.kept,"theirs",this.holder()),T(e)===T(this.kept)&&Gt(this.kept)!==Gt(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.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=$t(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Jt()?.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 Vt(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 N(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Xt(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var he={denied:2,unset:1,granted:0};function zs(r,e,t,s){let i=e&&!s.has(N(r,e))?e:void 0,n=t&&!s.has(N(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:he[i.state]!==he[n.state]?he[i.state]>he[n.state]?i:n:i.provisional?n:i}function Xs(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function $t(r,e,t,s){let i=U([...r.void??[],...e.void??[]]),n=U([...r.unvoid??[],...e.unvoid??[]]),a=Xt({void:i,unvoid:n}),o={},d,l={...r.gpc};for(let[y,R]of Object.entries(e.gpc??{}))l[y]=Math.max(l[y]??0,R);let c;if(T(r)===T(e)){d=e;for(let y of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let R=zs(y,r.choices[y],e.choices[y],a);R&&(o[y]=R)}c=Xs(r.unknown,e.unknown)}else{d=T(e)===s?e:T(r)===s?r:t==="ours"?e:r;for(let[y,R]of Object.entries(d.choices))a.has(N(y,R))||(o[y]=R);c=d.unknown}let h=U([...r.done??[],...e.done??[]]),p=Yt([...r.unsent,...e.unsent]).filter(y=>!h.includes(fe(y))),v=t==="ours"?e:r,f=t==="ours"?r:e,u=v.region??f.region,g=v.keys??f.keys;return{whose:d.whose??null,...d.whose==null&&d.install!==void 0?{install:d.install}:{},...d.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&T(r)===T(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:d.whose==null&&d.resetAt!==void 0?{resetAt:d.resetAt}:{},choices:o,unsent:p,...h.length>0?{done:h}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...v.link!==void 0?{link:v.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...c?{unknown:c}:{}}}function fe(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function Wt(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 T(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function U(r){return[...new Set(r)].slice(-Qs)}function Gt(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 Yt(r){let e=new Map;for(let t of r){let s=fe(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 Ys=new Set(["granted","denied","unset"]);function Zs(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,d)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Ys.has(l.state)&&typeof l.chosen_at=="string"&&(!d||typeof l.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(d=>typeof d=="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 Ht(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 Jt(){try{return globalThis.localStorage}catch{return}}function Qt(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function We(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var ei=`
|
|
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}
|
|
@@ -19,5 +19,5 @@ import{e as _t}from"./ZCMCYI2D.js";import{e as wt,g as bt,h as St}from"./ALT62XI
|
|
|
19
19
|
.empty{padding:24px 12px;text-align:center;color:var(--muted)}
|
|
20
20
|
.light{--bg:#f4f4f6;--fg:#111;--muted:#5c5c66;--accent:#2f6bff;--hover:#0000000f}
|
|
21
21
|
.dark{--bg:#1f1f24;--fg:#f2f2f5;--muted:#a0a0ab;--accent:#5b8cff;--hover:#ffffff14}
|
|
22
|
-
`,ge=class{api;session;constructor(e,t){this.api=H.client(e),this.session=t}async list(e={}){return(await this.api.listMyInbox({query:{limit:e.limit,cursor:e.cursor,locale:e.locale}})).data}async unread(){return(await this.list({limit:1})).unread}async markRead(e){let t=e==="all"?{all:!0}:{ids:[...e]};return(await this.api.readMyInbox({body:t})).data.read}async remove(e){await this.api.deleteMyInboxMessage({path:{id:e}})}mount(e,t={}){let s=e.ownerDocument,i=s.defaultView,n=s.createElement("div");n.setAttribute("data-palbase-inbox","");let a=n.attachShadow({mode:"open"});yt(s,a,Bs);let o=s.createElement("ul");o.className="list",a.append(o),e.append(n);let d=()=>t.appearance??(i?.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"),l=[],c=0,h=[],p=!1,b=m=>{c=m,t.onUnread?.(m)},f=(m,S)=>{m.read_at||(m.read_at=new Date().toISOString(),b(Math.max(0,c-1)),y(),this.markRead([m.id]).catch(()=>{})),!(!S||!gt(S))&&(t.onOpen?t.onOpen(m,S):S.startsWith("https://")?i?.open(S,"_blank","noopener,noreferrer"):i?.location.assign(S))},u=async m=>{l=l.filter(S=>S.id!==m.id),m.read_at||b(Math.max(0,c-1)),y(),await this.remove(m.id).catch(()=>{})},g=m=>{try{return new Intl.DateTimeFormat(t.locale,{dateStyle:"medium",timeStyle:"short"}).format(new Date(m))}catch{return m}};function y(){if(h.forEach(m=>m.destroy()),h=[],o.replaceChildren(),o.className=`list ${d()}`,!l.length){let m=s.createElement("li");m.className="empty",m.textContent=t.labels?.empty??"No messages",o.append(m);return}for(let m of l)o.append(R(m))}let R=m=>{let S=s.createElement("li");S.setAttribute("data-id",m.id),S.tabIndex=0;let E=s.createElement("button");if(E.type="button",E.className="delete",E.textContent="\xD7",E.setAttribute("aria-label",t.labels?.delete??"Delete"),E.addEventListener("click",M=>{M.stopPropagation(),u(m)}),m.card){S.className=`card ${m.read_at?"":"unread"}`;let M=s.createElement("div");S.append(M,E);let K={onAction:()=>f(m,void 0),onDeepLink:C=>f(m,C),onLink:C=>f(m,C),onCustom:t.onCustom};h.push(mt(M,{definition:m.card,locale:t.locale??i?.navigator.language??"en",appearance:d(),variables:m.variables??{}},K)),S.addEventListener("click",C=>{C.composedPath().some(D=>D instanceof HTMLElement&&D.tagName==="BUTTON")||f(m,m.deep_link)})}else{S.className=`item ${m.read_at?"":"unread"}`;let M=s.createElement("span");if(M.className="dot",S.append(M),m.image?.startsWith("https://")){let C=s.createElement("img");C.src=m.image,C.alt="",S.append(C)}let K=s.createElement("div");K.className="text";for(let[C,D]of[["title",m.title],["body",m.body],["when",g(m.created_at)]]){if(!D)continue;let v=s.createElement("span");v.className=C,v.textContent=D,K.append(v)}S.append(K,E),S.addEventListener("click",()=>f(m,m.deep_link))}return S.addEventListener("keydown",M=>{M.key==="Enter"&&M.target===S&&f(m,m.deep_link)}),S},x=0,j=async()=>{let m=++x;if(!(await this.session.session())?.userId){if(p||m!==x)return;l=[],b(0),y();return}let S=await this.list({limit:t.limit??50,locale:t.locale});p||m!==x||(l=S.items,b(S.unread),y())},se=()=>{s.visibilityState==="visible"&&j().catch(()=>{})};s.addEventListener("visibilitychange",se);let ie=this.session.onChange(()=>{j().catch(()=>{})});return y(),j().catch(()=>{}),{refresh:j,get items(){return l},get unread(){return c},destroy(){p=!0,s.removeEventListener("visibilitychange",se),ie?.(),h.forEach(m=>m.destroy()),n.remove()}}}};var Js=30*6e4,me="session_start";function ye(r){try{return r.localStorage}catch{return}}var Qs=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function zs(r,e){for(let[t,s]of Object.entries(r??{})){let i=e?.[t];if(i==null||String(i)!==s)return!1}return!0}var ve=class{api;session;installation;g;now;requestPush;analyticsAllowed;iap;asked=0;person=0;sessionKey;pendingKey;opts;messages=[];limits={per_session:1,per_day:3,min_minutes:10};shown={session:0,day:0,total:0};loaded=Promise.resolve();away=!1;memorySession;memoryPending=[];showing;stopWatching;queue=Promise.resolve();constructor(e,t,s,i,n,a,o,d=globalThis,l=Date.now){this.api=H.client({send:c=>e.send({...c,headers:{...c.headers,[O]:A(s)}})}),this.session=t,this.installation=s,this.requestPush=n,this.analyticsAllowed=a,this.iap=o,this.g=d,this.now=l,this.sessionKey=`palbase.notify.inapp.session.${i}`,this.pendingKey=`palbase.notify.inapp.conversions.${i}`,t.onChange(c=>{c!=="SIGNED_IN"&&c!=="SIGNED_OUT"&&c!=="SESSION_EXPIRED"||(this.forget(),this.opts&&(this.showing?.message.close(),this.loaded=this.load()))})}get started(){return this.opts!==void 0}start(e={}){let t=!this.opts;if(this.opts=e,!t)return;let s=this.g.document,i=()=>{s?.visibilityState==="visible"?this.enqueue(me,void 0,!0):this.away=!0};s?.addEventListener("visibilitychange",i),this.stopWatching=()=>s?.removeEventListener("visibilitychange",i);let n=this.touch();this.loaded=this.load(),n&&this.trigger(me)}stop(){this.opts=void 0,this.stopWatching?.(),this.stopWatching=void 0,this.showing?.message.close()}refresh(){return this.loaded=this.load(),this.loaded}trigger(e,t){this.enqueue(e,t,!1)}settled(){return this.queue}enqueue(e,t,s){this.queue=this.queue.then(()=>this.take(e,t,s)).catch(()=>{})}async take(e,t,s){if(await this.converted(e),!!this.opts){if(this.touch())this.loaded=this.load(),e!==me&&await this.show(me,void 0);else if(this.away&&(this.loaded=this.load()),s)return;await this.show(e,t)}}async show(e,t){if(await this.loaded,!(!this.opts||this.showing)){for(let s of this.messages)if(!(s.trigger.event!==e||!zs(s.trigger.where,t)||this.capped(s))&&await this.open(s))return}}capped(e){let t=this.now(),s=(o,d)=>o!==void 0&&d!==void 0&&t-Date.parse(o)<d*6e4,i=this.shown,n=e.shown,a=e.limits;return i.session>=this.limits.per_session||i.day>=this.limits.per_day||s(i.last_at,this.limits.min_minutes)||a.per_session!==void 0&&n.session>=a.per_session||a.per_day!==void 0&&n.day>=a.per_day||s(n.last_at,a.min_minutes)||a.max_total!==void 0&&n.total>=a.max_total}async open(e){let t=this.opts,s=this.person,i=await this.subject(),n,a;try{({id:n,variables:a}=(await this.api.showInAppMessage({body:{campaign_id:e.campaign_id,session_id:this.sessionId(),installation_id:this.installation.id}})).data)}catch(c){return c instanceof w&&c.status===409&&(this.loaded=this.load()),!1}if(!this.opts||this.showing||s!==this.person)return!0;let o=new Date(this.now()).toISOString();for(let c of[this.shown,e.shown])c.session++,c.day++,c.total++,c.last_at=o;e.conversion&&this.pend({impression:n,campaign:e.campaign_id,event:e.conversion.event,until:this.now()+e.conversion.hours*36e5,subject:i});let d=(c,h)=>{this.api.reportInAppEvent({path:{id:n},query:{installation_id:this.installation.id},body:{type:c,...h?{action:h}:{}}}).catch(()=>{})},l=vt({definition:e.definition,locale:t.locale??this.g.navigator?.language??"en",appearance:t.appearance??this.appearance(),variables:{...e.variables,...a}},{onAction:c=>{c.type!=="close"&&c.type!=="sheet"&&d("clicked",c.type)},onLink:t.onLink,onDeepLink:t.onDeepLink,onCustom:t.onCustom,onShowPaywall:t.onShowPaywall,onOffer:t.onOffer??(c=>this.takeOffer(c,t.onOfferError)),onApplyPromo:t.onApplyPromo,onCopyCode:t.onCopyCode,onRequestPush:t.onRequestPush??(()=>this.requestPush().then(()=>{})),labels:t.labels,onClose:c=>{this.showing?.message===l&&(this.showing=void 0),c!=="action"&&c!=="app"&&d("dismissed"),t.onClose?.(e.campaign_id,c)}},t.root?{root:t.root}:{});return this.showing={campaign:e.campaign_id,message:l},t.onShow?.(e.campaign_id),!0}async takeOffer(e,t){try{let s=(await this.iap.offers()).find(o=>o.key===e);if(s?.kind==="grant"){await this.iap.claimOffer(e);return}let i=s?.web?.plans[0];if(!s?.product||i===void 0)throw new w({op:"TakeOffer",status:0,code:"offer_not_open",message:`the offer ${e} is not the customer's to take on the web now`});let n=this.g.location,a=await this.iap.checkout({product:s.product,plan:i,successUrl:n.href,cancelUrl:n.href,offer:e});n.assign(a)}catch(s){if(!t)throw s;t(s,e)}}async converted(e){let t=this.now(),s=this.pending().filter(a=>a.until>t),i=await this.subject(),n=this.analyticsAllowed()?s.filter(a=>a.event===e&&a.subject===i):[];this.keepPending(s.filter(a=>!n.includes(a))),await Promise.all(n.map(a=>this.api.reportInAppEvent({path:{id:a.impression},query:{installation_id:this.installation.id},body:{type:"converted"}}).catch(()=>{})))}forget(){this.person++,this.asked++,this.messages=[],this.shown={session:0,day:0,total:0}}async load(){this.away=!1;let e=++this.asked;try{let t=(await this.api.listMyInAppMessages({query:{session_id:this.sessionId(!1),installation_id:this.installation.id}})).data;if(e!==this.asked)return;this.messages=t.messages,this.limits=t.limits,this.shown=t.shown}catch{}}async subject(){let e=(await this.session.session())?.userId;return e?`u:${e}`:`i:${this.installation.id}`}appearance(){return this.g.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}touch(){let e=this.now(),t=this.readSession(),s=!t||e-t.last>=Js;return this.writeSession(s?{id:`ses_${Qs()}`,last:e}:{id:t.id,last:e}),s}sessionId(e=!0){return e&&this.touch(),(this.readSession()??this.memorySession).id}readSession(){try{let e=ye(this.g)?.getItem(this.sessionKey);if(e)return JSON.parse(e)}catch{}return this.memorySession}writeSession(e){this.memorySession=e;try{ye(this.g)?.setItem(this.sessionKey,JSON.stringify(e))}catch{}}pending(){try{let e=ye(this.g)?.getItem(this.pendingKey);if(e)return JSON.parse(e)}catch{}return this.memoryPending}keepPending(e){this.memoryPending=e;try{let t=ye(this.g);e.length?t?.setItem(this.pendingKey,JSON.stringify(e)):t?.removeItem(this.pendingKey)}catch{}}pend(e){this.keepPending([...this.pending().filter(t=>t.until>this.now()),e].slice(-50))}};var Ge=r=>{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),s=new Uint8Array(t.length);for(let i=0;i<t.length;i++)s[i]=t.charCodeAt(i);return s},We=class{api;session;installation;baseUrl;publishableKey;g;registered;generation=0;wake=()=>{};replacing;changing=Promise.resolve();constructor(e,t,s,i,n,a=globalThis){this.api=H.client(e),this.session=t,this.installation=s,this.baseUrl=i,this.publishableKey=n,this.g=a,t.onChange(o=>{if(o==="SIGNED_IN"||o==="SIGNED_OUT"||o==="SESSION_EXPIRED"){this.registered=void 0;let d=++this.generation;this.wake(),this.changing=this.changing.then(()=>this.registerFor(d)).catch(()=>{})}})}supported(){return!!this.g.navigator?.serviceWorker&&this.g.PushManager!==void 0&&this.g.Notification!==void 0}permission(){return this.supported()?this.g.Notification.permission:"unsupported"}workerUrl(e="/palbase-sw.js"){let t=new URLSearchParams({url:this.baseUrl,key:this.publishableKey});return`${e}${e.includes("?")?"&":"?"}${t}`}async subscribe(e={}){if(!this.supported())return!1;let t=this.g.Notification;if(t.permission==="default"&&await t.requestPermission()!=="granted"||t.permission==="denied")return!1;let s=this.g.navigator.serviceWorker,i=this.workerUrl(e.serviceWorker),n=await this.scopeFor(s,i,e.scope),a=await s.register(i,n?{scope:n}:void 0);await Xs(a);let o=await a.pushManager.getSubscription(),d=(await this.api.getWebPushKey()).data.public_key;o&&!Ys(o.options.applicationServerKey,d)&&(await o.unsubscribe(),o=null),o??=await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Ge(d)});let l=this.generation;return await this.register(o),this.generation===l&&this.supersede(),!0}async unsubscribe(){this.supersede(),await this.changing;let e=await this.current();e&&await e.unsubscribe(),this.registered=void 0}supersede(){++this.generation,this.replacing=void 0,this.wake()}async refresh(){if(!this.supported()||this.permission()!=="granted")return;let e=await this.current();e&&await this.register(e)}async registerFor(e){if(e===this.generation){if(!this.replacing){try{return await this.refresh()}catch{}let t=await(await this.ours())?.pushManager.getSubscription();if(!t)return;this.replacing={key:t.options.applicationServerKey},await t.unsubscribe()}for(let t of[0,...Ht]){if(t>0&&await this.pause(t),e!==this.generation||this.permission()!=="granted")return;try{let s=await this.ours();if(!s)return void(this.replacing=void 0);let i=this.replacing?.key??Ge((await this.api.getWebPushKey()).data.public_key),n=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:i});if(e!==this.generation)return;await this.register(n),this.replacing=void 0;return}catch(s){if(t===Ht.at(-1))throw s}}}}pause(e){return new Promise(t=>{let s=setTimeout(i,e);function i(){clearTimeout(s),t()}this.wake=i})}async ours(){let e=this.g.navigator?.serviceWorker;if(e)return(await e.getRegistrations()).find(t=>this.isOurs(t))}isOurs(e){let t=Bt(e)?.searchParams.get("key");return!!t&&$e(t)!==void 0&&$e(t)===$e(this.publishableKey)}async current(){return await(await this.ours())?.pushManager.getSubscription()??null}async scopeFor(e,t,s){let i=this.g.location?.href;if(!i)return s;let n=new URL("./",new URL(t,i)).href,a=s===void 0?n:new URL(s,i).href,o=(await e.getRegistrations()).find(l=>l.scope===a);if(!o||this.isOurs(o))return s;let d=Bt(o);if(s!==void 0)throw new Error(`pb.notify.push.subscribe: ${a} is the scope of another service worker (${d?.href??"unknown"}); registering Palbase's there would replace it \u2014 give Palbase's a scope of its own`);return new URL("palbase-push/",n).href}async register(e){let t=e.toJSON(),s={endpoint:t.endpoint??e.endpoint,keys:{p256dh:t.keys?.p256dh??"",auth:t.keys?.auth??""}},n=`${this.session.snapshot()?.userId??""}|${s.endpoint}`;this.registered!==n&&(await this.api.registerDevice({headers:{[O]:A(this.installation)},body:{device_id:`web-${this.installation.id}`,token:JSON.stringify(s),platform:"web",locale:this.g.navigator?.language??null,installation_id:this.installation.id,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}),this.registered=n)}},Ht=[1e3,5e3,3e4,12e4,6e5];async function Xs(r){let e=r.installing??r.waiting;!e||r.active||await new Promise(t=>{let s=()=>{e.state!=="activated"&&e.state!=="redundant"||(e.removeEventListener("statechange",s),t())};e.addEventListener("statechange",s),s()})}function $e(r){let e=r.split("_");return e.length>=3&&e[0]==="pb"&&e[1]!==""?e[1]:void 0}function Bt(r){let e=(r.installing??r.waiting??r.active)?.scriptURL;return e?new URL(e):void 0}function Ys(r,e){if(!r)return!1;let t=new Uint8Array(r),s=Ge(e);return t.length===s.length&&t.every((i,n)=>i===s[n])}var we=class{push;inbox;inApp;constructor(e,t,s,i,n,a,o){this.push=new We(e,t,s,a,o),this.inbox=new ge(e,t),this.inApp=new ve(e,t,s,new URL(a).origin,()=>this.push.subscribe(),()=>i.state("analytics")==="granted",n)}};var be=class{api;session;socket;ref;installation;fetch;appVersion;app;listeners=new Set;watch;following;last;constructor(e,t,s,i,n,a,o,d){this.api=pt.client(e),this.session=t,this.socket=s,this.ref=i,this.installation=n,this.fetch=a,this.appVersion=o,this.app=d}async me(){let e=this.session.snapshot()?.userId,t=(await this.api.getMyCustomerInfo()).data;return this.watch&&this.watch.userId===e&&this.offer(this.watch,t),t}async offerings(e="web"){return(await this.api.getOfferings({query:{channel:e}})).data}async paywall(e,t={}){return kt(this.api,this.ref,e,this.installation.id,s=>this.checkout(s),{signal:t.signal,fetch:this.fetch,attributes:t.attributes,locale:t.locale,appVersion:this.appVersion,app:this.app})}async checkout(e){let t={product:e.product,plan:e.plan,success_url:e.successUrl,cancel_url:e.cancelUrl,...e.source!==void 0?{source:e.source}:{},...e.offer!==void 0?{offer:e.offer}:{},...e.channel!==void 0?{channel:e.channel}:{},...e.currency!==void 0?{currency:e.currency}:{}},s=(await this.api.createCheckout({body:t})).data;return s.redemption_key&&ei(this.keyName(s.session_id),s.redemption_key),s.url}async redemptionLink(e,t={}){let s=t.key??ti(this.keyName(e));if(!s)throw new w({op:"CreateCheckoutRedemption",status:0,code:"redemption_key_missing",message:"no redemption key for this checkout in this tab: the link was sent to the buyer's email"});let i=Date.now()+(t.waitSeconds??20)*1e3;for(;;)try{return(await this.api.createCheckoutRedemption({body:{session_id:e,key:s},signal:t.signal})).data}catch(n){let a=(n instanceof w&&n.code==="checkout_not_paid"?n.retryAfter??2:-1)*1e3;if(a<0||Date.now()+a>i)throw n;await si(a,t.signal)}}async redeem(e){let t=Zs(e);if(!t)throw new w({op:"RedeemPurchase",status:0,code:"invalid_redemption_link",message:"not a redemption link: <scheme>://palbase/redeem?token=\u2026 or \u2026/iap/redeem?token=\u2026"});let s=this.session.snapshot()?.userId,i=(await this.api.redeemPurchase({body:{token:t}})).data;return this.watch&&this.watch.userId===s&&this.offer(this.watch,i),i}async offers(){return(await this.api.listMyOffers()).data.offers}async offerShown(e){await this.api.recordOfferView({path:{offer_key:e}})}async claimOffer(e){return(await this.api.claimOffer({path:{offer_key:e}})).data}async redeemCoupon(e){return(await this.api.redeemCoupon({body:{code:e}})).data}async portal(e,t={}){let s={return_url:e,...t.channel!==void 0?{channel:t.channel}:{}};return(await this.api.createPortalSession({body:s})).data.url}async mergeGrant(){return(await this.api.createMergeGrant()).data}async merge(e){let t=this.session.snapshot()?.userId,s=(await this.api.mergeGuest({body:{grant:typeof e=="string"?e:e.grant}})).data;return this.watch&&this.watch.userId===t&&this.offer(this.watch,s),s}async setRefundDataConsent(e){return(await this.api.setRefundDataConsent({body:{consented:e}})).data}keyName(e){return`palbase:${this.ref}:redemption:${e}`}onCustomerInfo(e){if(this.listeners.add(e),this.listeners.size===1)this.start();else if(this.last!==void 0){let t=this.last;queueMicrotask(()=>this.listeners.has(e)&&Jt(e,t))}return()=>{this.listeners.delete(e)&&this.listeners.size===0&&this.stop()}}start(){this.following=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.follow(t)}),this.session.session().then(e=>{this.following&&!this.watch&&this.last===void 0&&this.follow(e)})}stop(){this.following?.(),this.following=void 0,this.unfollow(),this.last=void 0}follow(e){if(this.unfollow(),!e){this.tell(null);return}let t=this.socket.channel(`iap:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},revision:-1,reading:!1,wanted:Number.NEGATIVE_INFINITY},i=[t.on("broadcast",n=>{n.event==="changed"&&this.changed(s,He(n.payload))}),t.on("state_snapshot",n=>this.held(s,He(Qt(n.entries)))),t.on("state_diff",n=>this.held(s,He(Qt(n.set))))];s.off=()=>i.forEach(n=>n()),this.watch=s,t.join().catch(()=>{}),this.read(s)}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}changed(e,t){this.watch!==e||t!==void 0&&t<=e.revision||(e.reading?e.wanted=Math.max(e.wanted,t??Number.POSITIVE_INFINITY):this.read(e))}held(e,t){t!==void 0&&this.changed(e,t)}async read(e){e.reading=!0;try{for(;;){e.wanted=Number.NEGATIVE_INFINITY;try{let t=(await this.api.getMyCustomerInfo()).data;if(this.watch!==e)return;this.offer(e,t)}catch{}if(this.watch!==e||e.wanted<=e.revision)return}}finally{e.reading=!1}}offer(e,t){this.watch!==e||t.revision<=e.revision||(e.revision=t.revision,this.tell(t))}tell(e){if(!(this.last===null&&e===null)){this.last=e;for(let t of[...this.listeners])Jt(t,e)}}};function Jt(r,e){try{r(e)}catch{}}function Qt(r){let e=typeof r=="object"&&r!==null?r.revision:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function He(r){let e=typeof r=="object"&&r!==null?r.revision:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var zt=/^[A-Za-z0-9_-]{43}$/;function Zs(r){let e=r.trim();if(zt.test(e))return e;let t;try{t=new URL(e)}catch{return}let s=t.host==="palbase"&&t.pathname==="/redeem",i=(t.protocol==="https:"||t.protocol==="http:")&&t.pathname==="/iap/redeem",n=t.searchParams.get("token");return(s||i)&&n!==null&&zt.test(n)?n:void 0}function ei(r,e){try{globalThis.sessionStorage?.setItem(r,e)}catch{}}function ti(r){try{return globalThis.sessionStorage?.getItem(r)??void 0}catch{return}}function si(r,e){return new Promise((t,s)=>{if(e?.aborted)return s(e.reason);let i=setTimeout(()=>{e?.removeEventListener("abort",n),t()},r),n=()=>{clearTimeout(i),s(e?.reason)};e?.addEventListener("abort",n,{once:!0})})}var te={SEARCH_PERFORMED:"search.performed",PRODUCT_CLICKED:"product.clicked",PRODUCT_VIEWED:"product.viewed",CART_ITEM_ADDED:"cart.item_added",RECOMMENDATION_CLICKED:"recommendation.clicked"};function Xt(r){return typeof AbortSignal<"u"&&r instanceof AbortSignal?!0:typeof r=="object"&&r!==null&&"aborted"in r&&typeof r.addEventListener=="function"}function _(r){let e={};for(let[t,s]of Object.entries(r))t!=="signal"&&s!==void 0&&(e[t]=s);return e}var Be=class{storeId;api;constructor(e,t){this.storeId=e,this.api=W.client(t)}async listProducts(e,t){let s=e?_(e):void 0;return(await this.api.sellerListProducts({path:{store_id:this.storeId},query:s,signal:t})).data}async createQuickProduct(e,t){return(await this.api.sellerCreateQuickProduct({path:{store_id:this.storeId},body:e,signal:t})).data}async listListings(e){return(await this.api.sellerListListings({path:{store_id:this.storeId},signal:e})).data}async createListing(e,t){return(await this.api.sellerCreateListing({path:{store_id:this.storeId},body:e,signal:t})).data}async updateListing(e,t,s){return(await this.api.sellerUpdateListing({path:{store_id:this.storeId,listing_id:e},body:t,signal:s})).data}async upsertPrice(e,t,s){return(await this.api.sellerUpsertPrice({path:{store_id:this.storeId,listing_id:e},body:t,signal:s})).data}async listInventory(e){return(await this.api.sellerListInventory({path:{store_id:this.storeId},signal:e})).data}async adjustInventory(e,t){return(await this.api.sellerAdjustInventory({path:{store_id:this.storeId},body:e,signal:t})).data}async bulkSyncInventory(e,t){return(await this.api.sellerBulkSyncInventory({path:{store_id:this.storeId},body:e,signal:t})).data}async listOrders(e,t){return(await this.api.sellerListStoreOrders({path:{store_id:this.storeId},query:e,signal:t})).data}async getOrder(e,t){return(await this.api.sellerGetStoreOrder({path:{store_id:this.storeId,store_order_id:e},signal:t})).data}async createFulfillment(e,t,s){return(await this.api.sellerCreateFulfillment({path:{store_id:this.storeId,store_order_id:e},body:t,signal:s})).data}async updateFulfillment(e,t,s){return(await this.api.sellerUpdateFulfillment({path:{store_id:this.storeId,fulfillment_id:e},body:t,signal:s})).data}async cancelOrder(e,t,s){return(await this.api.sellerCancelStoreOrder({path:{store_id:this.storeId,store_order_id:e},body:t,signal:s})).data}async listReturns(e){return(await this.api.sellerListReturns({path:{store_id:this.storeId},signal:e})).data}async approveReturn(e,t={},s){return(await this.api.sellerApproveReturn({path:{store_id:this.storeId,return_id:e},body:t,signal:s})).data}async completeReturn(e,t={},s){return(await this.api.sellerCompleteReturn({path:{store_id:this.storeId,return_id:e},body:t,signal:s})).data}async listReviews(e,t){let s=e?_(e):void 0;return(await this.api.sellerListReviews({path:{store_id:this.storeId},query:s,signal:t})).data}async replyReview(e,t,s){let i=_(t);return(await this.api.sellerReplyReview({path:{store_id:this.storeId,review_id:e},body:i,signal:s})).data}async listSettlements(e){return(await this.api.sellerListSettlements({path:{store_id:this.storeId},signal:e})).data}async metrics(e){return(await this.api.sellerGetMetrics({path:{store_id:this.storeId},signal:e})).data}async onboardPayouts(e,t){return(await this.api.sellerOnboardPayouts({path:{store_id:this.storeId},body:e,signal:t})).data}async onboardingLink(e,t){return(await this.api.sellerOnboardingLink({path:{store_id:this.storeId},body:e,signal:t})).data}},Se=class{api;track;transport;userTransport;session;installation;analytics;consent;guestTokens=new Map;constructor(e,t,s,i,n,a){this.transport=e,this.userTransport=t,this.session=s,this.installation=i,this.analytics=n,this.consent=a,this.api=W.client(e),this.track={searchPerformed:o=>this.trackDiscoveryEvent(te.SEARCH_PERFORMED,o),productClicked:o=>this.trackDiscoveryEvent(te.PRODUCT_CLICKED,o),productViewed:o=>this.trackDiscoveryEvent(te.PRODUCT_VIEWED,o),cartItemAdded:o=>this.trackDiscoveryEvent(te.CART_ITEM_ADDED,o),recommendationClicked:o=>this.trackDiscoveryEvent(te.RECOMMENDATION_CLICKED,o)}}cartClient(e,t){let s=t??this.guestTokens.get(e);if(!s)return this.api;let i={send:n=>this.transport.send({...n,headers:{...n.headers,"X-Commerce-Guest-Token":s}})};return W.client(i)}discoveryHeaders(){if(this.installation&&!this.session.snapshot()?.userId&&this.consent?.state("personalization")!=="denied")return{[J]:this.installation.id,[O]:A(this.installation)}}discoveryClient(e,t){let s=e?t??this.guestTokens.get(e):void 0,i=this.discoveryHeaders();return!s&&!i?this.api:W.client({send:n=>this.transport.send({...n,headers:{...i,...s?{"X-Commerce-Guest-Token":s}:{},...n.headers}})})}trackDiscoveryEvent(e,t){this.analytics?.capture(e,t)}async listProducts(e,t){let s;if(e){let i=_(e),{attributes:n,...a}=i;s={...a,...n!==void 0?{attributes:typeof n=="string"?n:JSON.stringify(n)}:{}}}return(await this.discoveryClient().storefrontListProducts({query:s,signal:t})).data}async searchProducts(e={},t){let s=_(e);return(await this.discoveryClient().storefrontSearchProducts({body:s,signal:t})).data}async suggest(e,t,s){let i,n;typeof e=="string"?Xt(t)?(i={q:e},n=t):(i={...t??{},q:e},n=s):(i=e??{},n=Xt(t)?t:s);let{limit:a,max_results:o,...d}=_(i),l=o??a,c={...d,...l!==void 0?{max_results:l}:{}};return(await this.discoveryClient().storefrontSuggest({query:c,signal:n})).data}async recommend(e,t){let{guestToken:s,...i}=_(e);return(await this.discoveryClient(i.cart_id,s).storefrontRecommendProducts({body:i,signal:t})).data}async productRecommendations(e,t,s){let i;if(t){let{limit:n,max_results:a,...o}=_(t),d=a??n;i={...o,...d!==void 0?{max_results:d}:{}}}return(await this.discoveryClient().storefrontProductRecommendations({path:{product_id_or_handle:e},query:i,signal:s})).data}async similarProducts(e,t,s){return this.productStrategyRecommend(e,"similar",t,s)}async frequentlyBoughtTogether(e,t,s){return this.productStrategyRecommend(e,"fbt",t,s)}async productStrategyRecommend(e,t,s,i){let n=s?_(s):{},a=n.max_results??n.limit;if(!(n.exclude_product_ids!==void 0||n.category_id!==void 0||n.brand_id!==void 0||n.store_id!==void 0||n.params!==void 0||a!==void 0&&a>50))return this.productRecommendations(e,{strategy:t,...a!==void 0?{max_results:a}:{},...n.channel!==void 0?{channel:n.channel}:{},...n.region!==void 0?{region:n.region}:{},...n.currency!==void 0?{currency:n.currency}:{},...n.in_stock!==void 0?{in_stock:n.in_stock}:{}},i);let{max_results:d,limit:l,...c}=n;return this.recommend({...c,strategy:t,product_id:e,...a!==void 0?{limit:a}:{}},i)}async trendingProducts(e,t){return this.recommend({...e?_(e):{},strategy:"trending"},t)}async bestsellers(e,t){return this.recommend({...e?_(e):{},strategy:"bestsellers"},t)}async newArrivals(e,t){return this.recommend({...e?_(e):{},strategy:"new_arrivals"},t)}async topRated(e,t){return this.recommend({...e?_(e):{},strategy:"top_rated"},t)}async personalizedProducts(e,t){return this.recommend({...e?_(e):{},strategy:"personalized"},t)}async cartComplementary(e,t,s){return this.recommend({...t?_(t):{},strategy:"cart_complementary",cart_id:e},s)}async getProduct(e,t){return(await this.api.storefrontGetProduct({path:{product_id_or_handle:e},signal:t})).data}async listProductReviews(e,t,s){let i=t?_(t):void 0;return(await this.api.storefrontListProductReviews({path:{product_id_or_handle:e},query:i,signal:s})).data}async listStoreReviews(e,t,s){let i=t?_(t):void 0;return(await this.api.storefrontListStoreReviews({path:{store_id_or_slug:e},query:i,signal:s})).data}async createProductReview(e,t,s){let i=_(t);return(await this.api.createProductReview({path:{product_id_or_handle:e},body:i,signal:s})).data}async createStoreReview(e,t,s){let i=_(t);return(await this.api.createStoreReview({path:{store_id_or_slug:e},body:i,signal:s})).data}async myReviews(e){return(await this.api.listMyReviews({signal:e})).data}async deleteReview(e,t,s){let i=typeof t=="string"?t:t?.kind,n=i?{kind:i}:void 0;return(await this.api.deleteMyReview({path:{review_id:e},query:n,signal:s})).data}async voteReview(e,t,s){let i=_(t);return(await this.api.voteReview({path:{review_id:e},body:i,signal:s})).data}async mintReviewUploadUrl(e,t){let s=_(e);return(await this.api.mintReviewUploadUrl({body:s,signal:t})).data}async listCategories(e){return(await this.api.storefrontListCategories({signal:e})).data}async listBrands(e){return(await this.api.storefrontListBrands({signal:e})).data}async listCollections(e){return(await this.api.storefrontListCollections({signal:e})).data}async listStores(e,t){return(await this.api.storefrontListStores({query:e,signal:t})).data}async getStore(e,t){return(await this.api.storefrontGetStore({path:{store_id_or_slug:e},signal:t})).data}async listRegions(e){return(await this.api.storefrontListRegions({signal:e})).data}async listChannels(e){return(await this.api.storefrontListChannels({signal:e})).data}async createCart(e={},t){let s=(await this.api.createCart({body:e,signal:t})).data;return s.id&&s.guest_token&&this.guestTokens.set(s.id,s.guest_token),s}async getCart(e,t={}){return(await this.cartClient(e,t.guestToken).getCart({path:{cart_id:e},signal:t.signal})).data}async updateCart(e,t,s={}){return(await this.cartClient(e,s.guestToken).updateCart({path:{cart_id:e},body:t,signal:s.signal})).data}async addItem(e,t,s={}){return(await this.cartClient(e,s.guestToken).addCartItem({path:{cart_id:e},body:t,signal:s.signal})).data}async updateItem(e,t,s,i={}){return(await this.cartClient(e,i.guestToken).updateCartItem({path:{cart_id:e,line_id:t},body:s,signal:i.signal})).data}async removeItem(e,t,s={}){return(await this.cartClient(e,s.guestToken).deleteCartItem({path:{cart_id:e,line_id:t},signal:s.signal})).data}async selectShipping(e,t,s={}){return(await this.cartClient(e,s.guestToken).selectCartShipping({path:{cart_id:e},body:t,signal:s.signal})).data}async applyPromoCode(e,t,s={}){return(await this.cartClient(e,s.guestToken).applyCartPromoCode({path:{cart_id:e},body:{code:t},signal:s.signal})).data}async removePromoCode(e,t,s={}){return(await this.cartClient(e,s.guestToken).removeCartPromoCode({path:{cart_id:e,code:t},signal:s.signal})).data}async mergeCart(e,t={}){let s=t.guestToken??this.guestTokens.get(e),i=(await this.api.mergeGuestCart({path:{cart_id:e},body:s?{guest_token:s}:{},signal:t.signal})).data;return this.guestTokens.delete(e),i}async checkout(e,t={},s={}){return(await this.cartClient(e,s.guestToken).checkoutCart({path:{cart_id:e},body:t,signal:s.signal})).data}async getGuestOrder(e,t,s){let i={send:n=>this.transport.send({...n,headers:{...n.headers,"X-Commerce-Guest-Token":t}})};return(await W.client(i).getGuestOrder({path:{order_number:e},signal:s})).data}async myOrders(e,t){return(await this.api.listMyOrders({query:e,signal:t})).data}async myOrder(e,t){return(await this.api.getMyOrder({path:{order_id:e},signal:t})).data}async myOrderDownloads(e,t){return(await this.api.getMyOrderDownloads({path:{order_id:e},signal:t})).data}async requestReturn(e,t,s){return(await this.api.requestMyReturn({path:{store_order_id:e},body:t,signal:s})).data}async myReturns(e){return(await this.api.listMyReturns({signal:e})).data}seller(e){let t=this.session.snapshot()?.userId;if(!t)throw new T("seller portal requires a signed-in user session");return new Be(e,this.userTransport(t))}};var ii=720*60*60*1e3;function Je(r){try{return r.localStorage}catch{return}}var ke=class{api;commerce;installation;storageKey;g;now;memoryAttribution=null;constructor(e,t,s,i,n=globalThis,a=Date.now){this.api=ut.client({send:o=>e.send({...o,headers:{...o.headers,[O]:A(t)}})}),this.installation=t,this.commerce=s,this.storageKey=`palbase.campaigns.attribution.${i}`,this.g=n,this.now=a}async listOnSiteMessages(e){return(await this.api.listOnSiteMessages({signal:e})).data}async recordImpression(e,t){return(await this.api.createOnSiteImpression({body:{...e,installation_id:e.installation_id??this.installation.id},signal:t})).data}async recordEvent(e,t,s){await this.api.recordOnSiteEvent({path:{id:e},body:t,signal:s})}captureAttribution(e){let t=e??this.g.location?.search??this.g.location?.href??"";if(!t)return this.getAttribution();let s;try{t.includes("://")?s=new URL(t).searchParams:s=new URLSearchParams(t.startsWith("?")?t.slice(1):t)}catch{return this.getAttribution()}let i=s.get("pb_click")?.trim()||void 0,n=s.get("pb_promo")?.trim()||void 0,a=s.get("utm_source")?.trim()||void 0,o=s.get("utm_medium")?.trim()||void 0,d=s.get("utm_campaign")?.trim()||void 0,l=s.get("utm_content")?.trim()||void 0,c=s.get("utm_term")?.trim()||void 0;if(!i&&!n&&!a&&!o&&!d&&!l&&!c)return this.getAttribution();let h={...i?{clickToken:i}:{},...n?{promoCode:n}:{},...a?{utmSource:a}:{},...o?{utmMedium:o}:{},...d?{utmCampaign:d}:{},...l?{utmContent:l}:{},...c?{utmTerm:c}:{},capturedAt:this.now()};this.memoryAttribution=h;try{Je(this.g)?.setItem(this.storageKey,JSON.stringify(h))}catch{}return h}getAttribution(e=ii){let t=this.memoryAttribution;if(!t)try{let s=Je(this.g)?.getItem(this.storageKey);s&&(t=JSON.parse(s))}catch{t=null}return t?this.now()-t.capturedAt>e?(this.clearAttribution(),null):(this.memoryAttribution=t,t):null}clearAttribution(){this.memoryAttribution=null;try{Je(this.g)?.removeItem(this.storageKey)}catch{}}async applyAttributedPromo(e,t={}){let s=this.getAttribution();return s?.promoCode?this.commerce.applyPromoCode(e,s.promoCode,t):null}};var _e=class{api;session;socket;installation;ref;analytics;appVersion;storageKey;held;listeners=new Set;started;leave=[];running;queued;fresh=!0;constructor(e,t,s,i,n,a,o,d){this.api=ht.client(e),this.session=t,this.socket=s,this.installation=i,this.ref=n,this.analytics=o,this.appVersion=d,this.storageKey=`palbase.flags.${a}`,this.held=ni(this.storageKey)}value(e){let t=this.mine();if(!t||!Object.hasOwn(t.values,e))return;let s=t.experiments[e];return s&&this.analytics.captureOnce(`$flag_exposure:${e}:${s.experiment_id}`,"$flag_exposure",{flag:e,experiment:s.experiment_id,variant:s.variant}),t.values[e]}bool(e,t){let s=this.value(e);return typeof s=="boolean"?s:t}string(e,t){let s=this.value(e);return typeof s=="string"?s:t}number(e,t){let s=this.value(e);return typeof s=="number"&&Number.isFinite(s)?s:t}json(e,t){let s=this.value(e);return typeof s=="object"&&s!==null?s:t}all(){return{...this.mine()?.values}}source(e){return this.mine()?.sources[e]}get version(){return this.mine()?.syncVersion}onChange(e){return this.listeners.add(e),this.start(),()=>{this.listeners.delete(e)}}refresh(){return this.started?this.read():this.start()}mine(){this.start();let e=this.held;return e&&e.user===(this.session.snapshot()?.userId??null)?e:void 0}start(){if(this.started)return this.started;this.session.onChange((t,s)=>{(t==="SIGNED_IN"||t==="SIGNED_OUT"||t==="SESSION_EXPIRED")&&this.follow(s).catch(()=>{})});let e=this.session.session().then(t=>this.follow(t));return e.catch(()=>{}),this.started=e,e}follow(e){let t=e?.userId??null;if(this.held&&this.held.user!==t){let s=Object.keys(this.held.values);this.held=void 0,Yt(this.storageKey,void 0),this.tell(s)}return this.join(t),this.fresh=!0,this.read()}join(e){for(let s of this.leave.splice(0))s();let t=[`flags:${this.ref}`,...e!==null?[`flags:${this.ref}:${e}`]:[]];for(let s of t){let i=this.socket.channel(s),n=[i.on("broadcast",a=>{a.event==="changed"&&this.changed(Qe(a.payload))}),i.on("state_snapshot",a=>this.changed(Qe(Zt(a.entries)))),i.on("state_diff",a=>this.changed(Qe(Zt(a.set))))];i.join().catch(()=>{}),this.leave.push(()=>{n.forEach(a=>a()),i.leave()})}}changed(e){if(e===void 0)return;let t=this.mine();t&&Number(t.syncVersion)>=e||this.read().catch(()=>{})}read(){if(this.queued)return this.queued;let e=(this.running??Promise.resolve()).catch(()=>{}).then(()=>(this.queued=void 0,this.fetch()));this.queued=e,this.running=e;let t=()=>{this.running===e&&(this.running=void 0)};return e.then(t,t),e}async fetch(){let e=(await this.session.session())?.userId??null,t=this.held?.user===e?this.held:void 0,s=this.headers(e,t?.etag);if(t&&!this.fresh)try{let l=await this.api.getDelta({query:{since:Number(t.syncVersion)},headers:s});if(l.status===304)return;let c={...t,values:{...t.values},sources:{...t.sources},experiments:{...t.experiments},syncVersion:l.data.sync_version,etag:l.headers.get("etag")??t.etag},h=new Set;for(let p of l.data.ops)h.add(p.key),p.op==="delete"?(delete c.values[p.key],delete c.sources[p.key],delete c.experiments[p.key]):(c.values[p.key]=p.value??null,c.sources[p.key]=p.source,p.experiment?c.experiments[p.key]=p.experiment:delete c.experiments[p.key]);this.apply(c,[...h]);return}catch(l){if(!(l instanceof w&&l.status===410))throw l}let i=await this.api.getSnapshot({headers:s});if(this.fresh=!1,i.status===304)return;let n=i.data,a={user:e,values:n.values,sources:n.sources,experiments:n.experiments??{},syncVersion:n.sync_version,contextHash:n.context_hash,etag:i.headers.get("etag")??void 0},o=t?.values??{},d=[...new Set([...Object.keys(o),...Object.keys(a.values)])].filter(l=>JSON.stringify(o[l])!==JSON.stringify(a.values[l]));this.apply(a,d)}headers(e,t){return{"X-Platform":"web",...this.appVersion?{"X-Palbase-Client-Version":this.appVersion}:{},[J]:this.installation.id,...e===null?{[O]:A(this.installation)}:{},...t?{"If-None-Match":t}:{}}}apply(e,t){if(e.user!==(this.session.snapshot()?.userId??null))return;let s=this.held?.user===e.user?this.held:void 0;s&&!(Number(e.syncVersion)>Number(s.syncVersion)||e.syncVersion===s.syncVersion&&e.contextHash!==s.contextHash)||(this.held=e,Yt(this.storageKey,e),t.length>0&&this.tell(t))}tell(e){for(let t of[...this.listeners])try{t(e)}catch{}}};function ze(){try{return globalThis.localStorage}catch{return}}function ni(r){try{let e=ze()?.getItem(r);if(!e)return;let t=JSON.parse(e);return typeof t!="object"||t===null||typeof t.values!="object"||t.values===null||typeof t.syncVersion!="string"?void 0:{user:typeof t.user=="string"?t.user:null,values:t.values,sources:t.sources??{},experiments:t.experiments??{},syncVersion:t.syncVersion,contextHash:t.contextHash??"",...typeof t.etag=="string"?{etag:t.etag}:{}}}catch{return}}function Yt(r,e){try{e?ze()?.setItem(r,JSON.stringify(e)):ze()?.removeItem(r)}catch{}}function Zt(r){let e=typeof r=="object"&&r!==null?r.sync_version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Qe(r){let e=typeof r=="object"&&r!==null?r.sync_version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Re=class{items=new Map;add(e,t,s){let i={clientMessageId:t.client_message_id,conversationId:e,request:t,state:"pending",attempts:0,error:null,createdAt:s};return this.items.set(i.clientMessageId,i),i}get(e){return this.items.get(e)}all(e){return[...this.items.values()].filter(t=>!e||t.conversationId===e).sort((t,s)=>t.createdAt<s.createdAt?-1:t.createdAt>s.createdAt?1:0)}settle(e,t){return e.sender_id!==t||!e.client_message_id?!1:this.items.delete(e.client_message_id)}retry(e){let t=this.items.get(e);t&&t.state==="failed"&&Object.assign(t,{state:"pending",error:null})}discard(e){return this.items.delete(e)}async flush(e,t){let s=new Map;for(let n of this.all())n.state!=="failed"&&s.set(n.conversationId,[...s.get(n.conversationId)??[],n]);let i=!1;return await Promise.all([...s.values()].map(async n=>{for(let a of n){if(!this.items.has(a.clientMessageId))continue;a.state="sending",a.attempts++;let o;try{o=await e(a)}catch{o={kind:"wait"}}if(o.kind==="wait"){this.items.has(a.clientMessageId)&&(a.state="pending"),i=this.items.has(a.clientMessageId),t(a,o);return}o.kind==="refused"?Object.assign(a,{state:"failed",error:o.code}):this.items.delete(a.clientMessageId),t(a,o)}})),i}save(){return this.all().map(e=>({...e,state:e.state==="sending"?"pending":e.state}))}load(e){this.items.clear();for(let t of e)this.items.set(t.clientMessageId,{...t,state:t.state==="sending"?"pending":t.state})}};function Xe(r,e){if(r===200||r===201)return{kind:"sent",message:e};if(r===202)return{kind:"scheduled",scheduled:e};if(r<400||r>=500||r===408||r===429)return{kind:"wait"};let t=e?.error;return{kind:"refused",code:typeof t=="string"?t:`http_${r}`}}function es(){return{list:!1,conversations:new Set,threads:new Set,scheduled:!1}}var Pe=class{reader;cursor=null;conversations=new Map;members=new Map;messages=new Map;threads=new Map;scheduled=new Map;deleted=new Map;constructor(e){this.reader=e}apply(e){let t=es();for(let s of e.removed_conversations??[])this.removed(s,t);for(let s of e.hidden??[])this.messages.get(s.conversation_id)?.delete(s.message_id)&&t.conversations.add(s.conversation_id),this.threads.delete(s.message_id)&&t.threads.add(s.message_id),this.forgetLast(s.conversation_id,s.message_id)&&(t.list=!0);for(let s of e.conversations??[])this.putConversation(s,t);for(let s of e.members??[])this.putMember(s,t);for(let s of e.messages??[])this.putMessage(s,t);for(let s of e.threads??[])this.putThread(s,t);for(let s of e.scheduled??[])this.putScheduled(s,t);return t}reset(e){this.conversations.clear(),this.members.clear(),this.messages.clear(),this.threads.clear(),this.scheduled.clear();let t=this.apply(e);return t.list=!0,t.scheduled=!0,t}removed(e,t){if(e.reportable_until){let s=e.conversation_id,i=this.conversations.get(s)?.title??this.deleted.get(s)?.title??null;this.deleted.set(s,{id:s,title:i,deletedBy:e.deleted_by??null,reportableUntil:e.reportable_until})}this.drop(e.conversation_id,t)}drop(e,t){this.conversations.delete(e),this.members.delete(e),this.messages.delete(e);for(let[s,i]of this.threads)i.conversation_id===e&&this.threads.delete(s);t.list=!0,t.conversations.add(e)}putConversation(e,t){let s=this.conversations.get(e.id);if(e.deleted){this.drop(e.id,t);return}let i=s?.me&&e.me&&e.me.read_seq<s.me.read_seq?this.readTo(e,e.me,s.me.read_seq):e.me,n=s&&!ri(i,s.me)?s.me:i,a={...e,me:n,...e.last_message===void 0&&s?.last_message?{last_message:s.last_message}:{}};if(s){if(e.version<s.version){if(n===s.me)return;a={...s,me:n}}else if(e.version===s.version&&di(ts(a),s))return}e.gap&&this.messages.delete(e.id);for(let o of e.members??[])this.putMember(o,t);this.conversations.set(e.id,ts(a)),t.list=!0,t.conversations.add(e.id)}putMember(e,t){let s=this.members.get(e.conversation_id);s||(s=new Map,this.members.set(e.conversation_id,s));let i=s.get(e.user_id),n=e;if(i){if(e.version<i.version)return;if(e.version===i.version){let a=ai(i.read_seq,e.read_seq);if(a===i.read_seq&&e.delivered_seq<=i.delivered_seq)return;n={...i,read_seq:a,delivered_seq:Math.max(i.delivered_seq,e.delivered_seq)}}}s.set(e.user_id,n),t.conversations.add(e.conversation_id)}putMessage(e,t){let s=this.messages.get(e.conversation_id);s||(s=new Map,this.messages.set(e.conversation_id,s));let i=s.get(e.id);i&&e.version<=i.version||(s.set(e.id,e),t.conversations.add(e.conversation_id),e.thread_id&&t.threads.add(e.thread_id),(e.reply_count>0||i?.reply_count)&&t.threads.add(e.id),t.list=!0)}putThread(e,t){let s=this.threads.get(e.thread_id),i=s&&e.read_seq<s.read_seq?this.threadReadTo(e,s.read_seq):e;s&&i.version<=s.version&&i.unread_count===s.unread_count||(this.threads.set(e.thread_id,i),t.threads.add(e.thread_id))}putScheduled(e,t){let s=this.scheduled.get(e.id);s&&e.version<=s.version||(e.state==="scheduled"?this.scheduled.set(e.id,e):this.scheduled.delete(e.id),t.scheduled=!0)}read(e,t,s){let i=es(),n=this.conversations.get(e),a=n?Math.min(t,n.me?.left_seq??n.last_seq):t;if(s!==void 0){let o=this.threads.get(s);return!o||a<=o.read_seq||(this.threads.set(s,this.threadReadTo(o,a)),i.threads.add(s)),i}return!n?.me||a<=n.me.read_seq||(this.conversations.set(e,{...n,me:this.readTo(n,n.me,a)}),i.list=!0,i.conversations.add(e)),i}readTo(e,t,s){let i=t.left_seq??e.last_seq;if(s>=i)return{...t,read_seq:s,unread_count:0};let n=Math.max(t.read_seq,t.cleared_seq,t.joined_seq),a=this.timeline(e.id).filter(o=>o.seq>n&&o.seq<=s&&o.sender_id!==this.reader&&o.kind!=="system"&&o.kind!=="call"&&!o.deleted).length;return{...t,read_seq:s,unread_count:Math.max(0,t.unread_count-a)}}threadReadTo(e,t){let s=this.answers(e.conversation_id,e.thread_id).filter(i=>i.seq>e.read_seq&&i.seq<=t&&i.sender_id!==this.reader&&!i.deleted).length;return{...e,read_seq:t,unread_count:Math.max(0,e.unread_count-s)}}expire(e,t){let s=this.messages.get(e)?.delete(t)??!1;return this.forgetLast(e,t)||s}forgetLast(e,t){let s=this.conversations.get(e);if(s?.last_message?.id!==t)return!1;let{last_message:i,...n}=s;return this.conversations.set(e,n),!0}list(){return[...this.conversations.values()].map(e=>this.withLast(e)).sort(oi)}holdsAll(e){let t=this.conversations.get(e),s=this.messages.get(e);if(!t||!s)return!1;let i=Math.max(t.me?.joined_seq??0,t.me?.cleared_seq??0),n=t.me?.left_seq??t.last_seq;if(n<=i)return!1;let a=new Set([...s.values()].map(o=>o.seq));for(let o=i+1;o<=n;o++)if(!a.has(o))return!1;return!0}withLast(e){let t=Math.max(e.me?.joined_seq??0,e.me?.cleared_seq??0),s=e.me?.left_seq??Number.POSITIVE_INFINITY,i=c=>c!=null&&c.seq>t&&c.seq<=s&&!(c.expires_at&&Date.parse(c.expires_at)<=Date.now()&&!c.deleted),n=i(e.last_message)?e.last_message:void 0,a;for(let c of this.messages.get(e.id)?.values()??[])(!c.thread_id||c.also_in_conversation)&&i(c)&&(!a||c.seq>a.seq)&&(a=c);a&&(!n||a.seq>=n.seq)&&(n=a);let o=n&&this.messages.get(e.id)?.get(n.id);if(o&&n&&o.version>n.version&&(n=o),n===e.last_message)return e;let{last_message:d,...l}=e;return n?{...l,last_message:n}:l}timeline(e){return[...this.messages.get(e)?.values()??[]].filter(t=>!t.thread_id||t.also_in_conversation).sort((t,s)=>t.seq-s.seq)}answers(e,t){return[...this.messages.get(e)?.values()??[]].filter(s=>s.thread_id===t).sort((s,i)=>s.seq-i.seq)}deletedGroups(e){for(let[t,s]of this.deleted)Date.parse(s.reportableUntil)<=e&&this.deleted.delete(t);return[...this.deleted.values()].sort((t,s)=>Date.parse(s.reportableUntil)-Date.parse(t.reportableUntil)||(t.id<s.id?-1:t.id>s.id?1:0))}membersOf(e){return[...this.members.get(e)?.values()??[]].sort((t,s)=>t.user_id<s.user_id?-1:t.user_id>s.user_id?1:0)}snapshot(){return{cursor:this.cursor,conversations:[...this.conversations.values()],members:[...this.members.values()].flatMap(e=>[...e.values()]),messages:[...this.messages.values()].flatMap(e=>[...e.values()]),threads:[...this.threads.values()],scheduled:[...this.scheduled.values()],deleted:[...this.deleted.values()]}}load(e){this.reset({conversations:e.conversations,members:e.members,messages:e.messages,threads:e.threads,scheduled:e.scheduled}),this.cursor=e.cursor,this.deleted.clear();for(let t of e.deleted??[])this.deleted.set(t.id,t)}};function ri(r,e){return r?e?r.version!==e.version?r.version>e.version:r.read_seq!==e.read_seq?r.read_seq>e.read_seq:r.unread_count!==e.unread_count||r.delivered_seq>e.delivered_seq:!0:!1}function ai(r,e){return r===null?e:e===null?r:Math.max(r,e)}function oi(r,e){let t=r.last_message_at??r.created_at,s=e.last_message_at??e.created_at;return t!==s?t<s?1:-1:r.id<e.id?1:-1}function ts(r){let{members:e,gap:t,...s}=r;return s}function di(r,e){return JSON.stringify(r)===JSON.stringify(e)}var Te=class{store;outbox=new Re;me;now;constructor(e,t=Date.now){this.me=e,this.now=t,this.store=new Pe(e)}apply(e){return this.settled(e,this.store.apply(e))}reset(e){return this.settled(e,this.store.reset(e))}settled(e,t){for(let s of e.messages??[])this.outbox.settle(s,this.me)&&t.conversations.add(s.conversation_id);return t}write(e,t,s){return this.outbox.add(e,t,s)}read(e,t,s){let i=t??(s?Math.max(0,...this.store.answers(e,s).map(n=>n.seq)):this.store.conversations.get(e)?.last_seq??0);return{upTo:i,touched:this.store.read(e,i,s)}}sent(e){return e.kind==="sent"?this.apply({messages:[e.message]}):e.kind==="scheduled"?this.apply({scheduled:[e.scheduled]}):null}timeline(e){return this.entries(this.store.timeline(e),this.outbox.all(e).filter(t=>!t.request.thread_id||t.request.also_in_conversation))}answers(e,t){return this.entries(this.store.answers(e,t),this.outbox.all(e).filter(s=>s.request.thread_id===t))}entries(e,t){let s=new Set(e.filter(i=>i.sender_id===this.me&&i.client_message_id).map(i=>i.client_message_id));return[...e.map(i=>({kind:"message",message:i})),...t.filter(i=>!s.has(i.clientMessageId)&&!i.request.send_at).map(i=>({kind:"pending",item:i}))]}deletedGroups(){return this.store.deletedGroups(this.now())}kept(){return{store:this.store.snapshot(),outbox:this.outbox.save()}}load(e){this.store.load(e.store),this.outbox.load(e.outbox)}};function Ce(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("messaging: this platform has no WebCrypto to encrypt files with");return r}function li(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function ci(r){let e=atob(r.replaceAll("-","+").replaceAll("_","/")+"=".repeat((4-r.length%4)%4)),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}async function ss(r){let e=crypto.getRandomValues(new Uint8Array(32)),t=crypto.getRandomValues(new Uint8Array(12));return{sealed:await ui(r,e,t),fileKey:li(e)}}async function ui(r,e,t){let s=await Ce().importKey("raw",e,"AES-GCM",!1,["encrypt"]),i=new Uint8Array(await Ce().encrypt({name:"AES-GCM",iv:t},s,r)),n=new Uint8Array(1+t.length+i.length);return n[0]=1,n.set(t,1),n.set(i,1+t.length),n}async function is(r,e){if(r.length<29||r[0]!==1)throw new Error("messaging: not a file this SDK sealed");let t=await Ce().importKey("raw",ci(e),"AES-GCM",!1,["decrypt"]);return new Uint8Array(await Ce().decrypt({name:"AES-GCM",iv:r.subarray(1,13)},t,r.subarray(13)))}function z(r,e){return`palbase.messaging.v1.${r}.${e}`}var xe=class{kv;constructor(e){this.kv=e}async open(e){let t=await this.kv.get(e);if(t===null)return null;try{let s=JSON.parse(t);return s.format===1?{store:s.store,outbox:s.outbox}:null}catch{return null}}async save(e,t){await this.kv.set(e,JSON.stringify({format:1,store:hi(t.store),outbox:t.outbox}))}async drop(e){await this.kv.delete(e)}async dropOthers(e,t){let s=z(e,""),i=z(e,t);for(let n of await this.kv.list())n.startsWith(s)&&n!==i&&await this.kv.delete(n)}};function hi(r){let e=new Map;for(let s of r.messages)e.set(s.conversation_id,[...e.get(s.conversation_id)??[],s]);let t=[...e.values()].flatMap(s=>s.sort((i,n)=>n.seq-i.seq).slice(0,200));return{...r,messages:t}}function ns(){let r=new Map;return{async get(e){return r.get(e)??null},async set(e,t){r.set(e,t)},async delete(e){r.delete(e)},async list(){return[...r.keys()]},get keys(){return[...r.keys()]}}}var pi=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u,fi=/[\p{L}\p{Nd}\p{M}]/u,gi=/\p{M}/u,mi=/\p{Mn}/u;function yi(r){let e=r.codePointAt(0);if(e===304||e===305||r==="I")return["i"];let t=[];for(let s of r.toLowerCase().normalize("NFD"))mi.test(s)||t.push(s);return t}function rs(r){let e=[],t=null,s=0,i=0,n=!1;for(let a of r){let o=a.length;if(!fi.test(a))t=null,n=!1;else if(pi.test(a))n||(i++,n=!0),e.push({start:s,folded:[a.toLowerCase()],ends:[s+o],run:i}),t=null;else if(gi.test(a)&&!t){let d=e.at(-1);n&&d&&(d.ends[0]=s+o)}else{n=!1,t||(t={start:s,folded:[],ends:[],run:0},e.push(t));let d=yi(a);d.length===0&&t.ends.length>0&&(t.ends[t.ends.length-1]=s+o);for(let l of d)t.folded.push(l),t.ends.push(s+o)}s+=o}return e}function as(r){let e=[],t=0;for(let s of r)s.run!==0&&(s.run!==t&&(e.push(""),t=s.run),e[e.length-1]+=s.folded.join(""));return e}function os(r){let e={words:[],runs:[]},t=new Set,s=rs(r);for(let i of s){let n=i.folded.join("");if(n!==""&&!t.has(n)&&(t.add(n),e.words.push(i.folded)),e.words.length===8)break}return e.runs=as(s).filter(i=>[...i].length>1),e}function vi(r,e){return e.length===1?r.folded.length===1&&r.folded[0]===e[0]:r.folded.length>=e.length&&e.every((t,s)=>r.folded[s]===t)}function ds(r,...e){let t=r.words.map(()=>!1),s=[],i=e.map(n=>{let a=rs(n);return s.push(...as(a)),a.flatMap(o=>{let d=0;return r.words.forEach((l,c)=>{vi(o,l)&&(t[c]=!0,d=Math.max(d,l.length))}),d>0?[{offset:o.start,length:o.ends[d-1]-o.start}]:[]})});return r.runs.every(n=>s.some(a=>a.includes(n)))&&r.words.length>0&&t.every(Boolean)?i:null}var wi=500,bi=300,Si=2e3,ls=6e3,ki=3e4,cs=[1e3,2e3,5e3,1e4,3e4],_i=5*6e4,Ri=20,Pi=5,Ye=class{conversationId;messages=new Map;earlier=null;later=null;merged=!1;constructor(e){this.conversationId=e}put(e){for(let t of e){let s=this.messages.get(t.id);(!s||t.version>s.version)&&this.messages.set(t.id,t)}}apply(e){let t=!1;for(let s of e.messages??[]){let i=this.messages.get(s.id);i&&s.version>i.version&&(this.messages.set(s.id,s),t=!0)}for(let s of e.hidden??[])this.messages.delete(s.message_id)&&(t=!0);return((e.removed_conversations??[]).some(s=>s.conversation_id===this.conversationId)||(e.conversations??[]).some(s=>s.id===this.conversationId&&s.deleted))&&(this.messages.clear(),t=!0),t}expire(e){return this.messages.delete(e)}entries(){return[...this.messages.values()].filter(e=>!e.thread_id||e.also_in_conversation).sort((e,t)=>e.seq-t.seq).map(e=>({kind:"message",message:e}))}};function Ti(r="palbase.messaging"){let e=globalThis.indexedDB;if(!e)return null;let t=null,s=()=>t??=new Promise((n,a)=>{let o=e.open(r,1);o.onupgradeneeded=()=>o.result.createObjectStore("kv"),o.onsuccess=()=>n(o.result),o.onerror=()=>a(o.error)}),i=(n,a)=>s().then(o=>new Promise((d,l)=>{let c=a(o.transaction("kv",n).objectStore("kv"));c.onsuccess=()=>d(c.result),c.onerror=()=>l(c.error)}));return{get:async n=>await i("readonly",a=>a.get(n))??null,set:async(n,a)=>{await i("readwrite",o=>o.put(a,n))},delete:async n=>{await i("readwrite",a=>a.delete(n))},list:async()=>(await i("readonly",n=>n.getAllKeys())).map(String)}}var Me=class{api;local;transportFor;clients=new WeakMap;user=null;engine=null;starting=null;channel=null;off=[];heard=new Set;synced=!1;syncing=null;resync=!1;flushing=null;reflush=!1;retries=0;timers={save:void 0,deliver:void 0,retry:void 0,presence:void 0,reportable:void 0};delivered=new Map;expiring=new Map;typingTimers=new Map;typingBy=new Map;typedAt=new Map;loaded=new Set;earlier=new Map;saving=Promise.resolve();reopeners=new Set;incoming=new Set;windows=new Set;people=new Map;session;socket;ref;fetchFn;opts;constructor(e,t,s,i,n,a,o={}){this.transportFor=t,this.session=s,this.socket=i,this.ref=n,this.fetchFn=a,this.opts=o,this.api=Ue.client(e),this.local=new xe(o.storage??Ti()??ns()),s.onChange((l,c)=>{l==="SIGNED_OUT"||l==="SESSION_EXPIRED"?this.end():l==="SIGNED_IN"&&c?.userId!==this.user?this.end().then(async()=>{if(this.heard.size!==0){await this.ready();for(let h of[...this.reopeners])h()}}):l==="SIGNED_IN"&&this.engine&&this.user&&(this.unfollow(),this.follow(this.user),this.sync())});let d=globalThis;d.addEventListener?.("online",()=>this.wake()),d.document?.addEventListener?.("visibilitychange",()=>{d.document?.visibilityState==="visible"&&this.wake()})}async ready(){let e=this.session.snapshot()??await this.session.session();if(!e)throw new w({op:"messaging",status:401,code:"not_signed_in",message:"messaging is the signed-in person's: sign in first"});if(this.engine&&this.user===e.userId)return this.engine;if(this.starting&&this.user===e.userId)return this.starting;this.user=e.userId;let t=e.userId;return this.starting=(async()=>{let s=new Te(t);this.clients.set(s,Ue.client(this.transportFor(t)));let i=await this.local.open(z(this.ref,t));if(this.user!==t)throw new Error("messaging: the session changed while it started");i&&s.load(i),this.engine=s;for(let n of s.store.messages.values())for(let a of n.values())this.expireAt(a);return this.expireDeleted(s),this.tell({list:!0,conversations:new Set(s.store.conversations.keys()),threads:new Set,scheduled:!0}),this.follow(t),this.opts.keepOnSignOut||this.local.dropOthers(this.ref,t).catch(()=>{}),this.sync().then(()=>this.flush()),this.presence(s),s})(),this.starting.catch(()=>{this.user===t&&(this.starting=null)}),this.starting}async end(){let e=this.user,t=this.engine;this.unfollow();for(let[s,i]of Object.entries(this.timers))i&&clearTimeout(i),this.timers[s]=void 0;for(let s of this.expiring.values())clearTimeout(s);this.expiring.clear();for(let s of this.typingTimers.values())clearTimeout(s);this.typingTimers.clear(),this.typingBy.clear(),this.delivered.clear(),this.loaded.clear(),this.earlier.clear();for(let s of this.windows)s.merged=!0;if(this.windows.clear(),this.people.clear(),this.engine=null,this.starting=null,this.user=null,this.synced=!1,e){let s=z(this.ref,e);await this.saving,this.opts.keepOnSignOut&&t?await this.local.save(s,t.kept()):await this.local.drop(s)}this.tell({list:!0,conversations:new Set,threads:new Set,scheduled:!0})}unfollow(){for(let e of this.off.splice(0))e();this.channel?.leave(),this.channel=null}follow(e){let t=this.socket.channel(`messaging:${this.ref}:${e}`);this.channel=t,this.off.push(t.on("broadcast",s=>{this.user===e&&(s.event==="changes"?this.heardLive(s.payload):s.event==="typing"&&this.typed(s.payload))}),t.onJoined(()=>{this.sync()})),t.join().catch(()=>{})}wake(){this.engine&&this.sync().then(()=>this.flush())}sync(){return this.syncing?(this.resync=!0,this.syncing):(this.syncing=(async()=>{try{do{this.resync=!1;let e=this.engine;if(!e)return;let t=(await this.as(e).sync({query:e.store.cursor?{since:e.store.cursor}:{}})).data;if(this.engine!==e)return;let s=t.reset?e.reset(t):e.apply(t);this.toWindows(t,s);let i=t.reset?[...this.loaded]:t.conversations.filter(n=>n.gap&&this.loaded.has(n.id)).map(n=>n.id);t.reset&&this.loaded.clear();for(let n of i)this.loaded.delete(n),this.earlier.delete(n);e.store.cursor=t.cursor,this.after(t,s);for(let n of i)this.openPage(n).catch(()=>{});this.synced||(s.list=!0),this.synced=!0,this.tell(s)}while(this.resync)}finally{this.syncing=null}})(),this.syncing)}onIncoming(e){return this.incoming.add(e),()=>{this.incoming.delete(e)}}heardLive(e){let t=this.engine;if(!t)return;let s=(e.messages??[]).filter(i=>i.version===1&&i.sender_id!==t.me&&!i.deleted&&i.kind!=="system"&&i.kind!=="call"&&!t.store.messages.get(i.conversation_id)?.has(i.id));this.changed(e,t);for(let i of s)for(let n of[...this.incoming])n(i)}changed(e,t=this.engine){if(!t||t!==this.engine)return;let s=t.apply(e);this.toWindows(e,s),this.after(e,s),this.tell(s)}toWindows(e,t){for(let s of this.windows)s.apply(e)&&t.conversations.add(s.conversationId)}putWindow(e,t){e.put(t);for(let s of t)this.expireAt(s)}fromWindows(e,t){let s=!1;for(let i of this.windows)i.conversationId===e&&t(i)&&(s=!0);return s}after(e,t){for(let s of e.messages??[])this.expireAt(s),s.sender_id!==this.user&&!s.deleted&&(s.thread_id===null||s.also_in_conversation)&&this.delivered.set(s.conversation_id,Math.max(this.delivered.get(s.conversation_id)??0,s.seq));e.removed_conversations?.some(s=>s.reportable_until)&&this.engine&&this.expireDeleted(this.engine),this.delivered.size>0&&(this.timers.deliver??=setTimeout(()=>{this.deliver()},wi)),(t.list||t.conversations.size>0||t.threads.size>0||t.scheduled)&&this.save()}expireAt(e){let t=e.id,s=this.expiring.get(t);if(s&&clearTimeout(s),this.expiring.delete(t),!e.expires_at||e.deleted)return;let i=Date.parse(e.expires_at)-Date.now(),n=()=>{this.expiring.delete(t);let a=this.engine?.store.expire(e.conversation_id,e.id)??!1;(this.fromWindows(e.conversation_id,o=>o.expire(e.id))||a)&&(this.tell({list:!0,conversations:new Set([e.conversation_id]),threads:new Set(e.thread_id?[e.thread_id]:[]),scheduled:!1}),this.save())};i<=0?n():this.expiring.set(t,setTimeout(n,Math.min(i,2**31-1)))}expireDeleted(e){clearTimeout(this.timers.reportable),this.timers.reportable=void 0;let t=Math.min(...e.deletedGroups().map(s=>Date.parse(s.reportableUntil)));Number.isFinite(t)&&(this.timers.reportable=setTimeout(()=>{this.timers.reportable=void 0,this.engine===e&&(this.tell({list:!0,conversations:new Set,threads:new Set,scheduled:!1}),this.save(),this.expireDeleted(e))},Math.min(Math.max(0,t-Date.now()),2**31-1)))}async deliver(){this.timers.deliver=void 0;let e=[...this.delivered].map(([t,s])=>({conversation_id:t,delivered_seq:s}));if(this.delivered.clear(),!(e.length===0||!this.engine))try{await this.as(this.engine).receipts({body:{receipts:e.slice(0,100)}})}catch{}}save(){this.timers.save??=setTimeout(()=>{this.timers.save=void 0;let e=this.engine,t=this.user;e&&t&&(this.saving=this.saving.then(()=>this.local.save(z(this.ref,t),e.kept())).catch(()=>{}))},bi)}flush(){return this.flushing?(this.reflush=!0,this.flushing):(clearTimeout(this.timers.retry),this.timers.retry=void 0,this.flushing=(async()=>{try{let e=!1;do{this.reflush=!1;let t=this.engine;if(!t)return;let s=this.as(t);if(e=await t.outbox.flush(i=>this.post(s,i),(i,n)=>{let a=t.sent(n)??{list:!1,conversations:new Set([i.conversationId]),threads:new Set,scheduled:!1};a.conversations.add(i.conversationId),n.kind==="sent"&&this.after({messages:[n.message]},a),this.save(),this.tell(a)}),this.engine!==t)return}while(this.reflush&&!e);if(e){let t=cs[Math.min(this.retries++,cs.length-1)];this.timers.retry=setTimeout(()=>{this.flush()},t)}else this.retries=0}finally{this.flushing=null}})(),this.flushing)}async post(e,t){try{let s=await e.sendMessage({path:{conversation_id:t.conversationId},body:t.request});return Xe(s.status,s.data)}catch(s){return s instanceof w?s.isNetworkError?{kind:"wait"}:Xe(s.status,{error:s.code}):{kind:"wait"}}}presence(e){let t=()=>{if(this.engine!==e)return;let s=globalThis.document;(!s||s.visibilityState!=="hidden")&&this.as(e).presence().catch(()=>{}),this.timers.presence=setTimeout(t,ki)};t()}as(e){return this.clients.get(e)}async seat(){let e=await this.ready();return{e,as:this.as(e)}}typed(e){let t=this.typingBy.get(e.conversation_id);t||this.typingBy.set(e.conversation_id,t=new Map),t.set(e.user_id,Date.now()+ls),this.tell({list:!1,conversations:new Set([e.conversation_id]),threads:new Set,scheduled:!1});let s=`${e.conversation_id}\0${e.user_id}`,i=this.typingTimers.get(s);i&&clearTimeout(i);let n=setTimeout(()=>{this.typingTimers.delete(s),this.engine&&this.tell({list:!1,conversations:new Set([e.conversation_id]),threads:new Set,scheduled:!1})},ls+50);this.typingTimers.set(s,n)}tell(e){for(let t of[...this.heard])t(e)}listen(e){return this.heard.add(e),this.ready().catch(()=>{}),()=>{this.heard.delete(e)}}onPerson(e){return this.reopeners.add(e),()=>{this.reopeners.delete(e)}}current(){return this.engine}typingIn(e){let t=Date.now();return[...this.typingBy.get(e)??[]].filter(([s,i])=>i>t&&s!==this.user).map(([s])=>s)}touch(e){this.tell({list:!1,conversations:new Set([e]),threads:new Set,scheduled:!1})}isSynced(){return this.synced}conversations(e={}){return new Ze(this,e.spaces??[])}deletedGroups(){return new et(this)}conversation(e,t={}){return new tt(this,e,t.at??null)}async direct(e,t={}){let{e:s,as:i}=await this.seat(),n=(await i.openDirectConversation({body:{user_id:e,space:t.space}})).data;return this.changed({conversations:[n]},s),this.conversation(n.id)}async group(e){let{e:t,as:s}=await this.seat(),i=(await s.createGroup({body:{title:e.title,member_ids:e.memberIds,description:e.description,photo:e.photo,settings:e.settings,space:e.space,visibility:e.visibility}})).data;return this.changed({conversations:[i.conversation]},t),{conversation:this.conversation(i.conversation.id),notAdded:i.not_added}}thread(e,t,s={}){return new st(this,e,t,s.at??null)}async search(e,t={}){let s=os(e);if(s.words.length===0)return{conversations:[],messages:[],nextCursor:null};let i=t.by==="meaning",{e:n,as:a}=await this.seat(),o=async()=>{let f=t.cursor;for(let u=0;;u++){let g={q:e,...i?{by:"meaning"}:{},conversation_id:t.conversationId,...t.space?{space:[t.space]}:{},limit:t.limit,cursor:f},y=(await a.searchMessages({query:g})).data;if(i||y.data.length>0||!y.next_cursor||u+1===Pi)return y;f=y.next_cursor}},[d,l]=await Promise.all([o(),i||t.cursor||t.conversationId?Promise.resolve([]):this.named(s,n,t.space)]),c=Date.now();for(let f of d.profiles)this.people.set(f.user_id,{profile:f,at:c});let h=f=>f?this.people.get(f)?.profile??null:null,p=new Map(d.conversations.map(f=>[f.id,f])),b=d.data.flatMap(f=>{let u=p.get(f.message.conversation_id)??n.store.conversations.get(f.message.conversation_id);if(!u)return[];let g=u.kind==="direct"?h(u.peer_id):null;return[{message:f.message,conversation:u,title:u.kind==="direct"?g?.name??null:u.title,photo:u.kind==="direct"?g?.image??null:u.photo,sender:h(f.message.sender_id),peer:g,matches:f.matches,score:f.score??null,threadRootId:f.message.thread_id&&!f.message.also_in_conversation?f.message.thread_id:null}]});return{conversations:l,messages:b,nextCursor:i?null:d.next_cursor??null}}async named(e,t,s){let i=t.store.list().filter(a=>!s||a.space===s),n=[...new Set(i.filter(a=>a.kind==="direct"&&a.peer_id).map(a=>a.peer_id))].filter(a=>{let o=this.people.get(a);return!o||Date.now()-o.at>_i});for(let a=0;a<n.length;a+=100){let o=n.slice(a,a+100);try{let d=(await this.as(t).getProfiles({query:{user_ids:o.join(",")}})).data.data,l=Date.now();for(let c of o)this.people.set(c,{profile:d.find(h=>h.user_id===c)??null,at:l})}catch{}}return i.flatMap(a=>{let o=a.kind==="direct"&&a.peer_id?this.people.get(a.peer_id)?.profile??null:null,d=a.kind==="direct"?o?.name??null:a.title,l=d?ds(e,d):null;return l?[{conversation:a,title:d,photo:a.kind==="direct"?o?.image??null:a.photo,peer:o,matches:l[0]}]:[]})}async openGroups(e,t={}){let{as:s}=await this.seat(),i=(await s.listOpenGroups({query:{space:e,limit:t.limit,cursor:t.cursor}})).data;return{items:i.data,nextCursor:i.next_cursor??null}}async join(e){let{e:t,as:s}=await this.seat(),i=(await s.joinGroup({path:{conversation_id:e}})).data;return this.changed({conversations:[i]},t),this.conversation(i.id)}scheduled(){return new it(this)}async threads(){let{as:e}=await this.seat();return(await e.listThreads()).data.data}async send(e,t){let{e:s}=await this.seat(),i=typeof t=="string"?{text:t}:t,n=i.files?.length?await this.upload(e,i.files):void 0,a={client_message_id:crypto.randomUUID(),...i.text!==void 0?{text:i.text}:{},...i.mentions?{mentions:i.mentions}:{},...n?{attachments:n}:{},...i.replyTo?{reply_to_id:i.replyTo}:{},...i.threadId?{thread_id:i.threadId}:{},...i.alsoInConversation?{also_in_conversation:!0}:{},...i.expiresIn!==void 0?{expires_in:i.expiresIn,expires_from:i.expiresFrom??"send"}:{},...i.viewOnce?{view_once:{limit:i.viewOnce.limit,...i.viewOnce.seconds?{seconds:i.viewOnce.seconds}:{}}}:{},...i.sendAt?{send_at:i.sendAt.toISOString()}:{}};if(s!==this.engine)throw new T(`the session is no longer ${s.me}'s`);let o=s.write(e,a,new Date().toISOString());return this.tell({list:!1,conversations:new Set([e]),threads:new Set(i.threadId?[i.threadId]:[]),scheduled:!1}),this.save(),this.flush(),o}async upload(e,t){let{as:s}=await this.seat(),i=[];for(let n of t){let a=n.data instanceof Uint8Array?n.data:new Uint8Array(await n.data.arrayBuffer()),{sealed:o,fileKey:d}=await ss(a),l=(await s.createUpload({path:{conversation_id:e},body:{size:o.length}})).data,c=await this.fetchFn(l.url,{method:"PUT",body:o,headers:{"content-type":"application/octet-stream"}});if(!c.ok)throw new w({op:"UploadFile",status:c.status,code:"upload_failed",message:`the file was not uploaded (${c.status})`});i.push({upload_id:l.id,content_type:n.contentType,file_key:d,...n.name?{name:n.name}:{},...n.width?{width:n.width}:{},...n.height?{height:n.height}:{},...n.durationMs?{duration_ms:n.durationMs}:{},...n.thumbnail?{thumbnail:n.thumbnail}:{}})}return i}async open(e,t){let{as:s}=await this.seat(),i=e.attachments.find(a=>a.id===t);if(!i?.file_key)throw new w({op:"OpenFile",status:404,code:"attachment_not_found",message:"no such file of the message, or one seen once"});let n=(await s.attachmentUrl({path:{conversation_id:e.conversation_id,message_id:e.id,attachment_id:i.id}})).data;return{id:i.id,name:i.name,contentType:i.content_type,bytes:await this.bytes(n.url,i.file_key)}}async viewOnce(e){let{as:t}=await this.seat(),s=(await t.viewOnce({path:{conversation_id:e.conversation_id,message_id:e.id}})).data;return Promise.all(s.attachments.map(async i=>({id:i.id,name:null,contentType:i.content_type,bytes:await this.bytes(i.url,i.file_key)})))}async bytes(e,t){let s=await this.fetchFn(e);if(!s.ok)throw new w({op:"OpenFile",status:s.status,code:"download_failed",message:`the file was not read (${s.status})`});return is(new Uint8Array(await s.arrayBuffer()),t)}async edit(e,t,s,i){let{e:n,as:a}=await this.seat(),o=(await a.editMessage({path:{conversation_id:e,message_id:t},body:{text:s,...i?{mentions:i}:{}}})).data;return this.changed({messages:[o]},n),o}async remove(e,t,s="everyone"){let{e:i,as:n}=await this.seat(),a=await n.deleteMessage({path:{conversation_id:e,message_id:t},query:{for:s}});a.status===200?this.changed({messages:[a.data]},i):this.changed({hidden:[{conversation_id:e,message_id:t}]},i)}async react(e,t,s,i={}){let{e:n,as:a}=await this.seat(),o=(await a.react({path:{conversation_id:e,message_id:t,emoji:s},body:i.replace?{replace:!0}:{}})).data;return this.changed({messages:[o]},n),o}async unreact(e,t,s){let{e:i,as:n}=await this.seat(),a=(await n.unreact({path:{conversation_id:e,message_id:t,emoji:s}})).data;return this.changed({messages:[a]},i),a}async markRead(e,t,s){let{e:i,as:n}=await this.seat(),{upTo:a,touched:o}=i.read(e,t,s);a<=0||((o.list||o.conversations.size>0||o.threads.size>0)&&(this.tell(o),this.save()),await n.receipts({body:{receipts:[{conversation_id:e,read_seq:a,...s?{thread_id:s}:{}}]}}))}async typing(e,t){let{as:s}=await this.seat(),i=this.typedAt.get(e)??0;Date.now()-i<Si||(this.typedAt.set(e,Date.now()),await s.typing({path:{conversation_id:e},body:t?{thread_id:t}:{}}).catch(()=>{}))}async update(e,t){let{e:s,as:i}=await this.seat(),n=(await i.updateConversation({path:{conversation_id:e},body:t})).data;return this.changed({conversations:[n]},s),n}async close(e){let{e:t,as:s}=await this.seat();if(await s.closeConversation({path:{conversation_id:e}}),t!==this.engine)return;let i=t.store.conversations.get(e)?.me,n=d=>d.vanish&&d.sender_id!==t.me&&i&&d.seq<=i.read_seq,a=t.store.timeline(e).filter(n);for(let d of a)t.store.expire(e,d.id);let o=this.fromWindows(e,d=>[...d.messages.values()].filter(n).map(l=>d.expire(l.id)).includes(!0));(a.length>0||o)&&(this.tell({list:!0,conversations:new Set([e]),threads:new Set,scheduled:!1}),this.save())}async screenshot(e){let{e:t,as:s}=await this.seat(),i=(await s.reportScreenshot({path:{conversation_id:e}})).data;return this.changed({messages:[i]},t),i}async leave(e){let{e:t,as:s}=await this.seat();await s.removeMember({path:{conversation_id:e,user_id:t.me}}),this.sync()}async deleteConversation(e){let{e:t,as:s}=await this.seat();await s.deleteConversation({path:{conversation_id:e}}),this.changed({removed_conversations:[{conversation_id:e,reason:"deleted"}]},t)}async notifications(e,t){let{as:s}=await this.seat();await s.setConversationNotifications({path:{conversation_id:e},body:t}),this.sync()}async cancelScheduled(e){let{e:t,as:s}=await this.seat();await s.cancelScheduled({path:{scheduled_id:e}}),t===this.engine&&t.store.scheduled.delete(e)&&(this.tell({list:!1,conversations:new Set,threads:new Set,scheduled:!0}),this.save())}async editScheduled(e,t){let{e:s,as:i}=await this.seat(),n=(await i.updateScheduled({path:{scheduled_id:e},body:t})).data;return this.changed({scheduled:[n]},s),n}async me(){let{as:e}=await this.seat();return(await e.getMyProfile()).data}async updateMe(e){let{as:t}=await this.seat(),s=(await t.updateMyProfile({body:e})).data;return e.read_receipts!==void 0&&this.sync(),s}async profiles(e){let{as:t}=await this.seat();return(await t.getProfiles({query:{user_ids:e.join(",")}})).data.data}async block(e){let{as:t}=await this.seat();await t.block({path:{user_id:e}})}async unblock(e){let{as:t}=await this.seat();await t.unblock({path:{user_id:e}})}async report(e){let{as:t}=await this.seat();return(await t.report({body:e})).data}async openPage(e){let{e:t}=await this.seat();if(!this.loaded.has(e)){if(this.loaded.add(e),t.store.timeline(e).length>0&&this.synced){t.store.holdsAll(e)&&(this.earlier.set(e,null),this.tellConversation(e));return}await this.page(e,null)}}async page(e,t){let{e:s,as:i}=await this.seat(),n=(await i.listMessages({path:{conversation_id:e},query:t?{cursor:t,limit:50}:{limit:50}})).data;return s!==this.engine?!1:(this.earlier.set(e,n.next_cursor??null),this.changed({messages:n.data},s),this.tellConversation(e),!!n.next_cursor)}tellConversation(e){this.tell({list:!1,conversations:new Set([e]),threads:new Set,scheduled:!1})}earlierOf(e){return this.earlier.get(e)}async openAt(e,t){let{e:s,as:i}=await this.seat(),n=s.store.messages.get(e)?.get(t),a=this.earlier.get(e);if(n&&a!==void 0&&(a===null||parseInt(a,36)<=n.seq))return null;let o=(await i.listMessages({path:{conversation_id:e},query:{around:t,limit:50}})).data;if(s!==this.engine)return null;let d=new Ye(e);return this.putWindow(d,o.data),d.earlier=o.next_cursor??null,d.later=o.newer_cursor??null,d.later===null?(this.merge(d,s),null):(this.windows.add(d),d)}async windowPage(e,t){let{e:s,as:i}=await this.seat(),n=t==="earlier"?e.earlier:e.later;if(n===null||e.merged)return;let a=t==="earlier"?{cursor:n,limit:50}:{after:n,limit:50},o=(await i.listMessages({path:{conversation_id:e.conversationId},query:a})).data;s!==this.engine||e.merged||(this.putWindow(e,o.data),t==="earlier"?e.earlier=o.next_cursor??null:e.later=o.newer_cursor??null,e.later===null?this.merge(e,s):this.tell({list:!1,conversations:new Set([e.conversationId]),threads:new Set,scheduled:!1}))}dropWindow(e){e.merged=!0,this.windows.delete(e)}merge(e,t){this.dropWindow(e);let s=e.conversationId,i=this.earlier.get(s),n=i===void 0||i!==null&&(e.earlier===null||parseInt(e.earlier,36)<parseInt(i,36))?e.earlier:i;this.earlier.set(s,n),this.loaded.add(s),this.changed({messages:[...e.messages.values()]},t),this.tell({list:!1,conversations:new Set([s]),threads:new Set,scheduled:!1})}async openThread(e,t,s=null){let{e:i,as:n}=await this.seat(),a=(await n.getMessage({path:{conversation_id:e,message_id:t}})).data,o=[],d;for(let l=0;l<Ri;l++){let c=(await n.listReplies({path:{conversation_id:e,message_id:t},query:d?{limit:100,cursor:d}:{limit:100}})).data;if(o.push(...c.data),d=c.next_cursor,!d||!s||o.some(h=>h.id===s))break}this.changed({messages:[a,...o]},i)}async openScheduled(){let{e,as:t}=await this.seat();this.changed({scheduled:(await t.listScheduled()).data.data},e)}},F=class{listeners=new Set;unlisten=null;unperson=null;cached=null;m;constructor(e){this.m=e}get state(){return this.unlisten?this.cached??=this.read():this.read()}subscribe(e){return this.listeners.add(e),this.unlisten||(this.cached=null,this.unlisten=this.m.listen(t=>{if(this.touches(t)){this.cached=this.read();for(let s of[...this.listeners])s()}}),this.unperson=this.m.onPerson(()=>{this.cached=null,this.opened();for(let t of[...this.listeners])t()}),this.opened()),()=>{this.listeners.delete(e),this.listeners.size===0&&(this.unlisten?.(),this.unperson?.(),this.unlisten=null,this.unperson=null,this.closed())}}opened(){}closed(){}},Ze=class extends F{spaces;constructor(e,t=[]){super(e),this.spaces=[...t]}touches(e){return e.list||e.conversations.size>0}read(){let e=this.m.current()?.store.list()??[],t=this.spaces.length===0?e:e.filter(s=>s.space!=null&&this.spaces.includes(s.space));return{items:t,unread:t.reduce((s,i)=>s+(i.me?.unread_count??0),0),synced:this.m.isSynced()}}},et=class extends F{touches(e){return e.list}read(){return{items:this.m.current()?.deletedGroups()??[]}}},tt=class extends F{id;focus;window=null;opening=null;settled=!1;constructor(e,t,s=null){super(e),this.id=t,this.focus=s}opened(){if(!this.focus){this.m.openPage(this.id).catch(()=>{});return}this.window&&this.m.dropWindow(this.window),this.window=null,this.settled=!1,this.opening=this.m.openAt(this.id,this.focus).then(e=>{this.window=e,e||this.m.openPage(this.id).catch(()=>{})}).catch(()=>{this.m.openPage(this.id).catch(()=>{})}).finally(()=>{this.settled=!0,this.m.touch(this.id)})}closed(){this.window&&this.m.dropWindow(this.window),this.window=null}touches(e){return e.conversations.has(this.id)}stretch(){return this.window?.merged&&(this.window=null),this.window}read(){let e=this.m.current(),t=this.stretch(),s=this.focus!==null&&!this.settled;return{conversation:e?.store.conversations.get(this.id)??null,entries:s?[]:t?t.entries():e?.timeline(this.id)??[],members:e?.store.membersOf(this.id)??[],typing:this.m.typingIn(this.id),hasEarlier:t?t.earlier!==null:this.m.earlierOf(this.id)!==null,hasLater:t!==null,focus:this.focus}}refresh(){return this.m.page(this.id,null)}async loadEarlier(){await this.opening;let e=this.stretch();if(e)return await this.m.windowPage(e,"earlier"),e.earlier!==null;let t=this.m.earlierOf(this.id);return t===null?!1:this.m.page(this.id,t??null)}async loadLater(){await this.opening;let e=this.stretch();return e?(await this.m.windowPage(e,"later"),this.stretch()!==null):!1}showLatest(){this.window&&(this.m.dropWindow(this.window),this.window=null,this.m.openPage(this.id).catch(()=>{}),this.m.touch(this.id))}send(e){return this.m.send(this.id,e)}markRead(e){return this.m.markRead(this.id,e)}typing(){return this.m.typing(this.id)}thread(e){return this.m.thread(this.id,e)}},st=class extends F{conversationId;rootId;focus;constructor(e,t,s,i=null){super(e),this.conversationId=t,this.rootId=s,this.focus=i}opened(){this.m.openThread(this.conversationId,this.rootId,this.focus).catch(()=>{})}touches(e){return e.threads.has(this.rootId)||e.conversations.has(this.conversationId)}read(){let e=this.m.current();return{root:e?.store.messages.get(this.conversationId)?.get(this.rootId)??null,entries:e?.answers(this.conversationId,this.rootId)??[],thread:e?.store.threads.get(this.rootId)??null,focus:this.focus}}send(e){let t=typeof e=="string"?{text:e}:e;return this.m.send(this.conversationId,{...t,threadId:this.rootId})}markRead(){return this.m.markRead(this.conversationId,void 0,this.rootId)}},it=class extends F{opened(){this.m.openScheduled().catch(()=>{})}touches(e){return e.scheduled}read(){return[...this.m.current()?.store.scheduled.values()??[]].sort((e,t)=>e.send_at<t.send_at?-1:1)}};var us=async r=>Ci(await import("livekit-client"))(r);function Ci(r){return async e=>{let t=new r.Room({adaptiveStream:!1,dynacast:!0,stopLocalTrackOnUnpublish:!1}),s=()=>t.localParticipant,i={microphone:r.Track.Source.Microphone,camera:r.Track.Source.Camera,screen:r.Track.Source.ScreenShare,screen_audio:r.Track.Source.ScreenShareAudio},n=(d,l)=>l.source===r.Track.Source.ScreenShare?"screen":l.source===r.Track.Source.ScreenShareAudio?"screen_audio":d.kind==="video"?"camera":"microphone",a=!1;t.on(r.RoomEvent.TrackSubscribed,(d,l,c)=>e.track(c.identity,d.mediaStreamTrack,n(d,l))).on(r.RoomEvent.TrackUnsubscribed,(d,l,c)=>e.trackGone(c.identity,d.mediaStreamTrack)).on(r.RoomEvent.TrackMuted,(d,l)=>{l!==s()&&d.track&&e.muted(l.identity,d.track.mediaStreamTrack,!0)}).on(r.RoomEvent.TrackUnmuted,(d,l)=>{l!==s()&&d.track&&e.muted(l.identity,d.track.mediaStreamTrack,!1)}).on(r.RoomEvent.Reconnecting,()=>e.state("reconnecting")).on(r.RoomEvent.Reconnected,()=>e.state("connected")).on(r.RoomEvent.ActiveSpeakersChanged,d=>e.speakers(d.map(l=>l.identity))).on(r.RoomEvent.Disconnected,()=>{a||e.state("disconnected")});let o=new Map;return{async connect(d,l){await t.connect(d,l),e.state("connected")},async publish(d,l){o.set(d,await s().publishTrack(d,{source:i[l]}))},async unpublish(d){o.delete(d),await s().unpublishTrack(d,!1)},async mute(d,l){let c=o.get(d);c&&await(l?c.mute():c.unmute())},async close(){a=!0,await t.disconnect()}}}}var xi=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,nt=class extends w{call;constructor(e,t){super({op:e.op,status:e.status,code:e.code,message:e.message,requestId:e.requestId,retryAfter:e.retryAfter,body:e.body,cause:e}),this.name="PlaceBusyError",this.call=t}},rt=class{id;c;call;snapshot;listeners=new Set;owned=!1;entering=!1;phase="incoming";endReason=null;error=null;local=null;tracks={audio:null,video:null};opened=new Set;mic=!0;facing="user";shared=null;sharing=null;room=null;joiningRoom=null;roomState=null;streams=new Map;screens=new Map;owners=new Map;speakers=new Set;mutedInRoom=new Set;players=new Map;sink=null;quieted=!1;heartbeat;poll;done=!1;constructor(e,t,s=!1){this.c=e,this.id=t.id,this.call=t,this.entering=s,this.derive()}get state(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async accept(e={}){if(this.phase!=="incoming"&&this.phase!=="invited")throw this.refused("accept","not_ringing","the call does not ring here now");await this.enter(e,t=>this.c.api.acceptCall({path:{call_id:this.id},body:t}))}async join(e={}){if(this.owned&&!this.done)return;if(this.done)throw this.refused("join","call_ended","this session is over: pb.calls.join(callId) comes into the call again");let t={...e.name===void 0?{}:{name:e.name},...e.imageUrl===void 0?{}:{image_url:e.imageUrl}};await this.enter(e,s=>this.c.api.joinCall({path:{call_id:this.id},body:{...s,...t}}))}async decline(){let e=await this.c.api.declineCall({path:{call_id:this.id}}).catch(t=>this.refusal(t));this.apply(e.data)}async leave(){try{let e=await this.c.api.leaveCall({path:{call_id:this.id}});this.apply(e.data)}finally{!this.done&&this.owned&&this.end("left")}}async invite(e,t={}){let s=typeof e=="string"?[e]:e,i=await this.c.api.inviteToCall({path:{call_id:this.id},body:{user_ids:s,...t.ring===void 0?{}:{ring:t.ring}}});this.apply(i.data)}async setMicrophone(e){this.mic=e;let t=this.tracks.audio;t&&(t.enabled=e),this.changed(),t&&this.room&&await this.room.mute(t,!e)}async setCamera(e){if(!e){if(!this.tracks.video)return;await this.putVideo(null);return}this.tracks.video||await this.putVideo(await this.camera({facingMode:this.facing}))}async switchCamera(e){e===void 0&&(this.facing=this.facing==="user"?"environment":"user"),await this.putVideo(await this.camera(e===void 0?{facingMode:this.facing}:{deviceId:{exact:e}}))}async setScreenShare(e,t={}){if(!e){await this.sharing?.catch(()=>{}),await this.putScreen(null);return}if(this.shared)return;if(this.sharing)return this.sharing;if(!this.inCall)throw this.refused("setScreenShare","not_in_call","a screen is shared in a call this device is in");let s=this.c.rtc(),i=s.getDisplayMedia?.bind(s);if(!i)throw new TypeError("calls: this browser shares no screen (getDisplayMedia)");return this.sharing=(async()=>{let n=await i({video:!0,audio:t.audio===!0}),a=n.getVideoTracks()[0],o=t.audio===!0?n.getAudioTracks()[0]??null:null;for(let d of n.getTracks())d!==a&&d!==o&&d.stop();if(!a||this.done){for(let d of n.getTracks())d.stop();if(!a)throw new Error("calls: the screen gave no video");return}this.opened.add(a),o&&this.opened.add(o),a.addEventListener?.("ended",()=>{this.shared?.video===a&&this.putScreen(null).catch(()=>{})}),await this.putScreen({video:a,audio:o,stream:new s.MediaStream([a,...o?[o]:[]])})})().finally(()=>this.sharing=null),this.sharing}async setAudioOutput(e){this.sink=e;for(let t of this.players.values())await ps(t,e)}async refresh(){let e=await this.c.api.getCall({path:{call_id:this.id}});this.apply(e.data)}apply(e){e.id!==this.id||e.version<this.call.version||(this.call=e,this.derive())}caughtUp(){!this.owned||this.done||this.refresh().catch(()=>{})}online(){this.inCall&&!this.room&&this.toRoom()}get inCall(){return this.owned&&!this.done}drop(){this.done||this.end(this.endReason??"left")}me(){return this.call.participants.find(e=>e.user_id===this.c.me)}derive(){if(this.done)return;let e=this.call,t=this.me();if(e.state==="ended")return this.end(Ai(e,t));let s=t?.state==="joined"&&t.device_id===this.c.device;if(s&&this.entering&&(this.owned=!0),this.owned){if(t?.state==="joined"&&!s)return this.end("answered_elsewhere","elsewhere");if(!s)return this.end(t?.state??"left");this.quiet(),this.beat(),this.phase=e.state==="ringing"?"calling":this.mediaPhase(),this.toRoom()}else if(t?.state==="ringing")this.phase="incoming";else if(t?.state==="invited")this.phase="invited";else if(this.entering)this.phase="connecting";else if(t?.state==="joined")this.phase="elsewhere",this.quiet();else return this.end(t?.state??"ended");this.changed()}mediaPhase(){return this.roomState==="connected"?"connected":this.roomState==="reconnecting"?"reconnecting":"connecting"}async enter(e,t){this.entering=!0;try{await this.open(e.video??this.call.video,e.media);let s=await t({device_id:this.c.device});this.apply(s.data)}catch(s){this.entering=!1,this.owned||this.release();let i=ot(s);throw i?this.apply(i):this.derive(),s}this.entering=!1,this.derive(),this.inCall&&this.c.entered(this)}own(e){if(this.done){for(let t of e.opened)t.stop();return}this.owned=!0,this.local=e.local,this.tracks=e.tracks;for(let t of e.opened)this.opened.add(t);this.derive()}async open(e,t){let s=await fs(this.c.rtc(),e,t);this.local=s.local,this.tracks=s.tracks;for(let i of s.opened)this.opened.add(i)}async camera(e){try{let s=(await this.c.rtc().getUserMedia({video:e})).getVideoTracks()[0];if(!s)throw new Error("calls: the camera gave no video");return this.opened.add(s),s}catch(t){throw this.error=t instanceof Error?t:new Error(String(t)),this.changed(),t}}async putVideo(e){let t=this.tracks.video;this.tracks.video=e,t&&this.local?.removeTrack(t),e&&this.local?.addTrack(e),this.changed(),this.room&&(t&&await this.room.unpublish(t).catch(()=>{}),e&&await this.room.publish(e,"camera")),t&&t!==e&&this.stopIfOpened(t)}async putScreen(e){let t=this.shared;if(!(!t&&!e)){if(this.shared=e,this.changed(),this.room){if(t)for(let s of[t.video,t.audio])s&&await this.room.unpublish(s).catch(()=>{});e&&(await this.room.publish(e.video,"screen"),e.audio&&await this.room.publish(e.audio,"screen_audio"))}if(t)for(let s of[t.video,t.audio])s&&this.stopIfOpened(s)}}sent(){let e=[];return this.tracks.audio&&e.push([this.tracks.audio,"microphone"]),this.tracks.video&&e.push([this.tracks.video,"camera"]),this.shared&&e.push([this.shared.video,"screen"]),this.shared?.audio&&e.push([this.shared.audio,"screen_audio"]),e}toRoom(){return this.room||this.joiningRoom||this.done?Promise.resolve():(this.joiningRoom=(async()=>{let e=(await this.c.api.getCallMedia({path:{call_id:this.id},body:{device_id:this.c.device}})).data;if(this.done)return;let t=await this.c.room({track:(s,i,n)=>{this.room===t&&this.heard(s,i,n)},trackGone:(s,i)=>{this.room===t&&this.gone(s,i)},muted:(s,i,n)=>{this.room===t&&(n?this.mutedInRoom.add(i):this.mutedInRoom.delete(i),this.changed())},speakers:s=>{this.room===t&&(this.speakers=new Set(s),this.changed())},state:s=>{if(this.room===t){if(this.roomState=s,s==="disconnected"){this.room=null,this.roomState=null,this.speakers=new Set;for(let[i,n]of[...this.owners])this.gone(n,i);t.close().catch(()=>{})}this.derive()}}});if(this.done){await t.close();return}this.room=t,this.roomState=null,await t.connect(e.url,e.token);for(let[s,i]of this.sent())await t.publish(s,i);this.tracks.audio&&!this.mic&&await t.mute(this.tracks.audio,!0),this.derive()})().catch(e=>{let t=this.room;this.room=null,this.roomState=null,t?.close().catch(()=>{}),this.failed(e)}).finally(()=>this.joiningRoom=null),this.joiningRoom)}streamOf(e,t=this.streams){let s=t.get(e);return s||t.set(e,s=new(this.c.rtc()).MediaStream),s}heard(e,t,s){let i=s==="screen"||s==="screen_audio",n=this.streamOf(e,i?this.screens:this.streams);for(let a of n.getTracks())a.kind===t.kind&&a!==t&&this.gone(e,a);if(n.getTracks().includes(t)||n.addTrack(t),!this.owners.has(t)){let a=()=>this.changed();t.addEventListener?.("mute",a),t.addEventListener?.("unmute",a),t.addEventListener?.("ended",a)}this.owners.set(t,e),t.kind==="audio"&&this.play(i?`${e}\0screen`:e,n),this.changed()}gone(e,t){this.owners.delete(t),this.mutedInRoom.delete(t),this.streams.get(e)?.removeTrack(t),this.screens.get(e)?.removeTrack(t),this.changed()}play(e,t){if(!this.c.playAudio||this.players.has(e))return;let s=globalThis.document;if(!s)return;let i=s.createElement("audio");i.autoplay=!0,i.srcObject=t,this.players.set(e,i),this.sink&&ps(i,this.sink).catch(()=>{}),i.play?.()?.catch?.(()=>{})}beat(){this.heartbeat===void 0&&(this.heartbeat=setInterval(()=>{this.stillHere()},this.c.heartbeatMs)),this.poll===void 0&&(this.poll=setInterval(()=>{this.c.live()||this.done||this.refresh().catch(()=>{})},this.c.pollMs))}async stillHere(){if(!this.done)try{let e=(await this.c.api.callHeartbeat({path:{call_id:this.id},body:{device_id:this.c.device}})).data;(e.version>this.call.version||!e.in_call||e.state==="ended")&&await this.refresh()}catch(e){e instanceof w&&e.status===404&&this.end("ended")}}end(e,t="ended"){if(this.done)return;this.done=!0,this.entering=!1,this.phase=t,this.quiet(),this.endReason=e,clearInterval(this.heartbeat),clearInterval(this.poll);let s=this.room;this.room=null,this.shared=null,this.speakers=new Set,s?.close().catch(()=>{});for(let i of this.players.values())i.pause?.(),i.srcObject=null;this.players.clear(),this.release(),this.changed(),this.c.forget(this)}release(){for(let e of this.opened)e.stop();this.opened.clear()}stopIfOpened(e){this.opened.delete(e)&&e.stop()}quiet(){this.quieted||(this.quieted=!0,this.c.quiet(this.id))}failed(e){this.done||(this.error=e instanceof Error?e:new Error(String(e)),this.changed())}refusal(e){let t=ot(e);throw t&&this.apply(t),e}refused(e,t,s){return new w({op:e,status:409,code:t,message:`${e}: ${s}`})}changed(){let e=this.c.me,t=this.owned&&!this.done,s=t?this.call.participants.filter(a=>a.user_id!==e&&a.state==="joined"):[],i=s.map(a=>this.remoteOf(a.user_id,a));if(t)for(let a of new Set([...this.streams.keys(),...this.screens.keys()]))(this.streams.get(a)?.getTracks().length??0)+(this.screens.get(a)?.getTracks().length??0)>0&&!s.some(d=>d.user_id===a)&&i.push(this.remoteOf(a));let n=this.mic&&this.tracks.audio!==null;this.snapshot={call:this.call,me:this.me()??null,phase:this.phase,outgoing:this.call.caller_id===e,local:t?this.local:null,microphone:n,camera:this.tracks.video!==null,screenSharing:t&&this.shared!==null,screen:t?this.shared?.stream??null:null,speaking:t&&n&&this.speakers.has(e),remote:i,endReason:this.endReason,error:this.error};for(let a of[...this.listeners])try{a()}catch{}}remoteOf(e,t){let s=this.streamOf(e),i=this.screens.get(e),n=(a,o)=>a.getTracks().some(d=>d.kind===o&&d.readyState!=="ended"&&!d.muted&&!this.mutedInRoom.has(d));return{userId:e,name:t?.name??null,imageUrl:t?.image_url??null,bot:t?.kind==="bot"||e.startsWith("bot:"),stream:s,audio:n(s,"audio"),video:n(s,"video"),screen:i&&n(i,"video")?i:null,speaking:this.speakers.has(e)}}},Ie=class{deviceId;transportFor;session;socket;ref;opts;beacon;user=null;api=null;channel=null;off=[];sessions=new Map;incoming=new Set;entered=new Set;places=new Map;workerHeard=!1;constructor(e,t,s,i,n,a,o={}){this.transportFor=e,this.session=t,this.socket=s,this.ref=i,this.deviceId=n,this.beacon=a,this.opts=o,t.onChange((l,c)=>{if(l==="SIGNED_OUT"||l==="SESSION_EXPIRED")return this.stop();if(l==="SIGNED_IN"){if(this.user!==null&&c?.userId===this.user){this.unfollow(),this.follow(this.user);return}this.stop(),this.incoming.size>0&&this.ready().catch(()=>{})}});let d=globalThis;d.addEventListener?.("online",()=>{for(let l of this.sessions.values())l.online()}),d.addEventListener?.("pagehide",()=>{for(let l of this.sessions.values())l.inCall&&this.beacon(`/calls/${encodeURIComponent(l.id)}/leave`)})}get current(){for(let e of this.sessions.values())if(e.inCall)return e;return null}async start(e,t={}){let s=typeof e=="string"?[e]:[...e];if(s.length===0&&t.place===void 0)throw new TypeError("calls.start: name the person (or people) to call, or the place to hold it at");t.place!==void 0&&hs("calls.start",t.place),await this.ready();let i=this.api,n=await fs(this.rtc(),t.video===!0,t.media),a;try{a=(await i.startCall({body:{user_ids:s,device_id:this.deviceId,video:t.video===!0,...t.ring===void 0?{}:{ring:t.ring},...t.group===void 0?{}:{group:t.group},...t.conversationId===void 0?{}:{conversation_id:t.conversationId},...t.metadata===void 0?{}:{metadata:t.metadata},...t.callerName===void 0?{}:{caller_name:t.callerName},...t.callerImageUrl===void 0?{}:{caller_image_url:t.callerImageUrl},...t.place===void 0?{}:{place:t.place}}})).data}catch(d){for(let c of n.opened)c.stop();let l=d instanceof w&&d.code==="place_busy"?ot(d):void 0;throw l?(this.places.get(l.place??"")?.heard(l),new nt(d,l)):d}a.place!==null&&this.places.get(a.place)?.heard(a);let o=this.sessionOf(a,!1);return o.own(n),o.inCall&&(this.sessions.set(o.id,o),this.tell(this.entered,o)),o}voice(e,t={}){return this.start(e,{...t,video:!1})}video(e,t={}){return this.start(e,{...t,video:!0})}async join(e,t={}){await this.ready();let s=typeof e=="string"?e:e.id,i=this.sessions.get(s);return i||(i=this.sessionOf(typeof e=="string"?await this.toJoin(e):e,!0)),await i.join(t),i}place(e){hs("calls.place",e);let t=this.places.get(e);return t||(t=new at(e,{api:async()=>(await this.ready(),this.api),start:s=>this.start(s.userIds??[],{...s,place:e}),join:(s,i)=>this.join(s,i),live:()=>this.channel?.state==="joined",pollMs:this.opts.pollMs??2e3}),this.places.set(e,t)),t}onIncoming(e){return this.incoming.add(e),this.ready().catch(()=>{}),()=>this.incoming.delete(e)}onCall(e){return this.entered.add(e),()=>this.entered.delete(e)}async history(e={}){await this.ready();let t={};return e.limit!==void 0&&(t.limit=e.limit),e.cursor!==void 0&&(t.cursor=e.cursor),e.missed!==void 0&&(t.missed=e.missed),e.state!==void 0&&(t.state=e.state),(await this.api.listCalls({query:t})).data}async get(e){return await this.ready(),(await this.api.getCall({path:{call_id:e}})).data}async ready(){let e=this.session.snapshot()??await this.session.session();if(!e)throw new w({op:"calls",status:401,code:"not_signed_in",message:"calls are the signed-in person's: sign in first"});this.user===e.userId&&this.api||(this.stop(),this.user=e.userId,this.api=ct.client(this.transportFor(e.userId)),this.follow(e.userId),this.listenToWorker(),this.ringing().catch(()=>{}))}stop(){this.unfollow();for(let e of[...this.sessions.values()])e.drop();if(this.sessions.clear(),this.user!==null)for(let e of this.places.values())e.drop();this.user=null,this.api=null}unfollow(){for(let e of this.off.splice(0))e();this.channel?.leave(),this.channel=null}follow(e){let t=this.socket.channel(`calls:${this.ref}:${e}`);this.channel=t,this.off.push(t.on("broadcast",s=>{if(this.user===e){if(s.event==="call"){let i=s.payload;this.heardCall(i),i.place&&this.places.get(i.place)?.heard(i)}else if(s.event==="place"){let i=s.payload;this.places.get(i.place)?.told(i)}}}),t.onJoined(()=>{if(this.user===e){for(let s of this.sessions.values())s.caughtUp();for(let s of this.places.values())s.caughtUp();this.ringing().catch(()=>{})}})),t.join().catch(()=>{})}async toJoin(e){try{return(await this.api.getCall({path:{call_id:e}})).data}catch(t){if(!(t instanceof w)||t.status!==404)throw t;for(let s of this.places.values())if(s.state.call?.id===e)return s.state.call;throw t}}async ringing(){let e=this.user,t=this.api;if(!t)return;let s=await Promise.all([t.listCalls({query:{state:"ringing",limit:20}}),t.listCalls({query:{state:"active",limit:20}})]);if(this.user===e)for(let i of s)for(let n of i.data.calls)this.heardCall(n)}listenToWorker(){if(this.workerHeard)return;let e=globalThis.navigator?.serviceWorker;e?.addEventListener&&(this.workerHeard=!0,e.addEventListener("message",t=>{let s=t.data,i=s?.type==="palbase.push"?s.data?.call_id:void 0;!i||s?.data?.pb_call!=="incoming"||!this.api||this.api.getCall({path:{call_id:i}}).then(n=>this.heardCall(n.data)).catch(()=>{})}))}heardCall(e){let t=this.sessions.get(e.id);if(t){t.apply(e);return}let s=e.participants.find(i=>i.user_id===this.user);e.state==="ended"||s?.state!=="ringing"&&s?.state!=="invited"||this.tell(this.incoming,this.sessionOf(e,!1))}tell(e,t){for(let s of[...e])try{s(t)}catch{}}sessionOf(e,t){let s=this.sessions.get(e.id);if(s)return s.apply(e),s;let i=this.sessions,n=new rt({api:this.api,me:this.user,device:this.deviceId,rtc:()=>this.rtc(),room:this.opts.room??us,playAudio:this.opts.playAudio!==!1,heartbeatMs:this.opts.heartbeatMs??15e3,pollMs:this.opts.pollMs??2e3,live:()=>this.channel?.state==="joined",forget(a){i.get(a.id)===a&&i.delete(a.id)},quiet:a=>Ei(a),entered:a=>{i.set(a.id,a),this.tell(this.entered,a)}},e,t);return n.state.phase!=="ended"&&i.set(e.id,n),n}rtc(){if(this.opts.rtc)return this.opts.rtc;let e=globalThis;if(typeof e.RTCPeerConnection!="function"||typeof e.MediaStream!="function"||typeof e.navigator?.mediaDevices?.getUserMedia!="function")throw new TypeError("calls: this runtime has no WebRTC (RTCPeerConnection, navigator.mediaDevices): a call's media is a browser's");let t=e.navigator.mediaDevices;return{MediaStream:e.MediaStream,getUserMedia:s=>t.getUserMedia(s),...typeof t.getDisplayMedia=="function"?{getDisplayMedia:s=>t.getDisplayMedia(s)}:{}}}},Mi=120,Ii=1e4,Oi=32,at=class{place;c;snapshot;listeners=new Set;call=null;error=null;watchers=0;renewing=null;timer;poll;words=0;ended=new Set;constructor(e,t){this.place=e,this.c=t,this.snapshot=this.make()}get state(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async refresh(){let e=await this.c.api(),t=this.words;try{this.take((await e.getCallPlace({path:{place:this.place}})).data,t)}catch(s){this.fail(s)}return this.call}async watch(){this.watchers++,this.changed();try{await this.renew()}catch(e){throw this.watchers=Math.max(0,this.watchers-1),this.watchers===0&&this.idle(),this.changed(),e}return this.call}async unwatch(){if(this.watchers===0||--this.watchers>0||(this.idle(),this.changed(),await this.renewing?.catch(()=>{}),this.watchers>0))return;await(await this.c.api()).unwatchCallPlace({path:{place:this.place}})}start(e={}){return this.c.start(e)}async join(e={}){let t=this.call??await this.refresh();if(!t)throw new w({op:"join",status:404,code:"call_not_found",message:`join: no call goes on at ${this.place}`});return this.c.join(t,e)}told(e){this.words++,e.call?this.heard(e.call):this.set(null)}heard(e){if(e.place===this.place){if(e.state==="ended"){this.ended.add(e.id),this.ended.size>Oi&&this.ended.delete(this.ended.values().next().value),this.call?.id===e.id&&this.set(null);return}this.ended.has(e.id)||this.call?.id===e.id&&e.version<this.call.version||this.set({...e,participants:e.participants.map(t=>t.device_id===null?t:{...t,device_id:null})})}}caughtUp(){this.watchers>0&&this.renew().catch(()=>{})}drop(){this.watchers=0,this.idle(),this.call=null,this.error=null,this.ended.clear(),this.changed()}renew(){if(this.renewing)return this.renewing;clearTimeout(this.timer),this.timer=void 0;let e=this.words;return this.renewing=(async()=>(await(await this.c.api()).watchCallPlace({path:{place:this.place}})).data)().then(t=>(this.watchers===0||(this.error=null,this.take(t,e),this.later(Math.max(1,(t.watch_seconds??Mi)/2)*1e3),this.polling()),t),t=>(this.watchers>0&&(!(t instanceof w)||t.isNetworkError||t.status===429||t.status>=500?this.later(Ii):(this.watchers=0,this.idle())),this.fail(t))).finally(()=>this.renewing=null),this.renewing}later(e){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.renew().catch(()=>{})},e)}polling(){this.poll===void 0&&(this.poll=setInterval(()=>{this.watchers===0||this.c.live()||this.refresh().catch(()=>{})},this.c.pollMs))}idle(){clearTimeout(this.timer),clearInterval(this.poll),this.timer=void 0,this.poll=void 0}take(e,t){e.call?this.heard(e.call):this.words===t?this.set(null):this.changed()}set(e){this.call=e,this.error=null,this.changed()}fail(e){throw this.error=e instanceof Error?e:new Error(String(e)),this.changed(),e}make(){return{place:this.place,call:this.call,watching:this.watchers>0,error:this.error}}changed(){this.snapshot=this.make();for(let e of[...this.listeners])try{e()}catch{}}};function hs(r,e){if(!xi.test(e))throw new TypeError(`${r}: a place is 1 to 128 letters, digits and . _ : -, starting with a letter or digit (channel:42)`)}async function fs(r,e,t){let s=t,i=[];if(!s){try{s=await r.getUserMedia({audio:!0,video:e?{facingMode:"user"}:!1})}catch(d){let l=d?.name;if(!e||l==="NotAllowedError"||l==="SecurityError")throw d;s=await r.getUserMedia({audio:!0,video:!1})}i.push(...s.getTracks())}let n=s.getAudioTracks()[0]??null,a=e?s.getVideoTracks()[0]??null:null;if(!t&&!e)for(let d of s.getVideoTracks())d.stop();return{local:new r.MediaStream([n,a].filter(d=>d!==null)),tracks:{audio:n,video:a},opened:i.filter(d=>d===n||d===a)}}function Ai(r,e){return e?.state==="missed"||e?.state==="declined"||e?.state==="busy"?e.state:r.end_reason??"ended"}function ot(r){if(!(r instanceof w)||r.status!==409)return;let e=r.body;return e?.call&&typeof e.call.id=="string"?e.call:void 0}function Ei(r){let e=globalThis.navigator?.serviceWorker;typeof e?.getRegistration=="function"&&e.getRegistration().then(async t=>{for(let s of await t?.getNotifications({tag:r})??[])s.close()}).catch(()=>{})}async function ps(r,e){let t=r;if(typeof t.setSinkId!="function")throw new TypeError("calls: this browser cannot choose where audio plays (setSinkId)");await t.setSinkId(e)}function Oe(r){if(!r||r==="."||r==="..")throw new w({op:"ai.templates",status:0,code:"invalid_path_parameter",message:`template name ${JSON.stringify(r)} is invalid`});return encodeURIComponent(r)}async function Ae(r,e){let t=await e.text().catch(()=>""),s;try{s=t?JSON.parse(t):void 0}catch{s=void 0}let i=typeof s?.error=="string"?s.error:`http_${e.status}`,n=typeof s?.error_description=="string"?s.error_description:typeof s?.message=="string"?s.message:`${r}: server answered ${e.status}`,a=e.headers.get("retry-after"),o=a&&!Number.isNaN(Number(a))?Number(a):void 0;return new w({op:r,status:e.status,code:i,message:n,requestId:e.headers.get("x-request-id")??void 0,retryAfter:o,body:s})}var Ee=class{origin;publishableKey;session;installation;fetchFn;constructor(e,t,s,i,n){this.origin=e,this.publishableKey=t,this.session=s,this.installation=i,this.fetchFn=n}async buildHeaders(e){let t={apikey:this.publishableKey,"Content-Type":"application/json","X-Palbase-Platform":"web","X-Palbase-Installation-Id":this.installation.id};e.accept&&(t.Accept=e.accept);let s=await this.session.accessToken();return s&&(t.Authorization=`Bearer ${s}`),e.debugAttestToken&&(t["X-Palbase-Debug-Attest"]=e.debugAttestToken),t}async run(e,t={}){let s=Oe(e),i=new URL(`/ai/client/templates/${s}/run`,this.origin).href,n=await this.fetchFn(i,{method:"POST",headers:await this.buildHeaders({debugAttestToken:t.debugAttestToken}),body:JSON.stringify({variables:t.variables,attachments:t.attachments,stream:!1}),signal:t.signal});if(!n.ok)throw await Ae("ai.templates.run",n);return await n.json()}async*stream(e,t={}){let s=Oe(e),i=new URL(`/ai/client/templates/${s}/run`,this.origin).href,n=await this.fetchFn(i,{method:"POST",headers:await this.buildHeaders({debugAttestToken:t.debugAttestToken,accept:"text/event-stream"}),body:JSON.stringify({variables:t.variables,attachments:t.attachments,stream:!0}),signal:t.signal});if(!n.ok)throw await Ae("ai.templates.stream",n);if(!n.body)return;let a=n.body.getReader(),o=new TextDecoder,d="";try{for(;;){let{done:l,value:c}=await a.read();if(l)break;d+=o.decode(c,{stream:!0});let h;for(;(h=d.indexOf(`
|
|
23
|
-
`))!==-1;){let p=d.slice(0,h).trim();if(d=d.slice(h+1),!p.startsWith("data:"))continue;let b=p.slice(5).trim();if(b){if(b==="[DONE]")return;try{let f=JSON.parse(b),u=f.choices?.[0],g=u?.delta?.content??"",y=u?.finish_reason??void 0;(g||y)&&(yield{delta:g,model:f.model,finishReason:y})}catch{}}}}}finally{a.releaseLock()}}async speech(e,t={}){let s=Oe(e),i=new URL(`/ai/client/templates/${s}/run`,this.origin).href,n=await this.fetchFn(i,{method:"POST",headers:await this.buildHeaders({debugAttestToken:t.debugAttestToken}),body:JSON.stringify({variables:t.variables,stream:!1}),signal:t.signal});if(!n.ok)throw await Ae("ai.templates.speech",n);return n.arrayBuffer()}async startVoice(e,t){let s=Oe(e),i=new URL(`/ai/client/templates/${s}/voice`,this.origin).href,n=await this.fetchFn(i,{method:"POST",headers:await this.buildHeaders({debugAttestToken:t.debugAttestToken}),body:JSON.stringify({variables:t.variables,transport:{type:"webrtc",sdp:t.sdp}}),signal:t.signal});if(!n.ok)throw await Ae("ai.templates.startVoice",n);return await n.json()}};var Le=class{api;open;session;credentials;mfa;passkey;magicLink;phone;password;email;sessions;constructor(e,t,s,i){this.api=G.client(e),this.open=G.client(t),this.session=s,this.credentials=i;let n=this.api,a=this.open;this.mfa={challenge:async(o,d,l)=>this.signedIn((await a.mfaChallenge({body:{mfa_token:o,type:d,code:l}})).data),recovery:async(o,d)=>this.signedIn((await a.mfaRecovery({body:{mfa_token:o,code:d}})).data),sendSmsCode:async o=>{await a.mfaSmsChallenge({body:{mfa_token:o}})},sendEmailCode:async o=>{await a.mfaEmailChallenge({body:{mfa_token:o}})},enrollTotp:async()=>{let o=(await n.mfaEnroll({body:{type:"totp"}})).data;return{enrollmentId:o.enrollment_id,secret:o.secret,otpUrl:o.otp_url,qrCode:o.qr_code,recoveryCodes:o.recovery_codes}},verifyTotp:async o=>{await n.mfaVerifyEnrollment({body:{code:o}})},enrollSms:async o=>(await n.mfaSmsEnroll({body:{phone:o}})).data,verifySms:async o=>{await n.mfaSmsVerifyEnrollment({body:{code:o}})},enrollEmail:async()=>{await n.mfaEmailEnroll()},factors:async()=>(await n.mfaListFactors()).data,removeFactor:async(o,d)=>{await n.mfaRemoveFactor({path:{id:o},body:{current_password:d}})},regenerateRecoveryCodes:async()=>(await n.mfaRegenerateRecoveryCodes()).data,stepUp:async o=>this.steppedUp(async()=>(await n.stepUp({body:{method:"totp",code:o}})).data),sendStepUpSmsCode:async()=>{await n.stepUpSmsSend()},stepUpWithSms:async o=>this.steppedUp(async()=>(await n.stepUp({body:{method:"sms",code:o}})).data)},this.passkey={register:async o=>{let d=(await n.webauthnRegisterBegin({body:{name:o}})).data,l=await this.authenticator().create({publicKey:gs(d.options.publicKey)});return(await n.webauthnRegisterFinish({body:ms(l)})).data},signIn:async(o={})=>{let d=(await a.webauthnLoginBegin({body:o.userId?{user_id:o.userId}:{}})).data,l=await this.authenticator().get({publicKey:dt(d.options.publicKey)}),c=await a.webauthnLoginFinish({query:o.userId?{user_id:o.userId}:void 0,body:lt(l)});return this.signedIn(c.data)},signUp:async(o,d)=>{let l=(await a.webauthnSignupBegin({body:{identifier:o,user_name:d}})).data,c=await this.authenticator().create({publicKey:gs(l.options.publicKey)});await a.webauthnSignupFinish({query:{user_id:l.user_id},body:ms(c)});let h=(await a.webauthnLoginBegin({body:{user_id:l.user_id}})).data,p=await this.authenticator().get({publicKey:dt(h.options.publicKey)});return this.signedIn((await a.webauthnLoginFinish({query:{user_id:l.user_id},body:lt(p)})).data)},stepUp:async()=>this.steppedUp(async()=>{let o=(await n.stepUpWebAuthnBegin()).data,d=await this.authenticator().get({publicKey:dt(o.publicKey)});return(await n.stepUp({body:{method:"webauthn",...lt(d)}})).data}),list:async()=>(await n.webauthnListCredentials()).data,remove:async o=>{await n.webauthnDeleteCredential({path:{id:o}})}},this.magicLink={send:async(o,d={})=>{await a.magicLinkRequest({body:{email:o,...d.redirectTo?{redirect_to:d.redirectTo}:{}}})},verify:async o=>this.signInResult((await a.magicLinkVerify({body:{token:o}})).data)},this.phone={sendCode:async o=>(await a.requestPhoneOtp({body:{phone:o,channel:"sms"}})).data,verifyCode:async(o,d)=>this.signInResult((await a.verifyPhoneOtp({body:{phone:o,token:d}})).data)},this.password={requestReset:async(o,d={})=>{await a.passwordResetRequest({body:{email:o,...d.redirectTo?{redirect_to:d.redirectTo}:{}}})},confirmReset:async(o,d)=>{await a.passwordResetConfirm({body:{token:o,new_password:d}})},change:async o=>(await n.passwordChange({body:o})).data,set:async o=>(await n.setPassword({body:o})).data},this.email={verify:async o=>{await a.verifyEmail({body:o})},resendVerification:async o=>(await a.resendVerification({body:{email:o}})).data},this.sessions={list:async()=>(await n.listSessions()).data,revoke:async o=>{await n.revokeSession({path:{id:o}})},revokeAll:async()=>{await n.revokeAllSessions()}}}onAuthStateChange(e){return this.session.onChange(e)}currentSession(){return this.session.session()}get sessionEndReason(){return this.session.endReason}async signUp(e){let t=(await this.open.signup({body:e})).data;return t.access_token&&t.refresh_token&&t.expires_in!==void 0&&await this.session.set({access_token:t.access_token,refresh_token:t.refresh_token,expires_in:t.expires_in},"SIGNED_IN",t.user),t}async signIn(e,t){return this.signInResult((await this.open.login({body:{email:e,password:t}})).data)}async signOut(){try{await this.session.session()&&await this.api.logout()}finally{await this.session.clear("SIGNED_OUT")}}async getUser(){let e=this.session.snapshot(),t=(await this.api.getMe()).data;return await this.session.setUser(t,e),t}async refreshSession(){return this.session.refresh()}async deleteAccount(e){await this.api.deleteAccount(e===void 0?void 0:{body:{password:e}}),await this.session.clear("SIGNED_OUT")}async signInResult(e){return"mfa_required"in e&&e.mfa_required?{mfaRequired:{mfaToken:e.mfa_token,factors:e.factors}}:{user:await this.signedIn(e)}}async setSession(e){return this.signedIn(e)}async signedIn(e){let t=await this.session.set({access_token:e.access_token,refresh_token:e.refresh_token,expires_in:e.expires_in},"SIGNED_IN",e.user);if(e.user)return e.user;let s=(await this.api.verifyTokenUser()).data;return await this.session.setUser(s,t),s}async steppedUp(e){let t=await this.session.session();if(!t)throw new T("a step-up raises the signed-in session: nobody is signed in");let s=await e();if((await this.session.session())?.refreshToken!==t.refreshToken)throw new T("the session changed during the step-up");return this.session.set({access_token:s.access_token,refresh_token:t.refreshToken,expires_in:s.expires_in},"TOKEN_REFRESHED")}authenticator(){if(!this.credentials)throw new Error("passkeys need navigator.credentials (or createClient({ webauthn }))");return this.credentials}},De=r=>{let e=atob(r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=")),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t.buffer},q=r=>{if(!r)return;let e=r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength),t="";for(let s of e)t+=String.fromCharCode(s);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},ys=r=>Array.isArray(r)?r.map(e=>({...e,id:De(String(e.id))})):void 0;function gs(r){let e=r.user;return{...r,challenge:De(String(r.challenge)),user:{...e,id:De(String(e.id))},excludeCredentials:ys(r.excludeCredentials)}}function dt(r){return{...r,challenge:De(String(r.challenge)),allowCredentials:ys(r.allowCredentials)}}function ms(r){let e=r,t=e.response;return{id:e.id,rawId:q(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:q(t.clientDataJSON),attestationObject:q(t.attestationObject),transports:t.getTransports?.()}}}function lt(r){let e=r,t=e.response;return{id:e.id,rawId:q(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:q(t.clientDataJSON),authenticatorData:q(t.authenticatorData),signature:q(t.signature),userHandle:q(t.userHandle)}}}var Li=/^pb_[a-z0-9]+_s/,Di=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ni=new Set(["invalid_token","token_expired","session_expired","session_revoked","missing_token"]),Ui=new Set(["invalid_token","token_reuse","token_expired","session_revoked","session_expired","session_device_changed"]);function qi(r){return r.status===400&&r.code==="invalid_request"}function Sr(r){if(Li.test(r.publishableKey)||"secretKey"in r)throw new TypeError("a secret key never goes into a client app: palbase/web takes the publishable key (pb_<ref>_c\u2026); servers use palbase/server");let e=/^pb_([a-z0-9]+)_c/.exec(r.publishableKey)?.[1];if(e===void 0)throw new TypeError("publishableKey is the project publishable key (pb_<ref>_c\u2026)");if(r.appId!==void 0&&!Di.test(r.appId))throw new TypeError("appId is the registered app's id, a UUID (settings.appId of palbase apps:sync), not its slug");let t=vs(r.language),s=(v,k)=>{let I=r.fetch??globalThis.fetch;if(t===void 0)return I(v,k);let X=new Headers(k?.headers);return X.has("accept-language")||X.set("accept-language",t),I(v,{...k,headers:X})},i=new URL(r.url).origin,n=r.storage??(Ki()?Pt(`palbase.session.${i}`):Rt()),a=r.retry??ft,o=ee($({baseUrl:r.url,credentials:{publishableKey:r.publishableKey},fetch:s}),a),d=G.client(o),l=new ae(n,async v=>(await d.refreshToken({body:{refresh_token:v}})).data,v=>v instanceof w&&(v.status===401&&Ui.has(v.code)||qi(v)),{lockName:`palbase.session.refresh.${i}`,refresh:r.refresh}),c=$({baseUrl:r.url,credentials:{publishableKey:r.publishableKey,accessToken:()=>l.accessToken()},fetch:s,xmlHttpRequest:r.xmlHttpRequest??(r.fetch===void 0?globalThis.XMLHttpRequest:void 0)}),h=ee(Ne(c,l),a),p=new oe({baseUrl:r.url,publishableKey:r.publishableKey,accessToken:()=>l.accessToken(),webSocket:r.webSocket});l.onChange(v=>{v==="SIGNED_OUT"||v==="SESSION_EXPIRED"||v==="SIGNED_IN"?p.disconnect():v==="TOKEN_REFRESHED"&&p.tokenChanged()});let b=globalThis;b.addEventListener?.("online",()=>p.askRefusedAgain()),b.document?.addEventListener?.("visibilitychange",()=>{b.document?.visibilityState==="visible"&&p.askRefusedAgain()});let f=new de(i),u=v=>ee(Ne($({baseUrl:r.url,credentials:{publishableKey:r.publishableKey,accessToken:async()=>{let k=await l.accessToken();if(k===void 0||je(k)!==v)throw new T(`the session is no longer ${v}'s`);return k}},fetch:s}),l),a),g=v=>G.client(u(v)),y=new pe({userApi:g,deviceApi:d,session:l,socket:p,ref:e,installation:f,origin:i,options:r.consent}),R=$({baseUrl:r.url,credentials:{publishableKey:r.publishableKey},fetch:s}),x=new ue(Ne(c,l),R,l,y,f,i),j=new be(h,l,p,e,f,s,r.appVersion,r.appId),se=new _t(h,l,p,e,i),ie=new Se(h,u,l,f,x,y),m=new ke(h,f,ie,i),S=new we(h,l,f,y,j,r.url,r.publishableKey);x.onEvent((v,k)=>S.inApp.trigger(v,k)),r.analytics&&x.start(r.analytics===!0?{}:r.analytics);let E=new Map,M=v=>{let k=new URL(v).origin,I=E.get(k);return I||(I=ee(Ne($({baseUrl:k,credentials:{accessToken:()=>l.accessToken()},fetch:s}),l),a),E.set(k,I)),I},K=wt(h),C=v=>{let k=l.snapshot();k&&s(new URL(v,i).href,{method:"POST",keepalive:!0,headers:{apikey:r.publishableKey,authorization:`Bearer ${k.accessToken}`}}).catch(()=>{})},D=Object.assign(Object.create(bt),{auth:new Le(h,o,l,r.webauthn??globalThis.navigator?.credentials),socket:p,transport:h,analytics:x,consent:y,installation:f,iap:j,payments:se,commerce:ie,campaigns:m,notify:S,flags:new _e(h,l,p,f,e,i,x,r.appVersion),messaging:new Me(h,u,l,p,e,s,r.messaging),calls:new Ie(u,l,p,e,`web-${f.id}`,C,r.calls),ai:{templates:new Ee(i,r.publishableKey,l,f,s)},setLanguage(v){t=vs(v??void 0)},chatToolCall:(v,k,I={})=>K.toolCall(v,k,I.signal),watchSessions(v,k={}){let I=k.all?void 0:k.userId??l.snapshot()?.userId,X=I?`ai:sessions:${I}`:"ai:sessions",ne=p.channel(X),ws=ne.on("session.summary.v1",re=>{let Y=qe(re);Y&&v(Y)}),bs=ne.on("broadcast",re=>{if(re?.event!=="session.summary.v1")return;let Y=qe(re.payload);Y&&v(Y)});return ne.join().catch(()=>{}),()=>{ws(),bs(),ne.leave()}}});return St(D,i,M,h,p,()=>l.snapshot()?.userId),D}var ji=/^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$/;function vs(r){if(r===void 0)return;let e=typeof r=="string"?[r]:[...r];if(e.length!==0){for(let t of e)if(!ji.test(t))throw new TypeError(`language ${JSON.stringify(t)} is a BCP 47 tag ("tr", "pt-BR")`);return e.map((t,s)=>s===0?t:`${t};q=${Math.max(.1,1-s/10).toFixed(1)}`).join(", ")}}function Ki(){try{return typeof globalThis.localStorage<"u"}catch{return!1}}function Ne(r,e){return{async send(t){let s=await e.session();try{return await r.send(t)}catch(i){let n=t.auth.some(a=>a.includes("userJWT"));if(!(i instanceof w)||i.status!==401||!Ni.has(i.code)||!n||!s)throw i;try{e.snapshot()?.refreshToken===s.refreshToken&&await e.refresh()}catch{throw i}if(e.snapshot()?.userId!==s.userId)throw i;return r.send(t)}}}}export{T as a,Rt as b,Pt as c,ks as d,Ke as e,oe as f,de as g,ue as h,pe as i,ge as j,me as k,ve as l,We as m,we as n,be as o,Zs as p,te as q,Be as r,Se as s,ke as t,_e as u,Ti as v,Me as w,Ze as x,et as y,tt as z,st as A,it as B,nt as C,rt as D,Ie as E,at as F,Ee as G,Sr as H};
|
|
22
|
+
`,ge=class{api;session;constructor(e,t){this.api=H.client(e),this.session=t}async list(e={}){return(await this.api.listMyInbox({query:{limit:e.limit,cursor:e.cursor,locale:e.locale}})).data}async unread(){return(await this.list({limit:1})).unread}async markRead(e){let t=e==="all"?{all:!0}:{ids:[...e]};return(await this.api.readMyInbox({body:t})).data.read}async remove(e){await this.api.deleteMyInboxMessage({path:{id:e}})}mount(e,t={}){let s=e.ownerDocument,i=s.defaultView,n=s.createElement("div");n.setAttribute("data-palbase-inbox","");let a=n.attachShadow({mode:"open"});St(s,a,ei);let o=s.createElement("ul");o.className="list",a.append(o),e.append(n);let d=()=>t.appearance??(i?.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"),l=[],c=0,h=[],p=!1,v=m=>{c=m,t.onUnread?.(m)},f=(m,S)=>{m.read_at||(m.read_at=new Date().toISOString(),v(Math.max(0,c-1)),y(),this.markRead([m.id]).catch(()=>{})),!(!S||!wt(S))&&(t.onOpen?t.onOpen(m,S):S.startsWith("https://")?i?.open(S,"_blank","noopener,noreferrer"):i?.location.assign(S))},u=async m=>{l=l.filter(S=>S.id!==m.id),m.read_at||v(Math.max(0,c-1)),y(),await this.remove(m.id).catch(()=>{})},g=m=>{try{return new Intl.DateTimeFormat(t.locale,{dateStyle:"medium",timeStyle:"short"}).format(new Date(m))}catch{return m}};function y(){if(h.forEach(m=>m.destroy()),h=[],o.replaceChildren(),o.className=`list ${d()}`,!l.length){let m=s.createElement("li");m.className="empty",m.textContent=t.labels?.empty??"No messages",o.append(m);return}for(let m of l)o.append(R(m))}let R=m=>{let S=s.createElement("li");S.setAttribute("data-id",m.id),S.tabIndex=0;let E=s.createElement("button");if(E.type="button",E.className="delete",E.textContent="\xD7",E.setAttribute("aria-label",t.labels?.delete??"Delete"),E.addEventListener("click",M=>{M.stopPropagation(),u(m)}),m.card){S.className=`card ${m.read_at?"":"unread"}`;let M=s.createElement("div");S.append(M,E);let K={onAction:()=>f(m,void 0),onDeepLink:C=>f(m,C),onLink:C=>f(m,C),onCustom:t.onCustom};h.push(bt(M,{definition:m.card,locale:t.locale??i?.navigator.language??"en",appearance:d(),variables:m.variables??{}},K)),S.addEventListener("click",C=>{C.composedPath().some(D=>D instanceof HTMLElement&&D.tagName==="BUTTON")||f(m,m.deep_link)})}else{S.className=`item ${m.read_at?"":"unread"}`;let M=s.createElement("span");if(M.className="dot",S.append(M),m.image?.startsWith("https://")){let C=s.createElement("img");C.src=m.image,C.alt="",S.append(C)}let K=s.createElement("div");K.className="text";for(let[C,D]of[["title",m.title],["body",m.body],["when",g(m.created_at)]]){if(!D)continue;let w=s.createElement("span");w.className=C,w.textContent=D,K.append(w)}S.append(K,E),S.addEventListener("click",()=>f(m,m.deep_link))}return S.addEventListener("keydown",M=>{M.key==="Enter"&&M.target===S&&f(m,m.deep_link)}),S},x=0,j=async()=>{let m=++x;if(!(await this.session.session())?.userId){if(p||m!==x)return;l=[],v(0),y();return}let S=await this.list({limit:t.limit??50,locale:t.locale});p||m!==x||(l=S.items,v(S.unread),y())},se=()=>{s.visibilityState==="visible"&&j().catch(()=>{})};s.addEventListener("visibilitychange",se);let ie=this.session.onChange(()=>{j().catch(()=>{})});return y(),j().catch(()=>{}),{refresh:j,get items(){return l},get unread(){return c},destroy(){p=!0,s.removeEventListener("visibilitychange",se),ie?.(),h.forEach(m=>m.destroy()),n.remove()}}}};var ti=30*6e4,me="session_start";function ye(r){try{return r.localStorage}catch{return}}var si=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function ii(r,e){for(let[t,s]of Object.entries(r??{})){let i=e?.[t];if(i==null||String(i)!==s)return!1}return!0}var ve=class{api;session;installation;g;now;requestPush;analyticsAllowed;iap;asked=0;person=0;sessionKey;pendingKey;opts;messages=[];limits={per_session:1,per_day:3,min_minutes:10};shown={session:0,day:0,total:0};loaded=Promise.resolve();away=!1;memorySession;memoryPending=[];showing;stopWatching;queue=Promise.resolve();constructor(e,t,s,i,n,a,o,d=globalThis,l=Date.now){this.api=H.client({send:c=>e.send({...c,headers:{...c.headers,[O]:A(s)}})}),this.session=t,this.installation=s,this.requestPush=n,this.analyticsAllowed=a,this.iap=o,this.g=d,this.now=l,this.sessionKey=`palbase.notify.inapp.session.${i}`,this.pendingKey=`palbase.notify.inapp.conversions.${i}`,t.onChange(c=>{c!=="SIGNED_IN"&&c!=="SIGNED_OUT"&&c!=="SESSION_EXPIRED"||(this.forget(),this.opts&&(this.showing?.message.close(),this.loaded=this.load()))})}get started(){return this.opts!==void 0}start(e={}){let t=!this.opts;if(this.opts=e,!t)return;let s=this.g.document,i=()=>{s?.visibilityState==="visible"?this.enqueue(me,void 0,!0):this.away=!0};s?.addEventListener("visibilitychange",i),this.stopWatching=()=>s?.removeEventListener("visibilitychange",i);let n=this.touch();this.loaded=this.load(),n&&this.trigger(me)}stop(){this.opts=void 0,this.stopWatching?.(),this.stopWatching=void 0,this.showing?.message.close()}refresh(){return this.loaded=this.load(),this.loaded}trigger(e,t){this.enqueue(e,t,!1)}settled(){return this.queue}enqueue(e,t,s){this.queue=this.queue.then(()=>this.take(e,t,s)).catch(()=>{})}async take(e,t,s){if(await this.converted(e),!!this.opts){if(this.touch())this.loaded=this.load(),e!==me&&await this.show(me,void 0);else if(this.away&&(this.loaded=this.load()),s)return;await this.show(e,t)}}async show(e,t){if(await this.loaded,!(!this.opts||this.showing)){for(let s of this.messages)if(!(s.trigger.event!==e||!ii(s.trigger.where,t)||this.capped(s))&&await this.open(s))return}}capped(e){let t=this.now(),s=(o,d)=>o!==void 0&&d!==void 0&&t-Date.parse(o)<d*6e4,i=this.shown,n=e.shown,a=e.limits;return i.session>=this.limits.per_session||i.day>=this.limits.per_day||s(i.last_at,this.limits.min_minutes)||a.per_session!==void 0&&n.session>=a.per_session||a.per_day!==void 0&&n.day>=a.per_day||s(n.last_at,a.min_minutes)||a.max_total!==void 0&&n.total>=a.max_total}async open(e){let t=this.opts,s=this.person,i=await this.subject(),n,a;try{({id:n,variables:a}=(await this.api.showInAppMessage({body:{campaign_id:e.campaign_id,session_id:this.sessionId(),installation_id:this.installation.id}})).data)}catch(c){return c instanceof b&&c.status===409&&(this.loaded=this.load()),!1}if(!this.opts||this.showing||s!==this.person)return!0;let o=new Date(this.now()).toISOString();for(let c of[this.shown,e.shown])c.session++,c.day++,c.total++,c.last_at=o;e.conversion&&this.pend({impression:n,campaign:e.campaign_id,event:e.conversion.event,until:this.now()+e.conversion.hours*36e5,subject:i});let d=(c,h)=>{this.api.reportInAppEvent({path:{id:n},query:{installation_id:this.installation.id},body:{type:c,...h?{action:h}:{}}}).catch(()=>{})},l=kt({definition:e.definition,locale:t.locale??this.g.navigator?.language??"en",appearance:t.appearance??this.appearance(),variables:{...e.variables,...a}},{onAction:c=>{c.type!=="close"&&c.type!=="sheet"&&d("clicked",c.type)},onLink:t.onLink,onDeepLink:t.onDeepLink,onCustom:t.onCustom,onShowPaywall:t.onShowPaywall,onOffer:t.onOffer??(c=>this.takeOffer(c,t.onOfferError)),onApplyPromo:t.onApplyPromo,onCopyCode:t.onCopyCode,onRequestPush:t.onRequestPush??(()=>this.requestPush().then(()=>{})),labels:t.labels,onClose:c=>{this.showing?.message===l&&(this.showing=void 0),c!=="action"&&c!=="app"&&d("dismissed"),t.onClose?.(e.campaign_id,c)}},t.root?{root:t.root}:{});return this.showing={campaign:e.campaign_id,message:l},t.onShow?.(e.campaign_id),!0}async takeOffer(e,t){try{let s=(await this.iap.offers()).find(o=>o.key===e);if(s?.kind==="grant"){await this.iap.claimOffer(e);return}let i=s?.web?.plans[0];if(!s?.product||i===void 0)throw new b({op:"TakeOffer",status:0,code:"offer_not_open",message:`the offer ${e} is not the customer's to take on the web now`});let n=this.g.location,a=await this.iap.checkout({product:s.product,plan:i,successUrl:n.href,cancelUrl:n.href,offer:e});n.assign(a)}catch(s){if(!t)throw s;t(s,e)}}async converted(e){let t=this.now(),s=this.pending().filter(a=>a.until>t),i=await this.subject(),n=this.analyticsAllowed()?s.filter(a=>a.event===e&&a.subject===i):[];this.keepPending(s.filter(a=>!n.includes(a))),await Promise.all(n.map(a=>this.api.reportInAppEvent({path:{id:a.impression},query:{installation_id:this.installation.id},body:{type:"converted"}}).catch(()=>{})))}forget(){this.person++,this.asked++,this.messages=[],this.shown={session:0,day:0,total:0}}async load(){this.away=!1;let e=++this.asked;try{let t=(await this.api.listMyInAppMessages({query:{session_id:this.sessionId(!1),installation_id:this.installation.id}})).data;if(e!==this.asked)return;this.messages=t.messages,this.limits=t.limits,this.shown=t.shown}catch{}}async subject(){let e=(await this.session.session())?.userId;return e?`u:${e}`:`i:${this.installation.id}`}appearance(){return this.g.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}touch(){let e=this.now(),t=this.readSession(),s=!t||e-t.last>=ti;return this.writeSession(s?{id:`ses_${si()}`,last:e}:{id:t.id,last:e}),s}sessionId(e=!0){return e&&this.touch(),(this.readSession()??this.memorySession).id}readSession(){try{let e=ye(this.g)?.getItem(this.sessionKey);if(e)return JSON.parse(e)}catch{}return this.memorySession}writeSession(e){this.memorySession=e;try{ye(this.g)?.setItem(this.sessionKey,JSON.stringify(e))}catch{}}pending(){try{let e=ye(this.g)?.getItem(this.pendingKey);if(e)return JSON.parse(e)}catch{}return this.memoryPending}keepPending(e){this.memoryPending=e;try{let t=ye(this.g);e.length?t?.setItem(this.pendingKey,JSON.stringify(e)):t?.removeItem(this.pendingKey)}catch{}}pend(e){this.keepPending([...this.pending().filter(t=>t.until>this.now()),e].slice(-50))}};var He=r=>{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),s=new Uint8Array(t.length);for(let i=0;i<t.length;i++)s[i]=t.charCodeAt(i);return s},Be=class{api;session;installation;baseUrl;publishableKey;g;registered;generation=0;wake=()=>{};replacing;changing=Promise.resolve();constructor(e,t,s,i,n,a=globalThis){this.api=H.client(e),this.session=t,this.installation=s,this.baseUrl=i,this.publishableKey=n,this.g=a,t.onChange(o=>{if(o==="SIGNED_IN"||o==="SIGNED_OUT"||o==="SESSION_EXPIRED"){this.registered=void 0;let d=++this.generation;this.wake(),this.changing=this.changing.then(()=>this.registerFor(d)).catch(()=>{})}})}supported(){return!!this.g.navigator?.serviceWorker&&this.g.PushManager!==void 0&&this.g.Notification!==void 0}permission(){return this.supported()?this.g.Notification.permission:"unsupported"}workerUrl(e="/palbase-sw.js"){let t=new URLSearchParams({url:this.baseUrl,key:this.publishableKey});return`${e}${e.includes("?")?"&":"?"}${t}`}async subscribe(e={}){if(!this.supported())return!1;let t=this.g.Notification;if(t.permission==="default"&&await t.requestPermission()!=="granted"||t.permission==="denied")return!1;let s=this.g.navigator.serviceWorker,i=this.workerUrl(e.serviceWorker),n=await this.scopeFor(s,i,e.scope),a=await s.register(i,n?{scope:n}:void 0);await ni(a);let o=await a.pushManager.getSubscription(),d=(await this.api.getWebPushKey()).data.public_key;o&&!ri(o.options.applicationServerKey,d)&&(await o.unsubscribe(),o=null),o??=await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:He(d)});let l=this.generation;return await this.register(o),this.generation===l&&this.supersede(),!0}async unsubscribe(){this.supersede(),await this.changing;let e=await this.current();e&&await e.unsubscribe(),this.registered=void 0}supersede(){++this.generation,this.replacing=void 0,this.wake()}async refresh(){if(!this.supported()||this.permission()!=="granted")return;let e=await this.current();e&&await this.register(e)}async registerFor(e){if(e===this.generation){if(!this.replacing){try{return await this.refresh()}catch{}let t=await(await this.ours())?.pushManager.getSubscription();if(!t)return;this.replacing={key:t.options.applicationServerKey},await t.unsubscribe()}for(let t of[0,...Zt]){if(t>0&&await this.pause(t),e!==this.generation||this.permission()!=="granted")return;try{let s=await this.ours();if(!s)return void(this.replacing=void 0);let i=this.replacing?.key??He((await this.api.getWebPushKey()).data.public_key),n=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:i});if(e!==this.generation)return;await this.register(n),this.replacing=void 0;return}catch(s){if(t===Zt.at(-1))throw s}}}}pause(e){return new Promise(t=>{let s=setTimeout(i,e);function i(){clearTimeout(s),t()}this.wake=i})}async ours(){let e=this.g.navigator?.serviceWorker;if(e)return(await e.getRegistrations()).find(t=>this.isOurs(t))}isOurs(e){let t=es(e)?.searchParams.get("key");return!!t&&Ge(t)!==void 0&&Ge(t)===Ge(this.publishableKey)}async current(){return await(await this.ours())?.pushManager.getSubscription()??null}async scopeFor(e,t,s){let i=this.g.location?.href;if(!i)return s;let n=new URL("./",new URL(t,i)).href,a=s===void 0?n:new URL(s,i).href,o=(await e.getRegistrations()).find(l=>l.scope===a);if(!o||this.isOurs(o))return s;let d=es(o);if(s!==void 0)throw new Error(`pb.notify.push.subscribe: ${a} is the scope of another service worker (${d?.href??"unknown"}); registering Palbase's there would replace it \u2014 give Palbase's a scope of its own`);return new URL("palbase-push/",n).href}async register(e){let t=e.toJSON(),s={endpoint:t.endpoint??e.endpoint,keys:{p256dh:t.keys?.p256dh??"",auth:t.keys?.auth??""}},n=`${this.session.snapshot()?.userId??""}|${s.endpoint}`;this.registered!==n&&(await this.api.registerDevice({headers:{[O]:A(this.installation)},body:{device_id:`web-${this.installation.id}`,token:JSON.stringify(s),platform:"web",locale:this.g.navigator?.language??null,installation_id:this.installation.id,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}),this.registered=n)}},Zt=[1e3,5e3,3e4,12e4,6e5];async function ni(r){let e=r.installing??r.waiting;!e||r.active||await new Promise(t=>{let s=()=>{e.state!=="activated"&&e.state!=="redundant"||(e.removeEventListener("statechange",s),t())};e.addEventListener("statechange",s),s()})}function Ge(r){let e=r.split("_");return e.length>=3&&e[0]==="pb"&&e[1]!==""?e[1]:void 0}function es(r){let e=(r.installing??r.waiting??r.active)?.scriptURL;return e?new URL(e):void 0}function ri(r,e){if(!r)return!1;let t=new Uint8Array(r),s=He(e);return t.length===s.length&&t.every((i,n)=>i===s[n])}var we=class{push;inbox;inApp;constructor(e,t,s,i,n,a,o){this.push=new Be(e,t,s,a,o),this.inbox=new ge(e,t),this.inApp=new ve(e,t,s,new URL(a).origin,()=>this.push.subscribe(),()=>i.state("analytics")==="granted",n)}};var be=class{api;session;socket;ref;installation;fetch;appVersion;app;listeners=new Set;watch;following;last;constructor(e,t,s,i,n,a,o,d){this.api=yt.client(e),this.session=t,this.socket=s,this.ref=i,this.installation=n,this.fetch=a,this.appVersion=o,this.app=d}async me(){let e=this.session.snapshot()?.userId,t=(await this.api.getMyCustomerInfo()).data;return this.watch&&this.watch.userId===e&&this.offer(this.watch,t),t}async offerings(e="web"){return(await this.api.getOfferings({query:{channel:e}})).data}async paywall(e,t={}){return Tt(this.api,this.ref,e,this.installation.id,s=>this.checkout(s),{signal:t.signal,fetch:this.fetch,attributes:t.attributes,locale:t.locale,appVersion:this.appVersion,app:this.app})}async checkout(e){let t={product:e.product,plan:e.plan,success_url:e.successUrl,cancel_url:e.cancelUrl,...e.source!==void 0?{source:e.source}:{},...e.offer!==void 0?{offer:e.offer}:{},...e.channel!==void 0?{channel:e.channel}:{},...e.currency!==void 0?{currency:e.currency}:{}},s=(await this.api.createCheckout({body:t})).data;return s.redemption_key&&oi(this.keyName(s.session_id),s.redemption_key),s.url}async redemptionLink(e,t={}){let s=t.key??di(this.keyName(e));if(!s)throw new b({op:"CreateCheckoutRedemption",status:0,code:"redemption_key_missing",message:"no redemption key for this checkout in this tab: the link was sent to the buyer's email"});let i=Date.now()+(t.waitSeconds??20)*1e3;for(;;)try{return(await this.api.createCheckoutRedemption({body:{session_id:e,key:s},signal:t.signal})).data}catch(n){let a=(n instanceof b&&n.code==="checkout_not_paid"?n.retryAfter??2:-1)*1e3;if(a<0||Date.now()+a>i)throw n;await li(a,t.signal)}}async redeem(e){let t=ai(e);if(!t)throw new b({op:"RedeemPurchase",status:0,code:"invalid_redemption_link",message:"not a redemption link: <scheme>://palbase/redeem?token=\u2026 or \u2026/iap/redeem?token=\u2026"});let s=this.session.snapshot()?.userId,i=(await this.api.redeemPurchase({body:{token:t}})).data;return this.watch&&this.watch.userId===s&&this.offer(this.watch,i),i}async offers(){return(await this.api.listMyOffers()).data.offers}async offerShown(e){await this.api.recordOfferView({path:{offer_key:e}})}async claimOffer(e){return(await this.api.claimOffer({path:{offer_key:e}})).data}async redeemCoupon(e){return(await this.api.redeemCoupon({body:{code:e}})).data}async portal(e,t={}){let s={return_url:e,...t.channel!==void 0?{channel:t.channel}:{}};return(await this.api.createPortalSession({body:s})).data.url}async mergeGrant(){return(await this.api.createMergeGrant()).data}async merge(e){let t=this.session.snapshot()?.userId,s=(await this.api.mergeGuest({body:{grant:typeof e=="string"?e:e.grant}})).data;return this.watch&&this.watch.userId===t&&this.offer(this.watch,s),s}async setRefundDataConsent(e){return(await this.api.setRefundDataConsent({body:{consented:e}})).data}keyName(e){return`palbase:${this.ref}:redemption:${e}`}onCustomerInfo(e){if(this.listeners.add(e),this.listeners.size===1)this.start();else if(this.last!==void 0){let t=this.last;queueMicrotask(()=>this.listeners.has(e)&&ts(e,t))}return()=>{this.listeners.delete(e)&&this.listeners.size===0&&this.stop()}}start(){this.following=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.follow(t)}),this.session.session().then(e=>{this.following&&!this.watch&&this.last===void 0&&this.follow(e)})}stop(){this.following?.(),this.following=void 0,this.unfollow(),this.last=void 0}follow(e){if(this.unfollow(),!e){this.tell(null);return}let t=this.socket.channel(`iap:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},revision:-1,reading:!1,wanted:Number.NEGATIVE_INFINITY},i=[t.on("broadcast",n=>{n.event==="changed"&&this.changed(s,Je(n.payload))}),t.on("state_snapshot",n=>this.held(s,Je(ss(n.entries)))),t.on("state_diff",n=>this.held(s,Je(ss(n.set))))];s.off=()=>i.forEach(n=>n()),this.watch=s,t.join().catch(()=>{}),this.read(s)}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}changed(e,t){this.watch!==e||t!==void 0&&t<=e.revision||(e.reading?e.wanted=Math.max(e.wanted,t??Number.POSITIVE_INFINITY):this.read(e))}held(e,t){t!==void 0&&this.changed(e,t)}async read(e){e.reading=!0;try{for(;;){e.wanted=Number.NEGATIVE_INFINITY;try{let t=(await this.api.getMyCustomerInfo()).data;if(this.watch!==e)return;this.offer(e,t)}catch{}if(this.watch!==e||e.wanted<=e.revision)return}}finally{e.reading=!1}}offer(e,t){this.watch!==e||t.revision<=e.revision||(e.revision=t.revision,this.tell(t))}tell(e){if(!(this.last===null&&e===null)){this.last=e;for(let t of[...this.listeners])ts(t,e)}}};function ts(r,e){try{r(e)}catch{}}function ss(r){let e=typeof r=="object"&&r!==null?r.revision:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Je(r){let e=typeof r=="object"&&r!==null?r.revision:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var is=/^[A-Za-z0-9_-]{43}$/;function ai(r){let e=r.trim();if(is.test(e))return e;let t;try{t=new URL(e)}catch{return}let s=t.host==="palbase"&&t.pathname==="/redeem",i=(t.protocol==="https:"||t.protocol==="http:")&&t.pathname==="/iap/redeem",n=t.searchParams.get("token");return(s||i)&&n!==null&&is.test(n)?n:void 0}function oi(r,e){try{globalThis.sessionStorage?.setItem(r,e)}catch{}}function di(r){try{return globalThis.sessionStorage?.getItem(r)??void 0}catch{return}}function li(r,e){return new Promise((t,s)=>{if(e?.aborted)return s(e.reason);let i=setTimeout(()=>{e?.removeEventListener("abort",n),t()},r),n=()=>{clearTimeout(i),s(e?.reason)};e?.addEventListener("abort",n,{once:!0})})}var te={SEARCH_PERFORMED:"search.performed",PRODUCT_CLICKED:"product.clicked",PRODUCT_VIEWED:"product.viewed",CART_ITEM_ADDED:"cart.item_added",RECOMMENDATION_CLICKED:"recommendation.clicked"};function ns(r){return typeof AbortSignal<"u"&&r instanceof AbortSignal?!0:typeof r=="object"&&r!==null&&"aborted"in r&&typeof r.addEventListener=="function"}function _(r){let e={};for(let[t,s]of Object.entries(r))t!=="signal"&&s!==void 0&&(e[t]=s);return e}var Qe=class{storeId;api;constructor(e,t){this.storeId=e,this.api=G.client(t)}async listProducts(e,t){let s=e?_(e):void 0;return(await this.api.sellerListProducts({path:{store_id:this.storeId},query:s,signal:t})).data}async createQuickProduct(e,t){return(await this.api.sellerCreateQuickProduct({path:{store_id:this.storeId},body:e,signal:t})).data}async listListings(e){return(await this.api.sellerListListings({path:{store_id:this.storeId},signal:e})).data}async createListing(e,t){return(await this.api.sellerCreateListing({path:{store_id:this.storeId},body:e,signal:t})).data}async updateListing(e,t,s){return(await this.api.sellerUpdateListing({path:{store_id:this.storeId,listing_id:e},body:t,signal:s})).data}async upsertPrice(e,t,s){return(await this.api.sellerUpsertPrice({path:{store_id:this.storeId,listing_id:e},body:t,signal:s})).data}async listInventory(e){return(await this.api.sellerListInventory({path:{store_id:this.storeId},signal:e})).data}async adjustInventory(e,t){return(await this.api.sellerAdjustInventory({path:{store_id:this.storeId},body:e,signal:t})).data}async bulkSyncInventory(e,t){return(await this.api.sellerBulkSyncInventory({path:{store_id:this.storeId},body:e,signal:t})).data}async listOrders(e,t){return(await this.api.sellerListStoreOrders({path:{store_id:this.storeId},query:e,signal:t})).data}async getOrder(e,t){return(await this.api.sellerGetStoreOrder({path:{store_id:this.storeId,store_order_id:e},signal:t})).data}async createFulfillment(e,t,s){return(await this.api.sellerCreateFulfillment({path:{store_id:this.storeId,store_order_id:e},body:t,signal:s})).data}async updateFulfillment(e,t,s){return(await this.api.sellerUpdateFulfillment({path:{store_id:this.storeId,fulfillment_id:e},body:t,signal:s})).data}async cancelOrder(e,t,s){return(await this.api.sellerCancelStoreOrder({path:{store_id:this.storeId,store_order_id:e},body:t,signal:s})).data}async listReturns(e){return(await this.api.sellerListReturns({path:{store_id:this.storeId},signal:e})).data}async approveReturn(e,t={},s){return(await this.api.sellerApproveReturn({path:{store_id:this.storeId,return_id:e},body:t,signal:s})).data}async completeReturn(e,t={},s){return(await this.api.sellerCompleteReturn({path:{store_id:this.storeId,return_id:e},body:t,signal:s})).data}async listReviews(e,t){let s=e?_(e):void 0;return(await this.api.sellerListReviews({path:{store_id:this.storeId},query:s,signal:t})).data}async replyReview(e,t,s){let i=_(t);return(await this.api.sellerReplyReview({path:{store_id:this.storeId,review_id:e},body:i,signal:s})).data}async listSettlements(e){return(await this.api.sellerListSettlements({path:{store_id:this.storeId},signal:e})).data}async metrics(e){return(await this.api.sellerGetMetrics({path:{store_id:this.storeId},signal:e})).data}async onboardPayouts(e,t){return(await this.api.sellerOnboardPayouts({path:{store_id:this.storeId},body:e,signal:t})).data}async onboardingLink(e,t){return(await this.api.sellerOnboardingLink({path:{store_id:this.storeId},body:e,signal:t})).data}},Se=class{api;track;transport;userTransport;session;installation;analytics;consent;guestTokens=new Map;constructor(e,t,s,i,n,a){this.transport=e,this.userTransport=t,this.session=s,this.installation=i,this.analytics=n,this.consent=a,this.api=G.client(e),this.track={searchPerformed:o=>this.trackDiscoveryEvent(te.SEARCH_PERFORMED,o),productClicked:o=>this.trackDiscoveryEvent(te.PRODUCT_CLICKED,o),productViewed:o=>this.trackDiscoveryEvent(te.PRODUCT_VIEWED,o),cartItemAdded:o=>this.trackDiscoveryEvent(te.CART_ITEM_ADDED,o),recommendationClicked:o=>this.trackDiscoveryEvent(te.RECOMMENDATION_CLICKED,o)}}cartClient(e,t){let s=t??this.guestTokens.get(e);if(!s)return this.api;let i={send:n=>this.transport.send({...n,headers:{...n.headers,"X-Commerce-Guest-Token":s}})};return G.client(i)}discoveryHeaders(){if(this.installation&&!this.session.snapshot()?.userId&&this.consent?.state("personalization")!=="denied")return{[J]:this.installation.id,[O]:A(this.installation)}}discoveryClient(e,t){let s=e?t??this.guestTokens.get(e):void 0,i=this.discoveryHeaders();return!s&&!i?this.api:G.client({send:n=>this.transport.send({...n,headers:{...i,...s?{"X-Commerce-Guest-Token":s}:{},...n.headers}})})}trackDiscoveryEvent(e,t){this.analytics?.capture(e,t)}async listProducts(e,t){let s;if(e){let i=_(e),{attributes:n,...a}=i;s={...a,...n!==void 0?{attributes:typeof n=="string"?n:JSON.stringify(n)}:{}}}return(await this.discoveryClient().storefrontListProducts({query:s,signal:t})).data}async searchProducts(e={},t){let s=_(e);return(await this.discoveryClient().storefrontSearchProducts({body:s,signal:t})).data}async suggest(e,t,s){let i,n;typeof e=="string"?ns(t)?(i={q:e},n=t):(i={...t??{},q:e},n=s):(i=e??{},n=ns(t)?t:s);let{limit:a,max_results:o,...d}=_(i),l=o??a,c={...d,...l!==void 0?{max_results:l}:{}};return(await this.discoveryClient().storefrontSuggest({query:c,signal:n})).data}async recommend(e,t){let{guestToken:s,...i}=_(e);return(await this.discoveryClient(i.cart_id,s).storefrontRecommendProducts({body:i,signal:t})).data}async productRecommendations(e,t,s){let i;if(t){let{limit:n,max_results:a,...o}=_(t),d=a??n;i={...o,...d!==void 0?{max_results:d}:{}}}return(await this.discoveryClient().storefrontProductRecommendations({path:{product_id_or_handle:e},query:i,signal:s})).data}async similarProducts(e,t,s){return this.productStrategyRecommend(e,"similar",t,s)}async frequentlyBoughtTogether(e,t,s){return this.productStrategyRecommend(e,"fbt",t,s)}async productStrategyRecommend(e,t,s,i){let n=s?_(s):{},a=n.max_results??n.limit;if(!(n.exclude_product_ids!==void 0||n.category_id!==void 0||n.brand_id!==void 0||n.store_id!==void 0||n.params!==void 0||a!==void 0&&a>50))return this.productRecommendations(e,{strategy:t,...a!==void 0?{max_results:a}:{},...n.channel!==void 0?{channel:n.channel}:{},...n.region!==void 0?{region:n.region}:{},...n.currency!==void 0?{currency:n.currency}:{},...n.in_stock!==void 0?{in_stock:n.in_stock}:{}},i);let{max_results:d,limit:l,...c}=n;return this.recommend({...c,strategy:t,product_id:e,...a!==void 0?{limit:a}:{}},i)}async trendingProducts(e,t){return this.recommend({...e?_(e):{},strategy:"trending"},t)}async bestsellers(e,t){return this.recommend({...e?_(e):{},strategy:"bestsellers"},t)}async newArrivals(e,t){return this.recommend({...e?_(e):{},strategy:"new_arrivals"},t)}async topRated(e,t){return this.recommend({...e?_(e):{},strategy:"top_rated"},t)}async personalizedProducts(e,t){return this.recommend({...e?_(e):{},strategy:"personalized"},t)}async cartComplementary(e,t,s){return this.recommend({...t?_(t):{},strategy:"cart_complementary",cart_id:e},s)}async getProduct(e,t){return(await this.api.storefrontGetProduct({path:{product_id_or_handle:e},signal:t})).data}async listProductReviews(e,t,s){let i=t?_(t):void 0;return(await this.api.storefrontListProductReviews({path:{product_id_or_handle:e},query:i,signal:s})).data}async listStoreReviews(e,t,s){let i=t?_(t):void 0;return(await this.api.storefrontListStoreReviews({path:{store_id_or_slug:e},query:i,signal:s})).data}async createProductReview(e,t,s){let i=_(t);return(await this.api.createProductReview({path:{product_id_or_handle:e},body:i,signal:s})).data}async createStoreReview(e,t,s){let i=_(t);return(await this.api.createStoreReview({path:{store_id_or_slug:e},body:i,signal:s})).data}async myReviews(e){return(await this.api.listMyReviews({signal:e})).data}async deleteReview(e,t,s){let i=typeof t=="string"?t:t?.kind,n=i?{kind:i}:void 0;return(await this.api.deleteMyReview({path:{review_id:e},query:n,signal:s})).data}async voteReview(e,t,s){let i=_(t);return(await this.api.voteReview({path:{review_id:e},body:i,signal:s})).data}async mintReviewUploadUrl(e,t){let s=_(e);return(await this.api.mintReviewUploadUrl({body:s,signal:t})).data}async listCategories(e){return(await this.api.storefrontListCategories({signal:e})).data}async listBrands(e){return(await this.api.storefrontListBrands({signal:e})).data}async listCollections(e){return(await this.api.storefrontListCollections({signal:e})).data}async listStores(e,t){return(await this.api.storefrontListStores({query:e,signal:t})).data}async getStore(e,t){return(await this.api.storefrontGetStore({path:{store_id_or_slug:e},signal:t})).data}async listRegions(e){return(await this.api.storefrontListRegions({signal:e})).data}async listChannels(e){return(await this.api.storefrontListChannels({signal:e})).data}async createCart(e={},t){let s=(await this.api.createCart({body:e,signal:t})).data;return s.id&&s.guest_token&&this.guestTokens.set(s.id,s.guest_token),s}async getCart(e,t={}){return(await this.cartClient(e,t.guestToken).getCart({path:{cart_id:e},signal:t.signal})).data}async updateCart(e,t,s={}){return(await this.cartClient(e,s.guestToken).updateCart({path:{cart_id:e},body:t,signal:s.signal})).data}async addItem(e,t,s={}){return(await this.cartClient(e,s.guestToken).addCartItem({path:{cart_id:e},body:t,signal:s.signal})).data}async updateItem(e,t,s,i={}){return(await this.cartClient(e,i.guestToken).updateCartItem({path:{cart_id:e,line_id:t},body:s,signal:i.signal})).data}async removeItem(e,t,s={}){return(await this.cartClient(e,s.guestToken).deleteCartItem({path:{cart_id:e,line_id:t},signal:s.signal})).data}async selectShipping(e,t,s={}){return(await this.cartClient(e,s.guestToken).selectCartShipping({path:{cart_id:e},body:t,signal:s.signal})).data}async applyPromoCode(e,t,s={}){return(await this.cartClient(e,s.guestToken).applyCartPromoCode({path:{cart_id:e},body:{code:t},signal:s.signal})).data}async removePromoCode(e,t,s={}){return(await this.cartClient(e,s.guestToken).removeCartPromoCode({path:{cart_id:e,code:t},signal:s.signal})).data}async mergeCart(e,t={}){let s=t.guestToken??this.guestTokens.get(e),i=(await this.api.mergeGuestCart({path:{cart_id:e},body:s?{guest_token:s}:{},signal:t.signal})).data;return this.guestTokens.delete(e),i}async checkout(e,t={},s={}){return(await this.cartClient(e,s.guestToken).checkoutCart({path:{cart_id:e},body:t,signal:s.signal})).data}async getGuestOrder(e,t,s){let i={send:n=>this.transport.send({...n,headers:{...n.headers,"X-Commerce-Guest-Token":t}})};return(await G.client(i).getGuestOrder({path:{order_number:e},signal:s})).data}async myOrders(e,t){return(await this.api.listMyOrders({query:e,signal:t})).data}async myOrder(e,t){return(await this.api.getMyOrder({path:{order_id:e},signal:t})).data}async myOrderDownloads(e,t){return(await this.api.getMyOrderDownloads({path:{order_id:e},signal:t})).data}async requestReturn(e,t,s){return(await this.api.requestMyReturn({path:{store_order_id:e},body:t,signal:s})).data}async myReturns(e){return(await this.api.listMyReturns({signal:e})).data}seller(e){let t=this.session.snapshot()?.userId;if(!t)throw new P("seller portal requires a signed-in user session");return new Qe(e,this.userTransport(t))}};var ci=720*60*60*1e3;function ze(r){try{return r.localStorage}catch{return}}var ke=class{api;commerce;installation;storageKey;g;now;memoryAttribution=null;constructor(e,t,s,i,n=globalThis,a=Date.now){this.api=gt.client({send:o=>e.send({...o,headers:{...o.headers,[O]:A(t)}})}),this.installation=t,this.commerce=s,this.storageKey=`palbase.campaigns.attribution.${i}`,this.g=n,this.now=a}async listOnSiteMessages(e){return(await this.api.listOnSiteMessages({signal:e})).data}async recordImpression(e,t){return(await this.api.createOnSiteImpression({body:{...e,installation_id:e.installation_id??this.installation.id},signal:t})).data}async recordEvent(e,t,s){await this.api.recordOnSiteEvent({path:{id:e},body:t,signal:s})}captureAttribution(e){let t=e??this.g.location?.search??this.g.location?.href??"";if(!t)return this.getAttribution();let s;try{t.includes("://")?s=new URL(t).searchParams:s=new URLSearchParams(t.startsWith("?")?t.slice(1):t)}catch{return this.getAttribution()}let i=s.get("pb_click")?.trim()||void 0,n=s.get("pb_promo")?.trim()||void 0,a=s.get("utm_source")?.trim()||void 0,o=s.get("utm_medium")?.trim()||void 0,d=s.get("utm_campaign")?.trim()||void 0,l=s.get("utm_content")?.trim()||void 0,c=s.get("utm_term")?.trim()||void 0;if(!i&&!n&&!a&&!o&&!d&&!l&&!c)return this.getAttribution();let h={...i?{clickToken:i}:{},...n?{promoCode:n}:{},...a?{utmSource:a}:{},...o?{utmMedium:o}:{},...d?{utmCampaign:d}:{},...l?{utmContent:l}:{},...c?{utmTerm:c}:{},capturedAt:this.now()};this.memoryAttribution=h;try{ze(this.g)?.setItem(this.storageKey,JSON.stringify(h))}catch{}return h}getAttribution(e=ci){let t=this.memoryAttribution;if(!t)try{let s=ze(this.g)?.getItem(this.storageKey);s&&(t=JSON.parse(s))}catch{t=null}return t?this.now()-t.capturedAt>e?(this.clearAttribution(),null):(this.memoryAttribution=t,t):null}clearAttribution(){this.memoryAttribution=null;try{ze(this.g)?.removeItem(this.storageKey)}catch{}}async applyAttributedPromo(e,t={}){let s=this.getAttribution();return s?.promoCode?this.commerce.applyPromoCode(e,s.promoCode,t):null}};var _e=class{api;session;socket;installation;ref;analytics;appVersion;storageKey;held;listeners=new Set;started;leave=[];running;queued;fresh=!0;constructor(e,t,s,i,n,a,o,d){this.api=mt.client(e),this.session=t,this.socket=s,this.installation=i,this.ref=n,this.analytics=o,this.appVersion=d,this.storageKey=`palbase.flags.${a}`,this.held=ui(this.storageKey)}value(e){let t=this.mine();if(!t||!Object.hasOwn(t.values,e))return;let s=t.experiments[e];return s&&this.analytics.captureOnce(`$flag_exposure:${e}:${s.experiment_id}`,"$flag_exposure",{flag:e,experiment:s.experiment_id,variant:s.variant}),t.values[e]}bool(e,t){let s=this.value(e);return typeof s=="boolean"?s:t}string(e,t){let s=this.value(e);return typeof s=="string"?s:t}number(e,t){let s=this.value(e);return typeof s=="number"&&Number.isFinite(s)?s:t}json(e,t){let s=this.value(e);return typeof s=="object"&&s!==null?s:t}all(){return{...this.mine()?.values}}source(e){return this.mine()?.sources[e]}get version(){return this.mine()?.syncVersion}onChange(e){return this.listeners.add(e),this.start(),()=>{this.listeners.delete(e)}}refresh(){return this.started?this.read():this.start()}mine(){this.start();let e=this.held;return e&&e.user===(this.session.snapshot()?.userId??null)?e:void 0}start(){if(this.started)return this.started;this.session.onChange((t,s)=>{(t==="SIGNED_IN"||t==="SIGNED_OUT"||t==="SESSION_EXPIRED")&&this.follow(s).catch(()=>{})});let e=this.session.session().then(t=>this.follow(t));return e.catch(()=>{}),this.started=e,e}follow(e){let t=e?.userId??null;if(this.held&&this.held.user!==t){let s=Object.keys(this.held.values);this.held=void 0,rs(this.storageKey,void 0),this.tell(s)}return this.join(t),this.fresh=!0,this.read()}join(e){for(let s of this.leave.splice(0))s();let t=[`flags:${this.ref}`,...e!==null?[`flags:${this.ref}:${e}`]:[]];for(let s of t){let i=this.socket.channel(s),n=[i.on("broadcast",a=>{a.event==="changed"&&this.changed(Xe(a.payload))}),i.on("state_snapshot",a=>this.changed(Xe(as(a.entries)))),i.on("state_diff",a=>this.changed(Xe(as(a.set))))];i.join().catch(()=>{}),this.leave.push(()=>{n.forEach(a=>a()),i.leave()})}}changed(e){if(e===void 0)return;let t=this.mine();t&&Number(t.syncVersion)>=e||this.read().catch(()=>{})}read(){if(this.queued)return this.queued;let e=(this.running??Promise.resolve()).catch(()=>{}).then(()=>(this.queued=void 0,this.fetch()));this.queued=e,this.running=e;let t=()=>{this.running===e&&(this.running=void 0)};return e.then(t,t),e}async fetch(){let e=(await this.session.session())?.userId??null,t=this.held?.user===e?this.held:void 0,s=this.headers(e,t?.etag);if(t&&!this.fresh)try{let l=await this.api.getDelta({query:{since:Number(t.syncVersion)},headers:s});if(l.status===304)return;let c={...t,values:{...t.values},sources:{...t.sources},experiments:{...t.experiments},syncVersion:l.data.sync_version,etag:l.headers.get("etag")??t.etag},h=new Set;for(let p of l.data.ops)h.add(p.key),p.op==="delete"?(delete c.values[p.key],delete c.sources[p.key],delete c.experiments[p.key]):(c.values[p.key]=p.value??null,c.sources[p.key]=p.source,p.experiment?c.experiments[p.key]=p.experiment:delete c.experiments[p.key]);this.apply(c,[...h]);return}catch(l){if(!(l instanceof b&&l.status===410))throw l}let i=await this.api.getSnapshot({headers:s});if(this.fresh=!1,i.status===304)return;let n=i.data,a={user:e,values:n.values,sources:n.sources,experiments:n.experiments??{},syncVersion:n.sync_version,contextHash:n.context_hash,etag:i.headers.get("etag")??void 0},o=t?.values??{},d=[...new Set([...Object.keys(o),...Object.keys(a.values)])].filter(l=>JSON.stringify(o[l])!==JSON.stringify(a.values[l]));this.apply(a,d)}headers(e,t){return{"X-Platform":"web",...this.appVersion?{"X-Palbase-Client-Version":this.appVersion}:{},[J]:this.installation.id,...e===null?{[O]:A(this.installation)}:{},...t?{"If-None-Match":t}:{}}}apply(e,t){if(e.user!==(this.session.snapshot()?.userId??null))return;let s=this.held?.user===e.user?this.held:void 0;s&&!(Number(e.syncVersion)>Number(s.syncVersion)||e.syncVersion===s.syncVersion&&e.contextHash!==s.contextHash)||(this.held=e,rs(this.storageKey,e),t.length>0&&this.tell(t))}tell(e){for(let t of[...this.listeners])try{t(e)}catch{}}};function Ye(){try{return globalThis.localStorage}catch{return}}function ui(r){try{let e=Ye()?.getItem(r);if(!e)return;let t=JSON.parse(e);return typeof t!="object"||t===null||typeof t.values!="object"||t.values===null||typeof t.syncVersion!="string"?void 0:{user:typeof t.user=="string"?t.user:null,values:t.values,sources:t.sources??{},experiments:t.experiments??{},syncVersion:t.syncVersion,contextHash:t.contextHash??"",...typeof t.etag=="string"?{etag:t.etag}:{}}}catch{return}}function rs(r,e){try{e?Ye()?.setItem(r,JSON.stringify(e)):Ye()?.removeItem(r)}catch{}}function as(r){let e=typeof r=="object"&&r!==null?r.sync_version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Xe(r){let e=typeof r=="object"&&r!==null?r.sync_version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Re=class{items=new Map;add(e,t,s){let i={clientMessageId:t.client_message_id,conversationId:e,request:t,state:"pending",attempts:0,error:null,createdAt:s};return this.items.set(i.clientMessageId,i),i}get(e){return this.items.get(e)}all(e){return[...this.items.values()].filter(t=>!e||t.conversationId===e).sort((t,s)=>t.createdAt<s.createdAt?-1:t.createdAt>s.createdAt?1:0)}settle(e,t){return e.sender_id!==t||!e.client_message_id?!1:this.items.delete(e.client_message_id)}retry(e){let t=this.items.get(e);t&&t.state==="failed"&&Object.assign(t,{state:"pending",error:null})}discard(e){return this.items.delete(e)}async flush(e,t){let s=new Map;for(let n of this.all())n.state!=="failed"&&s.set(n.conversationId,[...s.get(n.conversationId)??[],n]);let i=!1;return await Promise.all([...s.values()].map(async n=>{for(let a of n){if(!this.items.has(a.clientMessageId))continue;a.state="sending",a.attempts++;let o;try{o=await e(a)}catch{o={kind:"wait"}}if(o.kind==="wait"){this.items.has(a.clientMessageId)&&(a.state="pending"),i=this.items.has(a.clientMessageId),t(a,o);return}o.kind==="refused"?Object.assign(a,{state:"failed",error:o.code}):this.items.delete(a.clientMessageId),t(a,o)}})),i}save(){return this.all().map(e=>({...e,state:e.state==="sending"?"pending":e.state}))}load(e){this.items.clear();for(let t of e)this.items.set(t.clientMessageId,{...t,state:t.state==="sending"?"pending":t.state})}};function Ze(r,e){if(r===200||r===201)return{kind:"sent",message:e};if(r===202)return{kind:"scheduled",scheduled:e};if(r<400||r>=500||r===408||r===429)return{kind:"wait"};let t=e?.error;return{kind:"refused",code:typeof t=="string"?t:`http_${r}`}}function os(){return{list:!1,conversations:new Set,threads:new Set,scheduled:!1}}var Pe=class{reader;cursor=null;conversations=new Map;members=new Map;messages=new Map;threads=new Map;scheduled=new Map;deleted=new Map;constructor(e){this.reader=e}apply(e){let t=os();for(let s of e.removed_conversations??[])this.removed(s,t);for(let s of e.hidden??[])this.messages.get(s.conversation_id)?.delete(s.message_id)&&t.conversations.add(s.conversation_id),this.threads.delete(s.message_id)&&t.threads.add(s.message_id),this.forgetLast(s.conversation_id,s.message_id)&&(t.list=!0);for(let s of e.conversations??[])this.putConversation(s,t);for(let s of e.members??[])this.putMember(s,t);for(let s of e.messages??[])this.putMessage(s,t);for(let s of e.threads??[])this.putThread(s,t);for(let s of e.scheduled??[])this.putScheduled(s,t);return t}reset(e){this.conversations.clear(),this.members.clear(),this.messages.clear(),this.threads.clear(),this.scheduled.clear();let t=this.apply(e);return t.list=!0,t.scheduled=!0,t}removed(e,t){if(e.reportable_until){let s=e.conversation_id,i=this.conversations.get(s)?.title??this.deleted.get(s)?.title??null;this.deleted.set(s,{id:s,title:i,deletedBy:e.deleted_by??null,reportableUntil:e.reportable_until})}this.drop(e.conversation_id,t)}drop(e,t){this.conversations.delete(e),this.members.delete(e),this.messages.delete(e);for(let[s,i]of this.threads)i.conversation_id===e&&this.threads.delete(s);t.list=!0,t.conversations.add(e)}putConversation(e,t){let s=this.conversations.get(e.id);if(e.deleted){this.drop(e.id,t);return}let i=s?.me&&e.me&&e.me.read_seq<s.me.read_seq?this.readTo(e,e.me,s.me.read_seq):e.me,n=s&&!hi(i,s.me)?s.me:i,a={...e,me:n,...e.last_message===void 0&&s?.last_message?{last_message:s.last_message}:{}};if(s){if(e.version<s.version){if(n===s.me)return;a={...s,me:n}}else if(e.version===s.version&&gi(ds(a),s))return}e.gap&&this.messages.delete(e.id);for(let o of e.members??[])this.putMember(o,t);this.conversations.set(e.id,ds(a)),t.list=!0,t.conversations.add(e.id)}putMember(e,t){let s=this.members.get(e.conversation_id);s||(s=new Map,this.members.set(e.conversation_id,s));let i=s.get(e.user_id),n=e;if(i){if(e.version<i.version)return;if(e.version===i.version){let a=pi(i.read_seq,e.read_seq);if(a===i.read_seq&&e.delivered_seq<=i.delivered_seq)return;n={...i,read_seq:a,delivered_seq:Math.max(i.delivered_seq,e.delivered_seq)}}}s.set(e.user_id,n),t.conversations.add(e.conversation_id)}putMessage(e,t){let s=this.messages.get(e.conversation_id);s||(s=new Map,this.messages.set(e.conversation_id,s));let i=s.get(e.id);i&&e.version<=i.version||(s.set(e.id,e),t.conversations.add(e.conversation_id),e.thread_id&&t.threads.add(e.thread_id),(e.reply_count>0||i?.reply_count)&&t.threads.add(e.id),t.list=!0)}putThread(e,t){let s=this.threads.get(e.thread_id),i=s&&e.read_seq<s.read_seq?this.threadReadTo(e,s.read_seq):e;s&&i.version<=s.version&&i.unread_count===s.unread_count||(this.threads.set(e.thread_id,i),t.threads.add(e.thread_id))}putScheduled(e,t){let s=this.scheduled.get(e.id);s&&e.version<=s.version||(e.state==="scheduled"?this.scheduled.set(e.id,e):this.scheduled.delete(e.id),t.scheduled=!0)}read(e,t,s){let i=os(),n=this.conversations.get(e),a=n?Math.min(t,n.me?.left_seq??n.last_seq):t;if(s!==void 0){let o=this.threads.get(s);return!o||a<=o.read_seq||(this.threads.set(s,this.threadReadTo(o,a)),i.threads.add(s)),i}return!n?.me||a<=n.me.read_seq||(this.conversations.set(e,{...n,me:this.readTo(n,n.me,a)}),i.list=!0,i.conversations.add(e)),i}readTo(e,t,s){let i=t.left_seq??e.last_seq;if(s>=i)return{...t,read_seq:s,unread_count:0};let n=Math.max(t.read_seq,t.cleared_seq,t.joined_seq),a=this.timeline(e.id).filter(o=>o.seq>n&&o.seq<=s&&o.sender_id!==this.reader&&o.kind!=="system"&&o.kind!=="call"&&!o.deleted).length;return{...t,read_seq:s,unread_count:Math.max(0,t.unread_count-a)}}threadReadTo(e,t){let s=this.answers(e.conversation_id,e.thread_id).filter(i=>i.seq>e.read_seq&&i.seq<=t&&i.sender_id!==this.reader&&!i.deleted).length;return{...e,read_seq:t,unread_count:Math.max(0,e.unread_count-s)}}expire(e,t){let s=this.messages.get(e)?.delete(t)??!1;return this.forgetLast(e,t)||s}forgetLast(e,t){let s=this.conversations.get(e);if(s?.last_message?.id!==t)return!1;let{last_message:i,...n}=s;return this.conversations.set(e,n),!0}list(){return[...this.conversations.values()].map(e=>this.withLast(e)).sort(fi)}holdsAll(e){let t=this.conversations.get(e),s=this.messages.get(e);if(!t||!s)return!1;let i=Math.max(t.me?.joined_seq??0,t.me?.cleared_seq??0),n=t.me?.left_seq??t.last_seq;if(n<=i)return!1;let a=new Set([...s.values()].map(o=>o.seq));for(let o=i+1;o<=n;o++)if(!a.has(o))return!1;return!0}withLast(e){let t=Math.max(e.me?.joined_seq??0,e.me?.cleared_seq??0),s=e.me?.left_seq??Number.POSITIVE_INFINITY,i=c=>c!=null&&c.seq>t&&c.seq<=s&&!(c.expires_at&&Date.parse(c.expires_at)<=Date.now()&&!c.deleted),n=i(e.last_message)?e.last_message:void 0,a;for(let c of this.messages.get(e.id)?.values()??[])(!c.thread_id||c.also_in_conversation)&&i(c)&&(!a||c.seq>a.seq)&&(a=c);a&&(!n||a.seq>=n.seq)&&(n=a);let o=n&&this.messages.get(e.id)?.get(n.id);if(o&&n&&o.version>n.version&&(n=o),n===e.last_message)return e;let{last_message:d,...l}=e;return n?{...l,last_message:n}:l}timeline(e){return[...this.messages.get(e)?.values()??[]].filter(t=>!t.thread_id||t.also_in_conversation).sort((t,s)=>t.seq-s.seq)}answers(e,t){return[...this.messages.get(e)?.values()??[]].filter(s=>s.thread_id===t).sort((s,i)=>s.seq-i.seq)}deletedGroups(e){for(let[t,s]of this.deleted)Date.parse(s.reportableUntil)<=e&&this.deleted.delete(t);return[...this.deleted.values()].sort((t,s)=>Date.parse(s.reportableUntil)-Date.parse(t.reportableUntil)||(t.id<s.id?-1:t.id>s.id?1:0))}membersOf(e){return[...this.members.get(e)?.values()??[]].sort((t,s)=>t.user_id<s.user_id?-1:t.user_id>s.user_id?1:0)}snapshot(){return{cursor:this.cursor,conversations:[...this.conversations.values()],members:[...this.members.values()].flatMap(e=>[...e.values()]),messages:[...this.messages.values()].flatMap(e=>[...e.values()]),threads:[...this.threads.values()],scheduled:[...this.scheduled.values()],deleted:[...this.deleted.values()]}}load(e){this.reset({conversations:e.conversations,members:e.members,messages:e.messages,threads:e.threads,scheduled:e.scheduled}),this.cursor=e.cursor,this.deleted.clear();for(let t of e.deleted??[])this.deleted.set(t.id,t)}};function hi(r,e){return r?e?r.version!==e.version?r.version>e.version:r.read_seq!==e.read_seq?r.read_seq>e.read_seq:r.unread_count!==e.unread_count||r.delivered_seq>e.delivered_seq:!0:!1}function pi(r,e){return r===null?e:e===null?r:Math.max(r,e)}function fi(r,e){let t=r.last_message_at??r.created_at,s=e.last_message_at??e.created_at;return t!==s?t<s?1:-1:r.id<e.id?1:-1}function ds(r){let{members:e,gap:t,...s}=r;return s}function gi(r,e){return JSON.stringify(r)===JSON.stringify(e)}var Te=class{store;outbox=new Re;me;now;constructor(e,t=Date.now){this.me=e,this.now=t,this.store=new Pe(e)}apply(e){return this.settled(e,this.store.apply(e))}reset(e){return this.settled(e,this.store.reset(e))}settled(e,t){for(let s of e.messages??[])this.outbox.settle(s,this.me)&&t.conversations.add(s.conversation_id);return t}write(e,t,s){return this.outbox.add(e,t,s)}read(e,t,s){let i=t??(s?Math.max(0,...this.store.answers(e,s).map(n=>n.seq)):this.store.conversations.get(e)?.last_seq??0);return{upTo:i,touched:this.store.read(e,i,s)}}sent(e){return e.kind==="sent"?this.apply({messages:[e.message]}):e.kind==="scheduled"?this.apply({scheduled:[e.scheduled]}):null}timeline(e){return this.entries(this.store.timeline(e),this.outbox.all(e).filter(t=>!t.request.thread_id||t.request.also_in_conversation))}answers(e,t){return this.entries(this.store.answers(e,t),this.outbox.all(e).filter(s=>s.request.thread_id===t))}entries(e,t){let s=new Set(e.filter(i=>i.sender_id===this.me&&i.client_message_id).map(i=>i.client_message_id));return[...e.map(i=>({kind:"message",message:i})),...t.filter(i=>!s.has(i.clientMessageId)&&!i.request.send_at).map(i=>({kind:"pending",item:i}))]}deletedGroups(){return this.store.deletedGroups(this.now())}kept(){return{store:this.store.snapshot(),outbox:this.outbox.save()}}load(e){this.store.load(e.store),this.outbox.load(e.outbox)}};function Ce(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("messaging: this platform has no WebCrypto to encrypt files with");return r}function mi(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function yi(r){let e=atob(r.replaceAll("-","+").replaceAll("_","/")+"=".repeat((4-r.length%4)%4)),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}async function ls(r){let e=crypto.getRandomValues(new Uint8Array(32)),t=crypto.getRandomValues(new Uint8Array(12));return{sealed:await vi(r,e,t),fileKey:mi(e)}}async function vi(r,e,t){let s=await Ce().importKey("raw",e,"AES-GCM",!1,["encrypt"]),i=new Uint8Array(await Ce().encrypt({name:"AES-GCM",iv:t},s,r)),n=new Uint8Array(1+t.length+i.length);return n[0]=1,n.set(t,1),n.set(i,1+t.length),n}async function cs(r,e){if(r.length<29||r[0]!==1)throw new Error("messaging: not a file this SDK sealed");let t=await Ce().importKey("raw",yi(e),"AES-GCM",!1,["decrypt"]);return new Uint8Array(await Ce().decrypt({name:"AES-GCM",iv:r.subarray(1,13)},t,r.subarray(13)))}function z(r,e){return`palbase.messaging.v1.${r}.${e}`}var xe=class{kv;constructor(e){this.kv=e}async open(e){let t=await this.kv.get(e);if(t===null)return null;try{let s=JSON.parse(t);return s.format===1?{store:s.store,outbox:s.outbox}:null}catch{return null}}async save(e,t){await this.kv.set(e,JSON.stringify({format:1,store:wi(t.store),outbox:t.outbox}))}async drop(e){await this.kv.delete(e)}async dropOthers(e,t){let s=z(e,""),i=z(e,t);for(let n of await this.kv.list())n.startsWith(s)&&n!==i&&await this.kv.delete(n)}};function wi(r){let e=new Map;for(let s of r.messages)e.set(s.conversation_id,[...e.get(s.conversation_id)??[],s]);let t=[...e.values()].flatMap(s=>s.sort((i,n)=>n.seq-i.seq).slice(0,200));return{...r,messages:t}}function us(){let r=new Map;return{async get(e){return r.get(e)??null},async set(e,t){r.set(e,t)},async delete(e){r.delete(e)},async list(){return[...r.keys()]},get keys(){return[...r.keys()]}}}var bi=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u,Si=/[\p{L}\p{Nd}\p{M}]/u,ki=/\p{M}/u,_i=/\p{Mn}/u;function Ri(r){let e=r.codePointAt(0);if(e===304||e===305||r==="I")return["i"];let t=[];for(let s of r.toLowerCase().normalize("NFD"))_i.test(s)||t.push(s);return t}function hs(r){let e=[],t=null,s=0,i=0,n=!1;for(let a of r){let o=a.length;if(!Si.test(a))t=null,n=!1;else if(bi.test(a))n||(i++,n=!0),e.push({start:s,folded:[a.toLowerCase()],ends:[s+o],run:i}),t=null;else if(ki.test(a)&&!t){let d=e.at(-1);n&&d&&(d.ends[0]=s+o)}else{n=!1,t||(t={start:s,folded:[],ends:[],run:0},e.push(t));let d=Ri(a);d.length===0&&t.ends.length>0&&(t.ends[t.ends.length-1]=s+o);for(let l of d)t.folded.push(l),t.ends.push(s+o)}s+=o}return e}function ps(r){let e=[],t=0;for(let s of r)s.run!==0&&(s.run!==t&&(e.push(""),t=s.run),e[e.length-1]+=s.folded.join(""));return e}function fs(r){let e={words:[],runs:[]},t=new Set,s=hs(r);for(let i of s){let n=i.folded.join("");if(n!==""&&!t.has(n)&&(t.add(n),e.words.push(i.folded)),e.words.length===8)break}return e.runs=ps(s).filter(i=>[...i].length>1),e}function Pi(r,e){return e.length===1?r.folded.length===1&&r.folded[0]===e[0]:r.folded.length>=e.length&&e.every((t,s)=>r.folded[s]===t)}function gs(r,...e){let t=r.words.map(()=>!1),s=[],i=e.map(n=>{let a=hs(n);return s.push(...ps(a)),a.flatMap(o=>{let d=0;return r.words.forEach((l,c)=>{Pi(o,l)&&(t[c]=!0,d=Math.max(d,l.length))}),d>0?[{offset:o.start,length:o.ends[d-1]-o.start}]:[]})});return r.runs.every(n=>s.some(a=>a.includes(n)))&&r.words.length>0&&t.every(Boolean)?i:null}var Ti=500,Ci=300,xi=2e3,ms=6e3,Mi=3e4,ys=[1e3,2e3,5e3,1e4,3e4],Ii=5*6e4,Oi=20,Ai=5,et=class{conversationId;messages=new Map;earlier=null;later=null;merged=!1;constructor(e){this.conversationId=e}put(e){for(let t of e){let s=this.messages.get(t.id);(!s||t.version>s.version)&&this.messages.set(t.id,t)}}apply(e){let t=!1;for(let s of e.messages??[]){let i=this.messages.get(s.id);i&&s.version>i.version&&(this.messages.set(s.id,s),t=!0)}for(let s of e.hidden??[])this.messages.delete(s.message_id)&&(t=!0);return((e.removed_conversations??[]).some(s=>s.conversation_id===this.conversationId)||(e.conversations??[]).some(s=>s.id===this.conversationId&&s.deleted))&&(this.messages.clear(),t=!0),t}expire(e){return this.messages.delete(e)}entries(){return[...this.messages.values()].filter(e=>!e.thread_id||e.also_in_conversation).sort((e,t)=>e.seq-t.seq).map(e=>({kind:"message",message:e}))}};function Ei(r="palbase.messaging"){let e=globalThis.indexedDB;if(!e)return null;let t=null,s=()=>t??=new Promise((n,a)=>{let o=e.open(r,1);o.onupgradeneeded=()=>o.result.createObjectStore("kv"),o.onsuccess=()=>n(o.result),o.onerror=()=>a(o.error)}),i=(n,a)=>s().then(o=>new Promise((d,l)=>{let c=a(o.transaction("kv",n).objectStore("kv"));c.onsuccess=()=>d(c.result),c.onerror=()=>l(c.error)}));return{get:async n=>await i("readonly",a=>a.get(n))??null,set:async(n,a)=>{await i("readwrite",o=>o.put(a,n))},delete:async n=>{await i("readwrite",a=>a.delete(n))},list:async()=>(await i("readonly",n=>n.getAllKeys())).map(String)}}var Me=class{api;local;transportFor;clients=new WeakMap;user=null;engine=null;starting=null;channel=null;off=[];heard=new Set;synced=!1;syncing=null;resync=!1;flushing=null;reflush=!1;retries=0;timers={save:void 0,deliver:void 0,retry:void 0,presence:void 0,reportable:void 0};delivered=new Map;expiring=new Map;typingTimers=new Map;typingBy=new Map;typedAt=new Map;loaded=new Set;earlier=new Map;saving=Promise.resolve();reopeners=new Set;incoming=new Set;windows=new Set;people=new Map;session;socket;ref;fetchFn;opts;constructor(e,t,s,i,n,a,o={}){this.transportFor=t,this.session=s,this.socket=i,this.ref=n,this.fetchFn=a,this.opts=o,this.api=qe.client(e),this.local=new xe(o.storage??Ei()??us()),s.onChange((l,c)=>{l==="SIGNED_OUT"||l==="SESSION_EXPIRED"?this.end():l==="SIGNED_IN"&&c?.userId!==this.user?this.end().then(async()=>{if(this.heard.size!==0){await this.ready();for(let h of[...this.reopeners])h()}}):l==="SIGNED_IN"&&this.engine&&this.user&&(this.unfollow(),this.follow(this.user),this.sync())});let d=globalThis;d.addEventListener?.("online",()=>this.wake()),d.document?.addEventListener?.("visibilitychange",()=>{d.document?.visibilityState==="visible"&&this.wake()})}async ready(){let e=this.session.snapshot()??await this.session.session();if(!e)throw new b({op:"messaging",status:401,code:"not_signed_in",message:"messaging is the signed-in person's: sign in first"});if(this.engine&&this.user===e.userId)return this.engine;if(this.starting&&this.user===e.userId)return this.starting;this.user=e.userId;let t=e.userId;return this.starting=(async()=>{let s=new Te(t);this.clients.set(s,qe.client(this.transportFor(t)));let i=await this.local.open(z(this.ref,t));if(this.user!==t)throw new Error("messaging: the session changed while it started");i&&s.load(i),this.engine=s;for(let n of s.store.messages.values())for(let a of n.values())this.expireAt(a);return this.expireDeleted(s),this.tell({list:!0,conversations:new Set(s.store.conversations.keys()),threads:new Set,scheduled:!0}),this.follow(t),this.opts.keepOnSignOut||this.local.dropOthers(this.ref,t).catch(()=>{}),this.sync().then(()=>this.flush()),this.presence(s),s})(),this.starting.catch(()=>{this.user===t&&(this.starting=null)}),this.starting}async end(){let e=this.user,t=this.engine;this.unfollow();for(let[s,i]of Object.entries(this.timers))i&&clearTimeout(i),this.timers[s]=void 0;for(let s of this.expiring.values())clearTimeout(s);this.expiring.clear();for(let s of this.typingTimers.values())clearTimeout(s);this.typingTimers.clear(),this.typingBy.clear(),this.delivered.clear(),this.loaded.clear(),this.earlier.clear();for(let s of this.windows)s.merged=!0;if(this.windows.clear(),this.people.clear(),this.engine=null,this.starting=null,this.user=null,this.synced=!1,e){let s=z(this.ref,e);await this.saving,this.opts.keepOnSignOut&&t?await this.local.save(s,t.kept()):await this.local.drop(s)}this.tell({list:!0,conversations:new Set,threads:new Set,scheduled:!0})}unfollow(){for(let e of this.off.splice(0))e();this.channel?.leave(),this.channel=null}follow(e){let t=this.socket.channel(`messaging:${this.ref}:${e}`);this.channel=t,this.off.push(t.on("broadcast",s=>{this.user===e&&(s.event==="changes"?this.heardLive(s.payload):s.event==="typing"&&this.typed(s.payload))}),t.onJoined(()=>{this.sync()})),t.join().catch(()=>{})}wake(){this.engine&&this.sync().then(()=>this.flush())}sync(){return this.syncing?(this.resync=!0,this.syncing):(this.syncing=(async()=>{try{do{this.resync=!1;let e=this.engine;if(!e)return;let t=(await this.as(e).sync({query:e.store.cursor?{since:e.store.cursor}:{}})).data;if(this.engine!==e)return;let s=t.reset?e.reset(t):e.apply(t);this.toWindows(t,s);let i=t.reset?[...this.loaded]:t.conversations.filter(n=>n.gap&&this.loaded.has(n.id)).map(n=>n.id);t.reset&&this.loaded.clear();for(let n of i)this.loaded.delete(n),this.earlier.delete(n);e.store.cursor=t.cursor,this.after(t,s);for(let n of i)this.openPage(n).catch(()=>{});this.synced||(s.list=!0),this.synced=!0,this.tell(s)}while(this.resync)}finally{this.syncing=null}})(),this.syncing)}onIncoming(e){return this.incoming.add(e),()=>{this.incoming.delete(e)}}heardLive(e){let t=this.engine;if(!t)return;let s=(e.messages??[]).filter(i=>i.version===1&&i.sender_id!==t.me&&!i.deleted&&i.kind!=="system"&&i.kind!=="call"&&!t.store.messages.get(i.conversation_id)?.has(i.id));this.changed(e,t);for(let i of s)for(let n of[...this.incoming])n(i)}changed(e,t=this.engine){if(!t||t!==this.engine)return;let s=t.apply(e);this.toWindows(e,s),this.after(e,s),this.tell(s)}toWindows(e,t){for(let s of this.windows)s.apply(e)&&t.conversations.add(s.conversationId)}putWindow(e,t){e.put(t);for(let s of t)this.expireAt(s)}fromWindows(e,t){let s=!1;for(let i of this.windows)i.conversationId===e&&t(i)&&(s=!0);return s}after(e,t){for(let s of e.messages??[])this.expireAt(s),s.sender_id!==this.user&&!s.deleted&&(s.thread_id===null||s.also_in_conversation)&&this.delivered.set(s.conversation_id,Math.max(this.delivered.get(s.conversation_id)??0,s.seq));e.removed_conversations?.some(s=>s.reportable_until)&&this.engine&&this.expireDeleted(this.engine),this.delivered.size>0&&(this.timers.deliver??=setTimeout(()=>{this.deliver()},Ti)),(t.list||t.conversations.size>0||t.threads.size>0||t.scheduled)&&this.save()}expireAt(e){let t=e.id,s=this.expiring.get(t);if(s&&clearTimeout(s),this.expiring.delete(t),!e.expires_at||e.deleted)return;let i=Date.parse(e.expires_at)-Date.now(),n=()=>{this.expiring.delete(t);let a=this.engine?.store.expire(e.conversation_id,e.id)??!1;(this.fromWindows(e.conversation_id,o=>o.expire(e.id))||a)&&(this.tell({list:!0,conversations:new Set([e.conversation_id]),threads:new Set(e.thread_id?[e.thread_id]:[]),scheduled:!1}),this.save())};i<=0?n():this.expiring.set(t,setTimeout(n,Math.min(i,2**31-1)))}expireDeleted(e){clearTimeout(this.timers.reportable),this.timers.reportable=void 0;let t=Math.min(...e.deletedGroups().map(s=>Date.parse(s.reportableUntil)));Number.isFinite(t)&&(this.timers.reportable=setTimeout(()=>{this.timers.reportable=void 0,this.engine===e&&(this.tell({list:!0,conversations:new Set,threads:new Set,scheduled:!1}),this.save(),this.expireDeleted(e))},Math.min(Math.max(0,t-Date.now()),2**31-1)))}async deliver(){this.timers.deliver=void 0;let e=[...this.delivered].map(([t,s])=>({conversation_id:t,delivered_seq:s}));if(this.delivered.clear(),!(e.length===0||!this.engine))try{await this.as(this.engine).receipts({body:{receipts:e.slice(0,100)}})}catch{}}save(){this.timers.save??=setTimeout(()=>{this.timers.save=void 0;let e=this.engine,t=this.user;e&&t&&(this.saving=this.saving.then(()=>this.local.save(z(this.ref,t),e.kept())).catch(()=>{}))},Ci)}flush(){return this.flushing?(this.reflush=!0,this.flushing):(clearTimeout(this.timers.retry),this.timers.retry=void 0,this.flushing=(async()=>{try{let e=!1;do{this.reflush=!1;let t=this.engine;if(!t)return;let s=this.as(t);if(e=await t.outbox.flush(i=>this.post(s,i),(i,n)=>{let a=t.sent(n)??{list:!1,conversations:new Set([i.conversationId]),threads:new Set,scheduled:!1};a.conversations.add(i.conversationId),n.kind==="sent"&&this.after({messages:[n.message]},a),this.save(),this.tell(a)}),this.engine!==t)return}while(this.reflush&&!e);if(e){let t=ys[Math.min(this.retries++,ys.length-1)];this.timers.retry=setTimeout(()=>{this.flush()},t)}else this.retries=0}finally{this.flushing=null}})(),this.flushing)}async post(e,t){try{let s=await e.sendMessage({path:{conversation_id:t.conversationId},body:t.request});return Ze(s.status,s.data)}catch(s){return s instanceof b?s.isNetworkError?{kind:"wait"}:Ze(s.status,{error:s.code}):{kind:"wait"}}}presence(e){let t=()=>{if(this.engine!==e)return;let s=globalThis.document;(!s||s.visibilityState!=="hidden")&&this.as(e).presence().catch(()=>{}),this.timers.presence=setTimeout(t,Mi)};t()}as(e){return this.clients.get(e)}async seat(){let e=await this.ready();return{e,as:this.as(e)}}typed(e){let t=this.typingBy.get(e.conversation_id);t||this.typingBy.set(e.conversation_id,t=new Map),t.set(e.user_id,Date.now()+ms),this.tell({list:!1,conversations:new Set([e.conversation_id]),threads:new Set,scheduled:!1});let s=`${e.conversation_id}\0${e.user_id}`,i=this.typingTimers.get(s);i&&clearTimeout(i);let n=setTimeout(()=>{this.typingTimers.delete(s),this.engine&&this.tell({list:!1,conversations:new Set([e.conversation_id]),threads:new Set,scheduled:!1})},ms+50);this.typingTimers.set(s,n)}tell(e){for(let t of[...this.heard])t(e)}listen(e){return this.heard.add(e),this.ready().catch(()=>{}),()=>{this.heard.delete(e)}}onPerson(e){return this.reopeners.add(e),()=>{this.reopeners.delete(e)}}current(){return this.engine}typingIn(e){let t=Date.now();return[...this.typingBy.get(e)??[]].filter(([s,i])=>i>t&&s!==this.user).map(([s])=>s)}touch(e){this.tell({list:!1,conversations:new Set([e]),threads:new Set,scheduled:!1})}isSynced(){return this.synced}conversations(e={}){return new tt(this,e.spaces??[])}deletedGroups(){return new st(this)}conversation(e,t={}){return new it(this,e,t.at??null)}async direct(e,t={}){let{e:s,as:i}=await this.seat(),n=(await i.openDirectConversation({body:{user_id:e,space:t.space}})).data;return this.changed({conversations:[n]},s),this.conversation(n.id)}async group(e){let{e:t,as:s}=await this.seat(),i=(await s.createGroup({body:{title:e.title,member_ids:e.memberIds,description:e.description,photo:e.photo,settings:e.settings,space:e.space,visibility:e.visibility}})).data;return this.changed({conversations:[i.conversation]},t),{conversation:this.conversation(i.conversation.id),notAdded:i.not_added}}thread(e,t,s={}){return new nt(this,e,t,s.at??null)}async search(e,t={}){let s=fs(e);if(s.words.length===0)return{conversations:[],messages:[],nextCursor:null};let i=t.by==="meaning",{e:n,as:a}=await this.seat(),o=async()=>{let f=t.cursor;for(let u=0;;u++){let g={q:e,...i?{by:"meaning"}:{},conversation_id:t.conversationId,...t.space?{space:[t.space]}:{},limit:t.limit,cursor:f},y=(await a.searchMessages({query:g})).data;if(i||y.data.length>0||!y.next_cursor||u+1===Ai)return y;f=y.next_cursor}},[d,l]=await Promise.all([o(),i||t.cursor||t.conversationId?Promise.resolve([]):this.named(s,n,t.space)]),c=Date.now();for(let f of d.profiles)this.people.set(f.user_id,{profile:f,at:c});let h=f=>f?this.people.get(f)?.profile??null:null,p=new Map(d.conversations.map(f=>[f.id,f])),v=d.data.flatMap(f=>{let u=p.get(f.message.conversation_id)??n.store.conversations.get(f.message.conversation_id);if(!u)return[];let g=u.kind==="direct"?h(u.peer_id):null;return[{message:f.message,conversation:u,title:u.kind==="direct"?g?.name??null:u.title,photo:u.kind==="direct"?g?.image??null:u.photo,sender:h(f.message.sender_id),peer:g,matches:f.matches,score:f.score??null,threadRootId:f.message.thread_id&&!f.message.also_in_conversation?f.message.thread_id:null}]});return{conversations:l,messages:v,nextCursor:i?null:d.next_cursor??null}}async named(e,t,s){let i=t.store.list().filter(a=>!s||a.space===s),n=[...new Set(i.filter(a=>a.kind==="direct"&&a.peer_id).map(a=>a.peer_id))].filter(a=>{let o=this.people.get(a);return!o||Date.now()-o.at>Ii});for(let a=0;a<n.length;a+=100){let o=n.slice(a,a+100);try{let d=(await this.as(t).getProfiles({query:{user_ids:o.join(",")}})).data.data,l=Date.now();for(let c of o)this.people.set(c,{profile:d.find(h=>h.user_id===c)??null,at:l})}catch{}}return i.flatMap(a=>{let o=a.kind==="direct"&&a.peer_id?this.people.get(a.peer_id)?.profile??null:null,d=a.kind==="direct"?o?.name??null:a.title,l=d?gs(e,d):null;return l?[{conversation:a,title:d,photo:a.kind==="direct"?o?.image??null:a.photo,peer:o,matches:l[0]}]:[]})}async openGroups(e,t={}){let{as:s}=await this.seat(),i=(await s.listOpenGroups({query:{space:e,limit:t.limit,cursor:t.cursor}})).data;return{items:i.data,nextCursor:i.next_cursor??null}}async join(e){let{e:t,as:s}=await this.seat(),i=(await s.joinGroup({path:{conversation_id:e}})).data;return this.changed({conversations:[i]},t),this.conversation(i.id)}scheduled(){return new rt(this)}async threads(){let{as:e}=await this.seat();return(await e.listThreads()).data.data}async send(e,t){let{e:s}=await this.seat(),i=typeof t=="string"?{text:t}:t,n=i.files?.length?await this.upload(e,i.files):void 0,a={client_message_id:crypto.randomUUID(),...i.text!==void 0?{text:i.text}:{},...i.mentions?{mentions:i.mentions}:{},...n?{attachments:n}:{},...i.replyTo?{reply_to_id:i.replyTo}:{},...i.threadId?{thread_id:i.threadId}:{},...i.alsoInConversation?{also_in_conversation:!0}:{},...i.expiresIn!==void 0?{expires_in:i.expiresIn,expires_from:i.expiresFrom??"send"}:{},...i.viewOnce?{view_once:{limit:i.viewOnce.limit,...i.viewOnce.seconds?{seconds:i.viewOnce.seconds}:{}}}:{},...i.sendAt?{send_at:i.sendAt.toISOString()}:{}};if(s!==this.engine)throw new P(`the session is no longer ${s.me}'s`);let o=s.write(e,a,new Date().toISOString());return this.tell({list:!1,conversations:new Set([e]),threads:new Set(i.threadId?[i.threadId]:[]),scheduled:!1}),this.save(),this.flush(),o}async upload(e,t){let{as:s}=await this.seat(),i=[];for(let n of t){let a=n.data instanceof Uint8Array?n.data:new Uint8Array(await n.data.arrayBuffer()),{sealed:o,fileKey:d}=await ls(a),l=(await s.createUpload({path:{conversation_id:e},body:{size:o.length}})).data,c=await this.fetchFn(l.url,{method:"PUT",body:o,headers:{"content-type":"application/octet-stream"}});if(!c.ok)throw new b({op:"UploadFile",status:c.status,code:"upload_failed",message:`the file was not uploaded (${c.status})`});i.push({upload_id:l.id,content_type:n.contentType,file_key:d,...n.name?{name:n.name}:{},...n.width?{width:n.width}:{},...n.height?{height:n.height}:{},...n.durationMs?{duration_ms:n.durationMs}:{},...n.thumbnail?{thumbnail:n.thumbnail}:{}})}return i}async open(e,t){let{as:s}=await this.seat(),i=e.attachments.find(a=>a.id===t);if(!i?.file_key)throw new b({op:"OpenFile",status:404,code:"attachment_not_found",message:"no such file of the message, or one seen once"});let n=(await s.attachmentUrl({path:{conversation_id:e.conversation_id,message_id:e.id,attachment_id:i.id}})).data;return{id:i.id,name:i.name,contentType:i.content_type,bytes:await this.bytes(n.url,i.file_key)}}async viewOnce(e){let{as:t}=await this.seat(),s=(await t.viewOnce({path:{conversation_id:e.conversation_id,message_id:e.id}})).data;return Promise.all(s.attachments.map(async i=>({id:i.id,name:null,contentType:i.content_type,bytes:await this.bytes(i.url,i.file_key)})))}async bytes(e,t){let s=await this.fetchFn(e);if(!s.ok)throw new b({op:"OpenFile",status:s.status,code:"download_failed",message:`the file was not read (${s.status})`});return cs(new Uint8Array(await s.arrayBuffer()),t)}async edit(e,t,s,i){let{e:n,as:a}=await this.seat(),o=(await a.editMessage({path:{conversation_id:e,message_id:t},body:{text:s,...i?{mentions:i}:{}}})).data;return this.changed({messages:[o]},n),o}async remove(e,t,s="everyone"){let{e:i,as:n}=await this.seat(),a=await n.deleteMessage({path:{conversation_id:e,message_id:t},query:{for:s}});a.status===200?this.changed({messages:[a.data]},i):this.changed({hidden:[{conversation_id:e,message_id:t}]},i)}async react(e,t,s,i={}){let{e:n,as:a}=await this.seat(),o=(await a.react({path:{conversation_id:e,message_id:t,emoji:s},body:i.replace?{replace:!0}:{}})).data;return this.changed({messages:[o]},n),o}async unreact(e,t,s){let{e:i,as:n}=await this.seat(),a=(await n.unreact({path:{conversation_id:e,message_id:t,emoji:s}})).data;return this.changed({messages:[a]},i),a}async markRead(e,t,s){let{e:i,as:n}=await this.seat(),{upTo:a,touched:o}=i.read(e,t,s);a<=0||((o.list||o.conversations.size>0||o.threads.size>0)&&(this.tell(o),this.save()),await n.receipts({body:{receipts:[{conversation_id:e,read_seq:a,...s?{thread_id:s}:{}}]}}))}async typing(e,t){let{as:s}=await this.seat(),i=this.typedAt.get(e)??0;Date.now()-i<xi||(this.typedAt.set(e,Date.now()),await s.typing({path:{conversation_id:e},body:t?{thread_id:t}:{}}).catch(()=>{}))}async update(e,t){let{e:s,as:i}=await this.seat(),n=(await i.updateConversation({path:{conversation_id:e},body:t})).data;return this.changed({conversations:[n]},s),n}async close(e){let{e:t,as:s}=await this.seat();if(await s.closeConversation({path:{conversation_id:e}}),t!==this.engine)return;let i=t.store.conversations.get(e)?.me,n=d=>d.vanish&&d.sender_id!==t.me&&i&&d.seq<=i.read_seq,a=t.store.timeline(e).filter(n);for(let d of a)t.store.expire(e,d.id);let o=this.fromWindows(e,d=>[...d.messages.values()].filter(n).map(l=>d.expire(l.id)).includes(!0));(a.length>0||o)&&(this.tell({list:!0,conversations:new Set([e]),threads:new Set,scheduled:!1}),this.save())}async screenshot(e){let{e:t,as:s}=await this.seat(),i=(await s.reportScreenshot({path:{conversation_id:e}})).data;return this.changed({messages:[i]},t),i}async leave(e){let{e:t,as:s}=await this.seat();await s.removeMember({path:{conversation_id:e,user_id:t.me}}),this.sync()}async deleteConversation(e){let{e:t,as:s}=await this.seat();await s.deleteConversation({path:{conversation_id:e}}),this.changed({removed_conversations:[{conversation_id:e,reason:"deleted"}]},t)}async notifications(e,t){let{as:s}=await this.seat();await s.setConversationNotifications({path:{conversation_id:e},body:t}),this.sync()}async cancelScheduled(e){let{e:t,as:s}=await this.seat();await s.cancelScheduled({path:{scheduled_id:e}}),t===this.engine&&t.store.scheduled.delete(e)&&(this.tell({list:!1,conversations:new Set,threads:new Set,scheduled:!0}),this.save())}async editScheduled(e,t){let{e:s,as:i}=await this.seat(),n=(await i.updateScheduled({path:{scheduled_id:e},body:t})).data;return this.changed({scheduled:[n]},s),n}async me(){let{as:e}=await this.seat();return(await e.getMyProfile()).data}async updateMe(e){let{as:t}=await this.seat(),s=(await t.updateMyProfile({body:e})).data;return e.read_receipts!==void 0&&this.sync(),s}async profiles(e){let{as:t}=await this.seat();return(await t.getProfiles({query:{user_ids:e.join(",")}})).data.data}async block(e){let{as:t}=await this.seat();await t.block({path:{user_id:e}})}async unblock(e){let{as:t}=await this.seat();await t.unblock({path:{user_id:e}})}async report(e){let{as:t}=await this.seat();return(await t.report({body:e})).data}async openPage(e){let{e:t}=await this.seat();if(!this.loaded.has(e)){if(this.loaded.add(e),t.store.timeline(e).length>0&&this.synced){t.store.holdsAll(e)&&(this.earlier.set(e,null),this.tellConversation(e));return}await this.page(e,null)}}async page(e,t){let{e:s,as:i}=await this.seat(),n=(await i.listMessages({path:{conversation_id:e},query:t?{cursor:t,limit:50}:{limit:50}})).data;return s!==this.engine?!1:(this.earlier.set(e,n.next_cursor??null),this.changed({messages:n.data},s),this.tellConversation(e),!!n.next_cursor)}tellConversation(e){this.tell({list:!1,conversations:new Set([e]),threads:new Set,scheduled:!1})}earlierOf(e){return this.earlier.get(e)}async openAt(e,t){let{e:s,as:i}=await this.seat(),n=s.store.messages.get(e)?.get(t),a=this.earlier.get(e);if(n&&a!==void 0&&(a===null||parseInt(a,36)<=n.seq))return null;let o=(await i.listMessages({path:{conversation_id:e},query:{around:t,limit:50}})).data;if(s!==this.engine)return null;let d=new et(e);return this.putWindow(d,o.data),d.earlier=o.next_cursor??null,d.later=o.newer_cursor??null,d.later===null?(this.merge(d,s),null):(this.windows.add(d),d)}async windowPage(e,t){let{e:s,as:i}=await this.seat(),n=t==="earlier"?e.earlier:e.later;if(n===null||e.merged)return;let a=t==="earlier"?{cursor:n,limit:50}:{after:n,limit:50},o=(await i.listMessages({path:{conversation_id:e.conversationId},query:a})).data;s!==this.engine||e.merged||(this.putWindow(e,o.data),t==="earlier"?e.earlier=o.next_cursor??null:e.later=o.newer_cursor??null,e.later===null?this.merge(e,s):this.tell({list:!1,conversations:new Set([e.conversationId]),threads:new Set,scheduled:!1}))}dropWindow(e){e.merged=!0,this.windows.delete(e)}merge(e,t){this.dropWindow(e);let s=e.conversationId,i=this.earlier.get(s),n=i===void 0||i!==null&&(e.earlier===null||parseInt(e.earlier,36)<parseInt(i,36))?e.earlier:i;this.earlier.set(s,n),this.loaded.add(s),this.changed({messages:[...e.messages.values()]},t),this.tell({list:!1,conversations:new Set([s]),threads:new Set,scheduled:!1})}async openThread(e,t,s=null){let{e:i,as:n}=await this.seat(),a=(await n.getMessage({path:{conversation_id:e,message_id:t}})).data,o=[],d;for(let l=0;l<Oi;l++){let c=(await n.listReplies({path:{conversation_id:e,message_id:t},query:d?{limit:100,cursor:d}:{limit:100}})).data;if(o.push(...c.data),d=c.next_cursor,!d||!s||o.some(h=>h.id===s))break}this.changed({messages:[a,...o]},i)}async openScheduled(){let{e,as:t}=await this.seat();this.changed({scheduled:(await t.listScheduled()).data.data},e)}},V=class{listeners=new Set;unlisten=null;unperson=null;cached=null;m;constructor(e){this.m=e}get state(){return this.unlisten?this.cached??=this.read():this.read()}subscribe(e){return this.listeners.add(e),this.unlisten||(this.cached=null,this.unlisten=this.m.listen(t=>{if(this.touches(t)){this.cached=this.read();for(let s of[...this.listeners])s()}}),this.unperson=this.m.onPerson(()=>{this.cached=null,this.opened();for(let t of[...this.listeners])t()}),this.opened()),()=>{this.listeners.delete(e),this.listeners.size===0&&(this.unlisten?.(),this.unperson?.(),this.unlisten=null,this.unperson=null,this.closed())}}opened(){}closed(){}},tt=class extends V{spaces;constructor(e,t=[]){super(e),this.spaces=[...t]}touches(e){return e.list||e.conversations.size>0}read(){let e=this.m.current()?.store.list()??[],t=this.spaces.length===0?e:e.filter(s=>s.space!=null&&this.spaces.includes(s.space));return{items:t,unread:t.reduce((s,i)=>s+(i.me?.unread_count??0),0),synced:this.m.isSynced()}}},st=class extends V{touches(e){return e.list}read(){return{items:this.m.current()?.deletedGroups()??[]}}},it=class extends V{id;focus;window=null;opening=null;settled=!1;constructor(e,t,s=null){super(e),this.id=t,this.focus=s}opened(){if(!this.focus){this.m.openPage(this.id).catch(()=>{});return}this.window&&this.m.dropWindow(this.window),this.window=null,this.settled=!1,this.opening=this.m.openAt(this.id,this.focus).then(e=>{this.window=e,e||this.m.openPage(this.id).catch(()=>{})}).catch(()=>{this.m.openPage(this.id).catch(()=>{})}).finally(()=>{this.settled=!0,this.m.touch(this.id)})}closed(){this.window&&this.m.dropWindow(this.window),this.window=null}touches(e){return e.conversations.has(this.id)}stretch(){return this.window?.merged&&(this.window=null),this.window}read(){let e=this.m.current(),t=this.stretch(),s=this.focus!==null&&!this.settled;return{conversation:e?.store.conversations.get(this.id)??null,entries:s?[]:t?t.entries():e?.timeline(this.id)??[],members:e?.store.membersOf(this.id)??[],typing:this.m.typingIn(this.id),hasEarlier:t?t.earlier!==null:this.m.earlierOf(this.id)!==null,hasLater:t!==null,focus:this.focus}}refresh(){return this.m.page(this.id,null)}async loadEarlier(){await this.opening;let e=this.stretch();if(e)return await this.m.windowPage(e,"earlier"),e.earlier!==null;let t=this.m.earlierOf(this.id);return t===null?!1:this.m.page(this.id,t??null)}async loadLater(){await this.opening;let e=this.stretch();return e?(await this.m.windowPage(e,"later"),this.stretch()!==null):!1}showLatest(){this.window&&(this.m.dropWindow(this.window),this.window=null,this.m.openPage(this.id).catch(()=>{}),this.m.touch(this.id))}send(e){return this.m.send(this.id,e)}markRead(e){return this.m.markRead(this.id,e)}typing(){return this.m.typing(this.id)}thread(e){return this.m.thread(this.id,e)}},nt=class extends V{conversationId;rootId;focus;constructor(e,t,s,i=null){super(e),this.conversationId=t,this.rootId=s,this.focus=i}opened(){this.m.openThread(this.conversationId,this.rootId,this.focus).catch(()=>{})}touches(e){return e.threads.has(this.rootId)||e.conversations.has(this.conversationId)}read(){let e=this.m.current();return{root:e?.store.messages.get(this.conversationId)?.get(this.rootId)??null,entries:e?.answers(this.conversationId,this.rootId)??[],thread:e?.store.threads.get(this.rootId)??null,focus:this.focus}}send(e){let t=typeof e=="string"?{text:e}:e;return this.m.send(this.conversationId,{...t,threadId:this.rootId})}markRead(){return this.m.markRead(this.conversationId,void 0,this.rootId)}},rt=class extends V{opened(){this.m.openScheduled().catch(()=>{})}touches(e){return e.scheduled}read(){return[...this.m.current()?.store.scheduled.values()??[]].sort((e,t)=>e.send_at<t.send_at?-1:1)}};var vs=async r=>Li(await import("livekit-client"))(r);function Li(r){return async e=>{let t=new r.Room({adaptiveStream:!1,dynacast:!0,stopLocalTrackOnUnpublish:!1}),s=()=>t.localParticipant,i={microphone:r.Track.Source.Microphone,camera:r.Track.Source.Camera,screen:r.Track.Source.ScreenShare,screen_audio:r.Track.Source.ScreenShareAudio},n=(d,l)=>l.source===r.Track.Source.ScreenShare?"screen":l.source===r.Track.Source.ScreenShareAudio?"screen_audio":d.kind==="video"?"camera":"microphone",a=!1;t.on(r.RoomEvent.TrackSubscribed,(d,l,c)=>e.track(c.identity,d.mediaStreamTrack,n(d,l))).on(r.RoomEvent.TrackUnsubscribed,(d,l,c)=>e.trackGone(c.identity,d.mediaStreamTrack)).on(r.RoomEvent.TrackMuted,(d,l)=>{l!==s()&&d.track&&e.muted(l.identity,d.track.mediaStreamTrack,!0)}).on(r.RoomEvent.TrackUnmuted,(d,l)=>{l!==s()&&d.track&&e.muted(l.identity,d.track.mediaStreamTrack,!1)}).on(r.RoomEvent.Reconnecting,()=>e.state("reconnecting")).on(r.RoomEvent.Reconnected,()=>e.state("connected")).on(r.RoomEvent.ActiveSpeakersChanged,d=>e.speakers(d.map(l=>l.identity))).on(r.RoomEvent.Disconnected,()=>{a||e.state("disconnected")});let o=new Map;return{async connect(d,l){await t.connect(d,l),e.state("connected")},async publish(d,l){o.set(d,await s().publishTrack(d,{source:i[l]}))},async unpublish(d){o.delete(d),await s().unpublishTrack(d,!1)},async mute(d,l){let c=o.get(d);c&&await(l?c.mute():c.unmute())},async close(){a=!0,await t.disconnect()}}}}var Di=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,at=class extends b{call;constructor(e,t){super({op:e.op,status:e.status,code:e.code,message:e.message,requestId:e.requestId,retryAfter:e.retryAfter,body:e.body,cause:e}),this.name="PlaceBusyError",this.call=t}},ot=class{id;c;call;snapshot;listeners=new Set;owned=!1;entering=!1;phase="incoming";endReason=null;error=null;local=null;tracks={audio:null,video:null};opened=new Set;mic=!0;facing="user";shared=null;sharing=null;room=null;joiningRoom=null;roomState=null;streams=new Map;screens=new Map;owners=new Map;speakers=new Set;mutedInRoom=new Set;players=new Map;sink=null;quieted=!1;heartbeat;poll;done=!1;constructor(e,t,s=!1){this.c=e,this.id=t.id,this.call=t,this.entering=s,this.derive()}get state(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async accept(e={}){if(this.phase!=="incoming"&&this.phase!=="invited")throw this.refused("accept","not_ringing","the call does not ring here now");await this.enter(e,t=>this.c.api.acceptCall({path:{call_id:this.id},body:t}))}async join(e={}){if(this.owned&&!this.done)return;if(this.done)throw this.refused("join","call_ended","this session is over: pb.calls.join(callId) comes into the call again");let t={...e.name===void 0?{}:{name:e.name},...e.imageUrl===void 0?{}:{image_url:e.imageUrl}};await this.enter(e,s=>this.c.api.joinCall({path:{call_id:this.id},body:{...s,...t}}))}async decline(){let e=await this.c.api.declineCall({path:{call_id:this.id}}).catch(t=>this.refusal(t));this.apply(e.data)}async leave(){try{let e=await this.c.api.leaveCall({path:{call_id:this.id}});this.apply(e.data)}finally{!this.done&&this.owned&&this.end("left")}}async invite(e,t={}){let s=typeof e=="string"?[e]:e,i=await this.c.api.inviteToCall({path:{call_id:this.id},body:{user_ids:s,...t.ring===void 0?{}:{ring:t.ring}}});this.apply(i.data)}async setMicrophone(e){this.mic=e;let t=this.tracks.audio;t&&(t.enabled=e),this.changed(),t&&this.room&&await this.room.mute(t,!e)}async setCamera(e){if(!e){if(!this.tracks.video)return;await this.putVideo(null);return}this.tracks.video||await this.putVideo(await this.camera({facingMode:this.facing}))}async switchCamera(e){e===void 0&&(this.facing=this.facing==="user"?"environment":"user"),await this.putVideo(await this.camera(e===void 0?{facingMode:this.facing}:{deviceId:{exact:e}}))}async setScreenShare(e,t={}){if(!e){await this.sharing?.catch(()=>{}),await this.putScreen(null);return}if(this.shared)return;if(this.sharing)return this.sharing;if(!this.inCall)throw this.refused("setScreenShare","not_in_call","a screen is shared in a call this device is in");let s=this.c.rtc(),i=s.getDisplayMedia?.bind(s);if(!i)throw new TypeError("calls: this browser shares no screen (getDisplayMedia)");return this.sharing=(async()=>{let n=await i({video:!0,audio:t.audio===!0}),a=n.getVideoTracks()[0],o=t.audio===!0?n.getAudioTracks()[0]??null:null;for(let d of n.getTracks())d!==a&&d!==o&&d.stop();if(!a||this.done){for(let d of n.getTracks())d.stop();if(!a)throw new Error("calls: the screen gave no video");return}this.opened.add(a),o&&this.opened.add(o),a.addEventListener?.("ended",()=>{this.shared?.video===a&&this.putScreen(null).catch(()=>{})}),await this.putScreen({video:a,audio:o,stream:new s.MediaStream([a,...o?[o]:[]])})})().finally(()=>this.sharing=null),this.sharing}async setAudioOutput(e){this.sink=e;for(let t of this.players.values())await bs(t,e)}async refresh(){let e=await this.c.api.getCall({path:{call_id:this.id}});this.apply(e.data)}apply(e){e.id!==this.id||e.version<this.call.version||(this.call=e,this.derive())}caughtUp(){!this.owned||this.done||this.refresh().catch(()=>{})}online(){this.inCall&&!this.room&&this.toRoom()}get inCall(){return this.owned&&!this.done}drop(){this.done||this.end(this.endReason??"left")}me(){return this.call.participants.find(e=>e.user_id===this.c.me)}derive(){if(this.done)return;let e=this.call,t=this.me();if(e.state==="ended")return this.end(ji(e,t));let s=t?.state==="joined"&&t.device_id===this.c.device;if(s&&this.entering&&(this.owned=!0),this.owned){if(t?.state==="joined"&&!s)return this.end("answered_elsewhere","elsewhere");if(!s)return this.end(t?.state??"left");this.quiet(),this.beat(),this.phase=e.state==="ringing"?"calling":this.mediaPhase(),this.toRoom()}else if(t?.state==="ringing")this.phase="incoming";else if(t?.state==="invited")this.phase="invited";else if(this.entering)this.phase="connecting";else if(t?.state==="joined")this.phase="elsewhere",this.quiet();else return this.end(t?.state??"ended");this.changed()}mediaPhase(){return this.roomState==="connected"?"connected":this.roomState==="reconnecting"?"reconnecting":"connecting"}async enter(e,t){this.entering=!0;try{await this.open(e.video??this.call.video,e.media);let s=await t({device_id:this.c.device});this.apply(s.data)}catch(s){this.entering=!1,this.owned||this.release();let i=lt(s);throw i?this.apply(i):this.derive(),s}this.entering=!1,this.derive(),this.inCall&&this.c.entered(this)}own(e){if(this.done){for(let t of e.opened)t.stop();return}this.owned=!0,this.local=e.local,this.tracks=e.tracks;for(let t of e.opened)this.opened.add(t);this.derive()}async open(e,t){let s=await Ss(this.c.rtc(),e,t);this.local=s.local,this.tracks=s.tracks;for(let i of s.opened)this.opened.add(i)}async camera(e){try{let s=(await this.c.rtc().getUserMedia({video:e})).getVideoTracks()[0];if(!s)throw new Error("calls: the camera gave no video");return this.opened.add(s),s}catch(t){throw this.error=t instanceof Error?t:new Error(String(t)),this.changed(),t}}async putVideo(e){let t=this.tracks.video;this.tracks.video=e,t&&this.local?.removeTrack(t),e&&this.local?.addTrack(e),this.changed(),this.room&&(t&&await this.room.unpublish(t).catch(()=>{}),e&&await this.room.publish(e,"camera")),t&&t!==e&&this.stopIfOpened(t)}async putScreen(e){let t=this.shared;if(!(!t&&!e)){if(this.shared=e,this.changed(),this.room){if(t)for(let s of[t.video,t.audio])s&&await this.room.unpublish(s).catch(()=>{});e&&(await this.room.publish(e.video,"screen"),e.audio&&await this.room.publish(e.audio,"screen_audio"))}if(t)for(let s of[t.video,t.audio])s&&this.stopIfOpened(s)}}sent(){let e=[];return this.tracks.audio&&e.push([this.tracks.audio,"microphone"]),this.tracks.video&&e.push([this.tracks.video,"camera"]),this.shared&&e.push([this.shared.video,"screen"]),this.shared?.audio&&e.push([this.shared.audio,"screen_audio"]),e}toRoom(){return this.room||this.joiningRoom||this.done?Promise.resolve():(this.joiningRoom=(async()=>{let e=(await this.c.api.getCallMedia({path:{call_id:this.id},body:{device_id:this.c.device}})).data;if(this.done)return;let t=await this.c.room({track:(s,i,n)=>{this.room===t&&this.heard(s,i,n)},trackGone:(s,i)=>{this.room===t&&this.gone(s,i)},muted:(s,i,n)=>{this.room===t&&(n?this.mutedInRoom.add(i):this.mutedInRoom.delete(i),this.changed())},speakers:s=>{this.room===t&&(this.speakers=new Set(s),this.changed())},state:s=>{if(this.room===t){if(this.roomState=s,s==="disconnected"){this.room=null,this.roomState=null,this.speakers=new Set;for(let[i,n]of[...this.owners])this.gone(n,i);t.close().catch(()=>{})}this.derive()}}});if(this.done){await t.close();return}this.room=t,this.roomState=null,await t.connect(e.url,e.token);for(let[s,i]of this.sent())await t.publish(s,i);this.tracks.audio&&!this.mic&&await t.mute(this.tracks.audio,!0),this.derive()})().catch(e=>{let t=this.room;this.room=null,this.roomState=null,t?.close().catch(()=>{}),this.failed(e)}).finally(()=>this.joiningRoom=null),this.joiningRoom)}streamOf(e,t=this.streams){let s=t.get(e);return s||t.set(e,s=new(this.c.rtc()).MediaStream),s}heard(e,t,s){let i=s==="screen"||s==="screen_audio",n=this.streamOf(e,i?this.screens:this.streams);for(let a of n.getTracks())a.kind===t.kind&&a!==t&&this.gone(e,a);if(n.getTracks().includes(t)||n.addTrack(t),!this.owners.has(t)){let a=()=>this.changed();t.addEventListener?.("mute",a),t.addEventListener?.("unmute",a),t.addEventListener?.("ended",a)}this.owners.set(t,e),t.kind==="audio"&&this.play(i?`${e}\0screen`:e,n),this.changed()}gone(e,t){this.owners.delete(t),this.mutedInRoom.delete(t),this.streams.get(e)?.removeTrack(t),this.screens.get(e)?.removeTrack(t),this.changed()}play(e,t){if(!this.c.playAudio||this.players.has(e))return;let s=globalThis.document;if(!s)return;let i=s.createElement("audio");i.autoplay=!0,i.srcObject=t,this.players.set(e,i),this.sink&&bs(i,this.sink).catch(()=>{}),i.play?.()?.catch?.(()=>{})}beat(){this.heartbeat===void 0&&(this.heartbeat=setInterval(()=>{this.stillHere()},this.c.heartbeatMs)),this.poll===void 0&&(this.poll=setInterval(()=>{this.c.live()||this.done||this.refresh().catch(()=>{})},this.c.pollMs))}async stillHere(){if(!this.done)try{let e=(await this.c.api.callHeartbeat({path:{call_id:this.id},body:{device_id:this.c.device}})).data;(e.version>this.call.version||!e.in_call||e.state==="ended")&&await this.refresh()}catch(e){e instanceof b&&e.status===404&&this.end("ended")}}end(e,t="ended"){if(this.done)return;this.done=!0,this.entering=!1,this.phase=t,this.quiet(),this.endReason=e,clearInterval(this.heartbeat),clearInterval(this.poll);let s=this.room;this.room=null,this.shared=null,this.speakers=new Set,s?.close().catch(()=>{});for(let i of this.players.values())i.pause?.(),i.srcObject=null;this.players.clear(),this.release(),this.changed(),this.c.forget(this)}release(){for(let e of this.opened)e.stop();this.opened.clear()}stopIfOpened(e){this.opened.delete(e)&&e.stop()}quiet(){this.quieted||(this.quieted=!0,this.c.quiet(this.id))}failed(e){this.done||(this.error=e instanceof Error?e:new Error(String(e)),this.changed())}refusal(e){let t=lt(e);throw t&&this.apply(t),e}refused(e,t,s){return new b({op:e,status:409,code:t,message:`${e}: ${s}`})}changed(){let e=this.c.me,t=this.owned&&!this.done,s=t?this.call.participants.filter(a=>a.user_id!==e&&a.state==="joined"):[],i=s.map(a=>this.remoteOf(a.user_id,a));if(t)for(let a of new Set([...this.streams.keys(),...this.screens.keys()]))(this.streams.get(a)?.getTracks().length??0)+(this.screens.get(a)?.getTracks().length??0)>0&&!s.some(d=>d.user_id===a)&&i.push(this.remoteOf(a));let n=this.mic&&this.tracks.audio!==null;this.snapshot={call:this.call,me:this.me()??null,phase:this.phase,outgoing:this.call.caller_id===e,local:t?this.local:null,microphone:n,camera:this.tracks.video!==null,screenSharing:t&&this.shared!==null,screen:t?this.shared?.stream??null:null,speaking:t&&n&&this.speakers.has(e),remote:i,endReason:this.endReason,error:this.error};for(let a of[...this.listeners])try{a()}catch{}}remoteOf(e,t){let s=this.streamOf(e),i=this.screens.get(e),n=(a,o)=>a.getTracks().some(d=>d.kind===o&&d.readyState!=="ended"&&!d.muted&&!this.mutedInRoom.has(d));return{userId:e,name:t?.name??null,imageUrl:t?.image_url??null,bot:t?.kind==="bot"||e.startsWith("bot:"),stream:s,audio:n(s,"audio"),video:n(s,"video"),screen:i&&n(i,"video")?i:null,speaking:this.speakers.has(e)}}},Ie=class{deviceId;transportFor;session;socket;ref;opts;beacon;user=null;api=null;channel=null;off=[];sessions=new Map;incoming=new Set;entered=new Set;places=new Map;workerHeard=!1;constructor(e,t,s,i,n,a,o={}){this.transportFor=e,this.session=t,this.socket=s,this.ref=i,this.deviceId=n,this.beacon=a,this.opts=o,t.onChange((l,c)=>{if(l==="SIGNED_OUT"||l==="SESSION_EXPIRED")return this.stop();if(l==="SIGNED_IN"){if(this.user!==null&&c?.userId===this.user){this.unfollow(),this.follow(this.user);return}this.stop(),this.incoming.size>0&&this.ready().catch(()=>{})}});let d=globalThis;d.addEventListener?.("online",()=>{for(let l of this.sessions.values())l.online()}),d.addEventListener?.("pagehide",()=>{for(let l of this.sessions.values())l.inCall&&this.beacon(`/calls/${encodeURIComponent(l.id)}/leave`)})}get current(){for(let e of this.sessions.values())if(e.inCall)return e;return null}async start(e,t={}){let s=typeof e=="string"?[e]:[...e];if(s.length===0&&t.place===void 0)throw new TypeError("calls.start: name the person (or people) to call, or the place to hold it at");t.place!==void 0&&ws("calls.start",t.place),await this.ready();let i=this.api,n=await Ss(this.rtc(),t.video===!0,t.media),a;try{a=(await i.startCall({body:{user_ids:s,device_id:this.deviceId,video:t.video===!0,...t.ring===void 0?{}:{ring:t.ring},...t.group===void 0?{}:{group:t.group},...t.conversationId===void 0?{}:{conversation_id:t.conversationId},...t.metadata===void 0?{}:{metadata:t.metadata},...t.callerName===void 0?{}:{caller_name:t.callerName},...t.callerImageUrl===void 0?{}:{caller_image_url:t.callerImageUrl},...t.place===void 0?{}:{place:t.place}}})).data}catch(d){for(let c of n.opened)c.stop();let l=d instanceof b&&d.code==="place_busy"?lt(d):void 0;throw l?(this.places.get(l.place??"")?.heard(l),new at(d,l)):d}a.place!==null&&this.places.get(a.place)?.heard(a);let o=this.sessionOf(a,!1);return o.own(n),o.inCall&&(this.sessions.set(o.id,o),this.tell(this.entered,o)),o}voice(e,t={}){return this.start(e,{...t,video:!1})}video(e,t={}){return this.start(e,{...t,video:!0})}async join(e,t={}){await this.ready();let s=typeof e=="string"?e:e.id,i=this.sessions.get(s);return i||(i=this.sessionOf(typeof e=="string"?await this.toJoin(e):e,!0)),await i.join(t),i}place(e){ws("calls.place",e);let t=this.places.get(e);return t||(t=new dt(e,{api:async()=>(await this.ready(),this.api),start:s=>this.start(s.userIds??[],{...s,place:e}),join:(s,i)=>this.join(s,i),live:()=>this.channel?.state==="joined",pollMs:this.opts.pollMs??2e3}),this.places.set(e,t)),t}onIncoming(e){return this.incoming.add(e),this.ready().catch(()=>{}),()=>this.incoming.delete(e)}onCall(e){return this.entered.add(e),()=>this.entered.delete(e)}async history(e={}){await this.ready();let t={};return e.limit!==void 0&&(t.limit=e.limit),e.cursor!==void 0&&(t.cursor=e.cursor),e.missed!==void 0&&(t.missed=e.missed),e.state!==void 0&&(t.state=e.state),(await this.api.listCalls({query:t})).data}async get(e){return await this.ready(),(await this.api.getCall({path:{call_id:e}})).data}async ready(){let e=this.session.snapshot()??await this.session.session();if(!e)throw new b({op:"calls",status:401,code:"not_signed_in",message:"calls are the signed-in person's: sign in first"});this.user===e.userId&&this.api||(this.stop(),this.user=e.userId,this.api=ft.client(this.transportFor(e.userId)),this.follow(e.userId),this.listenToWorker(),this.ringing().catch(()=>{}))}stop(){this.unfollow();for(let e of[...this.sessions.values()])e.drop();if(this.sessions.clear(),this.user!==null)for(let e of this.places.values())e.drop();this.user=null,this.api=null}unfollow(){for(let e of this.off.splice(0))e();this.channel?.leave(),this.channel=null}follow(e){let t=this.socket.channel(`calls:${this.ref}:${e}`);this.channel=t,this.off.push(t.on("broadcast",s=>{if(this.user===e){if(s.event==="call"){let i=s.payload;this.heardCall(i),i.place&&this.places.get(i.place)?.heard(i)}else if(s.event==="place"){let i=s.payload;this.places.get(i.place)?.told(i)}}}),t.onJoined(()=>{if(this.user===e){for(let s of this.sessions.values())s.caughtUp();for(let s of this.places.values())s.caughtUp();this.ringing().catch(()=>{})}})),t.join().catch(()=>{})}async toJoin(e){try{return(await this.api.getCall({path:{call_id:e}})).data}catch(t){if(!(t instanceof b)||t.status!==404)throw t;for(let s of this.places.values())if(s.state.call?.id===e)return s.state.call;throw t}}async ringing(){let e=this.user,t=this.api;if(!t)return;let s=await Promise.all([t.listCalls({query:{state:"ringing",limit:20}}),t.listCalls({query:{state:"active",limit:20}})]);if(this.user===e)for(let i of s)for(let n of i.data.calls)this.heardCall(n)}listenToWorker(){if(this.workerHeard)return;let e=globalThis.navigator?.serviceWorker;e?.addEventListener&&(this.workerHeard=!0,e.addEventListener("message",t=>{let s=t.data,i=s?.type==="palbase.push"?s.data?.call_id:void 0;!i||s?.data?.pb_call!=="incoming"||!this.api||this.api.getCall({path:{call_id:i}}).then(n=>this.heardCall(n.data)).catch(()=>{})}))}heardCall(e){let t=this.sessions.get(e.id);if(t){t.apply(e);return}let s=e.participants.find(i=>i.user_id===this.user);e.state==="ended"||s?.state!=="ringing"&&s?.state!=="invited"||this.tell(this.incoming,this.sessionOf(e,!1))}tell(e,t){for(let s of[...e])try{s(t)}catch{}}sessionOf(e,t){let s=this.sessions.get(e.id);if(s)return s.apply(e),s;let i=this.sessions,n=new ot({api:this.api,me:this.user,device:this.deviceId,rtc:()=>this.rtc(),room:this.opts.room??vs,playAudio:this.opts.playAudio!==!1,heartbeatMs:this.opts.heartbeatMs??15e3,pollMs:this.opts.pollMs??2e3,live:()=>this.channel?.state==="joined",forget(a){i.get(a.id)===a&&i.delete(a.id)},quiet:a=>Ki(a),entered:a=>{i.set(a.id,a),this.tell(this.entered,a)}},e,t);return n.state.phase!=="ended"&&i.set(e.id,n),n}rtc(){if(this.opts.rtc)return this.opts.rtc;let e=globalThis;if(typeof e.RTCPeerConnection!="function"||typeof e.MediaStream!="function"||typeof e.navigator?.mediaDevices?.getUserMedia!="function")throw new TypeError("calls: this runtime has no WebRTC (RTCPeerConnection, navigator.mediaDevices): a call's media is a browser's");let t=e.navigator.mediaDevices;return{MediaStream:e.MediaStream,getUserMedia:s=>t.getUserMedia(s),...typeof t.getDisplayMedia=="function"?{getDisplayMedia:s=>t.getDisplayMedia(s)}:{}}}},Ni=120,Ui=1e4,qi=32,dt=class{place;c;snapshot;listeners=new Set;call=null;error=null;watchers=0;renewing=null;timer;poll;words=0;ended=new Set;constructor(e,t){this.place=e,this.c=t,this.snapshot=this.make()}get state(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async refresh(){let e=await this.c.api(),t=this.words;try{this.take((await e.getCallPlace({path:{place:this.place}})).data,t)}catch(s){this.fail(s)}return this.call}async watch(){this.watchers++,this.changed();try{await this.renew()}catch(e){throw this.watchers=Math.max(0,this.watchers-1),this.watchers===0&&this.idle(),this.changed(),e}return this.call}async unwatch(){if(this.watchers===0||--this.watchers>0||(this.idle(),this.changed(),await this.renewing?.catch(()=>{}),this.watchers>0))return;await(await this.c.api()).unwatchCallPlace({path:{place:this.place}})}start(e={}){return this.c.start(e)}async join(e={}){let t=this.call??await this.refresh();if(!t)throw new b({op:"join",status:404,code:"call_not_found",message:`join: no call goes on at ${this.place}`});return this.c.join(t,e)}told(e){this.words++,e.call?this.heard(e.call):this.set(null)}heard(e){if(e.place===this.place){if(e.state==="ended"){this.ended.add(e.id),this.ended.size>qi&&this.ended.delete(this.ended.values().next().value),this.call?.id===e.id&&this.set(null);return}this.ended.has(e.id)||this.call?.id===e.id&&e.version<this.call.version||this.set({...e,participants:e.participants.map(t=>t.device_id===null?t:{...t,device_id:null})})}}caughtUp(){this.watchers>0&&this.renew().catch(()=>{})}drop(){this.watchers=0,this.idle(),this.call=null,this.error=null,this.ended.clear(),this.changed()}renew(){if(this.renewing)return this.renewing;clearTimeout(this.timer),this.timer=void 0;let e=this.words;return this.renewing=(async()=>(await(await this.c.api()).watchCallPlace({path:{place:this.place}})).data)().then(t=>(this.watchers===0||(this.error=null,this.take(t,e),this.later(Math.max(1,(t.watch_seconds??Ni)/2)*1e3),this.polling()),t),t=>(this.watchers>0&&(!(t instanceof b)||t.isNetworkError||t.status===429||t.status>=500?this.later(Ui):(this.watchers=0,this.idle())),this.fail(t))).finally(()=>this.renewing=null),this.renewing}later(e){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.renew().catch(()=>{})},e)}polling(){this.poll===void 0&&(this.poll=setInterval(()=>{this.watchers===0||this.c.live()||this.refresh().catch(()=>{})},this.c.pollMs))}idle(){clearTimeout(this.timer),clearInterval(this.poll),this.timer=void 0,this.poll=void 0}take(e,t){e.call?this.heard(e.call):this.words===t?this.set(null):this.changed()}set(e){this.call=e,this.error=null,this.changed()}fail(e){throw this.error=e instanceof Error?e:new Error(String(e)),this.changed(),e}make(){return{place:this.place,call:this.call,watching:this.watchers>0,error:this.error}}changed(){this.snapshot=this.make();for(let e of[...this.listeners])try{e()}catch{}}};function ws(r,e){if(!Di.test(e))throw new TypeError(`${r}: a place is 1 to 128 letters, digits and . _ : -, starting with a letter or digit (channel:42)`)}async function Ss(r,e,t){let s=t,i=[];if(!s){try{s=await r.getUserMedia({audio:!0,video:e?{facingMode:"user"}:!1})}catch(d){let l=d?.name;if(!e||l==="NotAllowedError"||l==="SecurityError")throw d;s=await r.getUserMedia({audio:!0,video:!1})}i.push(...s.getTracks())}let n=s.getAudioTracks()[0]??null,a=e?s.getVideoTracks()[0]??null:null;if(!t&&!e)for(let d of s.getVideoTracks())d.stop();return{local:new r.MediaStream([n,a].filter(d=>d!==null)),tracks:{audio:n,video:a},opened:i.filter(d=>d===n||d===a)}}function ji(r,e){return e?.state==="missed"||e?.state==="declined"||e?.state==="busy"?e.state:r.end_reason??"ended"}function lt(r){if(!(r instanceof b)||r.status!==409)return;let e=r.body;return e?.call&&typeof e.call.id=="string"?e.call:void 0}function Ki(r){let e=globalThis.navigator?.serviceWorker;typeof e?.getRegistration=="function"&&e.getRegistration().then(async t=>{for(let s of await t?.getNotifications({tag:r})??[])s.close()}).catch(()=>{})}async function bs(r,e){let t=r;if(typeof t.setSinkId!="function")throw new TypeError("calls: this browser cannot choose where audio plays (setSinkId)");await t.setSinkId(e)}function Oe(r){if(!r||r==="."||r==="..")throw new b({op:"ai.templates",status:0,code:"invalid_path_parameter",message:`template name ${JSON.stringify(r)} is invalid`});return encodeURIComponent(r)}async function Ae(r,e){let t=await e.text().catch(()=>""),s;try{s=t?JSON.parse(t):void 0}catch{s=void 0}let i=typeof s?.error=="string"?s.error:`http_${e.status}`,n=typeof s?.error_description=="string"?s.error_description:typeof s?.message=="string"?s.message:`${r}: server answered ${e.status}`,a=e.headers.get("retry-after"),o=a&&!Number.isNaN(Number(a))?Number(a):void 0;return new b({op:r,status:e.status,code:i,message:n,requestId:e.headers.get("x-request-id")??void 0,retryAfter:o,body:s})}var Ee=class{origin;publishableKey;session;installation;fetchFn;constructor(e,t,s,i,n){this.origin=e,this.publishableKey=t,this.session=s,this.installation=i,this.fetchFn=n}async buildHeaders(e){let t={apikey:this.publishableKey,"Content-Type":"application/json","X-Palbase-Platform":"web","X-Palbase-Installation-Id":this.installation.id};e.accept&&(t.Accept=e.accept);let s=await this.session.accessToken();return s&&(t.Authorization=`Bearer ${s}`),e.debugAttestToken&&(t["X-Palbase-Debug-Attest"]=e.debugAttestToken),t}async run(e,t={}){let s=Oe(e),i=new URL(`/ai/client/templates/${s}/run`,this.origin).href,n=await this.fetchFn(i,{method:"POST",headers:await this.buildHeaders({debugAttestToken:t.debugAttestToken}),body:JSON.stringify({variables:t.variables,attachments:t.attachments,stream:!1}),signal:t.signal});if(!n.ok)throw await Ae("ai.templates.run",n);return await n.json()}async*stream(e,t={}){let s=Oe(e),i=new URL(`/ai/client/templates/${s}/run`,this.origin).href,n=await this.fetchFn(i,{method:"POST",headers:await this.buildHeaders({debugAttestToken:t.debugAttestToken,accept:"text/event-stream"}),body:JSON.stringify({variables:t.variables,attachments:t.attachments,stream:!0}),signal:t.signal});if(!n.ok)throw await Ae("ai.templates.stream",n);if(!n.body)return;let a=n.body.getReader(),o=new TextDecoder,d="";try{for(;;){let{done:l,value:c}=await a.read();if(l)break;d+=o.decode(c,{stream:!0});let h;for(;(h=d.indexOf(`
|
|
23
|
+
`))!==-1;){let p=d.slice(0,h).trim();if(d=d.slice(h+1),!p.startsWith("data:"))continue;let v=p.slice(5).trim();if(v){if(v==="[DONE]")return;try{let f=JSON.parse(v),u=f.choices?.[0],g=u?.delta?.content??"",y=u?.finish_reason??void 0;(g||y)&&(yield{delta:g,model:f.model,finishReason:y})}catch{}}}}}finally{a.releaseLock()}}async speech(e,t={}){let s=Oe(e),i=new URL(`/ai/client/templates/${s}/run`,this.origin).href,n=await this.fetchFn(i,{method:"POST",headers:await this.buildHeaders({debugAttestToken:t.debugAttestToken}),body:JSON.stringify({variables:t.variables,stream:!1}),signal:t.signal});if(!n.ok)throw await Ae("ai.templates.speech",n);return n.arrayBuffer()}async startVoice(e,t){let s=Oe(e),i=new URL(`/ai/client/templates/${s}/voice`,this.origin).href,n=await this.fetchFn(i,{method:"POST",headers:await this.buildHeaders({debugAttestToken:t.debugAttestToken}),body:JSON.stringify({variables:t.variables,transport:{type:"webrtc",sdp:t.sdp}}),signal:t.signal});if(!n.ok)throw await Ae("ai.templates.startVoice",n);return await n.json()}};var Fi="machines.changed.v1",Vi=6e4;function $i(r){return r.unref?.(),r}var ct=()=>new b({op:"ai.machines.watch",status:401,code:"not_signed_in",message:"a person's machines are the signed-in person's: sign in first"});function Wi(r){return r instanceof P?!0:r instanceof b&&(r.status===401||r.status===403)}var ut=class{started=!1;done=!1;reading=!1;again=!1;taken;told;pending;failure;waiter;unfollow;offSession;floor;abort=new AbortController;source;constructor(e,t){this.source=e,t?.aborted?this.stop():t?.addEventListener("abort",()=>{this.return()},{once:!0})}[Symbol.asyncIterator](){return this}next(){if(this.pending){let t=this.pending;return this.pending=void 0,this.taken=t,Promise.resolve({value:t,done:!1})}if(this.failure){let{error:t}=this.failure;return this.failure=void 0,Promise.reject(t)}if(this.done)return Promise.resolve({value:void 0,done:!0});let e=new Promise((t,s)=>this.waiter={resolve:t,reject:s});return this.started||(this.started=!0,this.start()),e}return(){this.stop();let e=this.waiter;return this.waiter=void 0,e?.resolve({value:void 0,done:!0}),this.pending=void 0,Promise.resolve({value:void 0,done:!0})}stop(){this.done=!0,this.abort.abort(),this.floor!==void 0&&clearInterval(this.floor),this.floor=void 0,this.unfollow?.(),this.unfollow=void 0,this.offSession?.(),this.offSession=void 0}async start(){let e;try{e=await this.source()}catch(s){this.fail(s);return}if(this.done||(this.offSession=e.onGone(s=>this.fail(s)),this.leftBy(e)))return;this.reading=!0,this.unfollow=e.follow(()=>this.readAgain(e));let t;try{t=await e.read(this.abort.signal)}catch(s){!this.done&&!this.leftBy(e)&&this.fail(s);return}this.done||this.leftBy(e)||(this.tell(t),this.floor=$i(setInterval(()=>this.readAgain(e),e.floorMs)),this.again?await this.pump(e):this.reading=!1)}readAgain(e){if(!this.done){if(this.reading){this.again=!0;return}this.reading=!0,this.pump(e)}}async pump(e){do{if(this.again=!1,this.leftBy(e))return;try{let t=await e.read(this.abort.signal);if(this.done||this.leftBy(e))return;this.tell(t)}catch(t){if(this.done||this.leftBy(e))return;if(Wi(t)){this.fail(t);return}}}while(this.again&&!this.done);this.reading=!1}leftBy(e){if(this.done)return!0;let t=e.gone();return t===void 0?!1:(this.fail(t),!0)}tell(e){if(this.told!==void 0&&Ke(this.told,e))return;if(this.told=e,this.taken!==void 0&&Ke(this.taken,e)){this.pending=void 0;return}let t=this.waiter;t?(this.waiter=void 0,this.taken=e,t.resolve({value:e,done:!1})):this.pending=e}fail(e){if(this.done)return;this.stop();let t=this.waiter;this.waiter=void 0,t?t.reject(e):this.failure={error:e}}};function ks(r,e,t,s,i,n=Vi){let a=Mt(Ue.client(r),"user"),o=new Map,d=(l,c)=>{let h=o.get(l);if(!h){let v=s.channel(l),f={channel:v,hearers:new Set,off:[]},u=()=>{for(let g of[...f.hearers])g()};f.off.push(v.on("broadcast",g=>{g?.event===Fi&&u()}),v.onJoined(u),v.onClosed(()=>{o.get(l)===f&&o.delete(l)})),v.join().catch(()=>{}),o.set(l,h=f)}let p=h;return p.hearers.add(c),()=>{if(p.hearers.delete(c),!(p.hearers.size>0)){for(let v of p.off.splice(0))v();o.get(l)===p&&(o.delete(l),p.channel.leave())}}};return{...a,watch(l={}){return new ut(async()=>{let c=t.snapshot()??await t.session();if(!c)throw ct();let h=c.userId,p=Ue.client(e(h)),v=f=>f===null?ct():f.userId!==h?new P(`the session is no longer ${h}'s`):void 0;return{read:async f=>(await p.listMachines({signal:f})).data.machines.map(xt),follow:f=>d(`ai_machines:${i}:${h}`,f),floorMs:n,gone:()=>v(t.snapshot()),onGone:f=>t.onChange((u,g)=>{let y=u==="SIGNED_OUT"||u==="SESSION_EXPIRED"?ct():v(g);y!==void 0&&f(y)})}},l.signal)}}}var Le=class{api;open;session;credentials;mfa;passkey;magicLink;phone;password;email;sessions;constructor(e,t,s,i){this.api=W.client(e),this.open=W.client(t),this.session=s,this.credentials=i;let n=this.api,a=this.open;this.mfa={challenge:async(o,d,l)=>this.signedIn((await a.mfaChallenge({body:{mfa_token:o,type:d,code:l}})).data),recovery:async(o,d)=>this.signedIn((await a.mfaRecovery({body:{mfa_token:o,code:d}})).data),sendSmsCode:async o=>{await a.mfaSmsChallenge({body:{mfa_token:o}})},sendEmailCode:async o=>{await a.mfaEmailChallenge({body:{mfa_token:o}})},enrollTotp:async()=>{let o=(await n.mfaEnroll({body:{type:"totp"}})).data;return{enrollmentId:o.enrollment_id,secret:o.secret,otpUrl:o.otp_url,qrCode:o.qr_code,recoveryCodes:o.recovery_codes}},verifyTotp:async o=>{await n.mfaVerifyEnrollment({body:{code:o}})},enrollSms:async o=>(await n.mfaSmsEnroll({body:{phone:o}})).data,verifySms:async o=>{await n.mfaSmsVerifyEnrollment({body:{code:o}})},enrollEmail:async()=>{await n.mfaEmailEnroll()},factors:async()=>(await n.mfaListFactors()).data,removeFactor:async(o,d)=>{await n.mfaRemoveFactor({path:{id:o},body:{current_password:d}})},regenerateRecoveryCodes:async()=>(await n.mfaRegenerateRecoveryCodes()).data,stepUp:async o=>this.steppedUp(async()=>(await n.stepUp({body:{method:"totp",code:o}})).data),sendStepUpSmsCode:async()=>{await n.stepUpSmsSend()},stepUpWithSms:async o=>this.steppedUp(async()=>(await n.stepUp({body:{method:"sms",code:o}})).data)},this.passkey={register:async o=>{let d=(await n.webauthnRegisterBegin({body:{name:o}})).data,l=await this.authenticator().create({publicKey:_s(d.options.publicKey)});return(await n.webauthnRegisterFinish({body:Rs(l)})).data},signIn:async(o={})=>{let d=(await a.webauthnLoginBegin({body:o.userId?{user_id:o.userId}:{}})).data,l=await this.authenticator().get({publicKey:ht(d.options.publicKey)}),c=await a.webauthnLoginFinish({query:o.userId?{user_id:o.userId}:void 0,body:pt(l)});return this.signedIn(c.data)},signUp:async(o,d)=>{let l=(await a.webauthnSignupBegin({body:{identifier:o,user_name:d}})).data,c=await this.authenticator().create({publicKey:_s(l.options.publicKey)});await a.webauthnSignupFinish({query:{user_id:l.user_id},body:Rs(c)});let h=(await a.webauthnLoginBegin({body:{user_id:l.user_id}})).data,p=await this.authenticator().get({publicKey:ht(h.options.publicKey)});return this.signedIn((await a.webauthnLoginFinish({query:{user_id:l.user_id},body:pt(p)})).data)},stepUp:async()=>this.steppedUp(async()=>{let o=(await n.stepUpWebAuthnBegin()).data,d=await this.authenticator().get({publicKey:ht(o.publicKey)});return(await n.stepUp({body:{method:"webauthn",...pt(d)}})).data}),list:async()=>(await n.webauthnListCredentials()).data,remove:async o=>{await n.webauthnDeleteCredential({path:{id:o}})}},this.magicLink={send:async(o,d={})=>{await a.magicLinkRequest({body:{email:o,...d.redirectTo?{redirect_to:d.redirectTo}:{}}})},verify:async o=>this.signInResult((await a.magicLinkVerify({body:{token:o}})).data)},this.phone={sendCode:async o=>(await a.requestPhoneOtp({body:{phone:o,channel:"sms"}})).data,verifyCode:async(o,d)=>this.signInResult((await a.verifyPhoneOtp({body:{phone:o,token:d}})).data)},this.password={requestReset:async(o,d={})=>{await a.passwordResetRequest({body:{email:o,...d.redirectTo?{redirect_to:d.redirectTo}:{}}})},confirmReset:async(o,d)=>{await a.passwordResetConfirm({body:{token:o,new_password:d}})},change:async o=>(await n.passwordChange({body:o})).data,set:async o=>(await n.setPassword({body:o})).data},this.email={verify:async o=>{await a.verifyEmail({body:o})},resendVerification:async o=>(await a.resendVerification({body:{email:o}})).data},this.sessions={list:async()=>(await n.listSessions()).data,revoke:async o=>{await n.revokeSession({path:{id:o}})},revokeAll:async()=>{await n.revokeAllSessions()}}}onAuthStateChange(e){return this.session.onChange(e)}currentSession(){return this.session.session()}get sessionEndReason(){return this.session.endReason}async signUp(e){let t=(await this.open.signup({body:e})).data;return t.access_token&&t.refresh_token&&t.expires_in!==void 0&&await this.session.set({access_token:t.access_token,refresh_token:t.refresh_token,expires_in:t.expires_in},"SIGNED_IN",t.user),t}async signIn(e,t){return this.signInResult((await this.open.login({body:{email:e,password:t}})).data)}async signOut(){try{await this.session.session()&&await this.api.logout()}finally{await this.session.clear("SIGNED_OUT")}}async getUser(){let e=this.session.snapshot(),t=(await this.api.getMe()).data;return await this.session.setUser(t,e),t}async refreshSession(){return this.session.refresh()}async deleteAccount(e){await this.api.deleteAccount(e===void 0?void 0:{body:{password:e}}),await this.session.clear("SIGNED_OUT")}async signInResult(e){return"mfa_required"in e&&e.mfa_required?{mfaRequired:{mfaToken:e.mfa_token,factors:e.factors}}:{user:await this.signedIn(e)}}async setSession(e){return this.signedIn(e)}async signedIn(e){let t=await this.session.set({access_token:e.access_token,refresh_token:e.refresh_token,expires_in:e.expires_in},"SIGNED_IN",e.user);if(e.user)return e.user;let s=(await this.api.verifyTokenUser()).data;return await this.session.setUser(s,t),s}async steppedUp(e){let t=await this.session.session();if(!t)throw new P("a step-up raises the signed-in session: nobody is signed in");let s=await e();if((await this.session.session())?.refreshToken!==t.refreshToken)throw new P("the session changed during the step-up");return this.session.set({access_token:s.access_token,refresh_token:t.refreshToken,expires_in:s.expires_in},"TOKEN_REFRESHED")}authenticator(){if(!this.credentials)throw new Error("passkeys need navigator.credentials (or createClient({ webauthn }))");return this.credentials}},De=r=>{let e=atob(r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=")),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t.buffer},q=r=>{if(!r)return;let e=r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength),t="";for(let s of e)t+=String.fromCharCode(s);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},Ps=r=>Array.isArray(r)?r.map(e=>({...e,id:De(String(e.id))})):void 0;function _s(r){let e=r.user;return{...r,challenge:De(String(r.challenge)),user:{...e,id:De(String(e.id))},excludeCredentials:Ps(r.excludeCredentials)}}function ht(r){return{...r,challenge:De(String(r.challenge)),allowCredentials:Ps(r.allowCredentials)}}function Rs(r){let e=r,t=e.response;return{id:e.id,rawId:q(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:q(t.clientDataJSON),attestationObject:q(t.attestationObject),transports:t.getTransports?.()}}}function pt(r){let e=r,t=e.response;return{id:e.id,rawId:q(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:q(t.clientDataJSON),authenticatorData:q(t.authenticatorData),signature:q(t.signature),userHandle:q(t.userHandle)}}}var Gi=/^pb_[a-z0-9]+_s/,Hi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bi=new Set(["invalid_token","token_expired","session_expired","session_revoked","missing_token"]),Ji=new Set(["invalid_token","token_reuse","token_expired","session_revoked","session_expired","session_device_changed"]);function Qi(r){return r.status===400&&r.code==="invalid_request"}function Ur(r){if(Gi.test(r.publishableKey)||"secretKey"in r)throw new TypeError("a secret key never goes into a client app: palbase/web takes the publishable key (pb_<ref>_c\u2026); servers use palbase/server");let e=/^pb_([a-z0-9]+)_c/.exec(r.publishableKey)?.[1];if(e===void 0)throw new TypeError("publishableKey is the project publishable key (pb_<ref>_c\u2026)");if(r.appId!==void 0&&!Hi.test(r.appId))throw new TypeError("appId is the registered app's id, a UUID (settings.appId of palbase apps:sync), not its slug");let t=Ts(r.language),s=(w,k)=>{let I=r.fetch??globalThis.fetch;if(t===void 0)return I(w,k);let X=new Headers(k?.headers);return X.has("accept-language")||X.set("accept-language",t),I(w,{...k,headers:X})},i=new URL(r.url).origin,n=r.storage??(Xi()?Ot(`palbase.session.${i}`):It()),a=r.retry??vt,o=ee($({baseUrl:r.url,credentials:{publishableKey:r.publishableKey},fetch:s}),a),d=W.client(o),l=new ae(n,async w=>(await d.refreshToken({body:{refresh_token:w}})).data,w=>w instanceof b&&(w.status===401&&Ji.has(w.code)||Qi(w)),{lockName:`palbase.session.refresh.${i}`,refresh:r.refresh}),c=$({baseUrl:r.url,credentials:{publishableKey:r.publishableKey,accessToken:()=>l.accessToken()},fetch:s,xmlHttpRequest:r.xmlHttpRequest??(r.fetch===void 0?globalThis.XMLHttpRequest:void 0)}),h=ee(Ne(c,l),a),p=new oe({baseUrl:r.url,publishableKey:r.publishableKey,accessToken:()=>l.accessToken(),webSocket:r.webSocket});l.onChange(w=>{w==="SIGNED_OUT"||w==="SESSION_EXPIRED"||w==="SIGNED_IN"?p.disconnect():w==="TOKEN_REFRESHED"&&p.tokenChanged()});let v=globalThis;v.addEventListener?.("online",()=>p.askRefusedAgain()),v.document?.addEventListener?.("visibilitychange",()=>{v.document?.visibilityState==="visible"&&p.askRefusedAgain()});let f=new de(i),u=w=>ee(Ne($({baseUrl:r.url,credentials:{publishableKey:r.publishableKey,accessToken:async()=>{let k=await l.accessToken();if(k===void 0||Fe(k)!==w)throw new P(`the session is no longer ${w}'s`);return k}},fetch:s}),l),a),g=w=>W.client(u(w)),y=new pe({userApi:g,deviceApi:d,session:l,socket:p,ref:e,installation:f,origin:i,options:r.consent}),R=$({baseUrl:r.url,credentials:{publishableKey:r.publishableKey},fetch:s}),x=new ue(Ne(c,l),R,l,y,f,i),j=new be(h,l,p,e,f,s,r.appVersion,r.appId),se=new Ct(h,l,p,e,i),ie=new Se(h,u,l,f,x,y),m=new ke(h,f,ie,i),S=new we(h,l,f,y,j,r.url,r.publishableKey);x.onEvent((w,k)=>S.inApp.trigger(w,k)),r.analytics&&x.start(r.analytics===!0?{}:r.analytics);let E=new Map,M=w=>{let k=new URL(w).origin,I=E.get(k);return I||(I=ee(Ne($({baseUrl:k,credentials:{accessToken:()=>l.accessToken()},fetch:s}),l),a),E.set(k,I)),I},K=_t(h),C=w=>{let k=l.snapshot();k&&s(new URL(w,i).href,{method:"POST",keepalive:!0,headers:{apikey:r.publishableKey,authorization:`Bearer ${k.accessToken}`}}).catch(()=>{})},D=Object.assign(Object.create(Rt),{auth:new Le(h,o,l,r.webauthn??globalThis.navigator?.credentials),socket:p,transport:h,analytics:x,consent:y,installation:f,iap:j,payments:se,commerce:ie,campaigns:m,notify:S,flags:new _e(h,l,p,f,e,i,x,r.appVersion),messaging:new Me(h,u,l,p,e,s,r.messaging),calls:new Ie(u,l,p,e,`web-${f.id}`,C,r.calls),ai:{templates:new Ee(i,r.publishableKey,l,f,s),machines:ks(h,u,l,p,e)},setLanguage(w){t=Ts(w??void 0)},chatToolCall:(w,k,I={})=>K.toolCall(w,k,I.signal),watchSessions(w,k={}){let I=k.all?void 0:k.userId??l.snapshot()?.userId,X=I?`ai:sessions:${I}`:"ai:sessions",ne=p.channel(X),Cs=ne.on("session.summary.v1",re=>{let Y=je(re);Y&&w(Y)}),xs=ne.on("broadcast",re=>{if(re?.event!=="session.summary.v1")return;let Y=je(re.payload);Y&&w(Y)});return ne.join().catch(()=>{}),()=>{Cs(),xs(),ne.leave()}}});return Pt(D,i,M,h,p,()=>l.snapshot()?.userId),D}var zi=/^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$/;function Ts(r){if(r===void 0)return;let e=typeof r=="string"?[r]:[...r];if(e.length!==0){for(let t of e)if(!zi.test(t))throw new TypeError(`language ${JSON.stringify(t)} is a BCP 47 tag ("tr", "pt-BR")`);return e.map((t,s)=>s===0?t:`${t};q=${Math.max(.1,1-s/10).toFixed(1)}`).join(", ")}}function Xi(){try{return typeof globalThis.localStorage<"u"}catch{return!1}}function Ne(r,e){return{async send(t){let s=await e.session();try{return await r.send(t)}catch(i){let n=t.auth.some(a=>a.includes("userJWT"));if(!(i instanceof b)||i.status!==401||!Bi.has(i.code)||!n||!s)throw i;try{e.snapshot()?.refreshToken===s.refreshToken&&await e.refresh()}catch{throw i}if(e.snapshot()?.userId!==s.userId)throw i;return r.send(t)}}}}export{P as a,It as b,Ot as c,Is as d,Ve as e,oe as f,de as g,ue as h,pe as i,ge as j,me as k,ve as l,Be as m,we as n,be as o,ai as p,te as q,Qe as r,Se as s,ke as t,_e as u,Ei as v,Me as w,tt as x,st as y,it as z,nt as A,rt as B,at as C,ot as D,Ie as E,dt as F,Ee as G,Fi as H,Ur as I};
|