palbase 0.27.0 → 0.29.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.
Files changed (62) hide show
  1. package/README.md +12 -1
  2. package/dist/ai/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/{XUZ532UW.js → 3NB2Z2MF.js} +1 -1
  9. package/dist/chunks/{Y2RBMBJB.js → 4Q5QXL7S.js} +1 -1
  10. package/dist/chunks/{UJATFHC4.js → 62XTQSVZ.js} +2 -2
  11. package/dist/chunks/{CTKJ7E5R.js → 66PTYGSE.js} +2 -2
  12. package/dist/chunks/{2VZXMKE4.js → A6CGX34F.js} +2 -2
  13. package/dist/chunks/{7CVC2UYK.js → AMWYOTRD.js} +2 -2
  14. package/dist/chunks/C2SU644S.js +2 -0
  15. package/dist/chunks/{O5LG6IFL.js → EWMPKYBN.js} +1 -1
  16. package/dist/chunks/{R2KG2E4H.js → GJPGCOTW.js} +2 -2
  17. package/dist/chunks/{5ETIB37E.js → GV63GJ4D.js} +2 -2
  18. package/dist/chunks/{HKLIKCYR.js → HC2AGD3N.js} +2 -2
  19. package/dist/chunks/{UWZP4YV6.js → I5IDPWDM.js} +2 -2
  20. package/dist/chunks/IOU6E244.js +22 -0
  21. package/dist/chunks/{HHQ5RAYH.js → IQ6QJDM4.js} +2 -2
  22. package/dist/chunks/{JCS5FSY6.js → IYJRPKS2.js} +2 -2
  23. package/dist/chunks/{YS5GF7JB.js → KN6YJGWP.js} +2 -2
  24. package/dist/chunks/{NGAXCQJ4.js → MKLUERPB.js} +2 -2
  25. package/dist/chunks/{5PLOENVJ.js → OAVOR7X5.js} +1 -1
  26. package/dist/chunks/{AVQ7DQA4.js → OCZ5XVNP.js} +1 -1
  27. package/dist/chunks/{ZN4ELT45.js → OLRLJB7H.js} +1 -1
  28. package/dist/chunks/{LXS4IDDQ.js → VCUKXTAR.js} +2 -2
  29. package/dist/chunks/{QL42CXIT.js → WNEUGMU4.js} +1 -1
  30. package/dist/chunks/ZVRYGPBA.js +2 -0
  31. package/dist/cli.js +132 -132
  32. package/dist/cloud/index.js +2 -2
  33. package/dist/refuse/ai.js +1 -1
  34. package/dist/refuse/backend.js +1 -1
  35. package/dist/refuse/cloud.js +1 -1
  36. package/dist/refuse/server.js +1 -1
  37. package/dist/server/index.js +2 -2
  38. package/dist/server/testing.js +2 -2
  39. package/dist/web/calls-ui.js +46 -0
  40. package/dist/web/index.js +2 -2
  41. package/dist/web/message.js +2 -2
  42. package/dist/web/palbe.js +2 -2
  43. package/dist/web/paywall.js +2 -2
  44. package/dist/web/push-sw.js +2 -2
  45. package/dist/web/ssr.js +2 -2
  46. package/dist/web/vite.js +2 -2
  47. package/package.json +7 -2
  48. package/types/cloud/src/generated/project.d.ts +2 -1
  49. package/types/internal/src/modules/calls.d.ts +810 -0
  50. package/types/internal/src/modules/events.d.ts +4 -3
  51. package/types/internal/src/modules/index.d.ts +1 -0
  52. package/types/internal/src/modules/machines.d.ts +118 -8
  53. package/types/internal/src/modules/messaging.d.ts +53 -3
  54. package/types/internal/src/modules/realtime.d.ts +1 -1
  55. package/types/server/src/server.d.ts +7 -0
  56. package/types/web/src/calls-ui/index.d.ts +71 -0
  57. package/types/web/src/calls.d.ts +274 -0
  58. package/types/web/src/client.d.ts +5 -0
  59. package/types/web/src/index.d.ts +1 -0
  60. package/dist/chunks/BRK5A42K.js +0 -22
  61. package/dist/chunks/BXJGHBB5.js +0 -2
  62. package/dist/chunks/ZBY3Q6Q2.js +0 -2
@@ -1,2 +1,2 @@
1
- /*! palbase 0.27.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
2
  function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.27.0 — Palbase SDK License (see LICENSE) */
