From 8915d84fe09f8d39b464f4ee5ad674c2795a1798 Mon Sep 17 00:00:00 2001 From: Harsh Date: Thu, 12 Nov 2026 16:59:06 -0800 Subject: [PATCH 1/2] Workspace UI: keep burst messages reachable during live refresh Poll the newest history page, then walk back over burst pages (bounded to three) until they overlap what is already on screen. When the walk ends without overlapping, leave an explicit gap control that loads the missed range in place, so bursts larger than one page and hidden-tab resumes no longer strand messages between pages. Applies to conversations and channels; stale results are discarded on navigation and composer contents are untouched. Regenerate the embedded browser bundle. --- bus/hostedweb/app.js | 34 +++---- web/src/app.js | 119 ++++++++++++++++++++--- web/tests/workspace.spec.js | 186 ++++++++++++++++++++++++++++++++++++ 3 files changed, 310 insertions(+), 29 deletions(-) diff --git a/bus/hostedweb/app.js b/bus/hostedweb/app.js index ee96353..f20f63f 100644 --- a/bus/hostedweb/app.js +++ b/bus/hostedweb/app.js @@ -1,22 +1,22 @@ -function ue(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s{let n=new Array(128);for(let e=0;e=6;){let r=e.queue>>e.queuedBits-6&63;t(Ke[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let r=e.queue>>e.queuedBits-6&63;t(Ke[r]),e.queuedBits-=6}}function Wt(n,e,t){let r=Er[n];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function at(n){let e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Tr(o,r,t)};for(let o=0;o>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function Ir(n,e){for(let t=0;t55295&&r<=56319){let s=(r-55296)*1024&65535;r=(n.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}Ar(r,e)}}function Tr(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let r=1;r<6;r+=1)if((n>>7-r&1)===0){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function ae(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;se.push(t)),new Uint8Array(e)}function ne(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return n.forEach(s=>Ft(s,t,r)),Ft(null,t,r),e.join("")}function Fe(n){return Math.round(Date.now()/1e3)+n}function Gt(){return Symbol("auth-callback")}var L=()=>typeof window<"u"&&typeof document<"u",pe={tested:!1,writable:!1},We=()=>{if(!L())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(pe.tested)return pe.writable;let n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),pe.tested=!0,pe.writable=!0}catch{pe.tested=!0,pe.writable=!1}return pe.writable};function lt(n){let e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var Be=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),Vt=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",Q=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},M=async(n,e)=>{let t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}},W=async(n,e)=>{await n.removeItem(e)},Oe=class n{constructor(){this.promise=new n.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Oe.promiseConstructor=Promise;function Ue(n){let e=n.split(".");if(e.length!==3)throw new oe("Invalid JWT structure");for(let r=0;r{setTimeout(()=>e(null),n)})}function Jt(n,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await n(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function Ht(n){return("0"+n.toString(16)).substr(-2)}function xr(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,Ht).join("")}async function Cr(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function Or(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;let t=await Cr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Pr=/^[a-zA-Z0-9_-]{8,64}$/;function je(n){return typeof n=="string"&&Pr.test(n)?n:null}function Ur(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,Ht).join("")}let n="";for(let e=0;e<32;e++)n+=Math.floor(Math.random()*16).toString(16);return n}var we=(n,e)=>`${n}-flow-${e}-code-verifier`,Pe=n=>`${n}-flows-code-verifier`;async function ct(n,e){let t=await M(n,Pe(e));return Array.isArray(t)?t.filter(r=>je(r)!==null):[]}async function jr(n,e,t,r,s){await Q(n,we(e,t),r);let i=(await ct(n,e)).filter(o=>o!==t);for(i.push(t);i.length>Lt;){let o=i.shift();await W(n,we(e,o)),s?.(o)}await Q(n,Pe(e),i),await Q(n,`${e}-code-verifier`,r)}async function Yt(n,e,t){if(t){let s=await M(n,we(e,t));return{verifier:typeof s=="string"?s:null,flowId:t}}let r=await M(n,`${e}-code-verifier`);return{verifier:typeof r=="string"?r:null,flowId:null}}async function J(n,e,t){let r=`${e}-code-verifier`;if(!t){await W(n,r);return}let s=we(e,t),i=await M(n,s);await W(n,s);let o=await ct(n,e),l=o.filter(c=>c!==t);l.length!==o.length&&(l.length>0?await Q(n,Pe(e),l):await W(n,Pe(e))),i!=null&&i===await M(n,r)&&await W(n,r)}async function Xt(n,e){let t=await ct(n,e);for(let r of t)await W(n,we(e,r));await W(n,Pe(e)),await W(n,`${e}-code-verifier`)}function Qt(n,e){let t=n.indexOf("#"),r=t===-1?n:n.slice(0,t),s=t===-1?"":n.slice(t),i=r.indexOf("?");if(i!==-1){let l=r.slice(0,i),c=r.slice(i+1).split("&").filter(u=>u!==""&&u!==re&&!u.startsWith(`${re}=`));r=c.length>0?`${l}?${c.join("&")}`:l}let o=r.includes("?")?"&":"?";return`${r}${o}${re}=${encodeURIComponent(e)}${s}`}async function Zt(n,e,t=!1,r){let s=xr(),i=s;t&&(i+="/recovery");let o=Ur();await jr(n,e,o,i,r);let l=await Or(s);return[l,s===l?"plain":"s256",o]}var $r=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function er(n){let e=n.headers.get(Ee);if(!e||!e.match($r))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function tr(n){if(!n)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function rr(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Dr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Z(n){if(!Dr.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ke(n){if(!n.recoveryCodes)throw new Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function Ge(){let n={};return new Proxy(n,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){let r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function sr(n,e){return new Proxy(n,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){let i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,r,s)}})}function ut(n){return JSON.parse(JSON.stringify(n))}var ge=n=>{if(typeof n=="object"&&n!==null){let e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(n)},nr=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function ir(n){var e;if(!Vt(n))throw new fe(ge(n),0);let t;try{t=await n.json()}catch(i){throw nr.includes(n.status)?new fe(n.statusText||`HTTP ${n.status}`,n.status):new K(ge(i),i)}if(nr.includes(n.status))throw new fe(ge(t),n.status);let r,s=er(n);if(s&&s.getTime()>=nt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Te(ge(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new j}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Te(ge(t),n.status,t.weak_password.reasons);throw new qe(ge(t),n.status||500,r)}var Nr=(n,e,t,r)=>{let s={method:n,headers:e?.headers||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function y(n,e,t,r){var s;let i=Object.assign({},r?.headers);i[Ee]||(i[Ee]=nt["2024-01-01"].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Lr(n,e,t+l,{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Lr(n,e,t,r,s,i){let o=Nr(e,r,s,i),l;try{l=await n(t,Object.assign({},o))}catch(c){throw new fe(ge(c),0)}if(l.ok||await ir(l),r?.noResolveJson)return l;try{return await l.json()}catch(c){await ir(c)}}function V(n){var e;let t=null;qr(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Fe(n.expires_in)));let r=(e=n.user)!==null&&e!==void 0?e:typeof n?.id=="string"?n:null;return{data:{session:t,user:r},error:null}}function dt(n){let e=V(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=n.weak_password),e}function ee(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function or(n){return{data:n,error:null}}function ar(n){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i}=n,o=ue(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function ht(n){return n}function qr(n){return!!n.access_token&&!!n.refresh_token&&!!n.expires_in}var Ve=["global","local","others"];var ye=class{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=Be(r),this.experimental=s??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=Ve[0]){if(Ve.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ve.join(", ")}`);try{return await y(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await y(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ee})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=ue(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await y(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:ar,redirectTo:t?.redirectTo})}catch(t){if(w(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await y(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ee})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await y(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:ht});if(h.error)throw h.error;let f=await h.json(),g=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(k=>{let E=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(k.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Z(e);try{return await y(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ee})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Z(e);try{return await y(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ee})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){Z(e);try{return await y(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ee})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){Z(e.userId);try{let{data:t,error:r}=await y(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Z(e.userId),Z(e.id);try{return{data:await y(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await y(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:ht});if(h.error)throw h.error;let f=await h.json(),g=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(k=>{let E=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),A=JSON.parse(k.split(";")[1].split("=")[1]);u[`${A}Page`]=E}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(w(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await y(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await y(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await y(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await y(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await y(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await y(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:r=>{var s;return{data:{providers:(s=r?.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(t){if(w(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await y(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await y(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await y(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await y(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminListPasskeys(e){Z(e.userId);try{return await y(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminDeletePasskey(e){Z(e.userId),Z(e.passkeyId);try{return await y(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}};function ft(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}var Mr={debug:!!(globalThis&&We()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ze=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function lr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function pt(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function cr(n){return parseInt(n,16)}function ur(n){let e=new TextEncoder().encode(n);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function dr(n){var e;let{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:c,resources:u,scheme:h,uri:f,version:g}=n;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(` -`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}let p=pt(n.address),k=h?`${h}://${r}`:r,E=n.statement?`${n.statement} -`:"",A=`${k} wants you to sign in with your Ethereum account: -${p} +function ye(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s{let n=new Array(128);for(let e=0;e=6;){let r=e.queue>>e.queuedBits-6&63;t(He[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let r=e.queue>>e.queuedBits-6&63;t(He[r]),e.queuedBits-=6}}function Qt(n,e,t){let r=$r[n];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function wt(n){let e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Lr(o,r,t)};for(let o=0;o>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function Nr(n,e){for(let t=0;t55295&&r<=56319){let s=(r-55296)*1024&65535;r=(n.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}Dr(r,e)}}function Lr(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let r=1;r<6;r+=1)if((n>>7-r&1)===0){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function fe(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;se.push(t)),new Uint8Array(e)}function ce(n){let e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return n.forEach(s=>Xt(s,t,r)),Xt(null,t,r),e.join("")}function Ye(n){return Math.round(Date.now()/1e3)+n}function er(){return Symbol("auth-callback")}var W=()=>typeof window<"u"&&typeof document<"u",be={tested:!1,writable:!1},Xe=()=>{if(!W())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(be.tested)return be.writable;let n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),be.tested=!0,be.writable=!0}catch{be.tested=!0,be.writable=!1}return be.writable};function gt(n){let e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var Qe=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),tr=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",se=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},B=async(n,e)=>{let t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}},z=async(n,e)=>{await n.removeItem(e)},Le=class n{constructor(){this.promise=new n.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Le.promiseConstructor=Promise;function Me(n){let e=n.split(".");if(e.length!==3)throw new he("Invalid JWT structure");for(let r=0;r{setTimeout(()=>e(null),n)})}function sr(n,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await n(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function nr(n){return("0"+n.toString(16)).substr(-2)}function qr(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,nr).join("")}async function Mr(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function Kr(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;let t=await Mr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Fr=/^[a-zA-Z0-9_-]{8,64}$/;function Ke(n){return typeof n=="string"&&Fr.test(n)?n:null}function Wr(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,nr).join("")}let n="";for(let e=0;e<32;e++)n+=Math.floor(Math.random()*16).toString(16);return n}var ke=(n,e)=>`${n}-flow-${e}-code-verifier`,qe=n=>`${n}-flows-code-verifier`;async function yt(n,e){let t=await B(n,qe(e));return Array.isArray(t)?t.filter(r=>Ke(r)!==null):[]}async function Br(n,e,t,r,s){await se(n,ke(e,t),r);let i=(await yt(n,e)).filter(o=>o!==t);for(i.push(t);i.length>zt;){let o=i.shift();await z(n,ke(e,o)),s?.(o)}await se(n,qe(e),i),await se(n,`${e}-code-verifier`,r)}async function ir(n,e,t){if(t){let s=await B(n,ke(e,t));return{verifier:typeof s=="string"?s:null,flowId:t}}let r=await B(n,`${e}-code-verifier`);return{verifier:typeof r=="string"?r:null,flowId:null}}async function Z(n,e,t){let r=`${e}-code-verifier`;if(!t){await z(n,r);return}let s=ke(e,t),i=await B(n,s);await z(n,s);let o=await yt(n,e),l=o.filter(c=>c!==t);l.length!==o.length&&(l.length>0?await se(n,qe(e),l):await z(n,qe(e))),i!=null&&i===await B(n,r)&&await z(n,r)}async function or(n,e){let t=await yt(n,e);for(let r of t)await z(n,ke(e,r));await z(n,qe(e)),await z(n,`${e}-code-verifier`)}function ar(n,e){let t=n.indexOf("#"),r=t===-1?n:n.slice(0,t),s=t===-1?"":n.slice(t),i=r.indexOf("?");if(i!==-1){let l=r.slice(0,i),c=r.slice(i+1).split("&").filter(u=>u!==""&&u!==ae&&!u.startsWith(`${ae}=`));r=c.length>0?`${l}?${c.join("&")}`:l}let o=r.includes("?")?"&":"?";return`${r}${o}${ae}=${encodeURIComponent(e)}${s}`}async function lr(n,e,t=!1,r){let s=qr(),i=s;t&&(i+="/recovery");let o=Wr();await Br(n,e,o,i,r);let l=await Kr(s);return[l,s===l?"plain":"s256",o]}var Gr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function cr(n){let e=n.headers.get(Pe);if(!e||!e.match(Gr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ur(n){if(!n)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function dr(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Vr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ne(n){if(!Vr.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function xe(n){if(!n.recoveryCodes)throw new Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function Ze(){let n={};return new Proxy(n,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){let r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function hr(n,e){return new Proxy(n,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){let i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,r,s)}})}function mt(n){return JSON.parse(JSON.stringify(n))}var Se=n=>{if(typeof n=="object"&&n!==null){let e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(n)},fr=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function pr(n){var e;if(!tr(n))throw new ve(Se(n),0);let t;try{t=await n.json()}catch(i){throw fr.includes(n.status)?new ve(n.statusText||`HTTP ${n.status}`,n.status):new G(Se(i),i)}if(fr.includes(n.status))throw new ve(Se(t),n.status);let r,s=cr(n);if(s&&s.getTime()>=ht["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new $e(Se(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new L}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new $e(Se(t),n.status,t.weak_password.reasons);throw new ze(Se(t),n.status||500,r)}var zr=(n,e,t,r)=>{let s={method:n,headers:e?.headers||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function m(n,e,t,r){var s;let i=Object.assign({},r?.headers);i[Pe]||(i[Pe]=ht["2024-01-01"].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Jr(n,e,t+l,{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Jr(n,e,t,r,s,i){let o=zr(e,r,s,i),l;try{l=await n(t,Object.assign({},o))}catch(c){throw new ve(Se(c),0)}if(l.ok||await pr(l),r?.noResolveJson)return l;try{return await l.json()}catch(c){await pr(c)}}function X(n){var e;let t=null;Hr(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Ye(n.expires_in)));let r=(e=n.user)!==null&&e!==void 0?e:typeof n?.id=="string"?n:null;return{data:{session:t,user:r},error:null}}function _t(n){let e=X(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=n.weak_password),e}function ie(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function wr(n){return{data:n,error:null}}function gr(n){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i}=n,o=ye(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function vt(n){return n}function Hr(n){return!!n.access_token&&!!n.refresh_token&&!!n.expires_in}var et=["global","local","others"];var Re=class{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=Qe(r),this.experimental=s??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=et[0]){if(et.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${et.join(", ")}`);try{return await m(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await m(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ie})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=ye(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await m(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:gr,redirectTo:t?.redirectTo})}catch(t){if(w(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await m(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ie})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await m(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:vt});if(h.error)throw h.error;let p=await h.json(),g=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(k=>{let A=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),I=JSON.parse(k.split(";")[1].split("=")[1]);u[`${I}Page`]=A}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(w(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){ne(e);try{return await m(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ie})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){ne(e);try{return await m(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ie})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){ne(e);try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ie})}catch(r){if(w(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){ne(e.userId);try{let{data:t,error:r}=await m(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _deleteFactor(e){ne(e.userId),ne(e.id);try{return{data:await m(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,i,o,l,c;try{let u={nextPage:null,lastPage:0,total:0},h=await m(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:vt});if(h.error)throw h.error;let p=await h.json(),g=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(l=h.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(k=>{let A=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),I=JSON.parse(k.split(";")[1].split("=")[1]);u[`${I}Page`]=A}),u.total=parseInt(g)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(w(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await m(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await m(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await m(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await m(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await m(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await m(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:r=>{var s;return{data:{providers:(s=r?.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(t){if(w(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await m(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await m(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await m(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(w(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await m(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminListPasskeys(e){ne(e.userId);try{return await m(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _adminDeletePasskey(e){ne(e.userId),ne(e.passkeyId);try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}};function bt(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}var Yr={debug:!!(globalThis&&Xe()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},tt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function yr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function kt(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function mr(n){return parseInt(n,16)}function _r(n){let e=new TextEncoder().encode(n);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function vr(n){var e;let{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:c,resources:u,scheme:h,uri:p,version:g}=n;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!p)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(` +`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}let f=kt(n.address),k=h?`${h}://${r}`:r,A=n.statement?`${n.statement} +`:"",I=`${k} wants you to sign in with your Ethereum account: +${f} -${E}`,O=`URI: ${f} +${A}`,T=`URI: ${p} Version: ${g} Chain ID: ${t}${o?` Nonce: ${o}`:""} -Issued At: ${i.toISOString()}`;if(s&&(O+=` -Expiration Time: ${s.toISOString()}`),l&&(O+=` -Not Before: ${l.toISOString()}`),c&&(O+=` -Request ID: ${c}`),u){let R=` -Resources:`;for(let v of u){if(!v||typeof v!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${v}`);R+=` -- ${v}`}O+=R}return`${A} -${O}`}var U=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},me=class extends U{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function hr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new U({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new U({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new U({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new U({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new U({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new U({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(wt(o)){if(i.rp.id!==o)return new U({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new U({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function fr({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(wt(r)){if(t.rpId!==r)return new U({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var gt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},Ye=new gt;function yt(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=ue(n,["challenge","user","excludeCredentials"]),i=ae(e).buffer,o=Object.assign(Object.assign({},t),{id:ae(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Je(l,o):r[i]=Je(o)}else r[i]=o}return r}function Wr(n,e){return Je(Kr,n,e||{})}function Br(n,e){return Je(Fr,n,e||{})}var He=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??Ye.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,k=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${k}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Wr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:g}=await bt({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}case"request":{let h=Br(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:g}=await kt(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new K("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ie("rpId is required for WebAuthn authentication")};try{if(!$e())return{data:null,error:new K("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new K("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ie("rpId is required for WebAuthn registration")};try{if(!$e())return{data:null,error:new K("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new K("Unexpected error in register",o)}}}};lr();var Gr={url:jt,storageKey:$t,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Dt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Se={},pr=!1,Xe=class n{get jwks(){var e,t;return(t=(e=Se[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Se[this.storageKey]=Object.assign(Object.assign({},Se[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Se[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Se[this.storageKey]=Object.assign(Object.assign({},Se[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Gr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&L()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new ye({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Be(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,pr||(pr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new He(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(this)}},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:We()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ft(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=ft(this.memoryStorage)),L()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ne}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(L()&&(t=lt(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),L()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Mt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new K("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:V}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:g,options:p}=e,k=null,E=null;this.flowType==="pkce"&&([k,E,i]=await this._getCodeChallengeAndMethod()),o=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:g,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:k,code_challenge_method:E},xform:V})}else if("phone"in e){let{phone:f,password:g,options:p}=e;o=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:g,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:V})}else throw new de("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await J(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await J(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:dt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:dt})}else throw new de("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new se;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,g;let p,k;if("message"in e)p=e.message,k=e.signature;else{let{chain:E,wallet:A,statement:O,options:R}=e,v;if(L())if(typeof A=="object")v=A;else{let x=window;if("ethereum"in x&&typeof x.ethereum=="object"&&"request"in x.ethereum&&typeof x.ethereum.request=="function")v=x.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof A!="object"||!R?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=A}let P=new URL((t=R?.url)!==null&&t!==void 0?t:window.location.href),S=await v.request({method:"eth_requestAccounts"}).then(x=>x).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!S||S.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let m=pt(S[0]),I=(r=R?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!I){let x=await v.request({method:"eth_chainId"});I=cr(x)}let T={domain:P.host,address:m,statement:O,uri:P.href,version:"1",chainId:I,nonce:(s=R?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=R?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=R?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=R?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=R?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=R?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=dr(T),k=await v.request({method:"personal_sign",params:[ur(p),m]})}try{let{data:E,error:A}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:k},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:V});if(A)throw A;if(!E||!E.session||!E.user){let O=new se;return this._returnResult({data:{user:null,session:null},error:O})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,g,p;let k,E;if("message"in e)k=e.message,E=e.signature;else{let{chain:A,wallet:O,statement:R,options:v}=e,P;if(L())if(typeof O=="object")P=O;else{let m=window;if("solana"in m&&typeof m.solana=="object"&&("signIn"in m.solana&&typeof m.solana.signIn=="function"||"signMessage"in m.solana&&typeof m.solana.signMessage=="function"))P=m.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof O!="object"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");P=O}let S=new URL((t=v?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in P&&P.signIn){let m=await P.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v?.signInWithSolana),{version:"1",domain:S.host,uri:S.href}),R?{statement:R}:null)),I;if(Array.isArray(m)&&m[0]&&typeof m[0]=="object")I=m[0];else if(m&&typeof m=="object"&&"signedMessage"in m&&"signature"in m)I=m;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in I&&"signature"in I&&(typeof I.signedMessage=="string"||I.signedMessage instanceof Uint8Array)&&I.signature instanceof Uint8Array)k=typeof I.signedMessage=="string"?I.signedMessage:new TextDecoder().decode(I.signedMessage),E=I.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in P)||typeof P.signMessage!="function"||!("publicKey"in P)||typeof P!="object"||!P.publicKey||!("toBase58"in P.publicKey)||typeof P.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");k=[`${S.host} wants you to sign in with your Solana account:`,P.publicKey.toBase58(),...R?["",R,""]:[""],"Version: 1",`URI: ${S.href}`,`Issued At: ${(s=(r=v?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=v?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}`]:[],...!((o=v?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((l=v?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((c=v?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((u=v?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((f=(h=v?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...v.signInWithSolana.resources.map(I=>`- ${I}`)]:[]].join(` -`);let m=await P.signMessage(new TextEncoder().encode(k),"utf8");if(!m||!(m instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=m}}try{let{data:A,error:O}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:k,signature:ne(E)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:V});if(O)throw O;if(!A||!A.session||!A.user){let R=new se;return this._returnResult({data:{user:null,session:null},error:R})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:O})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?je(t?.flowId):L()?je(lt(window.location.href)[re]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await Yt(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Me;let{data:u,error:h}=await y(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:V});if(await J(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new se;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await J(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:V}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new se;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:g}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:g})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new de("You must provide either an email or phone number.")}catch(c){if(await J(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await y(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:V});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await y(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:or});return!((s=u.data)===null||s===void 0)&&s.url&&L()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await J(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new j;let{error:s}=await y(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await y(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await J(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await y(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new de("You must provide either an email or phone number and a type")}catch(r){if(await J(this.storage,this.storageKey,t),w(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await M(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await M(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:Ge()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=sr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ee}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new j}:await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ee})})}catch(t){if(w(t))return xe(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new j;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await y(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:ee});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await J(this.storage,this.storageKey,r),w(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new j;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=Ue(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new j;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!L())throw new he("No browser detected.");if(e.error||e.error_description||e.error_code)throw new he(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Ae("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new he("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ae("No code detected.");let{data:v,error:P}=await this._exchangeCodeForSession(e.code,{flowId:e[re]});if(P)throw P;let S=new URL(window.location.href);return S.searchParams.delete("code"),S.searchParams.delete(re),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:v.session,redirectType:(r=v.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new he("No session defined in URL");let f=Math.round(Date.now()/1e3),g=parseInt(c),p=f+g;u&&(p=parseInt(u));let k=p-f;k*1e3<=X&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${k}s, should have been closer to ${g}s`);let E=p-g;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:O}=await this._getUser(o);if(O)throw O;let R={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:g,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:R,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=je(e[re]);return t&&await M(this.storage,we(this.storageKey,t))?!0:!!await M(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!xe(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(it(c)&&(c.status===404||c.status===401||c.status===403)||xe(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Gt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),ot(i))return;xe(i)||Ce(i)||it(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await y(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await J(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:g,error:p}=o;if(p)throw p;let{url:k,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await y(this.fetch,"GET",k,{headers:this.headers,jwt:(f=(h=g.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return L()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:V}),{data:g,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new se}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:p}))}catch(s){if(await J(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await y(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await Jt(async s=>(s>0&&await zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await y(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Ce(i)&&Date.now()+o-r{});let i=await M(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new j;let c=await M(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let g={data:null,error:new Ie};return this.refreshingDeferred.resolve(g),g}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await W(this.storage,this.storageKey),this.userStorage&&await W(this.userStorage,this.storageKey+"-user");let g={data:null,error:new Ie};return this.refreshingDeferred.resolve(g),g}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!Ce(i)){let l=await M(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Ut},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),X);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/X);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${X}ms, refresh threshold is ${be} ticks`),s<=be&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof ze)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/X);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${X}ms, refresh threshold is ${be} ticks`),s<=be&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!L()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:Qt(e,t)}async _getCodeChallengeAndMethod(e=!1){return Zt(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await y(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?_t(e.webauthn.credential_response):vt(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:yt(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:mt(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=Ue(e),k=null;p.aal&&(k=p.aal);let E=k,{data:{user:A},error:O}=await this.getUser(e);if(O)return this._returnResult({data:null,error:O});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(P=>P.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let v=p.amr||[];return{data:{currentLevel:k,nextLevel:E,currentAuthenticationMethods:v},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ue(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let g=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:g},error:null}}async _getRecoveryCodesStatus(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){ke(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){ke(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Fe(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await y(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await y(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&L()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await y(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&L()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await y(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new j})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await y(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+qt>s)return r;let{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:k}=await this.getSession();if(k||!p.session)return this._returnResult({data:null,error:k});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=Ue(r);if(!t?.allowExpired)try{tr(i.exp)}catch(p){throw new oe(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=rr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Bt(`${l}.${c}`)))throw new oe("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!$e())return this._returnResult({data:null,error:new K("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=mt(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:Ye.createNewAbortSignal(),{data:h,error:f}=await kt({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new K("WebAuthn ceremony failed",null)});let g=vt(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:g})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!$e())return this._returnResult({data:null,error:new K("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=yt(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:Ye.createNewAbortSignal(),{data:c,error:u}=await bt({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new K("WebAuthn ceremony failed",null)});let h=_t(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await y(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await y(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await y(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:V});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await y(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await y(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{error:i}=await y(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};Xe.nextInstanceID={};var St=Xe;var Vr=St,Rt=Vr;var le=document.querySelector("#app"),De=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},wr,Ze=[];function mr(){for(let n of Ze.splice(0))n()}var _e=new URLSearchParams(location.search);_e.has("billing")&&(d.tab="billing");var xt="agentintercom-pending",$={};try{let n=JSON.parse(sessionStorage.getItem(xt)||"{}");n.until>Date.now()&&($=n)}catch{}_e.get("authorization_id")&&($.authorization=_e.get("authorization_id"));var _r=new URLSearchParams(location.hash.slice(1)),gr=_r.get("invite"),yr=_r.get("device")||_e.get("device_code");yr&&($.device=yr,history.replaceState(null,"",location.pathname+location.search));gr&&($.invite=gr,history.replaceState(null,"",location.pathname+location.search));($.authorization||$.invite||$.device)&&sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function H(n,e=!1){clearTimeout(wr),De.textContent=n,De.hidden=!1,De.className=e?"error":"",De.setAttribute("role",e?"alert":"status"),wr=setTimeout(()=>{De.hidden=!0},e?15e3:6e3)}async function Re(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){H(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function _(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Re(r.currentTarget,e)},n)}function N(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function F(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Re(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var ce=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),B=n=>n?new Date(n).toLocaleString():"\u2014",D=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function b(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function rt(n){await navigator.clipboard.writeText(n),H("Copied to clipboard.")}var Et=new WeakMap;async function Ct(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function vr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Et.has(e)||Et.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Et.get(e)}),s=await(await Ct(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function br(n,e,t){let r=await Ct(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function kr(n,e){let t=N("Attach a file",{type:"file"}),r=_("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await vr(n,s);e.value+=`${e.value?` +Issued At: ${i.toISOString()}`;if(s&&(T+=` +Expiration Time: ${s.toISOString()}`),l&&(T+=` +Not Before: ${l.toISOString()}`),c&&(T+=` +Request ID: ${c}`),u){let E=` +Resources:`;for(let v of u){if(!v||typeof v!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${v}`);E+=` +- ${v}`}T+=E}return`${I} +${T}`}var D=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},Ee=class extends D{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function br({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new D({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new D({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new D({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new D({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new D({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new D({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new D({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new D({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(St(o)){if(i.rp.id!==o)return new D({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new D({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new D({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new D({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new D({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function kr({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new D({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new D({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(St(r)){if(t.rpId!==r)return new D({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new D({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new D({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new D({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var Rt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},nt=new Rt;function Et(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=ye(n,["challenge","user","excludeCredentials"]),i=fe(e).buffer,o=Object.assign(Object.assign({},t),{id:fe(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=rt(l,o):r[i]=rt(o)}else r[i]=o}return r}function Zr(n,e){return rt(Xr,n,e||{})}function es(n,e){return rt(Qr,n,e||{})}var st=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??nt.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let p=r;if(p)h.name=`${h.id}:${p}`;else{let f=(await this.client.getUser()).data.user,k=((o=f?.user_metadata)===null||o===void 0?void 0:o.name)||f?.email||f?.id||"User";h.name=`${h.id}:${k}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Zr(l.webauthn.credential_options.publicKey,i?.create),{data:p,error:g}=await Tt({publicKey:h,signal:u});return p?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:p}},error:null}:{data:null,error:g}}case"request":{let h=es(l.webauthn.credential_options.publicKey,i?.request),{data:p,error:g}=await Ct(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return p?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:p}},error:null}:{data:null,error:g}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new G("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new de("rpId is required for WebAuthn authentication")};try{if(!Fe())return{data:null,error:new G("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new G("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new de("rpId is required for WebAuthn registration")};try{if(!Fe())return{data:null,error:new G("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var p;return(p=h.data)===null||p===void 0?void 0:p.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new G("Unexpected error in register",o)}}}};yr();var ts={url:Wt,storageKey:Bt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Gt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Te={},Sr=!1,it=class n{get jwks(){var e,t;return(t=(e=Te[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Te[this.storageKey]=Object.assign(Object.assign({},Te[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Te[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Te[this.storageKey]=Object.assign(Object.assign({},Te[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},ts),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&W()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new Re({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Qe(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,Sr||(Sr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new st(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(this)}},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Xe()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=bt(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=bt(this.memoryStorage)),W()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ge}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(W()&&(t=gt(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),W()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Ht(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new G("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:X}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:p,password:g,options:f}=e,k=null,A=null;this.flowType==="pkce"&&([k,A,i]=await this._getCodeChallengeAndMethod()),o=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(f?.emailRedirectTo,i),body:{email:p,password:g,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:k,code_challenge_method:A},xform:X})}else if("phone"in e){let{phone:p,password:g,options:f}=e;o=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:p,password:g,data:(r=f?.data)!==null&&r!==void 0?r:{},channel:(s=f?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:X})}else throw new me("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await Z(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await Z(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:_t})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:_t})}else throw new me("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new le;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,p,g;let f,k;if("message"in e)f=e.message,k=e.signature;else{let{chain:A,wallet:I,statement:T,options:E}=e,v;if(W())if(typeof I=="object")v=I;else{let H=window;if("ethereum"in H&&typeof H.ethereum=="object"&&"request"in H.ethereum&&typeof H.ethereum.request=="function")v=H.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof I!="object"||!E?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=I}let C=new URL((t=E?.url)!==null&&t!==void 0?t:window.location.href),K=await v.request({method:"eth_requestAccounts"}).then(H=>H).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!K||K.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let P=kt(K[0]),N=(r=E?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!N){let H=await v.request({method:"eth_chainId"});N=mr(H)}let ue={domain:C.host,address:P,statement:T,uri:C.href,version:"1",chainId:N,nonce:(s=E?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=E?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=E?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=E?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=E?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=E?.signInWithEthereum)===null||h===void 0?void 0:h.resources};f=vr(ue),k=await v.request({method:"personal_sign",params:[_r(f),P]})}try{let{data:A,error:I}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:k},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:X});if(I)throw I;if(!A||!A.session||!A.user){let T=new le;return this._returnResult({data:{user:null,session:null},error:T})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:I})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,p,g,f;let k,A;if("message"in e)k=e.message,A=e.signature;else{let{chain:I,wallet:T,statement:E,options:v}=e,C;if(W())if(typeof T=="object")C=T;else{let P=window;if("solana"in P&&typeof P.solana=="object"&&("signIn"in P.solana&&typeof P.solana.signIn=="function"||"signMessage"in P.solana&&typeof P.solana.signMessage=="function"))C=P.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof T!="object"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");C=T}let K=new URL((t=v?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in C&&C.signIn){let P=await C.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v?.signInWithSolana),{version:"1",domain:K.host,uri:K.href}),E?{statement:E}:null)),N;if(Array.isArray(P)&&P[0]&&typeof P[0]=="object")N=P[0];else if(P&&typeof P=="object"&&"signedMessage"in P&&"signature"in P)N=P;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in N&&"signature"in N&&(typeof N.signedMessage=="string"||N.signedMessage instanceof Uint8Array)&&N.signature instanceof Uint8Array)k=typeof N.signedMessage=="string"?N.signedMessage:new TextDecoder().decode(N.signedMessage),A=N.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in C)||typeof C.signMessage!="function"||!("publicKey"in C)||typeof C!="object"||!C.publicKey||!("toBase58"in C.publicKey)||typeof C.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");k=[`${K.host} wants you to sign in with your Solana account:`,C.publicKey.toBase58(),...E?["",E,""]:[""],"Version: 1",`URI: ${K.href}`,`Issued At: ${(s=(r=v?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=v?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}`]:[],...!((o=v?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((l=v?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((c=v?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((u=v?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((p=(h=v?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||p===void 0)&&p.length?["Resources",...v.signInWithSolana.resources.map(N=>`- ${N}`)]:[]].join(` +`);let P=await C.signMessage(new TextEncoder().encode(k),"utf8");if(!P||!(P instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");A=P}}try{let{data:I,error:T}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:k,signature:ce(A)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:X});if(T)throw T;if(!I||!I.session||!I.user){let E=new le;return this._returnResult({data:{user:null,session:null},error:E})}return I.session&&(await this._saveSession(I.session),await this._notifyAllSubscribers("SIGNED_IN",I.session)),this._returnResult({data:Object.assign({},I),error:T})}catch(I){if(w(I))return this._returnResult({data:{user:null,session:null},error:I});throw I}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?Ke(t?.flowId):W()?Ke(gt(window.location.href)[ae]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await ir(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Je;let{data:u,error:h}=await m(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:X});if(await Z(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let p=new le;return this._returnResult({data:{user:null,session:null,redirectType:null},error:p})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await Z(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:X}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new le;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,p=null;this.flowType==="pkce"&&([h,p,l]=await this._getCodeChallengeAndMethod());let{error:g}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:p},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:g})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:p}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:p})}throw new me("You must provide either an email or phone number.")}catch(c){if(await Z(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await m(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:X});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await m(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:wr});return!((s=u.data)===null||s===void 0)&&s.url&&W()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await Z(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new L;let{error:s}=await m(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await m(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await Z(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await m(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new me("You must provide either an email or phone number and a type")}catch(r){if(await Z(this.storage,this.storageKey,t),w(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await B(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await B(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:Ze()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=hr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ie}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new L}:await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ie})})}catch(t){if(w(t))return De(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new L;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:p}=await m(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:ie});if(p)throw p;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await Z(this.storage,this.storageKey,r),w(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new L;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=Me(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new L;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!W())throw new _e("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _e(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Ue("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new _e("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ue("No code detected.");let{data:v,error:C}=await this._exchangeCodeForSession(e.code,{flowId:e[ae]});if(C)throw C;let K=new URL(window.location.href);return K.searchParams.delete("code"),K.searchParams.delete(ae),window.history.replaceState(window.history.state,"",K.toString()),{data:{session:v.session,redirectType:(r=v.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new _e("No session defined in URL");let p=Math.round(Date.now()/1e3),g=parseInt(c),f=p+g;u&&(f=parseInt(u));let k=f-p;k*1e3<=re&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${k}s, should have been closer to ${g}s`);let A=f-g;p-A>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",A,f,p):p-A<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",A,f,p);let{data:I,error:T}=await this._getUser(o);if(T)throw T;let E={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:g,expires_at:f,refresh_token:l,token_type:h,user:I.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:E,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=Ke(e[ae]);return t&&await B(this.storage,ke(this.storageKey,t))?!0:!!await B(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!De(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(ft(c)&&(c.status===404||c.status===401||c.status===403)||De(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=er(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),pt(i))return;De(i)||Ne(i)||ft(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await m(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await Z(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,p;let{data:g,error:f}=o;if(f)throw f;let{url:k,flowId:A}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=A,await m(this.fetch,"GET",k,{headers:this.headers,jwt:(p=(h=g.session)===null||h===void 0?void 0:h.access_token)!==null&&p!==void 0?p:void 0})});if(i)throw i;return W()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,p=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:X}),{data:g,error:f}=p;return f?this._returnResult({data:{user:null,session:null},error:f}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new le}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:f}))}catch(s){if(await Z(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await m(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await sr(async s=>(s>0&&await rr(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await m(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:X})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Ne(i)&&Date.now()+o-r{});let i=await B(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new L;let c=await B(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let g={data:null,error:new je};return this.refreshingDeferred.resolve(g),g}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await z(this.storage,this.storageKey),this.userStorage&&await z(this.userStorage,this.storageKey+"-user");let g={data:null,error:new je};return this.refreshingDeferred.resolve(g),g}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let p={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(p),p}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!Ne(i)){let l=await B(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Ft},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),re);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/re);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${re}ms, refresh threshold is ${Ie} ticks`),s<=Ie&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof tt)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/re);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${re}ms, refresh threshold is ${Ie} ticks`),s<=Ie&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!W()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:ar(e,t)}async _getCodeChallengeAndMethod(e=!1){return lr(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await m(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await m(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?It(e.webauthn.credential_response):xt(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:Et(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:At(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:f}=Me(e),k=null;f.aal&&(k=f.aal);let A=k,{data:{user:I},error:T}=await this.getUser(e);if(T)return this._returnResult({data:null,error:T});((r=(t=I?.factors)===null||t===void 0?void 0:t.filter(C=>C.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(A="aal2");let v=f.amr||[];return{data:{currentLevel:k,nextLevel:A,currentAuthenticationMethods:v},error:null}}catch(f){if(w(f))return this._returnResult({data:null,error:f});throw f}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Me(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let g=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:g},error:null}}async _getRecoveryCodesStatus(){xe(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await m(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){xe(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await m(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){xe(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await m(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Ye(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){xe(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await m(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){xe(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await m(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await m(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new L})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new L});let o=await m(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&W()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new L});let o=await m(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&W()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await m(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new L})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await m(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new L})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+Jt>s)return r;let{data:i,error:o}=await m(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:f,error:k}=await this.getSession();if(k||!f.session)return this._returnResult({data:null,error:k});r=f.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=Me(r);if(!t?.allowExpired)try{ur(i.exp)}catch(f){throw new he(f instanceof Error?f.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:s,signature:o},error:null}}let h=dr(s.alg),p=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,p,o,Zt(`${l}.${c}`)))throw new he("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!Fe())return this._returnResult({data:null,error:new G("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=At(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:nt.createNewAbortSignal(),{data:h,error:p}=await Ct({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(p||!h)return this._returnResult({data:null,error:p??new G("WebAuthn ceremony failed",null)});let g=xt(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:g})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!Fe())return this._returnResult({data:null,error:new G("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=Et(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:nt.createNewAbortSignal(),{data:c,error:u}=await Tt({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new G("WebAuthn ceremony failed",null)});let h=It(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new L});let{data:s,error:i}=await m(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new L});let{data:i,error:o}=await m(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await m(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await m(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:X});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new L});let{data:s,error:i}=await m(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new L});let{data:i,error:o}=await m(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new L});let{error:i}=await m(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};it.nextInstanceID={};var Ot=it;var rs=Ot,Pt=rs;var pe=document.querySelector("#app"),We=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},Rr,Be=[];function Ir(){for(let n of Be.splice(0))n()}var Ae=new URLSearchParams(location.search);Ae.has("billing")&&(d.tab="billing");var Nt="agentintercom-pending",q={};try{let n=JSON.parse(sessionStorage.getItem(Nt)||"{}");n.until>Date.now()&&(q=n)}catch{}Ae.get("authorization_id")&&(q.authorization=Ae.get("authorization_id"));var xr=new URLSearchParams(location.hash.slice(1)),Er=xr.get("invite"),Ar=xr.get("device")||Ae.get("device_code");Ar&&(q.device=Ar,history.replaceState(null,"",location.pathname+location.search));Er&&(q.invite=Er,history.replaceState(null,"",location.pathname+location.search));(q.authorization||q.invite||q.device)&&sessionStorage.setItem(Nt,JSON.stringify({...q,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function ee(n,e=!1){clearTimeout(Rr),We.textContent=n,We.hidden=!1,We.className=e?"error":"",We.setAttribute("role",e?"alert":"status"),Rr=setTimeout(()=>{We.hidden=!0},e?15e3:6e3)}async function Ce(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){ee(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function _(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Ce(r.currentTarget,e)},n)}function F(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function V(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Ce(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var we=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),J=n=>n?new Date(n).toLocaleString():"\u2014",M=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function b(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function ct(n){await navigator.clipboard.writeText(n),ee("Copied to clipboard.")}var Ut=new WeakMap;async function Lt(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function Tr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Ut.has(e)||Ut.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Ut.get(e)}),s=await(await Lt(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function Cr(n,e,t){let r=await Lt(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function Or(n,e){let t=F("Attach a file",{type:"file"}),r=_("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await Tr(n,s);e.value+=`${e.value?` -`:""}${o.name}: ${o.uri}`,t.input.value="",H("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Sr(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>br(n,s,i))))}async function zr(){let n=D(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>te("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await b(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await C()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${B(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>br(n,l.id,l.name)),_("Copy reference",()=>rt(l.uri)),u)))}},s=await b(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=N("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},F([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await vr(n,o),await C()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await b(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function et(n){delete $[n],sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}function te(n,e){let t=a("dialog",{},a("h2",{},n)),r=()=>{t.close(),t.remove()};return t.append(e(r),a("div",{class:"actions end"},_("Close",r))),t.addEventListener("close",()=>t.remove()),document.body.append(t),t.showModal(),t}function tt(n,e,t){te(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>rt(e))))}function At(){mr(),d.user=null;let n=N("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),e=F([n.node],"Continue with email",async i=>{let{error:o}=await d.auth.signInWithOtp({email:i.get("email"),options:{emailRedirectTo:location.origin+"/app"+($.authorization?"?authorization_id="+encodeURIComponent($.authorization):$.device?"?device_code="+encodeURIComponent($.device):""),shouldCreateUser:!0}});if(o)throw o;H("Check your email for an October sign-in link. Open it in this browser."),e.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),t=N("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),r=N("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),s=F([t.node,r.node],"Sign in",async i=>{let{error:o}=await d.auth.signInWithPassword({email:i.get("email"),password:i.get("password")});if(o)throw o;await Y()});le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. -A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),e,a("details",{},a("summary",{},"Use an existing password"),s),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function Y(){d.user=await b("/api/me"),d.workspaces=await b("/api/workspaces");let n=_e.has("billing")&&_e.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,$.invite)return Jr();if($.authorization)return It();if($.device)return Tt();if(!d.workspace)return Rr();await C()}function st(n){let e=N("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return F([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await b("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Rr(){le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),st(C),_("Sign out",Ot))))}async function Ot(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,At()}function Pt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Re(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function It(){let n=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});et("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(It)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):st(It);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Tt(){let n=await b(`/api/device/authorizations/${encodeURIComponent($.device)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await b(`/api/device/authorizations/${encodeURIComponent($.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),et("device"),le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",Y,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(Tt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):st(Tt);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function Jr(){le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await b("/api/invites/accept",{method:"POST",body:{token:$.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),et("invite"),await Y()},"primary"),_("Use another account",Ot),_("Cancel",async()=>{et("invite"),await Y()})))))}var Qe={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function C(){if(mr(),!d.workspace)return Rr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(Qe).map(([s,[i]])=>_(i,async()=>{d.tab=s,await C()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(Qe)[i]===d.tab&&s.setAttribute("aria-current","page")}),le.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},ce(),a("div",{class:"workspace-switch"},Pt(C),_("+ New workspace",()=>te("New workspace",s=>st(async()=>{s(),await C()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",Ot,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},Qe[d.tab][0]),a("p",{class:"muted"},Qe[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await C()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ns,billing:ss,files:zr,channels:rs,messages:Zr,tasks:es,questions:ts,sessions:Hr,connect:Yr,members:Xr}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",C)))}}async function Hr(){let n=a("div"),e=a("div",{class:"grid"}),t=await b(D("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${B(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await C()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>rt(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await b(D("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",C)),n}function Yr(){let n=d.config.mcpUrl,e=D("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>rt(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),F([N("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await b(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});tt("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${B(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default -agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),F([N("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await b(D("/devices"),{method:"POST",body:{name:t.get("name")}});tt("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function Xr(){let n=D(""),[e,t]=await Promise.all([b(D("/members")),b(D("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await Y()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>te("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await Y()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${B(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>te("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let f=await b(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),tt("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${B(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>te("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await b(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await C()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${B(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=N("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=F([l.node],"Create invitation",async f=>{let g=await b(D("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});tt("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(g.token)}`,`Share this link with ${g.email}. It expires ${B(g.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await b(D("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${B(f.expiresAt)}`)),_("Revoke invitation",async()=>{await b(D(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await C()},"danger")));o.append(h)}return o}async function Qr(){if(d.config=await b("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Rt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await Y():At(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,At()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Re(null,Y),0)})}Qr().catch(n=>{le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});async function Zr(){let n=d.generation,e=D(""),[t,r]=await Promise.all([b(e+"/sessions"),b(e+"/members")]),s=t.sessions,i=new Map(s.map(S=>["agent:"+S.id,S.displayName]));for(let S of r)i.set("human:"+S.userId,S.email);let o=(S,m)=>i.get(S+":"+m)||m,l=new URLSearchParams;d.conversationAgent&&l.set("agentId",d.conversationAgent),d.search&&l.set("query",d.search);let c=a("select",{"aria-label":"Filter by session",onchange:S=>{d.conversationAgent=S.target.value,Re(null,C)}},a("option",{value:""},"All sessions"),s.map(S=>a("option",{value:S.id,selected:S.id===d.conversationAgent},S.displayName))),u=N("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),h=F([u.node],"Search",async S=>{d.search=S.get("query").trim(),await C()}),f=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",c),h)),g=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),p=new Map,k=!0,E=!1;Ze.push(()=>{k=!1});let A=S=>S.responseMessageId?"Replied":S.state==="acknowledged"?S.toKind==="human"?"Read":"Acknowledged":S.state==="delivered"?"Delivered to app":S.state==="expired"?"Expired":"Waiting for delivery",O=(S,m=!1)=>{let I=m?[...S.messages].reverse():S.messages;for(let T of I){let x=JSON.stringify(T),q=p.get(T.id);if(q?.fingerprint===x)continue;let G=a("article",{class:"card",id:T.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},o(T.fromKind,T.from))," \u2192 ",o(T.toKind,T.to),a("p",{class:"help"},B(T.createdAt))),a("span",{class:"badge"},A(T))),a("p",{class:"message"},T.body));G.append(Sr(e,T.body,T.context)),T.responseTo&&G.append(a("p",{class:"help"},"Reply to ",a("code",{},T.responseTo))),T.toKind==="human"&&T.to===d.user.id&&T.state!=="acknowledged"&&T.state!=="expired"&&G.append(_("Mark read",async()=>{await b(e+"/messages/read",{method:"POST",body:{messageIds:[T.id]}}),await C()},"subtle-button")),q?q.node.replaceWith(G):m?g.prepend(G):g.append(G),p.set(T.id,{fingerprint:x,node:G})}},R=await b(e+"/messages?"+l);O(R);let v=l.toString(),P=setInterval(async()=>{if(d.generation!==n){clearInterval(P);return}if(!(!k||E||document.hidden)){E=!0;try{let S=await b(e+"/messages?"+v);k&&(S.messages.length&&g.querySelector(".empty")?.remove(),O(S,!0))}catch(S){k&&H("Conversation refresh failed. "+S.message,!0)}finally{E=!1}}},5e3);if(Ze.push(()=>clearInterval(P)),R.messages.length||g.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),f.append(g),R.nextCursor){let S=R.nextCursor,m=_("Earlier messages",async()=>{l.set("before",S);let I=await b(e+"/messages?"+l);O(I),S=I.nextCursor,S||m.remove()});f.append(m)}if(s.length){let S=a("select",{name:"to",required:!0},s.map(q=>a("option",{value:q.id,selected:q.id===d.conversationAgent},q.displayName+(q.reachable?"":" \xB7 offline")))),m=N("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),I=crypto.randomUUID(),T="",x=F([a("label",{},"Send to",S),m.node,kr(e,m.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async q=>{let G=JSON.stringify([q.get("to"),q.get("body")]);T&&T!==G&&(I=crypto.randomUUID()),T=G,await b(e+"/messages",{method:"POST",body:{to:q.get("to"),body:q.get("body"),mode:"request",idempotencyKey:I}}),d.conversationAgent=q.get("to"),d.search="",H("Request saved. Delivery status will update when the app checks its inbox."),await C()});f.append(a("section",{class:"card"},a("h2",{},"Send a message"),x))}else f.append(_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));return f.append(_("Refresh conversation",C)),f}async function es(){let n=D(""),e=await b(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},B(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await b(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=N("Task title",{name:"title",maxlength:256,required:!0}),o=N("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),F([i.node,o.node],"Create task",async l=>{await b(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),H("Task created. An agent can now claim it."),await C()}))),t}async function ts(){let n=D(""),e=await b(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=N("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",B(i.createdAt)),a("div",{class:"actions"},l),F([o.node],"Send answer",async c=>{await b(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),H("Answer saved for the requesting session."),await C()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await b(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",C)),t}async function rs(){let n=d.generation,e=D(""),t=await b(e+"/channels"),r=t.find(m=>m.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>te("Create a channel",m=>F([N("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,N("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async I=>{let T=await b(e+"/channels",{method:"POST",body:{name:I.get("name"),description:I.get("description")}});d.channelId=T.id,d.threadId="",d.channelSearch="",m(),await C()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:m=>{d.channelId=m.target.value,d.threadId="",d.channelSearch="",Re(null,C)}},t.map(m=>a("option",{value:m.id,selected:m.id===r.id},"#"+m.name))),o=F([N("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async m=>{d.channelSearch=m.get("query").trim(),d.threadId="",await C()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),_("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await C()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let[u,h,f]=await Promise.all([b(e+"/channel-posts?"+c),b(e+"/members"),b(e+"/sessions")]),g=new Map(h.map(m=>["human:"+m.userId,m.email]));for(let m of f.sessions)g.set("agent:"+m.id,m.displayName);let p=a("div",{class:"conversation-list","aria-label":"Channel posts"}),k=new Map,E=(m,I=!1)=>{let T=I?[...m.posts].reverse():m.posts;for(let x of T){let q=JSON.stringify(x),G=k.get(x.id);if(G?.fingerprint===q)continue;let ve=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},g.get(x.authorKind+":"+x.authorId)||x.authorId),a("small",{},B(x.createdAt))),a("p",{class:"message"},x.body));ve.append(Sr(e,x.body)),(!d.threadId||d.channelSearch)&&ve.append(_(x.replies?`${x.replies} ${x.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=x.threadId||x.id,d.channelSearch="",await C()})),G?G.node.replaceWith(ve):I?p.prepend(ve):p.append(ve),k.set(x.id,{fingerprint:q,node:ve})}};if(E(u),u.posts.length||p.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(p),u.nextCursor){let m=u.nextCursor,I=_("Earlier posts",async()=>{let T=new URLSearchParams(c);T.set("before",m);let x=await b(e+"/channel-posts?"+T);E(x),m=x.nextCursor,m||I.remove()});l.append(I)}let A=N(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),O=crypto.randomUUID(),R="";l.append(a("section",{class:"card"},F([A.node,kr(e,A.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async m=>{let I=m.get("body");R&&R!==I&&(O=crypto.randomUUID()),R=I,await b(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:I,threadId:d.threadId||void 0,idempotencyKey:O}}),d.channelSearch="",await C()})));let v=!0,P=!1,S=setInterval(async()=>{if(d.generation!==n){clearInterval(S);return}if(!(!v||P||document.hidden)){P=!0;try{let m=await b(e+"/channel-posts?"+c);v&&(m.posts.length&&p.querySelector(".empty")?.remove(),E(m,!0))}catch(m){v&&H("Channel refresh failed. "+m.message,!0)}finally{P=!1}}},5e3);return Ze.push(()=>{v=!1,clearInterval(S)}),l}async function ss(){let n=D("/billing"),e=await b(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),_e.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${B(e.paidUntil)}.`:r?`Trial ends ${B(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${B(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,g){let p=await b(n+"/"+f,{method:"POST",body:g,timeout:3e4}),k=new URL(p.url);if(k.protocol!=="https:"||k.username||k.password||!["checkout.stripe.com","billing.stripe.com"].includes(k.host))throw new Error("Payment destination could not be verified.");location.assign(k.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await b(n+"/refresh",{method:"POST",timeout:3e4}),await C(),H("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await b(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await C()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,g,p,k]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${k(g)} / ${k(p)}`)),a("progress",{max:p,value:Math.min(g,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ns(){let n=D(""),e=d.workspace,t=await b(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>te(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await b(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await Y()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Ct(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=N("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),F([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await b(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});te("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await b(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await C(),H("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>te("Permanently delete this workspace?",o=>{let l=N("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),F([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await b(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await Y(),u}o(),await Y(),H("Workspace deleted.")}))}),"danger"))),s} +`:""}${o.name}: ${o.uri}`,t.input.value="",ee("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Pr(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>Cr(n,s,i))))}async function ss(){let n=M(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>oe("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await b(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await O()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${J(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>Cr(n,l.id,l.name)),_("Copy reference",()=>ct(l.uri)),u)))}},s=await b(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=F("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},V([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await Tr(n,o),await O()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await b(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function at(n){delete q[n],sessionStorage.setItem(Nt,JSON.stringify({...q,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}function oe(n,e){let t=a("dialog",{},a("h2",{},n)),r=()=>{t.close(),t.remove()};return t.append(e(r),a("div",{class:"actions end"},_("Close",r))),t.addEventListener("close",()=>t.remove()),document.body.append(t),t.showModal(),t}function lt(n,e,t){oe(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>ct(e))))}function jt(){Ir(),d.user=null;let n=F("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),e=V([n.node],"Continue with email",async i=>{let{error:o}=await d.auth.signInWithOtp({email:i.get("email"),options:{emailRedirectTo:location.origin+"/app"+(q.authorization?"?authorization_id="+encodeURIComponent(q.authorization):q.device?"?device_code="+encodeURIComponent(q.device):""),shouldCreateUser:!0}});if(o)throw o;ee("Check your email for an October sign-in link. Open it in this browser."),e.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),t=F("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),r=F("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),s=V([t.node,r.node],"Sign in",async i=>{let{error:o}=await d.auth.signInWithPassword({email:i.get("email"),password:i.get("password")});if(o)throw o;await te()});pe.replaceChildren(a("main",{id:"main",class:"auth-wrap"},we(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. +A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),e,a("details",{},a("summary",{},"Use an existing password"),s),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function te(){d.user=await b("/api/me"),d.workspaces=await b("/api/workspaces");let n=Ae.has("billing")&&Ae.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,q.invite)return ns();if(q.authorization)return $t();if(q.device)return Dt();if(!d.workspace)return Ur();await O()}function ut(n){let e=F("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return V([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await b("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Ur(){pe.replaceChildren(a("main",{id:"main",class:"auth-wrap"},we(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),ut(O),_("Sign out",qt))))}async function qt(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,jt()}function Mt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Ce(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function $t(){let n=await b(`/api/oauth/requests/${encodeURIComponent(q.authorization)}`),e=d.workspace?.id,r=(e?await b(M("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await b(`/api/oauth/requests/${encodeURIComponent(q.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});at("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Mt($t)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):ut($t);pe.replaceChildren(a("main",{id:"main",class:"consent"},we(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Dt(){let n=await b(`/api/device/authorizations/${encodeURIComponent(q.device)}`),e=d.workspace?.id,r=(e?await b(M("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await b(`/api/device/authorizations/${encodeURIComponent(q.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),at("device"),pe.replaceChildren(a("main",{id:"main",class:"consent"},we(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",te,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Mt(Dt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):ut(Dt);pe.replaceChildren(a("main",{id:"main",class:"consent"},we(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function ns(){pe.replaceChildren(a("main",{id:"main",class:"consent"},we(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await b("/api/invites/accept",{method:"POST",body:{token:q.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),at("invite"),await te()},"primary"),_("Use another account",qt),_("Cancel",async()=>{at("invite"),await te()})))))}var ot={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function O(){if(Ir(),!d.workspace)return Ur();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(ot).map(([s,[i]])=>_(i,async()=>{d.tab=s,await O()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(ot)[i]===d.tab&&s.setAttribute("aria-current","page")}),pe.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},we(),a("div",{class:"workspace-switch"},Mt(O),_("+ New workspace",()=>oe("New workspace",s=>ut(async()=>{s(),await O()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",qt,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},ot[d.tab][0]),a("p",{class:"muted"},ot[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await O()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ps,billing:fs,files:ss,channels:hs,messages:cs,tasks:us,questions:ds,sessions:is,connect:os,members:as}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",O)))}}async function is(){let n=a("div"),e=a("div",{class:"grid"}),t=await b(M("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${J(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await O()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>ct(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await b(M("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",O)),n}function os(){let n=d.config.mcpUrl,e=M("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>ct(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),V([F("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await b(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});lt("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${J(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default +agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),V([F("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await b(M("/devices"),{method:"POST",body:{name:t.get("name")}});lt("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function as(){let n=M(""),[e,t]=await Promise.all([b(M("/members")),b(M("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await b(M(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await te()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>oe("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await b(M(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await te()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${J(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>oe("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let p=await b(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),lt("Replacement MCP key",p.token,`Update your app\u2019s secret/API key field. Shown once; expires ${J(p.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>oe("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await b(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await O()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${J(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=F("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=V([l.node],"Create invitation",async p=>{let g=await b(M("/invites"),{method:"POST",body:{email:p.get("email"),role:"member"}});lt("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(g.token)}`,`Share this link with ${g.email}. It expires ${J(g.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await b(M("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let p of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},p.email),a("p",{class:"help"},`Expires ${J(p.expiresAt)}`)),_("Revoke invitation",async()=>{await b(M(`/invites/${encodeURIComponent(p.id)}`),{method:"DELETE"}),await O()},"danger")));o.append(h)}return o}async function ls(){if(d.config=await b("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Pt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await te():jt(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,jt()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Ce(null,te),0)})}ls().catch(n=>{pe.replaceChildren(a("main",{id:"main",class:"auth-wrap"},we(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});var Kt=3;async function jr(n,e,t){let r=[],s="";for(let i=0;ie.has(l.id))||!o.nextCursor)return{pages:r,connected:!0};s=o.nextCursor}return{pages:r,connected:!1,cursor:s}}async function cs(){let n=d.generation,e=M(""),[t,r]=await Promise.all([b(e+"/sessions"),b(e+"/members")]),s=t.sessions,i=new Map(s.map(S=>["agent:"+S.id,S.displayName]));for(let S of r)i.set("human:"+S.userId,S.email);let o=(S,U)=>i.get(S+":"+U)||U,l=new URLSearchParams;d.conversationAgent&&l.set("agentId",d.conversationAgent),d.search&&l.set("query",d.search);let c=a("select",{"aria-label":"Filter by session",onchange:S=>{d.conversationAgent=S.target.value,Ce(null,O)}},a("option",{value:""},"All sessions"),s.map(S=>a("option",{value:S.id,selected:S.id===d.conversationAgent},S.displayName))),u=F("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),h=V([u.node],"Search",async S=>{d.search=S.get("query").trim(),await O()}),p=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",c),h)),g=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),f=new Map,k=!0,A=!1;Be.push(()=>{k=!1});let I=S=>S.responseMessageId?"Replied":S.state==="acknowledged"?S.toKind==="human"?"Read":"Acknowledged":S.state==="delivered"?"Delivered to app":S.state==="expired"?"Expired":"Waiting for delivery",T=(S,U=!1,y=null)=>{let x=U?[...S.messages].reverse():S.messages;for(let R of x){let j=JSON.stringify(R),$=f.get(R.id);if($?.fingerprint===j)continue;let Y=a("article",{class:"card",id:R.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},o(R.fromKind,R.from))," \u2192 ",o(R.toKind,R.to),a("p",{class:"help"},J(R.createdAt))),a("span",{class:"badge"},I(R))),a("p",{class:"message"},R.body));Y.append(Pr(e,R.body,R.context)),R.responseTo&&Y.append(a("p",{class:"help"},"Reply to ",a("code",{},R.responseTo))),R.toKind==="human"&&R.to===d.user.id&&R.state!=="acknowledged"&&R.state!=="expired"&&Y.append(_("Mark read",async()=>{await b(e+"/messages/read",{method:"POST",body:{messageIds:[R.id]}}),await O()},"subtle-button")),$?$.node.replaceWith(Y):U?g.prepend(Y):y?g.insertBefore(Y,y):g.append(Y),f.set(R.id,{fingerprint:j,node:Y})}},E=await b(e+"/messages?"+l);T(E);let v=l.toString(),C=()=>!k||d.generation!==n,K=async S=>{let U=new URLSearchParams(v);S&&U.set("before",S);let y=await b(e+"/messages?"+U);return{items:y.messages,nextCursor:y.nextCursor}},P=new Map,N=async S=>{for(let U=0;Uf.has(j.id));if(T({messages:y.items},!1,x),S.cursor=y.nextCursor,R||!y.nextCursor){S.button.remove(),P.delete(S.anchorId);return}}},ue=async()=>{if(!(!k||A||document.hidden)){A=!0;try{let S=g.querySelector("article")?.id||"",U=await jr(K,f,C);if(U.stale||C())return;for(let y=U.pages.length-1;y>=0;y--)T({messages:U.pages[y].items},!0);if(U.pages.some(y=>y.items.length)&&g.querySelector(".empty")?.remove(),!U.connected&&U.cursor&&!P.has(S)){let y={anchorId:S,cursor:U.cursor,button:null};y.button=_(S?"Load missed messages":"Earlier messages",()=>N(y)),P.set(S,y);let x=S?f.get(S)?.node??null:null;x?g.insertBefore(y.button,x):p.insertBefore(y.button,g.nextSibling)}}catch(S){C()||ee("Conversation refresh failed. "+S.message,!0)}finally{A=!1}}},H=setInterval(()=>{if(d.generation!==n){clearInterval(H);return}ue()},5e3);Be.push(()=>clearInterval(H));let Oe=()=>{document.hidden||ue()};if(document.addEventListener("visibilitychange",Oe),Be.push(()=>document.removeEventListener("visibilitychange",Oe)),E.messages.length||g.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),p.append(g),E.nextCursor){let S=E.nextCursor,U=_("Earlier messages",async()=>{l.set("before",S);let y=await b(e+"/messages?"+l);T(y),S=y.nextCursor,S||U.remove()});p.append(U)}if(s.length){let S=a("select",{name:"to",required:!0},s.map(j=>a("option",{value:j.id,selected:j.id===d.conversationAgent},j.displayName+(j.reachable?"":" \xB7 offline")))),U=F("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),y=crypto.randomUUID(),x="",R=V([a("label",{},"Send to",S),U.node,Or(e,U.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async j=>{let $=JSON.stringify([j.get("to"),j.get("body")]);x&&x!==$&&(y=crypto.randomUUID()),x=$,await b(e+"/messages",{method:"POST",body:{to:j.get("to"),body:j.get("body"),mode:"request",idempotencyKey:y}}),d.conversationAgent=j.get("to"),d.search="",ee("Request saved. Delivery status will update when the app checks its inbox."),await O()});p.append(a("section",{class:"card"},a("h2",{},"Send a message"),R))}else p.append(_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));return p.append(_("Refresh conversation",O)),p}async function us(){let n=M(""),e=await b(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},J(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await b(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=F("Task title",{name:"title",maxlength:256,required:!0}),o=F("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),V([i.node,o.node],"Create task",async l=>{await b(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),ee("Task created. An agent can now claim it."),await O()}))),t}async function ds(){let n=M(""),e=await b(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=F("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",J(i.createdAt)),a("div",{class:"actions"},l),V([o.node],"Send answer",async c=>{await b(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),ee("Answer saved for the requesting session."),await O()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await b(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",O)),t}async function hs(){let n=d.generation,e=M(""),t=await b(e+"/channels"),r=t.find(y=>y.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>oe("Create a channel",y=>V([F("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,F("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async x=>{let R=await b(e+"/channels",{method:"POST",body:{name:x.get("name"),description:x.get("description")}});d.channelId=R.id,d.threadId="",d.channelSearch="",y(),await O()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:y=>{d.channelId=y.target.value,d.threadId="",d.channelSearch="",Ce(null,O)}},t.map(y=>a("option",{value:y.id,selected:y.id===r.id},"#"+y.name))),o=V([F("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async y=>{d.channelSearch=y.get("query").trim(),d.threadId="",await O()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),_("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await O()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let[u,h,p]=await Promise.all([b(e+"/channel-posts?"+c),b(e+"/members"),b(e+"/sessions")]),g=new Map(h.map(y=>["human:"+y.userId,y.email]));for(let y of p.sessions)g.set("agent:"+y.id,y.displayName);let f=a("div",{class:"conversation-list","aria-label":"Channel posts"}),k=new Map,A=(y,x=!1,R=null)=>{let j=x?[...y.posts].reverse():y.posts;for(let $ of j){let Y=JSON.stringify($),dt=k.get($.id);if(dt?.fingerprint===Y)continue;let ge=a("article",{class:"card",id:$.id},a("div",{class:"row"},a("strong",{},g.get($.authorKind+":"+$.authorId)||$.authorId),a("small",{},J($.createdAt))),a("p",{class:"message"},$.body));ge.append(Pr(e,$.body)),(!d.threadId||d.channelSearch)&&ge.append(_($.replies?`${$.replies} ${$.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=$.threadId||$.id,d.channelSearch="",await O()})),dt?dt.node.replaceWith(ge):x?f.prepend(ge):R?f.insertBefore(ge,R):f.append(ge),k.set($.id,{fingerprint:Y,node:ge})}};if(A(u),u.posts.length||f.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(f),u.nextCursor){let y=u.nextCursor,x=_("Earlier posts",async()=>{let R=new URLSearchParams(c);R.set("before",y);let j=await b(e+"/channel-posts?"+R);A(j),y=j.nextCursor,y||x.remove()});l.append(x)}let I=F(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),T=crypto.randomUUID(),E="";l.append(a("section",{class:"card"},V([I.node,Or(e,I.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async y=>{let x=y.get("body");E&&E!==x&&(T=crypto.randomUUID()),E=x,await b(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:x,threadId:d.threadId||void 0,idempotencyKey:T}}),d.channelSearch="",await O()})));let v=!0,C=!1,K=()=>!v||d.generation!==n,P=c.toString(),N=async y=>{let x=new URLSearchParams(P);y&&x.set("before",y);let R=await b(e+"/channel-posts?"+x);return{items:R.posts,nextCursor:R.nextCursor}},ue=new Map,H=async y=>{for(let x=0;xk.has(Y.id));if(A({posts:R.items},!1,j),y.cursor=R.nextCursor,$||!R.nextCursor){y.button.remove(),ue.delete(y.anchorId);return}}},Oe=async()=>{if(!(!v||C||document.hidden)){C=!0;try{let y=f.querySelector("article")?.id||"",x=await jr(N,k,K);if(x.stale||K())return;for(let R=x.pages.length-1;R>=0;R--)A({posts:x.pages[R].items},!0);if(x.pages.some(R=>R.items.length)&&f.querySelector(".empty")?.remove(),!x.connected&&x.cursor&&!ue.has(y)){let R={anchorId:y,cursor:x.cursor,button:null};R.button=_(y?"Load missed posts":"Earlier posts",()=>H(R)),ue.set(y,R);let j=y?k.get(y)?.node??null:null;j?f.insertBefore(R.button,j):l.insertBefore(R.button,f.nextSibling)}}catch(y){K()||ee("Channel refresh failed. "+y.message,!0)}finally{C=!1}}},S=setInterval(()=>{if(d.generation!==n){clearInterval(S);return}Oe()},5e3),U=()=>{document.hidden||Oe()};return document.addEventListener("visibilitychange",U),Be.push(()=>{v=!1,clearInterval(S),document.removeEventListener("visibilitychange",U)}),l}async function fs(){let n=M("/billing"),e=await b(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=p=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(p/100),i=p=>p>=1024**3?`${(p/1024**3).toFixed(1)} GiB`:`${(p/1024**2).toFixed(1)} MiB`,o=p=>Number(p).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),Ae.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${J(e.paidUntil)}.`:r?`Trial ends ${J(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${J(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(p,g){let f=await b(n+"/"+p,{method:"POST",body:g,timeout:3e4}),k=new URL(f.url);if(k.protocol!=="https:"||k.username||k.password||!["checkout.stripe.com","billing.stripe.com"].includes(k.host))throw new Error("Payment destination could not be verified.");location.assign(k.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await b(n+"/refresh",{method:"POST",timeout:3e4}),await O(),ee("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await b(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await O()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[p,g,f,k]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},p),a("span",{},`${k(g)} / ${k(f)}`)),a("progress",{max:f,value:Math.min(g,f),"aria-label":p})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ps(){let n=M(""),e=d.workspace,t=await b(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>oe(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await b(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await te()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Lt(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=F("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),V([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await b(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});oe("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await b(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await O(),ee("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>oe("Permanently delete this workspace?",o=>{let l=F("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),V([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await b(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await te(),u}o(),await te(),ee("Workspace deleted.")}))}),"danger"))),s} diff --git a/web/src/app.js b/web/src/app.js index bba9d0f..e471aa1 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -323,6 +323,24 @@ async function start() { } start().catch(error => { root.replaceChildren(el('main', { id: 'main', class: 'auth-wrap' }, brand(), el('section', { class: 'card consent' }, el('h1', {}, 'Couldn’t open your workspace'), el('p', {}, error.message), button('Try again', () => location.reload())))); }); +// Newest-first history lists (conversations, channels) share one live-refresh +// pattern: poll the newest page, then walk back over burst pages until they +// overlap what is already on screen. The walk is bounded; when it ends without +// overlapping, the caller leaves an explicit gap-loading control behind. +const historyCatchUpPages = 3; +async function catchUpHistory(fetchPage, rendered, stale) { + const pages = []; + let cursor = ''; + for (let i = 0; i < historyCatchUpPages; i++) { + const page = await fetchPage(cursor); + if (stale()) return { pages: [], stale: true }; + pages.push(page); + if (page.items.some(item => rendered.has(item.id)) || !page.nextCursor) return { pages, connected: true }; + cursor = page.nextCursor; + } + return { pages, connected: false, cursor }; +} + async function messagesView() { const generation = state.generation; const scopePath = path(''); @@ -343,7 +361,7 @@ async function messagesView() { let live = true, polling = false; viewCleanups.push(() => { live = false; }); const receipt = message => message.responseMessageId ? 'Replied' : message.state === 'acknowledged' ? (message.toKind === 'human' ? 'Read' : 'Acknowledged') : message.state === 'delivered' ? 'Delivered to app' : message.state === 'expired' ? 'Expired' : 'Waiting for delivery'; - const append = (page, fresh = false) => { + const append = (page, fresh = false, anchor = null) => { const rows = fresh ? [...page.messages].reverse() : page.messages; for (const message of rows) { const fingerprint = JSON.stringify(message); @@ -355,6 +373,7 @@ async function messagesView() { if (message.toKind === 'human' && message.to === state.user.id && message.state !== 'acknowledged' && message.state !== 'expired') item.append(button('Mark read', async () => { await api(scopePath + '/messages/read', { method: 'POST', body: { messageIds: [message.id] } }); await render(); }, 'subtle-button')); if (previous) previous.node.replaceWith(item); else if (fresh) list.prepend(item); + else if (anchor) list.insertBefore(item, anchor); else list.append(item); rendered.set(message.id, { fingerprint, node: item }); } @@ -362,15 +381,50 @@ async function messagesView() { const page = await api(scopePath + '/messages?' + query); append(page); const refreshQuery = query.toString(); - const timer = setInterval(async () => { - if (state.generation !== generation) { clearInterval(timer); return; } + const stale = () => !live || state.generation !== generation; + const fetchHistory = async cursor => { + const params = new URLSearchParams(refreshQuery); + if (cursor) params.set('before', cursor); + const data = await api(scopePath + '/messages?' + params); + return { items: data.messages, nextCursor: data.nextCursor }; + }; + const gaps = new Map(); + const fillGap = async control => { + for (let i = 0; i < historyCatchUpPages; i++) { + const data = await fetchHistory(control.cursor); + if (stale()) return; + const anchor = control.anchorId ? rendered.get(control.anchorId)?.node ?? null : null; + const connected = data.items.some(item => rendered.has(item.id)); + append({ messages: data.items }, false, anchor); + control.cursor = data.nextCursor; + if (connected || !data.nextCursor) { control.button.remove(); gaps.delete(control.anchorId); return; } + } + }; + const refresh = async () => { if (!live || polling || document.hidden) return; polling = true; - try { const next = await api(scopePath + '/messages?' + refreshQuery); if (live) { if (next.messages.length) list.querySelector('.empty')?.remove(); append(next, true); } } - catch (error) { if (live) inform('Conversation refresh failed. ' + error.message, true); } + try { + const anchorId = list.querySelector('article')?.id || ''; + const result = await catchUpHistory(fetchHistory, rendered, stale); + if (result.stale || stale()) return; + for (let i = result.pages.length - 1; i >= 0; i--) append({ messages: result.pages[i].items }, true); + if (result.pages.some(p => p.items.length)) list.querySelector('.empty')?.remove(); + if (!result.connected && result.cursor && !gaps.has(anchorId)) { + const control = { anchorId, cursor: result.cursor, button: null }; + control.button = button(anchorId ? 'Load missed messages' : 'Earlier messages', () => fillGap(control)); + gaps.set(anchorId, control); + const anchor = anchorId ? rendered.get(anchorId)?.node ?? null : null; + if (anchor) list.insertBefore(control.button, anchor); + else container.insertBefore(control.button, list.nextSibling); + } + } catch (error) { if (!stale()) inform('Conversation refresh failed. ' + error.message, true); } finally { polling = false; } - }, 5000); + }; + const timer = setInterval(() => { if (state.generation !== generation) { clearInterval(timer); return; } refresh(); }, 5000); viewCleanups.push(() => clearInterval(timer)); + const onVisible = () => { if (!document.hidden) refresh(); }; + document.addEventListener('visibilitychange', onVisible); + viewCleanups.push(() => document.removeEventListener('visibilitychange', onVisible)); if (!page.messages.length) list.append(el('section', { class: 'card empty' }, el('h2', {}, state.search ? 'No matching messages' : 'Start a conversation'), el('p', { class: 'muted' }, state.search ? 'Try a different phrase or session.' : 'Choose a connected session below and send it a request.'))); container.append(list); if (page.nextCursor) { @@ -455,15 +509,15 @@ async function channelsView() { for (const session of directory.sessions) names.set('agent:' + session.id, session.displayName); const list = el('div', { class: 'conversation-list', 'aria-label': 'Channel posts' }); const rendered = new Map(); - const append = (page, fresh = false) => { + const append = (page, fresh = false, anchor = null) => { const posts = fresh ? [...page.posts].reverse() : page.posts; for (const post of posts) { const fingerprint = JSON.stringify(post), previous = rendered.get(post.id); if (previous?.fingerprint === fingerprint) continue; - const item = el('article', { class: 'card' }, el('div', { class: 'row' }, el('strong', {}, names.get(post.authorKind + ':' + post.authorId) || post.authorId), el('small', {}, date(post.createdAt))), el('p', { class: 'message' }, post.body)); + const item = el('article', { class: 'card', id: post.id }, el('div', { class: 'row' }, el('strong', {}, names.get(post.authorKind + ':' + post.authorId) || post.authorId), el('small', {}, date(post.createdAt))), el('p', { class: 'message' }, post.body)); item.append(attachmentLinks(scopePath, post.body)); if (!state.threadId || state.channelSearch) item.append(button(post.replies ? `${post.replies} ${post.replies === 1 ? 'reply' : 'replies'}` : 'Open thread', async () => { state.threadId = post.threadId || post.id; state.channelSearch = ''; await render(); })); - if (previous) previous.node.replaceWith(item); else if (fresh) list.prepend(item); else list.append(item); + if (previous) previous.node.replaceWith(item); else if (fresh) list.prepend(item); else if (anchor) list.insertBefore(item, anchor); else list.append(item); rendered.set(post.id, { fingerprint, node: item }); } }; @@ -479,9 +533,50 @@ async function channelsView() { state.channelSearch = ''; await render(); }))); let live = true, polling = false; - const timer = setInterval(async () => { if (state.generation !== generation) { clearInterval(timer); return; } - if (!live || polling || document.hidden) return; polling = true; try { const next = await api(scopePath + '/channel-posts?' + query); if (live) { if (next.posts.length) list.querySelector('.empty')?.remove(); append(next, true); } } catch (error) { if (live) inform('Channel refresh failed. ' + error.message, true); } finally { polling = false; } }, 5000); - viewCleanups.push(() => { live = false; clearInterval(timer); }); + const stale = () => !live || state.generation !== generation; + const refreshQuery = query.toString(); + const fetchHistory = async cursor => { + const params = new URLSearchParams(refreshQuery); + if (cursor) params.set('before', cursor); + const data = await api(scopePath + '/channel-posts?' + params); + return { items: data.posts, nextCursor: data.nextCursor }; + }; + const gaps = new Map(); + const fillGap = async control => { + for (let i = 0; i < historyCatchUpPages; i++) { + const data = await fetchHistory(control.cursor); + if (stale()) return; + const anchor = control.anchorId ? rendered.get(control.anchorId)?.node ?? null : null; + const connected = data.items.some(item => rendered.has(item.id)); + append({ posts: data.items }, false, anchor); + control.cursor = data.nextCursor; + if (connected || !data.nextCursor) { control.button.remove(); gaps.delete(control.anchorId); return; } + } + }; + const refresh = async () => { + if (!live || polling || document.hidden) return; + polling = true; + try { + const anchorId = list.querySelector('article')?.id || ''; + const result = await catchUpHistory(fetchHistory, rendered, stale); + if (result.stale || stale()) return; + for (let i = result.pages.length - 1; i >= 0; i--) append({ posts: result.pages[i].items }, true); + if (result.pages.some(p => p.items.length)) list.querySelector('.empty')?.remove(); + if (!result.connected && result.cursor && !gaps.has(anchorId)) { + const control = { anchorId, cursor: result.cursor, button: null }; + control.button = button(anchorId ? 'Load missed posts' : 'Earlier posts', () => fillGap(control)); + gaps.set(anchorId, control); + const anchor = anchorId ? rendered.get(anchorId)?.node ?? null : null; + if (anchor) list.insertBefore(control.button, anchor); + else container.insertBefore(control.button, list.nextSibling); + } + } catch (error) { if (!stale()) inform('Channel refresh failed. ' + error.message, true); } + finally { polling = false; } + }; + const timer = setInterval(() => { if (state.generation !== generation) { clearInterval(timer); return; } refresh(); }, 5000); + const onVisible = () => { if (!document.hidden) refresh(); }; + document.addEventListener('visibilitychange', onVisible); + viewCleanups.push(() => { live = false; clearInterval(timer); document.removeEventListener('visibilitychange', onVisible); }); return container; } diff --git a/web/tests/workspace.spec.js b/web/tests/workspace.spec.js index 752e0cf..7c7f404 100644 --- a/web/tests/workspace.spec.js +++ b/web/tests/workspace.spec.js @@ -342,3 +342,189 @@ test('workspace deletion requires its name and recovers a failed cancellation', await expect(page.getByRole('heading', { name: 'Make room for your team.', exact: true })).toBeVisible(); expect(attempts).toEqual([{ confirmName: 'My workspace' }, { confirmName: 'My workspace' }]); }); + +// Newest-first history page mirroring the server: `before` names the oldest +// id of the previous page, `nextCursor` names the oldest id when more remain. +function historyPage(items, url, pageSize = 50) { + const before = url.searchParams.get('before'); + let start = 0; + if (before) { + const index = items.findIndex(item => item.id === before); + if (index < 0) return { error: 'History cursor is unavailable' }; + start = index + 1; + } + const slice = items.slice(start, start + pageSize); + return { slice, nextCursor: slice.length && start + pageSize < items.length ? slice[slice.length - 1].id : undefined }; +} + +function burstMessages(prefix, count) { + return Array.from({ length: count }, (_, i) => ({ + id: `msg-${prefix}-${count - i}`, + from: 'owner-id', fromKind: 'human', to: 'session-1', toKind: 'agent', + body: `${prefix} message ${count - i}`, state: 'delivered', createdAt: new Date(Date.now() - i * 1000).toISOString(), + })); +} + +function burstPosts(prefix, count, channelId = 'channel-1') { + return Array.from({ length: count }, (_, i) => ({ + id: `post-${prefix}-${count - i}`, channelId, authorKind: 'human', authorId: 'owner-id', + body: `${prefix} post ${count - i}`, createdAt: new Date(Date.now() - i * 1000).toISOString(), replies: 0, + })); +} + +test('conversation bursts larger than one page catch up without losing the middle', async ({ page }) => { + const events = await fixture(page); + const server = { messages: burstMessages('seed', 50) }; + await page.route('**/api/workspaces/workspace-1/messages*', async route => { + if (route.request().method() !== 'GET') { + events.push({ path: new URL(route.request().url()).pathname, method: route.request().method(), body: route.request().postDataJSON() }); + return route.fulfill({ json: { ok: true, result: {} } }); + } + const window = historyPage(server.messages, new URL(route.request().url())); + if (window.error) return route.fulfill({ status: 404, json: { ok: false, error: { message: window.error } } }); + await route.fulfill({ json: { ok: true, result: { messages: window.slice, nextCursor: window.nextCursor } } }); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const rows = page.locator('.conversation-list article'); + await expect(rows).toHaveCount(50); + await page.getByLabel('Your message', { exact: true }).fill('draft stays put'); + server.messages.unshift(...burstMessages('burst', 110)); + await expect(page.getByText('burst message 110', { exact: true })).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(160, { timeout: 20000 }); + await expect(page.getByText('burst message 55', { exact: true })).toBeVisible(); + await expect(rows.first()).toContainText('burst message 110'); + await expect(rows.last()).toContainText('seed message 1'); + await expect(page.getByRole('button', { name: 'Load missed messages', exact: true })).toHaveCount(0); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('draft stays put'); + expect(events.filter(e => e.path?.endsWith('/messages/read'))).toHaveLength(0); +}); + +test('conversation bursts beyond catch-up leave an explicit gap control', async ({ page }) => { + const events = await fixture(page); + const server = { messages: burstMessages('seed', 50) }; + server.messages[49] = { ...server.messages[49], toKind: 'human', to: 'owner-id' }; + await page.route('**/api/workspaces/workspace-1/messages*', async route => { + if (route.request().method() !== 'GET') { + events.push({ path: new URL(route.request().url()).pathname, method: route.request().method(), body: route.request().postDataJSON() }); + return route.fulfill({ json: { ok: true, result: {} } }); + } + const window = historyPage(server.messages, new URL(route.request().url())); + if (window.error) return route.fulfill({ status: 404, json: { ok: false, error: { message: window.error } } }); + await route.fulfill({ json: { ok: true, result: { messages: window.slice, nextCursor: window.nextCursor } } }); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const rows = page.locator('.conversation-list article'); + await expect(rows).toHaveCount(50); + await expect(page.getByRole('button', { name: 'Mark read', exact: true })).toHaveCount(1); + await page.getByLabel('Your message', { exact: true }).fill('draft stays put'); + server.messages.unshift(...burstMessages('burst', 200)); + const gap = page.getByRole('button', { name: 'Load missed messages', exact: true }); + await expect(gap).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(200); + await expect(page.getByText('burst message 200', { exact: true })).toBeVisible(); + await expect(page.getByText('burst message 25', { exact: true })).toHaveCount(0); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('draft stays put'); + await gap.click(); + await expect(page.getByText('burst message 25', { exact: true })).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(250); + await expect(rows.first()).toContainText('burst message 200'); + await expect(rows.last()).toContainText('seed message 1'); + await expect(gap).toHaveCount(0); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('draft stays put'); + expect(events.filter(e => e.path?.endsWith('/messages/read'))).toHaveLength(0); +}); + +test('returning to a hidden conversation tab catches up without a reload', async ({ page }) => { + await fixture(page); + const server = { messages: burstMessages('seed', 20) }; + await page.route('**/api/workspaces/workspace-1/messages*', async route => { + const window = historyPage(server.messages, new URL(route.request().url())); + await route.fulfill({ json: { ok: true, result: { messages: window.slice, nextCursor: window.nextCursor } } }); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const rows = page.locator('.conversation-list article'); + await expect(rows).toHaveCount(20); + await page.getByLabel('Your message', { exact: true }).fill('draft stays put'); + await page.evaluate(() => { + Object.defineProperty(document, 'hidden', { value: true, configurable: true }); + document.dispatchEvent(new Event('visibilitychange')); + }); + server.messages.unshift(...burstMessages('burst', 30)); + await page.waitForTimeout(6500); + await expect(rows).toHaveCount(20); + await page.evaluate(() => { + Object.defineProperty(document, 'hidden', { value: false, configurable: true }); + document.dispatchEvent(new Event('visibilitychange')); + }); + await expect(page.getByText('burst message 30', { exact: true })).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(50); + await expect(page.getByLabel('Your message', { exact: true })).toHaveValue('draft stays put'); +}); + +test('channel bursts keep every post reachable when older history is loaded', async ({ page }) => { + await fixture(page); + const server = { posts: burstPosts('seed', 60) }; + await page.route('**/api/workspaces/workspace-1/channels', async route => { + if (route.request().method() === 'GET') return route.fulfill({ json: { ok: true, result: [{ id: 'channel-1', name: 'general', description: 'General discussion', subscribers: 1 }] } }); + await route.fallback(); + }); + await page.route('**/api/workspaces/workspace-1/channel-posts*', async route => { + const window = historyPage(server.posts, new URL(route.request().url())); + if (window.error) return route.fulfill({ status: 404, json: { ok: false, error: { message: window.error } } }); + await route.fulfill({ json: { ok: true, result: { posts: window.slice, nextCursor: window.nextCursor } } }); + }); + await page.goto('/app'); + await page.getByRole('navigation', { name: 'Workspace' }).getByRole('button', { name: 'Channels', exact: true }).click(); + const rows = page.locator('.conversation-list article'); + await expect(rows).toHaveCount(50); + await page.getByRole('button', { name: 'Earlier posts', exact: true }).click(); + await expect(rows).toHaveCount(60); + await page.getByLabel('Your post', { exact: true }).fill('channel draft stays put'); + server.posts.unshift(...burstPosts('burst', 200)); + const gap = page.getByRole('button', { name: 'Load missed posts', exact: true }); + await expect(gap).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(210); + await expect(page.getByText('burst post 200', { exact: true })).toBeVisible(); + await expect(page.getByText('burst post 25', { exact: true })).toHaveCount(0); + await gap.click(); + await expect(page.getByText('burst post 25', { exact: true })).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(260); + await expect(rows.first()).toContainText('burst post 200'); + await expect(rows.last()).toContainText('seed post 1'); + await expect(gap).toHaveCount(0); + await expect(page.getByLabel('Your post', { exact: true })).toHaveValue('channel draft stays put'); +}); + +test('returning to a hidden channel tab catches up without a reload', async ({ page }) => { + await fixture(page); + const server = { posts: burstPosts('seed', 20) }; + await page.route('**/api/workspaces/workspace-1/channels', async route => { + if (route.request().method() === 'GET') return route.fulfill({ json: { ok: true, result: [{ id: 'channel-1', name: 'general', description: 'General discussion', subscribers: 1 }] } }); + await route.fallback(); + }); + await page.route('**/api/workspaces/workspace-1/channel-posts*', async route => { + const window = historyPage(server.posts, new URL(route.request().url())); + await route.fulfill({ json: { ok: true, result: { posts: window.slice, nextCursor: window.nextCursor } } }); + }); + await page.goto('/app'); + await page.getByRole('navigation', { name: 'Workspace' }).getByRole('button', { name: 'Channels', exact: true }).click(); + const rows = page.locator('.conversation-list article'); + await expect(rows).toHaveCount(20); + await page.evaluate(() => { + Object.defineProperty(document, 'hidden', { value: true, configurable: true }); + document.dispatchEvent(new Event('visibilitychange')); + }); + server.posts.unshift(...burstPosts('burst', 30)); + await page.waitForTimeout(6500); + await expect(rows).toHaveCount(20); + await page.evaluate(() => { + Object.defineProperty(document, 'hidden', { value: false, configurable: true }); + document.dispatchEvent(new Event('visibilitychange')); + }); + await expect(page.getByText('burst post 30', { exact: true })).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(50); + await expect(page.getByRole('button', { name: 'Load missed posts', exact: true })).toHaveCount(0); +}); From efb4dffb949d57ab0a4b572fbdd5078ce25bb5ec Mon Sep 17 00:00:00 2001 From: Harsh Savergaonkar Date: Fri, 13 Nov 2026 00:30:15 -0800 Subject: [PATCH 2/2] audit fix: keep the gap control at the remaining gap after a partial load Insert rows loaded by the gap control before the control itself, so it always sits directly above the older block instead of staying above the rows it just loaded. Applies to conversations and channels. Add a 400-item regression for each view that checks the control's neighbours after a partial load and the full row order once the gap closes. Regenerate the embedded browser bundle with web's build. Co-Authored-By: Claude Fable 5.2 --- bus/hostedweb/app.js | 2 +- web/src/app.js | 4 +-- web/tests/workspace.spec.js | 62 +++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/bus/hostedweb/app.js b/bus/hostedweb/app.js index 53888ba..52de735 100644 --- a/bus/hostedweb/app.js +++ b/bus/hostedweb/app.js @@ -19,4 +19,4 @@ ${T}`}var D=class extends Error{constructor({message:e,code:t,cause:r,name:s}){v `:""}${o.name}: ${o.uri}`,t.input.value="",ee("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Pr(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>Cr(n,s,i))))}async function ss(){let n=M(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>oe("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await b(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await O()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${J(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>Cr(n,l.id,l.name)),_("Copy reference",()=>ct(l.uri)),u)))}},s=await b(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=F("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},V([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await Tr(n,o),await O()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await b(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function at(n){delete q[n],sessionStorage.setItem(Nt,JSON.stringify({...q,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}var ns=0;function oe(n,e){let t=`modal-title-${++ns}`,r=a("dialog",{"aria-labelledby":t},a("h2",{id:t},n)),s=()=>r.close();return r.append(e(s),a("div",{class:"actions end"},_("Close",s))),r.addEventListener("close",()=>r.remove()),document.body.append(r),r.showModal(),r}function lt(n,e,t){oe(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>ct(e))))}function jt(){Ir(),d.user=null;let n=F("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),e=V([n.node],"Continue with email",async i=>{let{error:o}=await d.auth.signInWithOtp({email:i.get("email"),options:{emailRedirectTo:location.origin+"/app"+(q.authorization?"?authorization_id="+encodeURIComponent(q.authorization):q.device?"?device_code="+encodeURIComponent(q.device):""),shouldCreateUser:!0}});if(o)throw o;ee("Check your email for an October sign-in link. Open it in this browser."),e.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),t=F("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),r=F("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),s=V([t.node,r.node],"Sign in",async i=>{let{error:o}=await d.auth.signInWithPassword({email:i.get("email"),password:i.get("password")});if(o)throw o;await te()});pe.replaceChildren(a("main",{id:"main",class:"auth-wrap"},we(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),e,a("details",{},a("summary",{},"Use an existing password"),s),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function te(){d.user=await b("/api/me"),d.workspaces=await b("/api/workspaces");let n=Ae.has("billing")&&Ae.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,q.invite)return is();if(q.authorization)return $t();if(q.device)return Dt();if(!d.workspace)return Ur();await O()}function ut(n){let e=F("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return V([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await b("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Ur(){pe.replaceChildren(a("main",{id:"main",class:"auth-wrap"},we(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),ut(O),_("Sign out",qt))))}async function qt(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,jt()}function Mt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Ce(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function $t(){let n=await b(`/api/oauth/requests/${encodeURIComponent(q.authorization)}`),e=d.workspace?.id,r=(e?await b(M("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await b(`/api/oauth/requests/${encodeURIComponent(q.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});at("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Mt($t)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):ut($t);pe.replaceChildren(a("main",{id:"main",class:"consent"},we(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Dt(){let n=await b(`/api/device/authorizations/${encodeURIComponent(q.device)}`),e=d.workspace?.id,r=(e?await b(M("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await b(`/api/device/authorizations/${encodeURIComponent(q.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),at("device"),pe.replaceChildren(a("main",{id:"main",class:"consent"},we(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",te,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Mt(Dt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):ut(Dt);pe.replaceChildren(a("main",{id:"main",class:"consent"},we(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function is(){pe.replaceChildren(a("main",{id:"main",class:"consent"},we(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await b("/api/invites/accept",{method:"POST",body:{token:q.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),at("invite"),await te()},"primary"),_("Use another account",qt),_("Cancel",async()=>{at("invite"),await te()})))))}var ot={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function O(){if(Ir(),!d.workspace)return Ur();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(ot).map(([s,[i]])=>_(i,async()=>{d.tab=s,await O()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(ot)[i]===d.tab&&s.setAttribute("aria-current","page")}),pe.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},we(),a("div",{class:"workspace-switch"},Mt(O),_("+ New workspace",()=>oe("New workspace",s=>ut(async()=>{s(),await O()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",qt,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},ot[d.tab][0]),a("p",{class:"muted"},ot[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await O()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ws,billing:ps,files:ss,channels:fs,messages:us,tasks:ds,questions:hs,sessions:os,connect:as,members:ls}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",O)))}}async function os(){let n=a("div"),e=a("div",{class:"grid"}),t=await b(M("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${J(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await O()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>ct(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await b(M("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",O)),n}function as(){let n=d.config.mcpUrl,e=M("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>ct(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),V([F("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await b(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});lt("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${J(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default -agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),V([F("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await b(M("/devices"),{method:"POST",body:{name:t.get("name")}});lt("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function ls(){let n=M(""),[e,t]=await Promise.all([b(M("/members")),b(M("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await b(M(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await te()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>oe("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await b(M(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await te()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${J(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>oe("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let p=await b(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),lt("Replacement MCP key",p.token,`Update your app\u2019s secret/API key field. Shown once; expires ${J(p.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>oe("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await b(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await O()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${J(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=F("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=V([l.node],"Create invitation",async p=>{let g=await b(M("/invites"),{method:"POST",body:{email:p.get("email"),role:"member"}});lt("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(g.token)}`,`Share this link with ${g.email}. It expires ${J(g.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await b(M("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let p of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},p.email),a("p",{class:"help"},`Expires ${J(p.expiresAt)}`)),_("Revoke invitation",async()=>{await b(M(`/invites/${encodeURIComponent(p.id)}`),{method:"DELETE"}),await O()},"danger")));o.append(h)}return o}async function cs(){if(d.config=await b("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Pt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await te():jt(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,jt()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Ce(null,te),0)})}cs().catch(n=>{pe.replaceChildren(a("main",{id:"main",class:"auth-wrap"},we(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});var Kt=3;async function jr(n,e,t){let r=[],s="";for(let i=0;ie.has(l.id))||!o.nextCursor)return{pages:r,connected:!0};s=o.nextCursor}return{pages:r,connected:!1,cursor:s}}async function us(){let n=d.generation,e=M(""),[t,r]=await Promise.all([b(e+"/sessions"),b(e+"/members")]),s=t.sessions,i=new Map(s.map(S=>["agent:"+S.id,S.displayName]));for(let S of r)i.set("human:"+S.userId,S.email);let o=(S,U)=>i.get(S+":"+U)||U,l=new URLSearchParams;d.conversationAgent&&l.set("agentId",d.conversationAgent),d.search&&l.set("query",d.search);let c=a("select",{"aria-label":"Filter by session",onchange:S=>{d.conversationAgent=S.target.value,Ce(null,O)}},a("option",{value:""},"All sessions"),s.map(S=>a("option",{value:S.id,selected:S.id===d.conversationAgent},S.displayName))),u=F("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),h=V([u.node],"Search",async S=>{d.search=S.get("query").trim(),await O()}),p=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",c),h)),g=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),f=new Map,k=!0,A=!1;Be.push(()=>{k=!1});let I=S=>S.responseMessageId?"Replied":S.state==="acknowledged"?S.toKind==="human"?"Read":"Acknowledged":S.state==="delivered"?"Delivered to app":S.state==="expired"?"Expired":"Waiting for delivery",T=(S,U=!1,y=null)=>{let x=U?[...S.messages].reverse():S.messages;for(let R of x){let j=JSON.stringify(R),$=f.get(R.id);if($?.fingerprint===j)continue;let Y=a("article",{class:"card",id:R.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},o(R.fromKind,R.from))," \u2192 ",o(R.toKind,R.to),a("p",{class:"help"},J(R.createdAt))),a("span",{class:"badge"},I(R))),a("p",{class:"message"},R.body));Y.append(Pr(e,R.body,R.context)),R.responseTo&&Y.append(a("p",{class:"help"},"Reply to ",a("code",{},R.responseTo))),R.toKind==="human"&&R.to===d.user.id&&R.state!=="acknowledged"&&R.state!=="expired"&&Y.append(_("Mark read",async()=>{await b(e+"/messages/read",{method:"POST",body:{messageIds:[R.id]}}),await O()},"subtle-button")),$?$.node.replaceWith(Y):U?g.prepend(Y):y?g.insertBefore(Y,y):g.append(Y),f.set(R.id,{fingerprint:j,node:Y})}},E=await b(e+"/messages?"+l);T(E);let v=l.toString(),C=()=>!k||d.generation!==n,K=async S=>{let U=new URLSearchParams(v);S&&U.set("before",S);let y=await b(e+"/messages?"+U);return{items:y.messages,nextCursor:y.nextCursor}},P=new Map,N=async S=>{for(let U=0;Uf.has(j.id));if(T({messages:y.items},!1,x),S.cursor=y.nextCursor,R||!y.nextCursor){S.button.remove(),P.delete(S.anchorId);return}}},ue=async()=>{if(!(!k||A||document.hidden)){A=!0;try{let S=g.querySelector("article")?.id||"",U=await jr(K,f,C);if(U.stale||C())return;for(let y=U.pages.length-1;y>=0;y--)T({messages:U.pages[y].items},!0);if(U.pages.some(y=>y.items.length)&&g.querySelector(".empty")?.remove(),!U.connected&&U.cursor&&!P.has(S)){let y={anchorId:S,cursor:U.cursor,button:null};y.button=_(S?"Load missed messages":"Earlier messages",()=>N(y)),P.set(S,y);let x=S?f.get(S)?.node??null:null;x?g.insertBefore(y.button,x):p.insertBefore(y.button,g.nextSibling)}}catch(S){C()||ee("Conversation refresh failed. "+S.message,!0)}finally{A=!1}}},H=setInterval(()=>{if(d.generation!==n){clearInterval(H);return}ue()},5e3);Be.push(()=>clearInterval(H));let Oe=()=>{document.hidden||ue()};if(document.addEventListener("visibilitychange",Oe),Be.push(()=>document.removeEventListener("visibilitychange",Oe)),E.messages.length||g.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),p.append(g),E.nextCursor){let S=E.nextCursor,U=_("Earlier messages",async()=>{l.set("before",S);let y=await b(e+"/messages?"+l);T(y),S=y.nextCursor,S||U.remove()});p.append(U)}if(s.length){let S=a("select",{name:"to",required:!0},s.map(j=>a("option",{value:j.id,selected:j.id===d.conversationAgent},j.displayName+(j.reachable?"":" \xB7 offline")))),U=F("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),y=crypto.randomUUID(),x="",R=V([a("label",{},"Send to",S),U.node,Or(e,U.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async j=>{let $=JSON.stringify([j.get("to"),j.get("body")]);x&&x!==$&&(y=crypto.randomUUID()),x=$,await b(e+"/messages",{method:"POST",body:{to:j.get("to"),body:j.get("body"),mode:"request",idempotencyKey:y}}),d.conversationAgent=j.get("to"),d.search="",ee("Request saved. Delivery status will update when the app checks its inbox."),await O()});p.append(a("section",{class:"card"},a("h2",{},"Send a message"),R))}else p.append(_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));return p.append(_("Refresh conversation",O)),p}async function ds(){let n=M(""),e=await b(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},J(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await b(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=F("Task title",{name:"title",maxlength:256,required:!0}),o=F("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),V([i.node,o.node],"Create task",async l=>{await b(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),ee("Task created. An agent can now claim it."),await O()}))),t}async function hs(){let n=M(""),e=await b(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=F("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",J(i.createdAt)),a("div",{class:"actions"},l),V([o.node],"Send answer",async c=>{await b(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),ee("Answer saved for the requesting session."),await O()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await b(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",O)),t}async function fs(){let n=d.generation,e=M(""),t=await b(e+"/channels"),r=t.find(y=>y.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>oe("Create a channel",y=>V([F("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,F("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async x=>{let R=await b(e+"/channels",{method:"POST",body:{name:x.get("name"),description:x.get("description")}});d.channelId=R.id,d.threadId="",d.channelSearch="",y(),await O()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:y=>{d.channelId=y.target.value,d.threadId="",d.channelSearch="",Ce(null,O)}},t.map(y=>a("option",{value:y.id,selected:y.id===r.id},"#"+y.name))),o=V([F("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async y=>{d.channelSearch=y.get("query").trim(),d.threadId="",await O()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),_("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await O()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let[u,h,p]=await Promise.all([b(e+"/channel-posts?"+c),b(e+"/members"),b(e+"/sessions")]),g=new Map(h.map(y=>["human:"+y.userId,y.email]));for(let y of p.sessions)g.set("agent:"+y.id,y.displayName);let f=a("div",{class:"conversation-list","aria-label":"Channel posts"}),k=new Map,A=(y,x=!1,R=null)=>{let j=x?[...y.posts].reverse():y.posts;for(let $ of j){let Y=JSON.stringify($),dt=k.get($.id);if(dt?.fingerprint===Y)continue;let ge=a("article",{class:"card",id:$.id},a("div",{class:"row"},a("strong",{},g.get($.authorKind+":"+$.authorId)||$.authorId),a("small",{},J($.createdAt))),a("p",{class:"message"},$.body));ge.append(Pr(e,$.body)),(!d.threadId||d.channelSearch)&&ge.append(_($.replies?`${$.replies} ${$.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=$.threadId||$.id,d.channelSearch="",await O()})),dt?dt.node.replaceWith(ge):x?f.prepend(ge):R?f.insertBefore(ge,R):f.append(ge),k.set($.id,{fingerprint:Y,node:ge})}};if(A(u),u.posts.length||f.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(f),u.nextCursor){let y=u.nextCursor,x=_("Earlier posts",async()=>{let R=new URLSearchParams(c);R.set("before",y);let j=await b(e+"/channel-posts?"+R);A(j),y=j.nextCursor,y||x.remove()});l.append(x)}let I=F(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),T=crypto.randomUUID(),E="";l.append(a("section",{class:"card"},V([I.node,Or(e,I.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async y=>{let x=y.get("body");E&&E!==x&&(T=crypto.randomUUID()),E=x,await b(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:x,threadId:d.threadId||void 0,idempotencyKey:T}}),d.channelSearch="",await O()})));let v=!0,C=!1,K=()=>!v||d.generation!==n,P=c.toString(),N=async y=>{let x=new URLSearchParams(P);y&&x.set("before",y);let R=await b(e+"/channel-posts?"+x);return{items:R.posts,nextCursor:R.nextCursor}},ue=new Map,H=async y=>{for(let x=0;xk.has(Y.id));if(A({posts:R.items},!1,j),y.cursor=R.nextCursor,$||!R.nextCursor){y.button.remove(),ue.delete(y.anchorId);return}}},Oe=async()=>{if(!(!v||C||document.hidden)){C=!0;try{let y=f.querySelector("article")?.id||"",x=await jr(N,k,K);if(x.stale||K())return;for(let R=x.pages.length-1;R>=0;R--)A({posts:x.pages[R].items},!0);if(x.pages.some(R=>R.items.length)&&f.querySelector(".empty")?.remove(),!x.connected&&x.cursor&&!ue.has(y)){let R={anchorId:y,cursor:x.cursor,button:null};R.button=_(y?"Load missed posts":"Earlier posts",()=>H(R)),ue.set(y,R);let j=y?k.get(y)?.node??null:null;j?f.insertBefore(R.button,j):l.insertBefore(R.button,f.nextSibling)}}catch(y){K()||ee("Channel refresh failed. "+y.message,!0)}finally{C=!1}}},S=setInterval(()=>{if(d.generation!==n){clearInterval(S);return}Oe()},5e3),U=()=>{document.hidden||Oe()};return document.addEventListener("visibilitychange",U),Be.push(()=>{v=!1,clearInterval(S),document.removeEventListener("visibilitychange",U)}),l}async function ps(){let n=M("/billing"),e=await b(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=p=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(p/100),i=p=>p>=1024**3?`${(p/1024**3).toFixed(1)} GiB`:`${(p/1024**2).toFixed(1)} MiB`,o=p=>Number(p).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),Ae.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${J(e.paidUntil)}.`:r?`Trial ends ${J(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${J(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(p,g){let f=await b(n+"/"+p,{method:"POST",body:g,timeout:3e4}),k=new URL(f.url);if(k.protocol!=="https:"||k.username||k.password||!["checkout.stripe.com","billing.stripe.com"].includes(k.host))throw new Error("Payment destination could not be verified.");location.assign(k.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await b(n+"/refresh",{method:"POST",timeout:3e4}),await O(),ee("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await b(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await O()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[p,g,f,k]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},p),a("span",{},`${k(g)} / ${k(f)}`)),a("progress",{max:f,value:Math.min(g,f),"aria-label":p})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ws(){let n=M(""),e=d.workspace,t=await b(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>oe(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await b(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await te()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Lt(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=F("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),V([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await b(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});oe("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await b(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await O(),ee("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>oe("Permanently delete this workspace?",o=>{let l=F("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),V([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await b(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await te(),u}o(),await te(),ee("Workspace deleted.")}))}),"danger"))),s} +agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),V([F("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await b(M("/devices"),{method:"POST",body:{name:t.get("name")}});lt("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function ls(){let n=M(""),[e,t]=await Promise.all([b(M("/members")),b(M("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await b(M(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await te()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>oe("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await b(M(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await te()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${J(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>oe("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let p=await b(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),lt("Replacement MCP key",p.token,`Update your app\u2019s secret/API key field. Shown once; expires ${J(p.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>oe("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await b(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await O()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${J(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=F("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=V([l.node],"Create invitation",async p=>{let g=await b(M("/invites"),{method:"POST",body:{email:p.get("email"),role:"member"}});lt("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(g.token)}`,`Share this link with ${g.email}. It expires ${J(g.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await b(M("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let p of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},p.email),a("p",{class:"help"},`Expires ${J(p.expiresAt)}`)),_("Revoke invitation",async()=>{await b(M(`/invites/${encodeURIComponent(p.id)}`),{method:"DELETE"}),await O()},"danger")));o.append(h)}return o}async function cs(){if(d.config=await b("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Pt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await te():jt(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,jt()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Ce(null,te),0)})}cs().catch(n=>{pe.replaceChildren(a("main",{id:"main",class:"auth-wrap"},we(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});var Kt=3;async function jr(n,e,t){let r=[],s="";for(let i=0;ie.has(l.id))||!o.nextCursor)return{pages:r,connected:!0};s=o.nextCursor}return{pages:r,connected:!1,cursor:s}}async function us(){let n=d.generation,e=M(""),[t,r]=await Promise.all([b(e+"/sessions"),b(e+"/members")]),s=t.sessions,i=new Map(s.map(S=>["agent:"+S.id,S.displayName]));for(let S of r)i.set("human:"+S.userId,S.email);let o=(S,U)=>i.get(S+":"+U)||U,l=new URLSearchParams;d.conversationAgent&&l.set("agentId",d.conversationAgent),d.search&&l.set("query",d.search);let c=a("select",{"aria-label":"Filter by session",onchange:S=>{d.conversationAgent=S.target.value,Ce(null,O)}},a("option",{value:""},"All sessions"),s.map(S=>a("option",{value:S.id,selected:S.id===d.conversationAgent},S.displayName))),u=F("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),h=V([u.node],"Search",async S=>{d.search=S.get("query").trim(),await O()}),p=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",c),h)),g=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),f=new Map,k=!0,A=!1;Be.push(()=>{k=!1});let I=S=>S.responseMessageId?"Replied":S.state==="acknowledged"?S.toKind==="human"?"Read":"Acknowledged":S.state==="delivered"?"Delivered to app":S.state==="expired"?"Expired":"Waiting for delivery",T=(S,U=!1,y=null)=>{let x=U?[...S.messages].reverse():S.messages;for(let R of x){let j=JSON.stringify(R),$=f.get(R.id);if($?.fingerprint===j)continue;let Y=a("article",{class:"card",id:R.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},o(R.fromKind,R.from))," \u2192 ",o(R.toKind,R.to),a("p",{class:"help"},J(R.createdAt))),a("span",{class:"badge"},I(R))),a("p",{class:"message"},R.body));Y.append(Pr(e,R.body,R.context)),R.responseTo&&Y.append(a("p",{class:"help"},"Reply to ",a("code",{},R.responseTo))),R.toKind==="human"&&R.to===d.user.id&&R.state!=="acknowledged"&&R.state!=="expired"&&Y.append(_("Mark read",async()=>{await b(e+"/messages/read",{method:"POST",body:{messageIds:[R.id]}}),await O()},"subtle-button")),$?$.node.replaceWith(Y):U?g.prepend(Y):y?g.insertBefore(Y,y):g.append(Y),f.set(R.id,{fingerprint:j,node:Y})}},E=await b(e+"/messages?"+l);T(E);let v=l.toString(),C=()=>!k||d.generation!==n,K=async S=>{let U=new URLSearchParams(v);S&&U.set("before",S);let y=await b(e+"/messages?"+U);return{items:y.messages,nextCursor:y.nextCursor}},P=new Map,N=async S=>{for(let U=0;Uf.has(j.id));if(T({messages:y.items},!1,x),S.cursor=y.nextCursor,R||!y.nextCursor){S.button.remove(),P.delete(S.anchorId);return}}},ue=async()=>{if(!(!k||A||document.hidden)){A=!0;try{let S=g.querySelector("article")?.id||"",U=await jr(K,f,C);if(U.stale||C())return;for(let y=U.pages.length-1;y>=0;y--)T({messages:U.pages[y].items},!0);if(U.pages.some(y=>y.items.length)&&g.querySelector(".empty")?.remove(),!U.connected&&U.cursor&&!P.has(S)){let y={anchorId:S,cursor:U.cursor,button:null};y.button=_(S?"Load missed messages":"Earlier messages",()=>N(y)),P.set(S,y);let x=S?f.get(S)?.node??null:null;x?g.insertBefore(y.button,x):p.insertBefore(y.button,g.nextSibling)}}catch(S){C()||ee("Conversation refresh failed. "+S.message,!0)}finally{A=!1}}},H=setInterval(()=>{if(d.generation!==n){clearInterval(H);return}ue()},5e3);Be.push(()=>clearInterval(H));let Oe=()=>{document.hidden||ue()};if(document.addEventListener("visibilitychange",Oe),Be.push(()=>document.removeEventListener("visibilitychange",Oe)),E.messages.length||g.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),p.append(g),E.nextCursor){let S=E.nextCursor,U=_("Earlier messages",async()=>{l.set("before",S);let y=await b(e+"/messages?"+l);T(y),S=y.nextCursor,S||U.remove()});p.append(U)}if(s.length){let S=a("select",{name:"to",required:!0},s.map(j=>a("option",{value:j.id,selected:j.id===d.conversationAgent},j.displayName+(j.reachable?"":" \xB7 offline")))),U=F("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),y=crypto.randomUUID(),x="",R=V([a("label",{},"Send to",S),U.node,Or(e,U.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async j=>{let $=JSON.stringify([j.get("to"),j.get("body")]);x&&x!==$&&(y=crypto.randomUUID()),x=$,await b(e+"/messages",{method:"POST",body:{to:j.get("to"),body:j.get("body"),mode:"request",idempotencyKey:y}}),d.conversationAgent=j.get("to"),d.search="",ee("Request saved. Delivery status will update when the app checks its inbox."),await O()});p.append(a("section",{class:"card"},a("h2",{},"Send a message"),R))}else p.append(_("Connect an app",async()=>{d.tab="connect",await O()},"primary"));return p.append(_("Refresh conversation",O)),p}async function ds(){let n=M(""),e=await b(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},J(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await b(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=F("Task title",{name:"title",maxlength:256,required:!0}),o=F("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),V([i.node,o.node],"Create task",async l=>{await b(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),ee("Task created. An agent can now claim it."),await O()}))),t}async function hs(){let n=M(""),e=await b(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=F("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",J(i.createdAt)),a("div",{class:"actions"},l),V([o.node],"Send answer",async c=>{await b(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),ee("Answer saved for the requesting session."),await O()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await b(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",O)),t}async function fs(){let n=d.generation,e=M(""),t=await b(e+"/channels"),r=t.find(y=>y.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>oe("Create a channel",y=>V([F("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,F("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async x=>{let R=await b(e+"/channels",{method:"POST",body:{name:x.get("name"),description:x.get("description")}});d.channelId=R.id,d.threadId="",d.channelSearch="",y(),await O()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:y=>{d.channelId=y.target.value,d.threadId="",d.channelSearch="",Ce(null,O)}},t.map(y=>a("option",{value:y.id,selected:y.id===r.id},"#"+y.name))),o=V([F("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async y=>{d.channelSearch=y.get("query").trim(),d.threadId="",await O()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),_("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await O()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let[u,h,p]=await Promise.all([b(e+"/channel-posts?"+c),b(e+"/members"),b(e+"/sessions")]),g=new Map(h.map(y=>["human:"+y.userId,y.email]));for(let y of p.sessions)g.set("agent:"+y.id,y.displayName);let f=a("div",{class:"conversation-list","aria-label":"Channel posts"}),k=new Map,A=(y,x=!1,R=null)=>{let j=x?[...y.posts].reverse():y.posts;for(let $ of j){let Y=JSON.stringify($),dt=k.get($.id);if(dt?.fingerprint===Y)continue;let ge=a("article",{class:"card",id:$.id},a("div",{class:"row"},a("strong",{},g.get($.authorKind+":"+$.authorId)||$.authorId),a("small",{},J($.createdAt))),a("p",{class:"message"},$.body));ge.append(Pr(e,$.body)),(!d.threadId||d.channelSearch)&&ge.append(_($.replies?`${$.replies} ${$.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=$.threadId||$.id,d.channelSearch="",await O()})),dt?dt.node.replaceWith(ge):x?f.prepend(ge):R?f.insertBefore(ge,R):f.append(ge),k.set($.id,{fingerprint:Y,node:ge})}};if(A(u),u.posts.length||f.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(f),u.nextCursor){let y=u.nextCursor,x=_("Earlier posts",async()=>{let R=new URLSearchParams(c);R.set("before",y);let j=await b(e+"/channel-posts?"+R);A(j),y=j.nextCursor,y||x.remove()});l.append(x)}let I=F(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),T=crypto.randomUUID(),E="";l.append(a("section",{class:"card"},V([I.node,Or(e,I.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async y=>{let x=y.get("body");E&&E!==x&&(T=crypto.randomUUID()),E=x,await b(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:x,threadId:d.threadId||void 0,idempotencyKey:T}}),d.channelSearch="",await O()})));let v=!0,C=!1,K=()=>!v||d.generation!==n,P=c.toString(),N=async y=>{let x=new URLSearchParams(P);y&&x.set("before",y);let R=await b(e+"/channel-posts?"+x);return{items:R.posts,nextCursor:R.nextCursor}},ue=new Map,H=async y=>{for(let x=0;xk.has(Y.id));if(A({posts:R.items},!1,j),y.cursor=R.nextCursor,$||!R.nextCursor){y.button.remove(),ue.delete(y.anchorId);return}}},Oe=async()=>{if(!(!v||C||document.hidden)){C=!0;try{let y=f.querySelector("article")?.id||"",x=await jr(N,k,K);if(x.stale||K())return;for(let R=x.pages.length-1;R>=0;R--)A({posts:x.pages[R].items},!0);if(x.pages.some(R=>R.items.length)&&f.querySelector(".empty")?.remove(),!x.connected&&x.cursor&&!ue.has(y)){let R={anchorId:y,cursor:x.cursor,button:null};R.button=_(y?"Load missed posts":"Earlier posts",()=>H(R)),ue.set(y,R);let j=y?k.get(y)?.node??null:null;j?f.insertBefore(R.button,j):l.insertBefore(R.button,f.nextSibling)}}catch(y){K()||ee("Channel refresh failed. "+y.message,!0)}finally{C=!1}}},S=setInterval(()=>{if(d.generation!==n){clearInterval(S);return}Oe()},5e3),U=()=>{document.hidden||Oe()};return document.addEventListener("visibilitychange",U),Be.push(()=>{v=!1,clearInterval(S),document.removeEventListener("visibilitychange",U)}),l}async function ps(){let n=M("/billing"),e=await b(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=p=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(p/100),i=p=>p>=1024**3?`${(p/1024**3).toFixed(1)} GiB`:`${(p/1024**2).toFixed(1)} MiB`,o=p=>Number(p).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),Ae.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${J(e.paidUntil)}.`:r?`Trial ends ${J(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${J(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(p,g){let f=await b(n+"/"+p,{method:"POST",body:g,timeout:3e4}),k=new URL(f.url);if(k.protocol!=="https:"||k.username||k.password||!["checkout.stripe.com","billing.stripe.com"].includes(k.host))throw new Error("Payment destination could not be verified.");location.assign(k.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await b(n+"/refresh",{method:"POST",timeout:3e4}),await O(),ee("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await b(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await O()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[p,g,f,k]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},p),a("span",{},`${k(g)} / ${k(f)}`)),a("progress",{max:f,value:Math.min(g,f),"aria-label":p})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ws(){let n=M(""),e=d.workspace,t=await b(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>oe(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await b(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await te()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Lt(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=F("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),V([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await b(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});oe("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await b(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await O(),ee("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>oe("Permanently delete this workspace?",o=>{let l=F("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),V([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await b(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await te(),u}o(),await te(),ee("Workspace deleted.")}))}),"danger"))),s} diff --git a/web/src/app.js b/web/src/app.js index a9982de..21a19f6 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -396,7 +396,7 @@ async function messagesView() { for (let i = 0; i < historyCatchUpPages; i++) { const data = await fetchHistory(control.cursor); if (stale()) return; - const anchor = control.anchorId ? rendered.get(control.anchorId)?.node ?? null : null; + const anchor = control.button.parentNode === list ? control.button : null; const connected = data.items.some(item => rendered.has(item.id)); append({ messages: data.items }, false, anchor); control.cursor = data.nextCursor; @@ -549,7 +549,7 @@ async function channelsView() { for (let i = 0; i < historyCatchUpPages; i++) { const data = await fetchHistory(control.cursor); if (stale()) return; - const anchor = control.anchorId ? rendered.get(control.anchorId)?.node ?? null : null; + const anchor = control.button.parentNode === list ? control.button : null; const connected = data.items.some(item => rendered.has(item.id)); append({ posts: data.items }, false, anchor); control.cursor = data.nextCursor; diff --git a/web/tests/workspace.spec.js b/web/tests/workspace.spec.js index ecf5555..b325f77 100644 --- a/web/tests/workspace.spec.js +++ b/web/tests/workspace.spec.js @@ -529,6 +529,68 @@ test('returning to a hidden channel tab catches up without a reload', async ({ p await expect(page.getByRole('button', { name: 'Load missed posts', exact: true })).toHaveCount(0); }); +test('a conversation gap larger than one load keeps its control at the remaining gap', async ({ page }) => { + const events = await fixture(page); + const server = { messages: burstMessages('seed', 50) }; + await page.route('**/api/workspaces/workspace-1/messages*', async route => { + if (route.request().method() !== 'GET') { + events.push({ path: new URL(route.request().url()).pathname, method: route.request().method(), body: route.request().postDataJSON() }); + return route.fulfill({ json: { ok: true, result: {} } }); + } + const window = historyPage(server.messages, new URL(route.request().url())); + if (window.error) return route.fulfill({ status: 404, json: { ok: false, error: { message: window.error } } }); + await route.fulfill({ json: { ok: true, result: { messages: window.slice, nextCursor: window.nextCursor } } }); + }); + await page.goto('/app'); + await page.getByRole('button', { name: 'Conversations', exact: true }).click(); + const rows = page.locator('.conversation-list article'); + await expect(rows).toHaveCount(50); + server.messages.unshift(...burstMessages('burst', 400)); + const gap = page.getByRole('button', { name: 'Load missed messages', exact: true }); + await expect(gap).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(200); + await gap.click(); + await expect(rows).toHaveCount(350); + await expect(gap).toBeVisible(); + await expect(gap.locator('xpath=preceding-sibling::article[1]')).toContainText('burst message 101'); + await expect(gap.locator('xpath=following-sibling::article[1]')).toContainText('seed message 50'); + await gap.click(); + await expect(rows).toHaveCount(450); + await expect(gap).toHaveCount(0); + await expect(rows.locator('p.message')).toHaveText(server.messages.map(m => m.body)); +}); + +test('a channel gap larger than one load keeps its control at the remaining gap', async ({ page }) => { + await fixture(page); + const server = { posts: burstPosts('seed', 50) }; + await page.route('**/api/workspaces/workspace-1/channels', async route => { + if (route.request().method() === 'GET') return route.fulfill({ json: { ok: true, result: [{ id: 'channel-1', name: 'general', description: 'General discussion', subscribers: 1 }] } }); + await route.fallback(); + }); + await page.route('**/api/workspaces/workspace-1/channel-posts*', async route => { + const window = historyPage(server.posts, new URL(route.request().url())); + if (window.error) return route.fulfill({ status: 404, json: { ok: false, error: { message: window.error } } }); + await route.fulfill({ json: { ok: true, result: { posts: window.slice, nextCursor: window.nextCursor } } }); + }); + await page.goto('/app'); + await page.getByRole('navigation', { name: 'Workspace' }).getByRole('button', { name: 'Channels', exact: true }).click(); + const rows = page.locator('.conversation-list article'); + await expect(rows).toHaveCount(50); + server.posts.unshift(...burstPosts('burst', 400)); + const gap = page.getByRole('button', { name: 'Load missed posts', exact: true }); + await expect(gap).toBeVisible({ timeout: 20000 }); + await expect(rows).toHaveCount(200); + await gap.click(); + await expect(rows).toHaveCount(350); + await expect(gap).toBeVisible(); + await expect(gap.locator('xpath=preceding-sibling::article[1]')).toContainText('burst post 101'); + await expect(gap.locator('xpath=following-sibling::article[1]')).toContainText('seed post 50'); + await gap.click(); + await expect(rows).toHaveCount(450); + await expect(gap).toHaveCount(0); + await expect(rows.locator('p.message')).toHaveText(server.posts.map(p => p.body)); +}); + test('dialogs are found by their accessible name and keyboard focus stays predictable', async ({ page }) => { const events = await fixture(page); await page.goto('/app');