2
- import{a as M,c as ye,d as be,e as we}from"./UWZP4YV6.js";import{a as ke}from"./O5LG6IFL.js";import{a as ge}from"./BXJGHBB5.js";import{a as fe,b as me,c as he}from"./UJATFHC4.js";import{b as $,d as pe}from"./YS5GF7JB.js";async function*Te(e,t={}){let a=e.getReader(),o=new TextDecoder,i="",l="",u=[],h,r=()=>{a.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await a.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=o.decode(s,{stream:!0});for(let d=i.indexOf(`
1
+ /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as M,c as ye,d as be,e as we}from"./I5IDPWDM.js";import{a as ke}from"./EWMPKYBN.js";import{a as ge}from"./C2SU644S.js";import{a as fe,b as me,c as he}from"./62XTQSVZ.js";import{b as $,d as pe}from"./KN6YJGWP.js";async function*Te(e,t={}){let a=e.getReader(),o=new TextDecoder,i="",l="",u=[],h,r=()=>{a.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await a.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=o.decode(s,{stream:!0});for(let d=i.indexOf(`
3
3
  `);d>=0;d=i.indexOf(`
4
4
  `)){let p=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),p===""?(l!==""&&(yield h===void 0?{event:l,data:u.join(`
5
5
  `)}:{event:l,data:u.join(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.27.0 — Palbase SDK License (see LICENSE) */
2
- import{b as d,m as k}from"./ZN4ELT45.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
1
+ /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as d,m as k}from"./OLRLJB7H.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
@@ -1,4 +1,4 @@
1
- /*! palbase 0.27.0 — Palbase SDK License (see LICENSE) */
2
- import{f as m}from"./R2KG2E4H.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
1
+ /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
+ import{f as m}from"./GJPGCOTW.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
3
3
  `):process.stdout.write(`${o}
4
4
  `)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.27.0 — Palbase SDK License (see LICENSE) */
2
- import{a as u,b as d}from"./YS5GF7JB.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project's account has no balance to pay for Palbase's models: top it up (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof d)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new d({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=u(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
1
+ /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as u,b as d}from"./KN6YJGWP.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project's account has no balance to pay for Palbase's models: top it up (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof d)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new d({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=u(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
@@ -0,0 +1,22 @@
1
+ /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
+ import{e as Ze,g as et,h as tt}from"./IYJRPKS2.js";import{h as st}from"./AMWYOTRD.js";import{a as Qe}from"./IQ6QJDM4.js";import{r as ze,t as Xe,u as Ye}from"./WNEUGMU4.js";import{b as G,c as K,e as Ge,f as He,i as Pe,j as $,k as Be}from"./C2SU644S.js";import{a as Je,b as H}from"./62XTQSVZ.js";import{b as k,d as j}from"./KN6YJGWP.js";function Yt(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 it(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function nt(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 o=a=>{(a.key===r||a.key===null)&&i()};return n.addEventListener("storage",o),()=>n.removeEventListener?.("storage",o)}}}function xe(r){try{let e=r.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var Qt=6e4,Zt=15e3;function es(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var B=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??Zt,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??xe(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>Qt)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 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",Yt(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 Te=class{state="closed";refusal;logSeq;joinRef=null;listeners=new Map;closers=new Set;joiners=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}onJoined(e){return this.joiners.add(e),()=>this.joiners.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t;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;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{}}},z=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Te(e,this,t)),s}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed");this.lastJoin.clear()}async tokenChanged(){if(!this.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})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){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(),o=JSON.stringify([e.joinRef,n,e.topic,t,s]),a=this.awaitReply(n);return i.send(o),a}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,n)=>{let o=new e(t);this.ws=o,o.onopen=()=>{this.attempts=0,this.startHeartbeat(),i()},o.onmessage=a=>this.receive(String(a.data)),o.onerror=()=>n(new Error("the realtime socket could not be opened")),o.onclose=()=>this.dropped(o)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs||![...this.channels.values()].some(i=>i.state==="joining"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=J(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let i=[...this.channels.values()].filter(n=>n.state==="joining");this.open().then(()=>Promise.all(i.map(n=>this.sendJoin(n)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken();if(this.channels.get(e.name)!==e||e.state!=="joining")return;let s=this.nextRef();e.joinRef=s;let i=this.awaitReply(s),n={broadcast:{self:!1}};e.logSeq!==void 0&&(n.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(s,e.topic,"phx_join",{access_token:t,config:n},s);let{status:o,response:a}=await i;if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),o==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{}));return}e.settled(o==="ok",a)}awaitReply(e){return new Promise(t=>{let s=J(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,i,n,o]=t,a=typeof o=="object"&&o!==null?o:{};if(n==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(a.status),a.response??{});return}let d=[...this.channels.values()].find(l=>l.topic===i);if(d){if(n==="phx_close"){d.state="closed";return}if(n==="phx_error"){d.state="joining",J(setTimeout(()=>this.channels.get(d.name)===d&&d.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(d),1e3));return}d.deliver(n,a)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=J(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function J(r){return r.unref?.(),r}var E="X-Palbase-Installation-Secret",Y="X-Palbase-Installation",at=new WeakMap;function O(r){return at.get(r)}var ot=new WeakSet;function dt(r){return ot.has(r)}var ts=/^[A-Za-z0-9_-]{43}$/,X=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=rt()?.getItem(t);i&&ts.test(i)&&(s=i)}catch{}if(!s){ot.add(this),s=lt(crypto.getRandomValues(new Uint8Array(32)));try{rt()?.setItem(t,s)}catch{}}at.set(this,s),this.id=ss(s)}};function ss(r){return lt(ns(new TextEncoder().encode(r)).subarray(0,16))}function rt(){try{return globalThis.localStorage}catch{return}}function lt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var is=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]),R=(r,e)=>r>>>e|r<<32-e;function ns(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 a=0;a<t.length;a+=64){for(let p=0;p<16;p++)i[p]=s.getUint32(a+p*4);for(let p=16;p<64;p++){let y=R(i[p-15],7)^R(i[p-15],18)^i[p-15]>>>3,P=R(i[p-2],17)^R(i[p-2],19)^i[p-2]>>>10;i[p]=i[p-16]+y+i[p-7]+P|0}let[d,l,c,f,g,S,m,h]=e;for(let p=0;p<64;p++){let y=h+(R(g,6)^R(g,11)^R(g,25))+(g&S^~g&m)+is[p]+i[p]|0,P=(R(d,2)^R(d,13)^R(d,22))+(d&l^d&c^l&c)|0;h=m,m=S,S=g,g=f+y|0,f=c,c=l,l=d,d=y+P|0}e[0]+=d,e[1]+=l,e[2]+=c,e[3]+=f,e[4]+=g,e[5]+=S,e[6]+=m,e[7]+=h}let n=new Uint8Array(32),o=new DataView(n.buffer);for(let a=0;a<8;a++)o.setUint32(a*4,e[a]);return n}var as=30*6e4,ct=1e3,os=100,ds=60*1024,Q=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function U(){try{return globalThis.localStorage}catch{return}}var ee=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,o,a={}){this.session=s,this.consent=i;let d={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[Y]:n.id}}:c)};this.api=G.client(d);let l={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=G.client(l),this.closingApi=G.client({send:c=>d.send({...c,keepalive:!0})}),this.closingPerfApi=G.client({send:c=>l.send({...c,keepalive:!0})}),this.flushMs=a.flushMs??5e3,this.flushAt=a.flushAt??20,this.now=a.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${o}`,this.sessionKey=`palbase.analytics.session.${o}`,this.onceKey=`palbase.analytics.once.${o}`,s.onChange(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,f)=>{f!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map(Ce),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(),o=n?.session===i?n.keys:[];o.includes(e)||(this.writeOnce({session:i,keys:[...o,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=U()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{U()?.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}${V(t.pathname)}`:"");if(!i)return;let n=e.referrer??fs(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{U()?.removeItem(this.anonKey),U()?.removeItem(this.sessionKey),U()?.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(Ce)):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 o=this.take(this.events,e);try{await t.batch({body:{events:o.map(a=>({...a,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let o=this.take(this.samples,e);try{await s.sendPerf({body:{items:o}})}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(hs((o,a)=>this.sample("web_vital",o,a))),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 o of s.splice(0))o();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>=ct&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=ct&&this.samples.shift();let n={row_id:Q(),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()}:Ce(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,os);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>ds;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=U();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${Q()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${Q()}`,this.memoryAnon}sessionId(e){let t=U(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<as?{id:s.id,last:e}:{id:`ses_${Q()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=()=>{let a=`${e.location.origin}${e.location.pathname}`;if(a===t)return;t=a;let d=`${e.location.origin}${V(e.location.pathname)}`;setTimeout(()=>this.page({url:d}),0)},i=e.history,n=i.pushState.bind(i),o=i.replaceState.bind(i);return i.pushState=(...a)=>{n(...a),s()},i.replaceState=(...a)=>{o(...a),s()},e.addEventListener("popstate",s),s(),()=>{i.pushState=n,i.replaceState=o,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let o=performance.now(),a=i instanceof Request?i:void 0,d=(n?.method??a?.method??"GET").toUpperCase(),l;try{l=new URL(a?.url??String(i),e.location.href)}catch{l=void 0}let c=!!l&&l.pathname.startsWith("/analytics/")||us(n?.headers??a?.headers);try{let f=await t(i,n);return l&&!c&&this.sample("network",`${d} ${l.origin}${V(l.pathname)}`,performance.now()-o,{attrs:{status:String(f.status)},...f.headers.get("x-request-id")?{request_id:f.headers.get("x-request-id")}:{}}),f}catch(f){throw l&&!c&&this.sample("network",`${d} ${l.origin}${V(l.pathname)}`,performance.now()-o,{attrs:{status:"0"}}),f}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function Ce(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,cs=r=>r.entryType==="event"||r.entryType==="first-input";function Z(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 hs(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[Z("largest-contentful-paint",l=>{for(let c of l)e=Math.max(e,c.startTime)}),Z("layout-shift",l=>{for(let c of l)ls(c)&&!c.hadRecentInput&&(t+=c.value)}),Z("event",l=>{for(let c of l)cs(c)&&(s=Math.max(s,c.duration))}),Z("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 o=!1,a=()=>{o||(o=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},d=()=>{document.visibilityState==="hidden"&&a()};return document.addEventListener("visibilitychange",d),()=>{a(),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 ps=/^[a-z][a-z0-9_-]{0,31}$/;function V(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return ps.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 fs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${V(e.pathname)}`}catch{return V(r.split(/[?#]/,1)[0]??"")}}var kt=/^custom\.[a-z0-9_]{1,48}$/,gs=/^[a-z][a-z0-9_]{0,63}$/,ht=r=>gs.test(r)||kt.test(r),ms=50,ut=[5e3,3e4,12e4,6e5],vs=100,se=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(!ht(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(!kt.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=()=>dt(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 o=globalThis;typeof o.addEventListener=="function"&&(o.addEventListener("storage",d=>{(d.key===this.storeKey||d.key===null)&&this.reload()}),o.addEventListener("online",()=>{this.engaged&&this.send()}));let a=this.kept;(e.options!==void 0||s!=="empty"&&(a.unknown?.on||a.unsent.length>0||a.link!==void 0||Object.keys(a.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(x(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=gt(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||x(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[o,a]of t){if(!ht(o))throw new TypeError(`${JSON.stringify(o)} is not a consent key (a platform key, or custom.<name>)`);if(a!=="granted"&&a!=="denied")throw new TypeError(`${o}: 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[o,a]of t)this.queue({key:o,state:a,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)),o=this.kept.region?.jurisdiction==="us",a=new Date(this.now());return a.setUTCMonth(a.getUTCMonth()-12),s.filter(d=>{let l=this.kept.choices[d];return o&&n.has(d)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>a.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{[E]:O(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),n={};for(let h of e.choices)n[h.key]={state:h.state,source:h.source,chosen_at:h.chosen_at,...h.text_version!==void 0?{text_version:h.text_version}:{},...h.last_denied_at!==void 0?{last_denied_at:h.last_denied_at}:{}};let o=s.filter(h=>n[h.key]?.state!==h.state||Date.parse(n[h.key]?.chosen_at??"")!==Date.parse(h.chosen_at)).map(h=>A(h.key,h)),d=x(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,h])=>h.provisional).map(([h,p])=>A(h,p)):[];if(o.length+d.length>0&&(this.kept={...this.kept,void:D([...this.kept.void??[],...o,...d])}),t===null&&this.kept.resetAt!==void 0)for(let[h,p]of Object.entries(n))Date.parse(p.chosen_at)<this.kept.resetAt&&delete n[h];let l=new Set(Object.entries(n).map(([h,p])=>A(h,p))),c=(this.kept.void??[]).filter(h=>l.has(h));c.length>0&&(this.kept={...this.kept,unvoid:D([...this.kept.unvoid??[],...c])});let f=St(this.kept),g;if(x(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))g=n;else{g={};for(let h of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let p=this.kept.choices[h],y=p&&!p.provisional&&!f.has(A(h,p))?p:void 0,P=n[h],I=P&&(!y||Date.parse(P.chosen_at)>=Date.parse(y.chosen_at))?P:y;I&&(g[h]=I)}}for(let h of this.kept.unsent){if(h.user!==null&&h.user!==t||h.user===null&&h.device!==void 0&&h.device!==this.installation.id||h.user===null&&t!==null)continue;let p=g[h.key];p&&Date.parse(p.chosen_at)>Date.parse(h.chosen_at)||(g[h.key]=pt(h,p))}let{install:S,...m}=this.kept;this.kept={...m,whose:t,...t===null?{install:this.installation.id}:{},choices:g,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&&x(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=D([...this.kept.void??[],...s.map(d=>A(d.key,d))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let o=this.states(),a={...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=a[d.key];a[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:a,void:n},this.commit(o);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=x(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:_t([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:pt(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(!yt(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],o=e===null?this.deviceApi:this.userApi(e),a;try{a=(await o.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(!yt(d))throw d;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(c=>vt(c,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(d=>!i.some(l=>vt(l,d))),done:D([...this.kept.done??[],...i.map(ie)])},this.commit(),a?(s=!0,e===t&&this.adopt(a,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(o=>o.user===e&&(e!==null||(o.device??this.installation.id)===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let o of t)if(!n.has(o.key)&&(n.add(o.key),!(o.alone||o.source!==s.source||o.text_version!==s.text_version)&&(i.push(o),i.length===ms)))break;return i}retryLater(){if(this.retryTimer)return;let e=ut[Math.min(this.retries,ut.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(([,a])=>a.state!=="unset").map(([a])=>a),...this.kept.unsent.filter(a=>a.user===null&&(a.device??this.installation.id)===this.installation.id).map(a=>a.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(a=>a.key)]),i={};for(let[a,d]of Object.entries(this.kept.choices))i[a]={state:"unset",source:"app",chosen_at:t,...d.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{}};let n=a=>a.user===null&&(a.device??this.installation.id)===this.installation.id,o=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(a=>!n(a)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:D([...this.kept.done??[],...o.map(ie)]),...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 a of s)this.queue({key:a,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,Me(n.payload))}),t.on("state_snapshot",n=>this.held(s,Me(bt(n.entries)))),t.on("state_diff",n=>this.held(s,Me(bt(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=gt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[x(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||x(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(x(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(o=>o.ads&&this.gpcRefuses(o.key)&&!this.kept.unsent.some(a=>a.key===o.key&&a.source==="gpc"&&a.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let o of s)this.queue({key:o.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[x(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=wt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(ks(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=ft(e,this.kept,"theirs",this.holder()),x(e)===x(this.kept)&&mt(this.kept)!==mt(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&(i.device??this.installation.id)===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=ft(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{wt()?.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 pt(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 A(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function St(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var te={denied:2,unset:1,granted:0};function ys(r,e,t,s){let i=e&&!s.has(A(r,e))?e:void 0,n=t&&!s.has(A(r,t))?t:void 0;if(!i||!n)return i??n;let o=Date.parse(i.chosen_at),a=Date.parse(n.chosen_at);return o!==a?o>a?i:n:te[i.state]!==te[n.state]?te[i.state]>te[n.state]?i:n:i.provisional?n:i}function ws(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function ft(r,e,t,s){let i=D([...r.void??[],...e.void??[]]),n=D([...r.unvoid??[],...e.unvoid??[]]),o=St({void:i,unvoid:n}),a={},d,l={...r.gpc};for(let[y,P]of Object.entries(e.gpc??{}))l[y]=Math.max(l[y]??0,P);let c;if(x(r)===x(e)){d=e;for(let y of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let P=ys(y,r.choices[y],e.choices[y],o);P&&(a[y]=P)}c=ws(r.unknown,e.unknown)}else{d=x(e)===s?e:x(r)===s?r:t==="ours"?e:r;for(let[y,P]of Object.entries(d.choices))o.has(A(y,P))||(a[y]=P);c=d.unknown}let f=D([...r.done??[],...e.done??[]]),g=_t([...r.unsent,...e.unsent]).filter(y=>!f.includes(ie(y))),S=t==="ours"?e:r,m=t==="ours"?r:e,h=S.region??m.region,p=S.keys??m.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)&&x(r)===x(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:d.whose==null&&d.resetAt!==void 0?{resetAt:d.resetAt}:{},choices:a,unsent:g,...f.length>0?{done:f}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...S.link!==void 0?{link:S.link}:{},...h?{region:h}:{},...Object.keys(l).length>0?{gpc:l}:{},...p?{keys:p}:{},...c?{unknown:c}:{}}}function ie(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function gt(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 x(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function D(r){return[...new Set(r)].slice(-vs)}function mt(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 _t(r){let e=new Map;for(let t of r){let s=ie(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 bs=new Set(["granted","denied","unset"]);function ks(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=(a,d)=>{if(typeof a!="object"||a===null)return!1;let l=a;return bs.has(l.state)&&typeof l.chosen_at=="string"&&(!d||typeof l.key=="string")},s=a=>a===void 0||typeof a=="object"&&a!==null&&typeof a.on=="boolean"&&typeof a.w=="number",i=r,n=a=>a===void 0||Array.isArray(a)&&a.every(d=>typeof d=="string"),o=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(a=>t(a,!1))&&e.unsent.every(a=>t(a,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(a=>typeof a=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&o}function vt(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 yt(r){return r instanceof k&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function wt(){try{return globalThis.localStorage}catch{return}}function bt(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Me(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Ss=`
3
+ :host{display:block;color-scheme:light dark;font:15px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
4
+ .list{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none}
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}
6
+ .item:focus-visible{box-shadow:0 0 0 2px var(--accent)}
7
+ .item.unread .title{font-weight:600}
8
+ .item .dot{flex:0 0 8px;height:8px;margin-top:7px;border-radius:50%;background:transparent}
9
+ .item.unread .dot{background:var(--accent)}
10
+ .item img{flex:0 0 48px;width:48px;height:48px;border-radius:8px;object-fit:cover}
11
+ .text{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1 1 auto}
12
+ .title{overflow-wrap:anywhere}
13
+ .body{color:var(--muted);overflow-wrap:anywhere}
14
+ .when{color:var(--muted);font-size:12px}
15
+ .card{position:relative;padding-right:32px;cursor:pointer}
16
+ .card.unread::before{content:"";position:absolute;left:-12px;top:14px;width:8px;height:8px;border-radius:50%;background:var(--accent)}
17
+ .delete{position:absolute;top:8px;right:8px;width:28px;height:28px;border:0;border-radius:14px;background:transparent;color:var(--muted);font-size:18px;line-height:1;cursor:pointer}
18
+ .delete:hover,.delete:focus-visible{background:var(--hover)}
19
+ .empty{padding:24px 12px;text-align:center;color:var(--muted)}
20
+ .light{--bg:#f4f4f6;--fg:#111;--muted:#5c5c66;--accent:#2f6bff;--hover:#0000000f}
21
+ .dark{--bg:#1f1f24;--fg:#f2f2f5;--muted:#a0a0ab;--accent:#5b8cff;--hover:#ffffff14}
22
+ `,ne=class{api;session;constructor(e,t){this.api=$.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 o=n.attachShadow({mode:"open"});Ye(s,o,Ss);let a=s.createElement("ul");a.className="list",o.append(a),e.append(n);let d=()=>t.appearance??(i?.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"),l=[],c=0,f=[],g=!1,S=u=>{c=u,t.onUnread?.(u)},m=(u,w)=>{u.read_at||(u.read_at=new Date().toISOString(),S(Math.max(0,c-1)),y(),this.markRead([u.id]).catch(()=>{})),!(!w||!ze(w))&&(t.onOpen?t.onOpen(u,w):w.startsWith("https://")?i?.open(w,"_blank","noopener,noreferrer"):i?.location.assign(w))},h=async u=>{l=l.filter(w=>w.id!==u.id),u.read_at||S(Math.max(0,c-1)),y(),await this.remove(u.id).catch(()=>{})},p=u=>{try{return new Intl.DateTimeFormat(t.locale,{dateStyle:"medium",timeStyle:"short"}).format(new Date(u))}catch{return u}};function y(){if(f.forEach(u=>u.destroy()),f=[],a.replaceChildren(),a.className=`list ${d()}`,!l.length){let u=s.createElement("li");u.className="empty",u.textContent=t.labels?.empty??"No messages",a.append(u);return}for(let u of l)a.append(P(u))}let P=u=>{let w=s.createElement("li");w.setAttribute("data-id",u.id),w.tabIndex=0;let M=s.createElement("button");if(M.type="button",M.className="delete",M.textContent="\xD7",M.setAttribute("aria-label",t.labels?.delete??"Delete"),M.addEventListener("click",v=>{v.stopPropagation(),h(u)}),u.card){w.className=`card ${u.read_at?"":"unread"}`;let v=s.createElement("div");w.append(v,M);let b={onAction:()=>m(u,void 0),onDeepLink:_=>m(u,_),onLink:_=>m(u,_),onCustom:t.onCustom};f.push(Xe(v,{definition:u.card,locale:t.locale??i?.navigator.language??"en",appearance:d(),variables:u.variables??{}},b)),w.addEventListener("click",_=>{_.composedPath().some(C=>C instanceof HTMLElement&&C.tagName==="BUTTON")||m(u,u.deep_link)})}else{w.className=`item ${u.read_at?"":"unread"}`;let v=s.createElement("span");if(v.className="dot",w.append(v),u.image?.startsWith("https://")){let _=s.createElement("img");_.src=u.image,_.alt="",w.append(_)}let b=s.createElement("div");b.className="text";for(let[_,C]of[["title",u.title],["body",u.body],["when",p(u.created_at)]]){if(!C)continue;let _e=s.createElement("span");_e.className=_,_e.textContent=C,b.append(_e)}w.append(b,M),w.addEventListener("click",()=>m(u,u.deep_link))}return w.addEventListener("keydown",v=>{v.key==="Enter"&&v.target===w&&m(u,u.deep_link)}),w},I=0,N=async()=>{let u=++I;if(!(await this.session.session())?.userId){if(g||u!==I)return;l=[],S(0),y();return}let w=await this.list({limit:t.limit??50,locale:t.locale});g||u!==I||(l=w.items,S(w.unread),y())},W=()=>{s.visibilityState==="visible"&&N().catch(()=>{})};s.addEventListener("visibilitychange",W);let Se=this.session.onChange(()=>{N().catch(()=>{})});return y(),N().catch(()=>{}),{refresh:N,get items(){return l},get unread(){return c},destroy(){g=!0,s.removeEventListener("visibilitychange",W),Se?.(),f.forEach(u=>u.destroy()),n.remove()}}}};var _s=30*6e4,re="session_start";function ae(r){try{return r.localStorage}catch{return}}var Ps=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function xs(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 oe=class{api;session;installation;g;now;requestPush;analyticsAllowed;purchases;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,o,a,d=globalThis,l=Date.now){this.api=$.client({send:c=>e.send({...c,headers:{...c.headers,[E]:O(s)}})}),this.session=t,this.installation=s,this.requestPush=n,this.analyticsAllowed=o,this.purchases=a,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(re,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(re)}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!==re&&await this.show(re,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||!xs(s.trigger.where,t)||this.capped(s))&&await this.open(s))return}}capped(e){let t=this.now(),s=(a,d)=>a!==void 0&&d!==void 0&&t-Date.parse(a)<d*6e4,i=this.shown,n=e.shown,o=e.limits;return i.session>=this.limits.per_session||i.day>=this.limits.per_day||s(i.last_at,this.limits.min_minutes)||o.per_session!==void 0&&n.session>=o.per_session||o.per_day!==void 0&&n.day>=o.per_day||s(n.last_at,o.min_minutes)||o.max_total!==void 0&&n.total>=o.max_total}async open(e){let t=this.opts,s=this.person,i=await this.subject(),n,o;try{({id:n,variables:o}=(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 k&&c.status===409&&(this.loaded=this.load()),!1}if(!this.opts||this.showing||s!==this.person)return!0;let a=new Date(this.now()).toISOString();for(let c of[this.shown,e.shown])c.session++,c.day++,c.total++,c.last_at=a;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,f)=>{this.api.reportInAppEvent({path:{id:n},query:{installation_id:this.installation.id},body:{type:c,...f?{action:f}:{}}}).catch(()=>{})},l=Qe({definition:e.definition,locale:t.locale??this.g.navigator?.language??"en",appearance:t.appearance??this.appearance(),variables:{...e.variables,...o}},{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)),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.purchases.offers()).find(a=>a.key===e);if(s?.kind==="grant"){await this.purchases.claimOffer(e);return}let i=s?.web?.plans[0];if(!s?.product||i===void 0)throw new k({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,o=await this.purchases.checkout({product:s.product,plan:i,successUrl:n.href,cancelUrl:n.href,offer:e});n.assign(o)}catch(s){if(!t)throw s;t(s,e)}}async converted(e){let t=this.now(),s=this.pending().filter(o=>o.until>t),i=await this.subject(),n=this.analyticsAllowed()?s.filter(o=>o.event===e&&o.subject===i):[];this.keepPending(s.filter(o=>!n.includes(o))),await Promise.all(n.map(o=>this.api.reportInAppEvent({path:{id:o.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>=_s;return this.writeSession(s?{id:`ses_${Ps()}`,last:e}:{id:t.id,last:e}),s}sessionId(e=!0){return e&&this.touch(),(this.readSession()??this.memorySession).id}readSession(){try{let e=ae(this.g)?.getItem(this.sessionKey);if(e)return JSON.parse(e)}catch{}return this.memorySession}writeSession(e){this.memorySession=e;try{ae(this.g)?.setItem(this.sessionKey,JSON.stringify(e))}catch{}}pending(){try{let e=ae(this.g)?.getItem(this.pendingKey);if(e)return JSON.parse(e)}catch{}return this.memoryPending}keepPending(e){this.memoryPending=e;try{let t=ae(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 Ie=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},Ee=class{api;session;installation;baseUrl;publishableKey;g;registered;generation=0;wake=()=>{};replacing;changing=Promise.resolve();constructor(e,t,s,i,n,o=globalThis){this.api=$.client(e),this.session=t,this.installation=s,this.baseUrl=i,this.publishableKey=n,this.g=o,t.onChange(a=>{if(a==="SIGNED_IN"||a==="SIGNED_OUT"||a==="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),o=await s.register(i,n?{scope:n}:void 0);await Ts(o);let a=await o.pushManager.getSubscription(),d=(await this.api.getWebPushKey()).data.public_key;a&&!Cs(a.options.applicationServerKey,d)&&(await a.unsubscribe(),a=null),a??=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Ie(d)});let l=this.generation;return await this.register(a),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,...Pt]){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??Ie((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===Pt.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=xt(e)?.searchParams.get("key");return!!t&&Re(t)!==void 0&&Re(t)===Re(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,o=s===void 0?n:new URL(s,i).href,a=(await e.getRegistrations()).find(l=>l.scope===o);if(!a||this.isOurs(a))return s;let d=xt(a);if(s!==void 0)throw new Error(`pb.notify.push.subscribe: ${o} 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:{[E]:O(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)}},Pt=[1e3,5e3,3e4,12e4,6e5];async function Ts(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 Re(r){let e=r.split("_");return e.length>=3&&e[0]==="pb"&&e[1]!==""?e[1]:void 0}function xt(r){let e=(r.installing??r.waiting??r.active)?.scriptURL;return e?new URL(e):void 0}function Cs(r,e){if(!r)return!1;let t=new Uint8Array(r),s=Ie(e);return t.length===s.length&&t.every((i,n)=>i===s[n])}var de=class{push;inbox;inApp;constructor(e,t,s,i,n,o,a){this.push=new Ee(e,t,s,o,a),this.inbox=new ne(e,t),this.inApp=new oe(e,t,s,new URL(o).origin,()=>this.push.subscribe(),()=>i.state("analytics")==="granted",n)}};var le=class{api;session;socket;ref;fetch;appVersion;app;listeners=new Set;watch;following;last;constructor(e,t,s,i,n,o,a){this.api=Be.client(e),this.session=t,this.socket=s,this.ref=i,this.fetch=n,this.appVersion=o,this.app=a}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 st(this.api,this.ref,e,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,source:e.source,...e.offer!==void 0?{offer:e.offer}:{}},s=(await this.api.createCheckout({body:t})).data;return s.redemption_key&&Rs(this.keyName(s.session_id),s.redemption_key),s.url}async redemptionLink(e,t={}){let s=t.key??Is(this.keyName(e));if(!s)throw new k({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 o=(n instanceof k&&n.code==="checkout_not_paid"?n.retryAfter??2:-1)*1e3;if(o<0||Date.now()+o>i)throw n;await Es(o,t.signal)}}async redeem(e){let t=Ms(e);if(!t)throw new k({op:"RedeemPurchase",status:0,code:"invalid_redemption_link",message:"not a redemption link: <scheme>://palbase/redeem?token=\u2026 or \u2026/purchases/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){return(await this.api.createPortalSession({body:{return_url:e}})).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)&&Tt(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(`purchases:${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,Oe(n.payload))}),t.on("state_snapshot",n=>this.held(s,Oe(Ct(n.entries)))),t.on("state_diff",n=>this.held(s,Oe(Ct(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])Tt(t,e)}}};function Tt(r,e){try{r(e)}catch{}}function Ct(r){let e=typeof r=="object"&&r!==null?r.revision:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Oe(r){let e=typeof r=="object"&&r!==null?r.revision:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var Mt=/^[A-Za-z0-9_-]{43}$/;function Ms(r){let e=r.trim();if(Mt.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==="/purchases/redeem",n=t.searchParams.get("token");return(s||i)&&n!==null&&Mt.test(n)?n:void 0}function Rs(r,e){try{globalThis.sessionStorage?.setItem(r,e)}catch{}}function Is(r){try{return globalThis.sessionStorage?.getItem(r)??void 0}catch{return}}function Es(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 ce=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,o,a,d){this.api=He.client(e),this.session=t,this.socket=s,this.installation=i,this.ref=n,this.analytics=a,this.appVersion=d,this.storageKey=`palbase.flags.${o}`,this.held=Os(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,Rt(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",o=>{o.event==="changed"&&this.changed(Ae(o.payload))}),i.on("state_snapshot",o=>this.changed(Ae(It(o.entries)))),i.on("state_diff",o=>this.changed(Ae(It(o.set))))];i.join().catch(()=>{}),this.leave.push(()=>{n.forEach(o=>o()),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},f=new Set;for(let g of l.data.ops)f.add(g.key),g.op==="delete"?(delete c.values[g.key],delete c.sources[g.key],delete c.experiments[g.key]):(c.values[g.key]=g.value??null,c.sources[g.key]=g.source,g.experiment?c.experiments[g.key]=g.experiment:delete c.experiments[g.key]);this.apply(c,[...f]);return}catch(l){if(!(l instanceof k&&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,o={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},a=t?.values??{},d=[...new Set([...Object.keys(a),...Object.keys(o.values)])].filter(l=>JSON.stringify(a[l])!==JSON.stringify(o.values[l]));this.apply(o,d)}headers(e,t){return{"X-Platform":"web",...this.appVersion?{"X-Palbase-Client-Version":this.appVersion}:{},[Y]:this.installation.id,...e===null?{[E]:O(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,Rt(this.storageKey,e),t.length>0&&this.tell(t))}tell(e){for(let t of[...this.listeners])try{t(e)}catch{}}};function De(){try{return globalThis.localStorage}catch{return}}function Os(r){try{let e=De()?.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 Rt(r,e){try{e?De()?.setItem(r,JSON.stringify(e)):De()?.removeItem(r)}catch{}}function It(r){let e=typeof r=="object"&&r!==null?r.sync_version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function Ae(r){let e=typeof r=="object"&&r!==null?r.sync_version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var he=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 o of n){if(!this.items.has(o.clientMessageId))continue;o.state="sending",o.attempts++;let a;try{a=await e(o)}catch{a={kind:"wait"}}if(a.kind==="wait"){this.items.has(o.clientMessageId)&&(o.state="pending"),i=this.items.has(o.clientMessageId),t(o,a);return}a.kind==="refused"?Object.assign(o,{state:"failed",error:a.code}):this.items.delete(o.clientMessageId),t(o,a)}})),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 Le(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 Et(){return{list:!1,conversations:new Set,threads:new Set,scheduled:!1}}var ue=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=Et();for(let s of e.removed_conversations??[])this.removed(s,t);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.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);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&&!As(i,s.me)?s.me:i,o={...e,me:n};if(s){if(e.version<s.version){if(n===s.me)return;o={...s,me:n}}else if(e.version===s.version&&Ns(Ot(o),s))return}e.gap&&this.messages.delete(e.id);for(let a of e.members??[])this.putMember(a,t);this.conversations.set(e.id,Ot(o)),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 o=Ds(i.read_seq,e.read_seq);if(o===i.read_seq&&e.delivered_seq<=i.delivered_seq)return;n={...i,read_seq:o,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=Et(),n=this.conversations.get(e),o=n?Math.min(t,n.me?.left_seq??n.last_seq):t;if(s!==void 0){let a=this.threads.get(s);return!a||o<=a.read_seq||(this.threads.set(s,this.threadReadTo(a,o)),i.threads.add(s)),i}return!n?.me||o<=n.me.read_seq||(this.conversations.set(e,{...n,me:this.readTo(n,n.me,o)}),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),o=this.timeline(e.id).filter(a=>a.seq>n&&a.seq<=s&&a.sender_id!==this.reader&&a.kind!=="system"&&a.kind!=="call"&&!a.deleted).length;return{...t,read_seq:s,unread_count:Math.max(0,t.unread_count-o)}}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){return this.messages.get(e)?.delete(t)??!1}list(){return[...this.conversations.values()].sort(Ls)}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 As(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 Ds(r,e){return r===null?e:e===null?r:Math.max(r,e)}function Ls(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 Ot(r){let{members:e,gap:t,...s}=r;return s}function Ns(r,e){return JSON.stringify(r)===JSON.stringify(e)}var pe=class{store;outbox=new he;me;now;constructor(e,t=Date.now){this.me=e,this.now=t,this.store=new ue(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 fe(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("messaging: this platform has no WebCrypto to encrypt files with");return r}function Us(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function qs(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 At(r){let e=crypto.getRandomValues(new Uint8Array(32)),t=crypto.getRandomValues(new Uint8Array(12));return{sealed:await js(r,e,t),fileKey:Us(e)}}async function js(r,e,t){let s=await fe().importKey("raw",e,"AES-GCM",!1,["encrypt"]),i=new Uint8Array(await fe().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 Dt(r,e){if(r.length<29||r[0]!==1)throw new Error("messaging: not a file this SDK sealed");let t=await fe().importKey("raw",qs(e),"AES-GCM",!1,["decrypt"]);return new Uint8Array(await fe().decrypt({name:"AES-GCM",iv:r.subarray(1,13)},t,r.subarray(13)))}function F(r,e){return`palbase.messaging.v1.${r}.${e}`}var ge=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:Ks(t.store),outbox:t.outbox}))}async drop(e){await this.kv.delete(e)}async dropOthers(e,t){let s=F(e,""),i=F(e,t);for(let n of await this.kv.list())n.startsWith(s)&&n!==i&&await this.kv.delete(n)}};function Ks(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 Lt(){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 $s=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u,Vs=/[\p{L}\p{Nd}\p{M}]/u,Fs=/\p{M}/u,Ws=/\p{Mn}/u;function Gs(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"))Ws.test(s)||t.push(s);return t}function Nt(r){let e=[],t=null,s=0,i=0,n=!1;for(let o of r){let a=o.length;if(!Vs.test(o))t=null,n=!1;else if($s.test(o))n||(i++,n=!0),e.push({start:s,folded:[o.toLowerCase()],ends:[s+a],run:i}),t=null;else if(Fs.test(o)&&!t){let d=e.at(-1);n&&d&&(d.ends[0]=s+a)}else{n=!1,t||(t={start:s,folded:[],ends:[],run:0},e.push(t));let d=Gs(o);d.length===0&&t.ends.length>0&&(t.ends[t.ends.length-1]=s+a);for(let l of d)t.folded.push(l),t.ends.push(s+a)}s+=a}return e}function Ut(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 qt(r){let e={words:[],runs:[]},t=new Set,s=Nt(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=Ut(s).filter(i=>[...i].length>1),e}function Hs(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 jt(r,...e){let t=r.words.map(()=>!1),s=[],i=e.map(n=>{let o=Nt(n);return s.push(...Ut(o)),o.flatMap(a=>{let d=0;return r.words.forEach((l,c)=>{Hs(a,l)&&(t[c]=!0,d=Math.max(d,l.length))}),d>0?[{offset:a.start,length:a.ends[d-1]-a.start}]:[]})});return r.runs.every(n=>s.some(o=>o.includes(n)))&&r.words.length>0&&t.every(Boolean)?i:null}var Bs=500,Js=300,zs=2e3,Kt=6e3,Xs=3e4,$t=[1e3,2e3,5e3,1e4,3e4],Ys=5*6e4,Qs=20,Zs=5,Ne=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,o)=>{let a=e.open(r,1);a.onupgradeneeded=()=>a.result.createObjectStore("kv"),a.onsuccess=()=>n(a.result),a.onerror=()=>o(a.error)}),i=(n,o)=>s().then(a=>new Promise((d,l)=>{let c=o(a.transaction("kv",n).objectStore("kv"));c.onsuccess=()=>d(c.result),c.onerror=()=>l(c.error)}));return{get:async n=>await i("readonly",o=>o.get(n))??null,set:async(n,o)=>{await i("readwrite",a=>a.put(o,n))},delete:async n=>{await i("readwrite",o=>o.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;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,o,a={}){this.transportFor=t,this.session=s,this.socket=i,this.ref=n,this.fetchFn=o,this.opts=a,this.api=Pe.client(e),this.local=new ge(a.storage??ei()??Lt()),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 f of[...this.reopeners])f()}}):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 k({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 pe(t);this.clients.set(s,Pe.client(this.transportFor(t)));let i=await this.local.open(F(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 o of n.values())this.expireAt(o);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 of Object.values(this.timers))s&&clearTimeout(s);for(let s of this.expiring.values())clearTimeout(s);this.expiring.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=F(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()},Bs)),(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 o=this.engine?.store.expire(e.conversation_id,e.id)??!1;(this.fromWindows(e.conversation_id,a=>a.expire(e.id))||o)&&(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(F(this.ref,t),e.kept())).catch(()=>{}))},Js)}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 o=t.sent(n)??{list:!1,conversations:new Set([i.conversationId]),threads:new Set,scheduled:!1};o.conversations.add(i.conversationId),n.kind==="sent"&&this.after({messages:[n.message]},o),this.save(),this.tell(o)}),this.engine!==t)return}while(this.reflush&&!e);if(e){let t=$t[Math.min(this.retries++,$t.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 Le(s.status,s.data)}catch(s){return s instanceof k?s.isNetworkError?{kind:"wait"}:Le(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,Xs)};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()+Kt),this.tell({list:!1,conversations:new Set([e.conversation_id]),threads:new Set,scheduled:!1}),setTimeout(()=>this.tell({list:!1,conversations:new Set([e.conversation_id]),threads:new Set,scheduled:!1}),Kt+50)}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 Ue(this,e.spaces??[])}deletedGroups(){return new qe(this)}conversation(e,t={}){return new je(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 Ke(this,e,t,s.at??null)}async search(e,t={}){let s=qt(e);if(s.words.length===0)return{conversations:[],messages:[],nextCursor:null};let i=t.by==="meaning",{e:n,as:o}=await this.seat(),a=async()=>{let m=t.cursor;for(let h=0;;h++){let p={q:e,...i?{by:"meaning"}:{},conversation_id:t.conversationId,...t.space?{space:[t.space]}:{},limit:t.limit,cursor:m},y=(await o.searchMessages({query:p})).data;if(i||y.data.length>0||!y.next_cursor||h+1===Zs)return y;m=y.next_cursor}},[d,l]=await Promise.all([a(),i||t.cursor||t.conversationId?Promise.resolve([]):this.named(s,n,t.space)]),c=Date.now();for(let m of d.profiles)this.people.set(m.user_id,{profile:m,at:c});let f=m=>m?this.people.get(m)?.profile??null:null,g=new Map(d.conversations.map(m=>[m.id,m])),S=d.data.flatMap(m=>{let h=g.get(m.message.conversation_id)??n.store.conversations.get(m.message.conversation_id);if(!h)return[];let p=h.kind==="direct"?f(h.peer_id):null;return[{message:m.message,conversation:h,title:h.kind==="direct"?p?.name??null:h.title,photo:h.kind==="direct"?p?.image??null:h.photo,sender:f(m.message.sender_id),peer:p,matches:m.matches,score:m.score??null,threadRootId:m.message.thread_id&&!m.message.also_in_conversation?m.message.thread_id:null}]});return{conversations:l,messages:S,nextCursor:i?null:d.next_cursor??null}}async named(e,t,s){let i=t.store.list().filter(o=>!s||o.space===s),n=[...new Set(i.filter(o=>o.kind==="direct"&&o.peer_id).map(o=>o.peer_id))].filter(o=>{let a=this.people.get(o);return!a||Date.now()-a.at>Ys});for(let o=0;o<n.length;o+=100){let a=n.slice(o,o+100);try{let d=(await this.as(t).getProfiles({query:{user_ids:a.join(",")}})).data.data,l=Date.now();for(let c of a)this.people.set(c,{profile:d.find(f=>f.user_id===c)??null,at:l})}catch{}}return i.flatMap(o=>{let a=o.kind==="direct"&&o.peer_id?this.people.get(o.peer_id)?.profile??null:null,d=o.kind==="direct"?a?.name??null:o.title,l=d?jt(e,d):null;return l?[{conversation:o,title:d,photo:o.kind==="direct"?a?.image??null:o.photo,peer:a,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 $e(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,o={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 a=s.write(e,o,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(),a}async upload(e,t){let{as:s}=await this.seat(),i=[];for(let n of t){let o=n.data instanceof Uint8Array?n.data:new Uint8Array(await n.data.arrayBuffer()),{sealed:a,fileKey:d}=await At(o),l=(await s.createUpload({path:{conversation_id:e},body:{size:a.length}})).data,c=await this.fetchFn(l.url,{method:"PUT",body:a,headers:{"content-type":"application/octet-stream"}});if(!c.ok)throw new k({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(o=>o.id===t);if(!i?.file_key)throw new k({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 k({op:"OpenFile",status:s.status,code:"download_failed",message:`the file was not read (${s.status})`});return Dt(new Uint8Array(await s.arrayBuffer()),t)}async edit(e,t,s,i){let{e:n,as:o}=await this.seat(),a=(await o.editMessage({path:{conversation_id:e,message_id:t},body:{text:s,...i?{mentions:i}:{}}})).data;return this.changed({messages:[a]},n),a}async remove(e,t,s="everyone"){let{e:i,as:n}=await this.seat(),o=await n.deleteMessage({path:{conversation_id:e,message_id:t},query:{for:s}});o.status===200?this.changed({messages:[o.data]},i):this.changed({hidden:[{conversation_id:e,message_id:t}]},i)}async react(e,t,s,i={}){let{e:n,as:o}=await this.seat(),a=(await o.react({path:{conversation_id:e,message_id:t,emoji:s},body:i.replace?{replace:!0}:{}})).data;return this.changed({messages:[a]},n),a}async unreact(e,t,s){let{e:i,as:n}=await this.seat(),o=(await n.unreact({path:{conversation_id:e,message_id:t,emoji:s}})).data;return this.changed({messages:[o]},i),o}async markRead(e,t,s){let{e:i,as:n}=await this.seat(),{upTo:o,touched:a}=i.read(e,t,s);o<=0||((a.list||a.conversations.size>0||a.threads.size>0)&&(this.tell(a),this.save()),await n.receipts({body:{receipts:[{conversation_id:e,read_seq:o,...s?{thread_id:s}:{}}]}}))}async typing(e,t){let{as:s}=await this.seat(),i=this.typedAt.get(e)??0;Date.now()-i<zs||(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,o=t.store.timeline(e).filter(n);for(let d of o)t.store.expire(e,d.id);let a=this.fromWindows(e,d=>[...d.messages.values()].filter(n).map(l=>d.expire(l.id)).includes(!0));(o.length>0||a)&&(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();this.loaded.has(e)||(this.loaded.add(e),t.store.timeline(e).length>0&&this.synced)||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),!!n.next_cursor)}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),o=this.earlier.get(e);if(n&&o!==void 0&&(o===null||parseInt(o,36)<=n.seq))return null;let a=(await i.listMessages({path:{conversation_id:e},query:{around:t,limit:50}})).data;if(s!==this.engine)return null;let d=new Ne(e);return this.putWindow(d,a.data),d.earlier=a.next_cursor??null,d.later=a.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 o=t==="earlier"?{cursor:n,limit:50}:{after:n,limit:50},a=(await i.listMessages({path:{conversation_id:e.conversationId},query:o})).data;s!==this.engine||e.merged||(this.putWindow(e,a.data),t==="earlier"?e.earlier=a.next_cursor??null:e.later=a.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(),o=(await n.getMessage({path:{conversation_id:e,message_id:t}})).data,a=[],d;for(let l=0;l<Qs;l++){let c=(await n.listReplies({path:{conversation_id:e,message_id:t},query:d?{limit:100,cursor:d}:{limit:100}})).data;if(a.push(...c.data),d=c.next_cursor,!d||!s||a.some(f=>f.id===s))break}this.changed({messages:[o,...a]},i)}async openScheduled(){let{e,as:t}=await this.seat();this.changed({scheduled:(await t.listScheduled()).data.data},e)}},q=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(){}},Ue=class extends q{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()}}},qe=class extends q{touches(e){return e.list}read(){return{items:this.m.current()?.deletedGroups()??[]}}},je=class extends q{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)}},Ke=class extends q{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)}},$e=class extends q{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 ve=class{pc;o;early=[];sending={};state="connecting";connected=!1;restarts=0;timer;restarting=null;constructor(e){this.o=e;let t=new e.RTCPeerConnection({iceServers:e.iceServers.map(Vt),iceTransportPolicy:e.relay?"relay":"all"});this.pc=t,t.onicecandidate=s=>{let i=s.candidate;i&&i.candidate&&e.send({type:"candidate",candidate:{candidate:i.candidate,sdp_mid:i.sdpMid??null,sdp_m_line_index:i.sdpMLineIndex??null}})},t.ontrack=s=>e.onTrack(s.track),t.onconnectionstatechange=()=>this.changed()}async start(){this.o.offerer&&(this.sending.audio=this.pc.addTransceiver(this.o.audio??"audio",{direction:"sendrecv"}),this.sending.video=this.pc.addTransceiver(this.o.video??"video",{direction:"sendrecv"}),await this.offer(!1))}async receive(e){if(this.state!=="closed")switch(e.type){case"offer":{if(this.o.offerer||!e.sdp)return;await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp}),await this.sendBoth(),await this.flush(),await this.pc.setLocalDescription(await this.pc.createAnswer()),this.o.send({type:"answer",sdp:this.pc.localDescription?.sdp??""});return}case"answer":if(!this.o.offerer||!e.sdp||this.pc.signalingState!=="have-local-offer")return;await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}),await this.flush();return;case"candidate":{if(!e.candidate)return;let t={candidate:e.candidate.candidate,sdpMid:e.candidate.sdp_mid??null,sdpMLineIndex:e.candidate.sdp_m_line_index??null};this.pc.remoteDescription?await this.pc.addIceCandidate(t).catch(()=>{}):this.early.push(t);return}case"bye":this.close()}}async setTrack(e,t){e==="audio"?this.o.audio=t:this.o.video=t,await this.sending[e]?.sender.replaceTrack(t)}nudge(){this.state!=="connected"&&this.state!=="closed"&&this.restart()}close(){this.state!=="closed"&&(clearTimeout(this.timer),this.pc.onicecandidate=null,this.pc.ontrack=null,this.pc.onconnectionstatechange=null,this.pc.close(),this.set("closed"))}async sendBoth(){for(let e of this.pc.getTransceivers()){let t=e.receiver.track?.kind;!t||this.sending[t]||(this.sending[t]=e,e.direction="sendrecv",await e.sender.replaceTrack(t==="audio"?this.o.audio:this.o.video))}}async flush(){for(let e of this.early.splice(0))await this.pc.addIceCandidate(e).catch(()=>{})}async offer(e){await this.pc.setLocalDescription(await this.pc.createOffer(e?{iceRestart:!0}:void 0)),this.o.send({type:"offer",sdp:this.pc.localDescription?.sdp??""}),this.watch(this.o.connectWithinMs??15e3)}restart(){return!this.o.offerer||this.state==="closed"||this.restarts>=6?Promise.resolve():(this.restarting??=(async()=>{this.restarts++;try{let e=await this.o.servers();if(this.state==="closed")return;this.pc.setConfiguration({...this.pc.getConfiguration(),iceServers:e.map(Vt)})}catch{}this.state!=="closed"&&(this.pc.signalingState==="have-local-offer"&&await this.pc.setLocalDescription({type:"rollback"}),await this.offer(!0))})().catch(()=>{}).finally(()=>this.restarting=null),this.restarting)}watch(e){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.pc.connectionState!=="connected"&&this.restart()},e)}changed(){switch(this.pc.connectionState){case"connected":clearTimeout(this.timer),this.connected=!0,this.restarts=0,this.set("connected");return;case"disconnected":this.set("reconnecting"),this.watch(this.o.restartAfterMs??4e3);return;case"failed":this.set("reconnecting"),this.restart();return;case"closed":this.set("closed");return;default:this.set(this.connected?"reconnecting":"connecting")}}set(e){e!==this.state&&(this.state=e,this.o.onState(e))}};function Vt(r){return{urls:r.urls,...r.username===void 0?{}:{username:r.username},...r.credential===void 0?{}:{credential:r.credential}}}var Ft=async r=>ti(await import("livekit-client"))(r);function ti(r){return async e=>{let t=new r.Room({adaptiveStream:!1,dynacast:!0,stopLocalTrackOnUnpublish:!1}),s=()=>t.localParticipant,i=!1;t.on(r.RoomEvent.TrackSubscribed,(o,a,d)=>e.track(d.identity,o.mediaStreamTrack)).on(r.RoomEvent.TrackUnsubscribed,(o,a,d)=>e.trackGone(d.identity,o.mediaStreamTrack)).on(r.RoomEvent.TrackMuted,(o,a)=>{a!==s()&&o.track&&e.muted(a.identity,o.track.mediaStreamTrack,!0)}).on(r.RoomEvent.TrackUnmuted,(o,a)=>{a!==s()&&o.track&&e.muted(a.identity,o.track.mediaStreamTrack,!1)}).on(r.RoomEvent.Reconnecting,()=>e.state("reconnecting")).on(r.RoomEvent.Reconnected,()=>e.state("connected")).on(r.RoomEvent.Disconnected,()=>{i||e.state("disconnected")});let n=new Map;return{async connect(o,a,d){await t.connect(o,a,d?{rtcConfig:{iceTransportPolicy:"relay"}}:void 0),e.state("connected")},async publish(o){let a=o.kind==="video"?r.Track.Source.Camera:r.Track.Source.Microphone;n.set(o,await s().publishTrack(o,{source:a}))},async unpublish(o){n.delete(o),await s().unpublishTrack(o,!1)},async mute(o,a){let d=n.get(o);d&&await(a?d.mute():d.unmute())},async close(){i=!0,await t.disconnect()}}}}var Ve=class{id;c;call;snapshot;listeners=new Set;owned=!1;entering=!1;phase="incoming";endReason=null;error=null;relay=!1;local=null;tracks={audio:null,video:null};opened=new Set;mic=!0;facing="user";link=null;linking=null;linkState="connecting";sdpSent=Promise.resolve();answered;answer;inbox=Promise.resolve();lastSeq=0;seen=new Set;sentSeqs=new Set;room=null;joiningRoom=null;roomState=null;streams=new Map;via=new Map;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.answered=new Promise(i=>this.answer=i),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)){if(this.done)throw this.refused("join","call_ended","this session is over: pb.calls.join(callId) comes into the call again");await this.enter(e,t=>this.c.api.joinCall({path:{call_id:this.id},body: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 setAudioOutput(e){this.sink=e;for(let t of this.players.values())await Gt(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())}receive(e){e.to_device_id!==this.c.device||!this.owned||(this.inbox=this.inbox.then(()=>this.take(e)).catch(()=>{}))}caughtUp(){!this.owned||this.done||(this.refresh().catch(()=>{}),this.link&&(this.inbox=this.inbox.then(()=>this.fetchSignals()).catch(()=>{})))}online(){this.link?.nudge()}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==="active"&&this.answer(!0),e.state==="ended")return this.end(si(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(),e.mode==="p2p"?this.toPeer():this.toRoom()}else if(t?.state==="ringing")this.phase="incoming";else if(t?.state==="invited")this.phase="invited";else if(!this.entering)if(t?.state==="joined")this.phase="elsewhere",this.quiet();else return this.end(t?.state??"ended");this.changed()}mediaPhase(){if(this.call.mode==="sfu"&&this.roomState){if(this.roomState==="connected")return"connected";if(this.roomState==="reconnecting")return"reconnecting"}return this.link&&this.linkState!=="closed"?this.linkState==="connected"?"connected":this.linkState:"connecting"}async enter(e,t){this.relay=this.c.relay||e.forceRelay===!0,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=Wt(s);throw i?this.apply(i):this.derive(),s}this.entering=!1,this.derive(),this.inCall&&this.c.entered(this)}own(e,t){if(this.done){for(let s of e.opened)s.stop();return}this.owned=!0,this.relay=t,this.local=e.local,this.tracks=e.tracks;for(let s of e.opened)this.opened.add(s);this.derive()}async open(e,t){let s=await Ht(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(),await this.link?.setTrack("video",e),this.room&&(t&&await this.room.unpublish(t).catch(()=>{}),e&&await this.room.publish(e)),t&&t!==e&&this.stopIfOpened(t)}toPeer(){return this.link||this.linking||this.room?Promise.resolve():(this.linking=(async()=>{let e=(await this.c.api.getCallMedia({path:{call_id:this.id},body:{device_id:this.c.device}})).data;if(e.mode!=="p2p"||this.done||this.room)return;let t=e.peer_user_id??this.call.participants.find(n=>n.user_id!==this.c.me&&n.kind==="user")?.user_id??"",s=this.c.rtc(),i=new ve({RTCPeerConnection:s.RTCPeerConnection,offerer:e.offerer,iceServers:e.ice_servers,relay:this.relay||e.ice_transport_policy==="relay",audio:this.tracks.audio,video:this.tracks.video,send:n=>this.signal(i,n),onTrack:n=>{this.link===i&&this.heard(t,n,"p2p")},onState:n=>{this.link===i&&(this.linkState=n,n==="closed"&&this.unlink(),this.derive())},servers:async()=>(await this.c.api.getCallMedia({path:{call_id:this.id},body:{device_id:this.c.device}})).data.ice_servers});this.link=i,this.linkState="connecting",await i.start(),this.inbox=this.inbox.then(()=>this.fetchSignals()).catch(()=>{})})().catch(e=>this.failed(e)).finally(()=>this.linking=null),this.linking)}signal(e,t){let s=async()=>{if(!await this.answered||this.link!==e)return;let i=t.type==="candidate"?{device_id:this.c.device,type:"candidate",candidate:t.candidate}:{device_id:this.c.device,type:t.type,sdp:t.sdp};for(let n=0;;n++)try{this.sentSeqs.add((await this.c.api.sendCallSignal({path:{call_id:this.id},body:i})).data.seq);return}catch(o){if(t.type==="candidate"||n>=2||!(o instanceof k)||!o.isNetworkError)return;await new Promise(a=>setTimeout(a,500*(n+1)))}};t.type==="candidate"?this.sdpSent.then(s).catch(()=>{}):this.sdpSent=this.sdpSent.then(s).catch(()=>{})}async take(e){this.seen.has(e.seq)||!this.link||(this.gapBefore(e.seq)&&await this.fetchSignals(),this.seen.has(e.seq)||await this.handle(e))}gapBefore(e){if(e-this.lastSeq>1e3)return!0;for(let t=this.lastSeq+1;t<e;t++)if(!this.seen.has(t)&&!this.sentSeqs.has(t))return!0;return!1}async fetchSignals(){if(!this.link||this.done)return;let e=await this.c.api.listCallSignals({path:{call_id:this.id},query:{device_id:this.c.device,after:this.lastSeq}});for(let t of e.data.signals)this.seen.has(t.seq)||await this.handle(t)}async handle(e){this.seen.add(e.seq),this.lastSeq=Math.max(this.lastSeq,e.seq),await this.link?.receive(e)}unlink(){let e=this.link;this.link=null,e?.close();for(let[t,s]of[...this.via])s.how==="p2p"&&this.gone(s.user,t)}toRoom(){return this.room||this.joiningRoom?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(e.mode!=="sfu"||!e.url||!e.token||this.done)return;let t=await this.c.room({track:(s,i)=>{this.room===t&&this.heard(s,i,"sfu")},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())},state:s=>{if(this.room===t){if(this.roomState=s,s==="disconnected"){this.room=null,this.roomState=null;for(let[i,n]of[...this.via])n.how==="sfu"&&this.gone(n.user,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,this.relay);for(let s of[this.tracks.audio,this.tracks.video])s&&await t.publish(s);this.tracks.audio&&!this.mic&&await t.mute(this.tracks.audio,!0),this.link&&this.unlink(),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){let t=this.streams.get(e);return t||this.streams.set(e,t=new(this.c.rtc()).MediaStream),t}heard(e,t,s){let i=this.streamOf(e);for(let n of i.getTracks())n.kind===t.kind&&n!==t&&this.via.get(n)?.how!==s&&this.gone(e,n);if(i.getTracks().includes(t)||i.addTrack(t),!this.via.has(t)){let n=()=>this.changed();t.addEventListener?.("mute",n),t.addEventListener?.("unmute",n),t.addEventListener?.("ended",n)}this.via.set(t,{user:e,how:s}),t.kind==="audio"&&this.play(e,i),this.changed()}gone(e,t){this.via.delete(t),this.mutedInRoom.delete(t),this.streams.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&&Gt(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.link&&this.linkState!=="connected"&&(this.inbox=this.inbox.then(()=>this.fetchSignals()).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 k&&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,this.answer(!1),clearInterval(this.heartbeat),clearInterval(this.poll),this.unlink();let s=this.room;this.room=null,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=Wt(e);throw t&&this.apply(t),e}refused(e,t,s){return new k({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(n=>n.user_id!==e&&n.state==="joined"):[],i=s.map(n=>this.remoteOf(n.user_id,n));if(t)for(let[n,o]of this.streams)o.getTracks().length>0&&!s.some(a=>a.user_id===n)&&i.push(this.remoteOf(n));this.snapshot={call:this.call,me:this.me()??null,phase:this.phase,outgoing:this.call.caller_id===e,mode:this.call.mode,local:t?this.local:null,microphone:this.mic&&this.tracks.audio!==null,camera:this.tracks.video!==null,remote:i,endReason:this.endReason,error:this.error};for(let n of[...this.listeners])try{n()}catch{}}remoteOf(e,t){let s=this.streamOf(e),i=n=>s.getTracks().some(o=>o.kind===n&&o.readyState!=="ended"&&!o.muted&&!this.mutedInRoom.has(o));return{userId:e,name:t?.name??null,imageUrl:t?.image_url??null,bot:t?.kind==="bot"||e.startsWith("bot:"),stream:s,audio:i("audio"),video:i("video")}}},ye=class{deviceId;transportFor;session;socket;ref;opts;beacon;user=null;api=null;channel=null;off=[];sessions=new Map;incoming=new Set;entered=new Set;workerHeard=!1;constructor(e,t,s,i,n,o,a={}){this.transportFor=e,this.session=t,this.socket=s,this.ref=i,this.deviceId=n,this.beacon=o,this.opts=a,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)throw new TypeError("calls.start: name the person (or people) to call");await this.ready();let i=this.api,n=await Ht(this.rtc(),t.video===!0,t.media),o;try{o=(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}}})).data}catch(d){for(let l of n.opened)l.stop();throw d}let a=this.sessionOf(o,!1);return a.own(n,this.opts.forceRelay===!0||t.forceRelay===!0),a.inCall&&(this.sessions.set(a.id,a),this.tell(this.entered,a)),a}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=this.sessions.get(e);return s||(s=this.sessionOf((await this.api.getCall({path:{call_id:e}})).data,!0)),await s.join(t),s}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 k({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=Ge.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();this.sessions.clear(),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=>{this.user===e&&(s.event==="call"?this.heardCall(s.payload):s.event==="signal"&&this.sessions.get(s.payload.call_id)?.receive(s.payload))}),t.onJoined(()=>{if(this.user===e){for(let s of this.sessions.values())s.caughtUp();this.ringing().catch(()=>{})}})),t.join().catch(()=>{})}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 Ve({api:this.api,me:this.user,device:this.deviceId,rtc:()=>this.rtc(),room:this.opts.room??Ft,relay:this.opts.forceRelay===!0,playAudio:this.opts.playAudio!==!1,heartbeatMs:this.opts.heartbeatMs??15e3,pollMs:this.opts.pollMs??2e3,live:()=>this.channel?.state==="joined",forget(o){i.get(o.id)===o&&i.delete(o.id)},quiet:o=>ii(o),entered:o=>{i.set(o.id,o),this.tell(this.entered,o)}},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{RTCPeerConnection:e.RTCPeerConnection,MediaStream:e.MediaStream,getUserMedia:s=>t.getUserMedia(s)}}};async function Ht(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,o=e?s.getVideoTracks()[0]??null:null;if(!t&&!e)for(let d of s.getVideoTracks())d.stop();return{local:new r.MediaStream([n,o].filter(d=>d!==null)),tracks:{audio:n,video:o},opened:i.filter(d=>d===n||d===o)}}function si(r,e){return e?.state==="missed"||e?.state==="declined"||e?.state==="busy"?e.state:r.end_reason??"ended"}function Wt(r){if(!(r instanceof k)||r.status!==409)return;let e=r.body;return e?.call&&typeof e.call.id=="string"?e.call:void 0}function ii(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 Gt(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)}var we=class{api;open;session;credentials;mfa;passkey;magicLink;phone;password;email;sessions;constructor(e,t,s,i){this.api=K.client(e),this.open=K.client(t),this.session=s,this.credentials=i;let n=this.api,o=this.open;this.mfa={challenge:async(a,d,l)=>this.signedIn((await o.mfaChallenge({body:{mfa_token:a,type:d,code:l}})).data),recovery:async(a,d)=>this.signedIn((await o.mfaRecovery({body:{mfa_token:a,code:d}})).data),sendSmsCode:async a=>{await o.mfaSmsChallenge({body:{mfa_token:a}})},sendEmailCode:async a=>{await o.mfaEmailChallenge({body:{mfa_token:a}})},enrollTotp:async()=>{let a=(await n.mfaEnroll({body:{type:"totp"}})).data;return{enrollmentId:a.enrollment_id,secret:a.secret,otpUrl:a.otp_url,qrCode:a.qr_code,recoveryCodes:a.recovery_codes}},verifyTotp:async a=>{await n.mfaVerifyEnrollment({body:{code:a}})},enrollSms:async a=>(await n.mfaSmsEnroll({body:{phone:a}})).data,verifySms:async a=>{await n.mfaSmsVerifyEnrollment({body:{code:a}})},enrollEmail:async()=>{await n.mfaEmailEnroll()},factors:async()=>(await n.mfaListFactors()).data,removeFactor:async(a,d)=>{await n.mfaRemoveFactor({path:{id:a},body:{current_password:d}})},regenerateRecoveryCodes:async()=>(await n.mfaRegenerateRecoveryCodes()).data,stepUp:async a=>this.steppedUp(async()=>(await n.stepUp({body:{method:"totp",code:a}})).data),sendStepUpSmsCode:async()=>{await n.stepUpSmsSend()},stepUpWithSms:async a=>this.steppedUp(async()=>(await n.stepUp({body:{method:"sms",code:a}})).data)},this.passkey={register:async a=>{let d=(await n.webauthnRegisterBegin({body:{name:a}})).data,l=await this.authenticator().create({publicKey:Bt(d.options.publicKey)});return(await n.webauthnRegisterFinish({body:Jt(l)})).data},signIn:async(a={})=>{let d=(await o.webauthnLoginBegin({body:a.userId?{user_id:a.userId}:{}})).data,l=await this.authenticator().get({publicKey:Fe(d.options.publicKey)}),c=await o.webauthnLoginFinish({query:a.userId?{user_id:a.userId}:void 0,body:We(l)});return this.signedIn(c.data)},signUp:async(a,d)=>{let l=(await o.webauthnSignupBegin({body:{identifier:a,user_name:d}})).data,c=await this.authenticator().create({publicKey:Bt(l.options.publicKey)});await o.webauthnSignupFinish({query:{user_id:l.user_id},body:Jt(c)});let f=(await o.webauthnLoginBegin({body:{user_id:l.user_id}})).data,g=await this.authenticator().get({publicKey:Fe(f.options.publicKey)});return this.signedIn((await o.webauthnLoginFinish({query:{user_id:l.user_id},body:We(g)})).data)},stepUp:async()=>this.steppedUp(async()=>{let a=(await n.stepUpWebAuthnBegin()).data,d=await this.authenticator().get({publicKey:Fe(a.publicKey)});return(await n.stepUp({body:{method:"webauthn",...We(d)}})).data}),list:async()=>(await n.webauthnListCredentials()).data,remove:async a=>{await n.webauthnDeleteCredential({path:{id:a}})}},this.magicLink={send:async(a,d={})=>{await o.magicLinkRequest({body:{email:a,...d.redirectTo?{redirect_to:d.redirectTo}:{}}})},verify:async a=>this.signedIn((await o.magicLinkVerify({body:{token:a}})).data)},this.phone={sendCode:async a=>(await o.requestPhoneOtp({body:{phone:a,channel:"sms"}})).data,verifyCode:async(a,d)=>this.signInResult((await o.verifyPhoneOtp({body:{phone:a,token:d}})).data)},this.password={requestReset:async(a,d={})=>{await o.passwordResetRequest({body:{email:a,...d.redirectTo?{redirect_to:d.redirectTo}:{}}})},confirmReset:async(a,d)=>{await o.passwordResetConfirm({body:{token:a,new_password:d}})},change:async a=>(await n.passwordChange({body:a})).data,set:async a=>(await n.setPassword({body:a})).data},this.email={verify:async a=>{await o.verifyEmail({body:a})},resendVerification:async a=>(await o.resendVerification({body:{email:a}})).data},this.sessions={list:async()=>(await n.listSessions()).data,revoke:async a=>{await n.revokeSession({path:{id:a}})},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}},be=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},L=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(/=+$/,"")},zt=r=>Array.isArray(r)?r.map(e=>({...e,id:be(String(e.id))})):void 0;function Bt(r){let e=r.user;return{...r,challenge:be(String(r.challenge)),user:{...e,id:be(String(e.id))},excludeCredentials:zt(r.excludeCredentials)}}function Fe(r){return{...r,challenge:be(String(r.challenge)),allowCredentials:zt(r.allowCredentials)}}function Jt(r){let e=r,t=e.response;return{id:e.id,rawId:L(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:L(t.clientDataJSON),attestationObject:L(t.attestationObject),transports:t.getTransports?.()}}}function We(r){let e=r,t=e.response;return{id:e.id,rawId:L(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:L(t.clientDataJSON),authenticatorData:L(t.authenticatorData),signature:L(t.signature),userHandle:L(t.userHandle)}}}var ni=/^pb_[a-z0-9]+_s/,ri=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ai=new Set(["invalid_token","token_expired","session_expired","session_revoked","missing_token"]),oi=new Set(["invalid_token","token_reuse","token_expired","session_revoked","session_expired","session_device_changed"]);function di(r){return r.status===400&&r.code==="invalid_request"}function Dn(r){if(ni.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&&!ri.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=Xt(r.language),s=(v,b)=>{let _=r.fetch??globalThis.fetch;if(t===void 0)return _(v,b);let C=new Headers(b?.headers);return C.has("accept-language")||C.set("accept-language",t),_(v,{...b,headers:C})},i=new URL(r.url).origin,n=r.storage??(ci()?nt(`palbase.session.${i}`):it()),o=r.retry??Je,a=H(j({baseUrl:r.url,credentials:{publishableKey:r.publishableKey},fetch:s}),o),d=K.client(a),l=new B(n,async v=>(await d.refreshToken({body:{refresh_token:v}})).data,v=>v instanceof k&&(v.status===401&&oi.has(v.code)||di(v)),{lockName:`palbase.session.refresh.${i}`,refresh:r.refresh}),c=j({baseUrl:r.url,credentials:{publishableKey:r.publishableKey,accessToken:()=>l.accessToken()},fetch:s,xmlHttpRequest:r.xmlHttpRequest??(r.fetch===void 0?globalThis.XMLHttpRequest:void 0)}),f=H(ke(c,l),o),g=new z({baseUrl:r.url,publishableKey:r.publishableKey,accessToken:()=>l.accessToken(),webSocket:r.webSocket});l.onChange(v=>{v==="SIGNED_OUT"||v==="SESSION_EXPIRED"||v==="SIGNED_IN"?g.disconnect():v==="TOKEN_REFRESHED"&&g.tokenChanged()});let S=new X(i),m=v=>H(ke(j({baseUrl:r.url,credentials:{publishableKey:r.publishableKey,accessToken:async()=>{let b=await l.accessToken();if(b===void 0||xe(b)!==v)throw new T(`the session is no longer ${v}'s`);return b}},fetch:s}),l),o),h=v=>K.client(m(v)),p=new se({userApi:h,deviceApi:d,session:l,socket:g,ref:e,installation:S,origin:i,options:r.consent}),y=j({baseUrl:r.url,credentials:{publishableKey:r.publishableKey},fetch:s}),P=new ee(ke(c,l),y,l,p,S,i),I=new le(f,l,g,e,s,r.appVersion,r.appId),N=new de(f,l,S,p,I,r.url,r.publishableKey);P.onEvent((v,b)=>N.inApp.trigger(v,b)),r.analytics&&P.start(r.analytics===!0?{}:r.analytics);let W=new Map,Se=v=>{let b=new URL(v).origin,_=W.get(b);return _||(_=H(ke(j({baseUrl:b,credentials:{accessToken:()=>l.accessToken()},fetch:s}),l),o),W.set(b,_)),_},u=Ze(f),w=v=>{let b=l.snapshot();b&&s(new URL(v,i).href,{method:"POST",keepalive:!0,headers:{apikey:r.publishableKey,authorization:`Bearer ${b.accessToken}`}}).catch(()=>{})},M=Object.assign(Object.create(et),{auth:new we(f,a,l,r.webauthn??globalThis.navigator?.credentials),socket:g,transport:f,analytics:P,consent:p,installation:S,purchases:I,notify:N,flags:new ce(f,l,g,S,e,i,P,r.appVersion),messaging:new me(f,m,l,g,e,s,r.messaging),calls:new ye(m,l,g,e,`web-${S.id}`,w,r.calls),setLanguage(v){t=Xt(v??void 0)},chatToolCall:(v,b,_={})=>u.toolCall(v,b,_.signal),chatWorkspaceFile:(v,b,_,C={})=>u.workspaceFile(v,b,_,C.signal)});return tt(M,i,Se,f,g,()=>l.snapshot()?.userId),M}var li=/^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$/;function Xt(r){if(r===void 0)return;let e=typeof r=="string"?[r]:[...r];if(e.length!==0){for(let t of e)if(!li.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 ci(){try{return typeof globalThis.localStorage<"u"}catch{return!1}}function ke(r,e){return{async send(t){let s=await e.session();try{return await r.send(t)}catch(i){let n=t.auth.some(o=>o.includes("userJWT"));if(!(i instanceof k)||i.status!==401||!ai.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,it as b,nt as c,Te as d,z as e,X as f,ee as g,se as h,ne as i,re as j,oe as k,Ee as l,de as m,le as n,Ms as o,ce as p,ei as q,me as r,Ue as s,qe as t,je as u,Ke as v,$e as w,Ve as x,ye as y,Dn as z};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.27.0 — Palbase SDK License (see LICENSE) */
2
- import{p as R,t as k,u as H}from"./QL42CXIT.js";var N=40,V=`
1
+ /*! palbase 0.29.0 — Palbase SDK License (see LICENSE) */
2
+ import{p as R,t as k,u as H}from"./WNEUGMU4.js";var N=40,V=`
3
3
  :host{display:contents}
4
4
  .pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
5
5
  .pm-modal::backdrop,.pm-full::backdrop{background:transparent}