orquesta-embed 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/EmbedPanel.d.ts +3 -1
- package/dist/core/auth.d.ts +52 -0
- package/dist/core/client.d.ts +7 -1
- package/dist/core/config.d.ts +16 -0
- package/dist/core/state.d.ts +10 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/vanilla.js +1 -1
- package/dist/vanilla.min.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsxs as e,jsx as t,Fragment as r}from"react/jsx-runtime";import n,{createContext as s,useState as i,useContext as o,useRef as a,useEffect as l,useCallback as c}from"react";function h(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]])}return r}function u(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}l((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class d extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class p extends d{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class m extends d{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class f extends d{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var g;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(g||(g={}));class w{constructor(e,{headers:t={},customFetch:r,region:n=g.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return u(this,arguments,void 0,function*(e,t={}){var r;let n,s;try{const{headers:i,method:o,body:a,signal:l,timeout:c}=t;let h={},{region:u}=t;u||(u=this.region);const d=new URL(`${this.url}/${e}`);let g;u&&"any"!==u&&(h["x-region"]=u,d.searchParams.set("forceFunctionRegion",u)),a&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)?"undefined"!=typeof Blob&&a instanceof Blob||a instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",g=a):"string"==typeof a?(h["Content-Type"]="text/plain",g=a):"undefined"!=typeof FormData&&a instanceof FormData?g=a:(h["Content-Type"]="application/json",g=JSON.stringify(a)):g=!a||"string"==typeof a||"undefined"!=typeof Blob&&a instanceof Blob||a instanceof ArrayBuffer||"undefined"!=typeof FormData&&a instanceof FormData?a:JSON.stringify(a);let w=l;c&&(s=new AbortController,n=setTimeout(()=>s.abort(),c),l?(w=s.signal,l.addEventListener("abort",()=>s.abort())):w=s.signal);const y=yield this.fetch(d.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),i),body:g,signal:w}).catch(e=>{throw new p(e)}),b=y.headers.get("x-relay-error");if(b&&"true"===b)throw new m(y);if(!y.ok)throw new f(y);let v,_=(null!==(r=y.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return v="application/json"===_?yield y.json():"application/octet-stream"===_||"application/pdf"===_?yield y.blob():"text/event-stream"===_?y:"multipart/form-data"===_?yield y.formData():yield y.text(),{data:v,error:null,response:y}}catch(e){return{data:null,error:e,response:e instanceof f||e instanceof m?e.context:void 0}}finally{n&&clearTimeout(n)}})}}var y=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},b=class{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let n=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,n=null,s=null,i=e.status,o=e.statusText;if(e.ok){var a,l;if("HEAD"!==r.method){var c;const t=await e.text();""===t||(n="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null===(c=r.headers.get("Accept"))||void 0===c?void 0:c.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}const h=null===(a=r.headers.get("Prefer"))||void 0===a?void 0:a.match(/count=(exact|planned|estimated)/),u=null===(l=e.headers.get("content-range"))||void 0===l?void 0:l.split("/");h&&u&&u.length>1&&(s=parseInt(u[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(n)&&(n.length>1?(t={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,s=null,i=406,o="Not Acceptable"):n=1===n.length?n[0]:null)}else{var h;const s=await e.text();try{t=JSON.parse(s),Array.isArray(t)&&404===e.status&&(n=[],t=null,i=200,o="OK")}catch(r){404===e.status&&""===s?(i=204,o="No Content"):t={message:s}}if(t&&r.isMaybeSingle&&(null==t||null===(h=t.details)||void 0===h?void 0:h.includes("0 rows"))&&(t=null,i=200,o="OK"),t&&r.shouldThrowOnError)throw new y(t)}return{error:t,data:n,count:s,status:i,statusText:o}});return this.shouldThrowOnError||(n=n.catch(e=>{var t;let r="";const n=null==e?void 0:e.cause;if(n){var s,i,o,a;const t=null!==(s=null==n?void 0:n.message)&&void 0!==s?s:"",l=null!==(i=null==n?void 0:n.code)&&void 0!==i?i:"";r=`${null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(a=null==n?void 0:n.name)&&void 0!==a?a:"Error"}: ${t}`,l&&(r+=` (${l})`),(null==n?void 0:n.stack)&&(r+=`\n${n.stack}`)}else{var l;r=null!==(l=null==e?void 0:e.stack)&&void 0!==l?l:""}return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}returns(){return this}overrideTypes(){return this}},v=class extends b{select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:n,referencedTable:s=n}={}){const i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:n=r}={}){const s=void 0===n?"offset":`${n}.offset`,i=void 0===n?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.get("Accept"))&&void 0!==o?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const _=new RegExp("[,()]");var k=class extends v{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&_.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&_.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:n}={}){let s="";"plain"===n?s="pl":"phrase"===n?s="ph":"websearch"===n&&(s="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${s}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},x=class{constructor(e,{headers:t={},schema:r,fetch:n}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:n}=null!=t?t:{},s=r?"HEAD":"GET";let i=!1;const o=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new k({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var n;const{url:s,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);s.searchParams.set("columns",e.join(","))}}return new k({method:"POST",url:s,headers:i,schema:this.schema,body:e,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:n,defaultToNull:s=!0}={}){var i;const{url:o,headers:a}=this.cloneRequestState();if(a.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&o.searchParams.set("on_conflict",t),n&&a.append("Prefer",`count=${n}`),s||a.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);o.searchParams.set("columns",e.join(","))}}return new k({method:"POST",url:o,headers:a,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}update(e,{count:t}={}){var r;const{url:n,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new k({method:"PATCH",url:n,headers:s,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var t;const{url:r,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new k({method:"DELETE",url:r,headers:n,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch})}},S=class e{constructor(e,{headers:t={},schema:r,fetch:n}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=n}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new x(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:n=!1,count:s}={}){var i;let o;const a=new URL(`${this.url}/rpc/${e}`);let l;const c=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(c)),h=r&&Object.values(t).some(c);h?(o="POST",l=t):r||n?(o=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{a.searchParams.append(e,t)})):(o="POST",l=t);const u=new Headers(this.headers);return h?u.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&u.set("Prefer",`count=${s}`),new k({method:o,url:a,headers:u,schema:this.schemaName,body:l,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}};class E{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const t=globalThis.process;if(t){const e=t.versions;if(e&&e.node){const t=e.node,r=parseInt(t.replace(/^v/,"").split(".")[0]);return r>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const T="1.0.0",C=T,O=1e4;var R,N,$,j,I,A;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(R||(R={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(N||(N={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}($||($={})),function(e){e.websocket="websocket"}(j||(j={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(I||(I={}));class P{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const n=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,r;const n=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},s=(new TextEncoder).encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,s)}_encodeUserBroadcastPush(e,t,r){var n,s;const i=e.topic,o=null!==(n=e.ref)&&void 0!==n?n:"",a=null!==(s=e.join_ref)&&void 0!==s?s:"",l=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(c).length?"":JSON.stringify(c);if(a.length>255)throw new Error(`joinRef length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+o.length+i.length+l.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+u);let p=new DataView(d),m=0;p.setUint8(m++,this.KINDS.userBroadcastPush),p.setUint8(m++,a.length),p.setUint8(m++,o.length),p.setUint8(m++,i.length),p.setUint8(m++,l.length),p.setUint8(m++,h.length),p.setUint8(m++,t),Array.from(a,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(o,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(i,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(l,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(h,e=>p.setUint8(m++,e.charCodeAt(0)));var f=new Uint8Array(d.byteLength+r.byteLength);return f.set(new Uint8Array(d),0),f.set(new Uint8Array(r),d.byteLength),f.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const r=JSON.parse(e),[n,s,i,o,a]=r;return t({join_ref:n,ref:s,topic:i,event:o,payload:a})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,n)}_decodeUserBroadcast(e,t,r){const n=t.getUint8(1),s=t.getUint8(2),i=t.getUint8(3),o=t.getUint8(4);let a=this.HEADER_LENGTH+4;const l=r.decode(e.slice(a,a+n));a+=n;const c=r.decode(e.slice(a,a+s));a+=s;const h=r.decode(e.slice(a,a+i));a+=i;const u=e.slice(a,e.byteLength),d=o===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:c,payload:d};return i>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class L{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(A||(A={}));const U=(e,t,r={})=>{var n;const s=null!==(n=r.skipTypes)&&void 0!==n?n:[];return t?Object.keys(t).reduce((r,n)=>(r[n]=z(n,e,t,s),r),{}):{}},z=(e,t,r,n)=>{const s=t.find(t=>t.name===e),i=null==s?void 0:s.type,o=r[e];return i&&!n.includes(i)?D(i,o):H(o)},D=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return W(t,r)}switch(e){case A.bool:return B(t);case A.float4:case A.float8:case A.int2:case A.int4:case A.int8:case A.numeric:case A.oid:return q(t);case A.json:case A.jsonb:return M(t);case A.timestamp:return K(t);case A.abstime:case A.date:case A.daterange:case A.int4range:case A.int8range:case A.money:case A.reltime:case A.text:case A.time:case A.timestamptz:case A.timetz:case A.tsrange:case A.tstzrange:default:return H(t)}},H=e=>e,B=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},q=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},M=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},W=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,n=e[r];if("{"===e[0]&&"}"===n){let n;const s=e.slice(1,r);try{n=JSON.parse("["+s+"]")}catch(e){n=s?s.split(","):[]}return n.map(e=>D(t,e))}return e},K=e=>"string"==typeof e?e.replace(" ","T"):e,F=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class V{constructor(e,t,r={},n=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var J,G,X,Y;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(J||(J={}));class Q{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{const{onJoin:t,onLeave:r,onSync:n}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Q.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=Q.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],n()}),this.channel._on(r.diff,{},e=>{const{onJoin:t,onLeave:r,onSync:n}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=Q.syncDiff(this.state,e,t,r),n())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,n){const s=this.cloneDeep(e),i=this.transformState(t),o={},a={};return this.map(s,(e,t)=>{i[e]||(a[e]=t)}),this.map(i,(e,t)=>{const r=s[e];if(r){const n=t.map(e=>e.presence_ref),s=r.map(e=>e.presence_ref),i=t.filter(e=>s.indexOf(e.presence_ref)<0),l=r.filter(e=>n.indexOf(e.presence_ref)<0);i.length>0&&(o[e]=i),l.length>0&&(a[e]=l)}else o[e]=t}),this.syncDiff(s,{joins:o,leaves:a},r,n)}static syncDiff(e,t,r,n){const{joins:s,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),n||(n=()=>{}),this.map(s,(t,n)=>{var s;const i=null!==(s=e[t])&&void 0!==s?s:[];if(e[t]=this.cloneDeep(n),i.length>0){const r=e[t].map(e=>e.presence_ref),n=i.filter(e=>r.indexOf(e.presence_ref)<0);e[t].unshift(...n)}r(t,i,n)}),this.map(i,(t,r)=>{let s=e[t];if(!s)return;const i=r.map(e=>e.presence_ref);s=s.filter(e=>i.indexOf(e.presence_ref)<0),e[t]=s,n(t,s,r),0===s.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const n=e[r];return t[r]="metas"in n?n.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):n,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(G||(G={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(X||(X={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(Y||(Y={}));class Z{constructor(e,t={config:{}},r){var n,s;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=N.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new V(this,$.join,this.params,this.timeout),this.rejoinTimer=new L(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=N.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=N.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=N.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=N.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=N.errored,this.rejoinTimer.scheduleTimeout())}),this._on($.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Q(this),this.broadcastEndpointURL=F(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(s=null===(n=this.params.config)||void 0===n?void 0:n.broadcast)||void 0===s?void 0:s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,n,s;if(this.socket.isConnected()||this.socket.connect(),this.state==N.closed){const{config:{broadcast:i,presence:o,private:a}}=this.params,l=null!==(n=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==n?n:[],c=!!this.bindings[X.PRESENCE]&&this.bindings[X.PRESENCE].length>0||!0===(null===(s=this.params.config.presence)||void 0===s?void 0:s.enabled),h={},u={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(Y.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(Y.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket._isManualToken()||this.socket.setAuth(),void 0!==t){const n=this.bindings.postgres_changes,s=null!==(r=null==n?void 0:n.length)&&void 0!==r?r:0,i=[];for(let r=0;r<s;r++){const s=n[r],{filter:{event:o,schema:a,table:l,filter:c}}=s,h=t&&t[r];if(!(h&&h.event===o&&Z.isFilterValueEqual(h.schema,a)&&Z.isFilterValueEqual(h.table,l)&&Z.isFilterValueEqual(h.filter,c)))return this.unsubscribe(),this.state=N.errored,void(null==e||e(Y.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));i.push(Object.assign(Object.assign({},s),{id:h.id}))}return this.bindings.postgres_changes=i,void(e&&e(Y.SUBSCRIBED))}null==e||e(Y.SUBSCRIBED)}).receive("error",t=>{this.state=N.errored,null==e||e(Y.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(Y.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===N.joined&&e===X.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var n;if(null==t)return Promise.reject("Payload is required for httpSend()");const s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!==(n=r.timeout)&&void 0!==n?n:this.timeout);if(202===o.status)return{success:!0};let a=o.statusText;try{const e=await o.json();a=e.error||e.message||a}catch(e){}return Promise.reject(new Error(a))}async send(e,t={}){var r,n;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var n,s,i;const o=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(s=null===(n=this.params)||void 0===n?void 0:n.config)||void 0===s?void 0:s.broadcast)||void 0===i?void 0:i.ack)||r("ok"),o.receive("ok",()=>r("ok")),o.receive("error",()=>r("error")),o.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:s,payload:i}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:i,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(n=e.body)||void 0===n?void 0:n.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=N.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger($.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(n=>{r=new V(this,$.leave,{},e),r.receive("ok",()=>{t(),n("ok")}).receive("timeout",()=>{t(),n("timed out")}).receive("error",()=>{n("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=N.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const n=new AbortController,s=setTimeout(()=>n.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(s),i}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new V(this,e,t,r);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var n,s;const i=e.toLocaleLowerCase(),{close:o,error:a,leave:l,join:c}=$;if(r&&[o,a,l,c].indexOf(i)>=0&&r!==this._joinRef())return;let h=this._onMessage(i,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null===(n=this.bindings.postgres_changes)||void 0===n||n.filter(e=>{var t,r,n;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(n=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===n?void 0:n.toLocaleLowerCase())===i}).map(e=>e.callback(h,r)):null===(s=this.bindings[i])||void 0===s||s.filter(e=>{var r,n,s,o,a,l,c,h;if(["broadcast","presence","postgres_changes"].includes(i)){if("id"in e){const i=e.id,l=null===(r=e.filter)||void 0===r?void 0:r.event;return i&&(null===(n=t.ids)||void 0===n?void 0:n.includes(i))&&("*"===l||(null==l?void 0:l.toLocaleLowerCase())===(null===(s=t.data)||void 0===s?void 0:s.type.toLocaleLowerCase()))&&(!(null===(o=e.filter)||void 0===o?void 0:o.table)||e.filter.table===(null===(a=t.data)||void 0===a?void 0:a.table))}{const r=null===(c=null===(l=null==e?void 0:e.filter)||void 0===l?void 0:l.event)||void 0===c?void 0:c.toLocaleLowerCase();return"*"===r||r===(null===(h=null==t?void 0:t.event)||void 0===h?void 0:h.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===i}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.data,{schema:t,table:r,commit_timestamp:n,type:s,errors:i}=e,o={schema:t,table:r,commit_timestamp:n,eventType:s,new:{},old:{},errors:i};h=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===N.closed}_isJoined(){return this.state===N.joined}_isJoining(){return this.state===N.joining}_isLeaving(){return this.state===N.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const n=e.toLocaleLowerCase(),s={type:n,filter:t,callback:r};return this.bindings[n]?this.bindings[n].push(s):this.bindings[n]=[s],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var n;return!((null===(n=e.type)||void 0===n?void 0:n.toLocaleLowerCase())===r&&Z.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on($.close,{},e)}_onError(e){this._on($.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=N.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=U(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=U(e.columns,e.old_record)),t}}const ee=()=>{},te=25e3,re=10,ne=100,se=[1e3,2e3,5e3,1e4];class ie{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=O,this.transport=null,this.heartbeatIntervalMs=te,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ee,this.ref=0,this.reconnectTimer=null,this.vsn=C,this.logger=ee,this.conn=null,this.sendBuffer=[],this.serializer=new P,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${j.websocket}`,this.httpEndpoint=F(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=E.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case R.connecting:return I.Connecting;case R.open:return I.Open;case R.closing:return I.Closing;default:return I.Closed}}isConnected(){return this.connectionState()===I.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const r=`realtime:${e}`,n=this.getChannels().find(e=>e.topic===r);if(n)return n;{const r=new Z(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){const{topic:t,event:r,payload:n,ref:s}=e,i=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${r} (${s})`,n),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},ne)}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){const t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:t,event:r,payload:n,ref:s}=e,i=s?`(${s})`:"",o=n.status||"";this.log("receive",`${o} ${t} ${r} ${i}`.trim(),n),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,n,s)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===R.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===R.open||this.conn.readyState===R.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`);(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger($.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const r={access_token:t,version:"realtime-js/2.90.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push($.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new L(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},re)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,n,s,i,o,a,l,c,h,u,d;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(r=null==e?void 0:e.timeout)&&void 0!==r?r:O,this.heartbeatIntervalMs=null!==(n=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==n?n:te,this.worker=null!==(s=null==e?void 0:e.worker)&&void 0!==s&&s,this.accessToken=null!==(i=null==e?void 0:e.accessToken)&&void 0!==i?i:null,this.heartbeatCallback=null!==(o=null==e?void 0:e.heartbeatCallback)&&void 0!==o?o:ee,this.vsn=null!==(a=null==e?void 0:e.vsn)&&void 0!==a?a:C,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(l=null==e?void 0:e.reconnectAfterMs)&&void 0!==l?l:e=>se[e-1]||1e4,this.vsn){case T:this.encode=null!==(c=null==e?void 0:e.encode)&&void 0!==c?c:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:(e,t)=>t(JSON.parse(e));break;case"2.0.0":this.encode=null!==(u=null==e?void 0:e.encode)&&void 0!==u?u:this.serializer.encode.bind(this.serializer),this.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}var oe=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function ae(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:o}){const a=function(e,t,r){const n=new URL(t,e);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&n.searchParams.set(e,t);return n.toString()}(e.baseUrl,n,s),l=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),c=await t(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),h=await c.text(),u=(c.headers.get("content-type")||"").includes("application/json"),d=u&&h?JSON.parse(h):h;if(!c.ok){const e=u?d:void 0,t=e?.error;throw new oe(t?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:c.status,headers:c.headers,data:d}}}}function le(e){return e.join("")}var ce=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:le(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${le(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${le(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${le(e.namespace)}`}),!0}catch(e){if(e instanceof oe&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof oe&&409===e.status)return;throw e}}};function he(e){return e.join("")}var ue=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof oe&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof oe&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},de=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=ae({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new ce(this.client,t),this.tableOps=new ue(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},pe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function me(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var fe=class extends pe{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},ge=class extends pe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};const we=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),ye=e=>{if(Array.isArray(e))return e.map(e=>ye(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const n=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[n]=ye(r)}),t};function be(e){return(be="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ve(e){var t=function(e,t){if("object"!=be(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=be(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==be(t)?t:t+""}function _e(e,t,r){return(t=ve(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ke(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function xe(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ke(Object(r),!0).forEach(function(t){_e(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ke(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const Se=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)},Ee=async(e,t,r)=>{e instanceof await Response&&!(null==r?void 0:r.noResolveJson)?e.json().then(r=>{const n=e.status||500,s=(null==r?void 0:r.statusCode)||n+"";t(new fe(Se(r),n,s))}).catch(e=>{t(new ge(Se(e),e))}):t(new ge(Se(e),e))},Te=(e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&n?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(n)?(s.headers=xe({"Content-Type":"application/json"},null==t?void 0:t.headers),s.body=JSON.stringify(n)):s.body=n,(null==t?void 0:t.duplex)&&(s.duplex=t.duplex),xe(xe({},s),r)):s};async function Ce(e,t,r,n,s,i){return new Promise((o,a)=>{e(r,Te(t,n,s,i)).then(e=>{if(!e.ok)throw e;return(null==n?void 0:n.noResolveJson)?e:e.json()}).then(e=>o(e)).catch(e=>Ee(e,a,n))})}async function Oe(e,t,r,n){return Ce(e,"GET",t,r,n)}async function Re(e,t,r,n,s){return Ce(e,"POST",t,n,s,r)}async function Ne(e,t,r,n,s){return Ce(e,"PUT",t,n,s,r)}async function $e(e,t,r,n,s){return Ce(e,"DELETE",t,n,s,r)}var je=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}};let Ie;Ie=Symbol.toStringTag;var Ae=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Ie]="BlobDownloadBuilder",this.promise=null}asStream(){return new je(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}};const Pe={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Le={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Ue=class{constructor(e,t={},r,n){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=we(n)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(e,t,r,n){var s=this;try{let i;const o=xe(xe({},Le),n);let a=xe(xe({},s.headers),"POST"===e&&{"x-upsert":String(o.upsert)});const l=o.metadata;"undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!o.duplex&&(o.duplex="half")),(null==n?void 0:n.headers)&&(a=xe(xe({},a),n.headers));const c=s._removeEmptyFolders(t),h=s._getFinalPath(c),u=await("PUT"==e?Ne:Re)(s.fetch,`${s.url}/object/${h}`,i,xe({headers:a},(null==o?void 0:o.duplex)?{duplex:o.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,n){var s=this;const i=s._removeEmptyFolders(e),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let e;const t=xe({upsert:Le.upsert},n),o=xe(xe({},s.headers),{"x-upsert":String(t.upsert)});return"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,o["cache-control"]=`max-age=${t.cacheControl}`,o["content-type"]=t.contentType),{data:{path:i,fullPath:(await Ne(s.fetch,a.toString(),e,{headers:o})).Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async createSignedUploadUrl(e,t){var r=this;try{let n=r._getFinalPath(e);const s=xe({},r.headers);(null==t?void 0:t.upsert)&&(s["x-upsert"]="true");const i=await Re(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new pe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var n=this;try{return{data:await Re(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:n.headers}),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async copy(e,t,r){var n=this;try{return{data:{path:(await Re(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:n.headers})).Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async createSignedUrl(e,t,r){var n=this;try{let s=n._getFinalPath(e),i=await Re(n.fetch,`${n.url}/object/sign/${s}`,xe({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:n.headers});const o=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${n.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async createSignedUrls(e,t,r){var n=this;try{const s=await Re(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:t,paths:e},{headers:n.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:s.map(e=>xe(xe({},e),{},{signedUrl:e.signedURL?encodeURI(`${n.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}download(e,t){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",n=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),s=n?`?${n}`:"",i=this._getFinalPath(e);return new Ae(()=>Oe(this.fetch,`${this.url}/${r}/${i}${s}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}async info(e){var t=this;const r=t._getFinalPath(e);try{return{data:ye(await Oe(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async exists(e){var t=this;const r=t._getFinalPath(e);try{return await async function(e,t,r,n){return Ce(e,"HEAD",t,xe(xe({},r),{},{noResolveJson:!0}),n)}(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e)&&e instanceof ge){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){const r=this._getFinalPath(e),n=[],s=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==s&&n.push(s);const i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&n.push(o);let a=n.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}async remove(e){var t=this;try{return{data:await $e(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async list(e,t,r){var n=this;try{const s=xe(xe(xe({},Pe),t),{},{prefix:e||""});return{data:await Re(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},r),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async listV2(e,t){var r=this;try{const n=xe({},e);return{data:await Re(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},t),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};const ze="2.90.1",De={"X-Client-Info":`storage-js/${ze}`};var He=class{constructor(e,t={},r,n){this.shouldThrowOnError=!1;const s=new URL(e);(null==n?void 0:n.useNewHostname)&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase.")),this.url=s.href.replace(/\/$/,""),this.headers=xe(xe({},De),t),this.fetch=we(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(e){var t=this;try{const r=t.listBucketOptionsToQueryString(e);return{data:await Oe(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await Oe(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){var r=this;try{return{data:await Re(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async updateBucket(e,t){var r=this;try{return{data:await Ne(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async emptyBucket(e){var t=this;try{return{data:await Re(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await $e(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},Be=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=xe(xe({},De),t),this.fetch=we(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await Re(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async listBuckets(e){var t=this;try{const r=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&r.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);const n=r.toString(),s=n?`${t.url}/bucket?${n}`:`${t.url}/bucket`;return{data:await Oe(t.fetch,s,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await $e(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e)&&!(0===e.length||e.length>100)&&e.trim()===e&&!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new pe("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new de({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(e,t){const r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(n)throw e;return{data:null,error:e}}}}})}};const qe={"X-Client-Info":`storage-js/${ze}`,"Content-Type":"application/json"};var Me=class extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function We(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}var Ke=class extends Me{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Fe=class extends Me{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}};const Ve=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Je=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Ge=(e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return n?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(n)?(s.headers=xe({"Content-Type":"application/json"},null==t?void 0:t.headers),s.body=JSON.stringify(n)):s.body=n,xe(xe({},s),r)):s};async function Xe(e,t,r,n,s,i){return new Promise((o,a)=>{e(r,Ge(t,n,s,i)).then(e=>{if(!e.ok)throw e;if(null==n?void 0:n.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>o(e)).catch(e=>(async(e,t,r)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){const r=e.status||500,n=e;if("function"==typeof n.json)n.json().then(e=>{const n=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new Ke(Je(e),r,n))}).catch(()=>{const e=r+"";t(new Ke(n.statusText||`HTTP ${r} error`,r,e))});else{const e=r+"";t(new Ke(n.statusText||`HTTP ${r} error`,r,e))}}else t(new Fe(Je(e),e))})(e,a,n))})}async function Ye(e,t,r,n,s){return Xe(e,"POST",t,n,s,r)}var Qe=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=xe(xe({},qe),t),this.fetch=Ve(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async getIndex(e,t){var r=this;try{return{data:await Ye(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async listIndexes(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async deleteIndex(e,t){var r=this;try{return{data:await Ye(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}},Ze=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=xe(xe({},qe),t),this.fetch=Ve(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(e){var t=this;try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:await Ye(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async getVectors(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async listVectors(e){var t=this;try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:await Ye(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async queryVectors(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async deleteVectors(e){var t=this;try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:await Ye(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}},et=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=xe(xe({},qe),t),this.fetch=Ve(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async listBuckets(e={}){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}},tt=class extends et{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new rt(this.url,this.headers,e,this.fetch)}async createBucket(e){return(()=>super.createBucket)().call(this,e)}async getBucket(e){return(()=>super.getBucket)().call(this,e)}async listBuckets(e={}){return(()=>super.listBuckets)().call(this,e)}async deleteBucket(e){return(()=>super.deleteBucket)().call(this,e)}},rt=class extends Qe{constructor(e,t,r,n){super(e,t,n),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,xe(xe({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,xe(xe({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return(()=>super.getIndex)().call(this,this.vectorBucketName,e)}async deleteIndex(e){return(()=>super.deleteIndex)().call(this,this.vectorBucketName,e)}index(e){return new nt(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},nt=class extends Ze{constructor(e,t,r,n,s){super(e,t,s),this.vectorBucketName=r,this.indexName=n}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},st=class extends He{constructor(e,t={},r,n){super(e,t,r,n)}from(e){return new Ue(this.url,this.headers,e,this.fetch)}get vectors(){return new tt(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Be(this.url+"/iceberg",this.headers,this.fetch)}};const it="2.90.1",ot=3e4,at=9e4,lt={"X-Client-Info":`gotrue-js/${it}`},ct="X-Supabase-Api-Version",ht={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},ut=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class dt extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function pt(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class mt extends dt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class ft extends dt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class gt extends dt{constructor(e,t,r,n){super(e,r,n),this.name=t,this.status=r}}class wt extends gt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class yt extends gt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class bt extends gt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class vt extends gt{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class _t extends gt{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class kt extends gt{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class xt extends gt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function St(e){return pt(e)&&"AuthRetryableFetchError"===e.name}class Et extends gt{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class Tt extends gt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ot=" \t\n\r=".split(""),Rt=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Ot.length;t+=1)e[Ot[t].charCodeAt(0)]=-2;for(let t=0;t<Ct.length;t+=1)e[Ct[t].charCodeAt(0)]=t;return e})();function Nt(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(Ct[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(Ct[e]),t.queuedBits-=6}}function $t(e,t,r){const n=Rt[e];if(!(n>-1)){if(-2===n)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|n,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function jt(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,n,r)};for(let t=0;t<e.length;t+=1)$t(e.charCodeAt(t),s,i);return t.join("")}function It(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function At(e){const t=[],r={queue:0,queuedBits:0},n=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)$t(e.charCodeAt(t),r,n);return new Uint8Array(t)}function Pt(e){const t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>55295&&n<=56319){const t=1024*(n-55296)&65535;n=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}It(n,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function Lt(e){const t=[],r={queue:0,queuedBits:0},n=e=>{t.push(e)};return e.forEach(e=>Nt(e,r,n)),Nt(null,r,n),t.join("")}const Ut=()=>"undefined"!=typeof window&&"undefined"!=typeof document,zt={tested:!1,writable:!1},Dt=()=>{if(!Ut())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(zt.tested)return zt.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),zt.tested=!0,zt.writable=!0}catch(e){zt.tested=!0,zt.writable=!1}return zt.writable};const Ht=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Bt=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},qt=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},Mt=async(e,t)=>{await e.removeItem(t)};class Wt{constructor(){this.promise=new Wt.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function Kt(e){const t=e.split(".");if(3!==t.length)throw new Tt("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!ut.test(t[e]))throw new Tt("JWT not in base64url format");return{header:JSON.parse(jt(t[0])),payload:JSON.parse(jt(t[1])),signature:At(t[2]),raw:{header:t[0],payload:t[1]}}}function Ft(e){return("0"+e.toString(16)).substr(-2)}async function Vt(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(r);return Array.from(n).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Jt(e,t,r=!1){const n=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let n=0;n<56;n++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,Ft).join("")}();let s=n;r&&(s+="/PASSWORD_RECOVERY"),await Bt(e,`${t}-code-verifier`,s);const i=await Vt(n);return[i,n===i?"plain":"s256"]}Wt.promiseConstructor=Promise;const Gt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const Xt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Yt(e){if(!Xt.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Qt(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)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 Zt(e){return JSON.parse(JSON.stringify(e))}const er=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tr=[502,503,504];async function rr(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new xt(er(e),0);if(tr.includes(e.status))throw new xt(er(e),e.status);let n,s;try{n=await e.json()}catch(e){throw new ft(er(e),e)}const i=function(e){const t=e.headers.get(ct);if(!t)return null;if(!t.match(Gt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=ht.timestamp&&"object"==typeof n&&n&&"string"==typeof n.code?s=n.code:"object"==typeof n&&n&&"string"==typeof n.error_code&&(s=n.error_code),s){if("weak_password"===s)throw new Et(er(n),e.status,(null===(t=n.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===s)throw new wt}else if("object"==typeof n&&n&&"object"==typeof n.weak_password&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new Et(er(n),e.status,n.weak_password.reasons);throw new mt(er(n),e.status||500,s)}async function nr(e,t,r,n){var s;const i=Object.assign({},null==n?void 0:n.headers);i[ct]||(i[ct]=ht.name),(null==n?void 0:n.jwt)&&(i.Authorization=`Bearer ${n.jwt}`);const o=null!==(s=null==n?void 0:n.query)&&void 0!==s?s:{};(null==n?void 0:n.redirectTo)&&(o.redirect_to=n.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await async function(e,t,r,n,s,i){const o=((e,t,r,n)=>{const s={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))})(t,n,s,i);let a;try{a=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new xt(er(e),0)}a.ok||await rr(a);if(null==n?void 0:n.noResolveJson)return a;try{return await a.json()}catch(e){await rr(e)}}(e,t,r+a,{headers:i,noResolveJson:null==n?void 0:n.noResolveJson},{},null==n?void 0:n.body);return(null==n?void 0:n.xform)?null==n?void 0:n.xform(l):{data:Object.assign({},l),error:null}}function sr(e){var t;let r=null;var n;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(n=e.expires_in,Math.round(Date.now()/1e3)+n)));return{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ir(e){const t=sr(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function or(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ar(e){return{data:e,error:null}}function lr(e){const{action_link:t,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i}=e,o=h(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i},user:Object.assign({},o)},error:null}}function cr(e){return e}const hr=["global","local","others"];class ur{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Ht(r),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)}}async signOut(e,t=hr[0]){if(hr.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${hr.join(", ")}`);try{return await nr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(pt(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await nr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,r=h(e,["options"]),n=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(n.new_email=null==r?void 0:r.newEmail,delete n.newEmail),await nr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:lr,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(pt(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await nr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,n,s,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await nr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(s=null===(n=null==e?void 0:e.perPage)||void 0===n?void 0:n.toString())&&void 0!==s?s:""},xform:cr});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(pt(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Yt(e);try{return await nr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Yt(e);try{return await nr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Yt(e);try{return await nr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Yt(e.userId);try{const{data:t,error:r}=await nr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Yt(e.userId),Yt(e.id);try{return{data:await nr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,n,s,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await nr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(s=null===(n=null==e?void 0:e.perPage)||void 0===n?void 0:n.toString())&&void 0!==s?s:""},xform:cr});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(pt(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await nr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await nr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await nr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await nr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await nr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pt(e))return{data:null,error:e};throw e}}}function dr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const pr=!!(globalThis&&Dt()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class mr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class fr extends mr{}async function gr(e,t,r){pr&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),pr&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async n=>{if(!n){if(0===t)throw pr&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new fr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(pr)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}pr&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,n.name);try{return await r()}finally{pr&&console.log("@supabase/gotrue-js: navigatorLock: released",e,n.name)}}))}function wr(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function yr(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class br extends Error{constructor({message:e,code:t,cause:r,name:n}){var s;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(s=null!=n?n:r instanceof Error?r.name:void 0)&&void 0!==s?s:"Unknown Error",this.code=t}}class vr extends br{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function _r({error:e,options:t}){var r,n,s;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new br({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new br({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new br({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new br({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new br({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new br({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new br({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new br({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!Or(t))return new br({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new br({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new br({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new br({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new br({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function kr({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new br({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new br({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Or(t))return new br({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new br({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new br({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new br({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const xr=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Sr(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:r,excludeCredentials:n}=e,s=h(e,["challenge","user","excludeCredentials"]),i=At(t).buffer,o=Object.assign(Object.assign({},r),{id:At(r.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];a.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:At(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return a}function Er(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:r}=e,n=h(e,["challenge","allowCredentials"]),s=At(t).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];i.allowCredentials[e]=Object.assign(Object.assign({},t),{id:At(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}function Tr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:Lt(new Uint8Array(e.response.attestationObject)),clientDataJSON:Lt(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Cr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e,n=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Lt(new Uint8Array(s.authenticatorData)),clientDataJSON:Lt(new Uint8Array(s.clientDataJSON)),signature:Lt(new Uint8Array(s.signature)),userHandle:s.userHandle?Lt(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Or(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Rr(){var e,t;return!!(Ut()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const Nr={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},$r={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function jr(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),n={};for(const s of e)if(s)for(const e in s){const i=s[e];if(void 0!==i)if(Array.isArray(i))n[e]=i;else if(r(i))n[e]=i;else if(t(i)){const r=n[e];t(r)?n[e]=jr(r,i):n[e]=jr(i)}else n[e]=i}return n}class Ir{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:n},s){try{const{data:i,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:o};const a=null!=n?n:xr.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return jr(Nr,e,t||{})}(i.webauthn.credential_options.publicKey,null==s?void 0:s.create),{data:r,error:n}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:_r({error:t,options:e})}}}({publicKey:t,signal:a});return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:n}}case"request":{const t=function(e,t){return jr($r,e,t||{})}(i.webauthn.credential_options.publicKey,null==s?void 0:s.request),{data:r,error:n}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:kr({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:a}));return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:n}}}}catch(e){return pt(e)?{data:null,error:e}:{data:null,error:new ft("Unexpected error in challenge",e)}}}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=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:n}={}},s){if(!t)return{data:null,error:new dt("rpId is required for WebAuthn authentication")};try{if(!Rr())return{data:null,error:new ft("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:n},{request:s});if(!i)return{data:null,error:o};const{webauthn:a}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:r,credential_response:a.credential_response}})}catch(e){return pt(e)?{data:null,error:e}:{data:null,error:new ft("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:n}={}},s){if(!t)return{data:null,error:new dt("rpId is required for WebAuthn registration")};try{if(!Rr())return{data:null,error:new ft("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:o};const{data:a,error:l}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:n},{create:s});return a?this._verify({factorId:i.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:r,type:a.webauthn.type,credential_response:a.webauthn.credential_response}}):{data:null,error:l}}catch(e){return pt(e)?{data:null,error:e}:{data:null,error:new ft("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Ar={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:lt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Pr(e,t,r){return await r()}const Lr={};class Ur{get jwks(){var e,t;return null!==(t=null===(e=Lr[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Lr[this.storageKey]=Object.assign(Object.assign({},Lr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Lr[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Lr[this.storageKey]=Object.assign(Object.assign({},Lr[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const s=Object.assign(Object.assign({},Ar),e);if(this.storageKey=s.storageKey,this.instanceID=null!==(t=Ur.nextInstanceID[this.storageKey])&&void 0!==t?t:0,Ur.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,"function"==typeof s.debug&&(this.logger=s.debug),this.instanceID>0&&Ut()){const e=`${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(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new ur({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Ht(s.fetch),this.lock=s.lock||Pr,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&Ut()&&(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===r?void 0:r.locks)?this.lock=gr:this.lock=Pr,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 Ir(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.persistSession?(s.storage?this.storage=s.storage:Dt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=dr(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=dr(this.memoryStorage)),Ut()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(n=this.broadcastChannel)||void 0===n||n.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${it}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(Ut()&&(t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),Ut()&&this.detectSessionInUrl&&"none"!==r){const{data:n,error:s}=await this._getSessionFromURL(t,r);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),function(e){return pt(e)&&"AuthImplicitGrantRedirectError"===e.name}(s)){const t=null===(e=s.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:s}}return{error:s}}const{session:i,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",o),await this._saveSession(i),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return pt(e)?this._returnResult({error:e}):this._returnResult({error:new ft("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,n;try{const s=await nr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(n=null==e?void 0:e.options)||void 0===n?void 0:n.captchaToken}},xform:sr}),{data:i,error:o}=s;if(o||!i)return this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,n;try{let s;if("email"in e){const{email:r,password:n,options:i}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Jt(this.storage,this.storageKey)),s=await nr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:n,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:o,code_challenge_method:a},xform:sr})}else{if(!("phone"in e))throw new bt("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:o}=e;s=await nr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{},channel:null!==(n=null==o?void 0:o.channel)&&void 0!==n?n:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:sr})}}const{data:i,error:o}=s;if(o||!i)return await Mt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:n,options:s}=e;t=await nr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:ir})}else{if(!("phone"in e))throw new bt("You must provide either an email or phone number and a password");{const{phone:r,password:n,options:s}=e;t=await nr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:ir})}}const{data:r,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!r||!r.session||!r.user){const e=new yt;return this._returnResult({data:{user:null,session:null},error:e})}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:n})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:null===(s=e.options)||void 0===s?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{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,n,s,i,o,a,l,c,h,u;let d,p;if("message"in e)d=e.message,p=e.signature;else{const{chain:h,wallet:u,statement:m,options:f}=e;let g;if(Ut())if("object"==typeof u)g=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)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.");g=e.ethereum}else{if("object"!=typeof u||!(null==f?void 0:f.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=u}const w=new URL(null!==(t=null==f?void 0:f.url)&&void 0!==t?t:window.location.href),y=await g.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!y||0===y.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const b=wr(y[0]);let v=null===(r=null==f?void 0:f.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!v){const e=await g.request({method:"eth_chainId"});v=parseInt(e,16)}d=function(e){var t;const{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:u,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)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(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const p=`${h?`${h}://${n}`:n} wants you to sign in with your Ethereum account:\n${wr(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let m=`URI: ${u}\nVersion: ${d}\nChain ID: ${r}${o?`\nNonce: ${o}`:""}\nIssued At: ${i.toISOString()}`;if(s&&(m+=`\nExpiration Time: ${s.toISOString()}`),a&&(m+=`\nNot Before: ${a.toISOString()}`),l&&(m+=`\nRequest ID: ${l}`),c){let e="\nResources:";for(const t of c){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}m+=e}return`${p}\n${m}`}({domain:w.host,address:b,statement:m,uri:w.href,version:"1",chainId:v,nonce:null===(n=null==f?void 0:f.signInWithEthereum)||void 0===n?void 0:n.nonce,issuedAt:null!==(i=null===(s=null==f?void 0:f.signInWithEthereum)||void 0===s?void 0:s.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(o=null==f?void 0:f.signInWithEthereum)||void 0===o?void 0:o.expirationTime,notBefore:null===(a=null==f?void 0:f.signInWithEthereum)||void 0===a?void 0:a.notBefore,requestId:null===(l=null==f?void 0:f.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==f?void 0:f.signInWithEthereum)||void 0===c?void 0:c.resources}),p=await g.request({method:"personal_sign",params:[yr(d),b]})}try{const{data:t,error:r}=await nr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:sr});if(r)throw r;if(!t||!t.session||!t.user){const e=new yt;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,n,s,i,o,a,l,c,h,u,d;let p,m;if("message"in e)p=e.message,m=e.signature;else{const{chain:u,wallet:d,statement:f,options:g}=e;let w;if(Ut())if("object"==typeof d)w=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))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.");w=e.solana}else{if("object"!=typeof d||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=d}const y=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href);if("signIn"in w&&w.signIn){const e=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==g?void 0:g.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),f?{statement:f}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),m=t.signature}else{if(!("signMessage"in w&&"function"==typeof w.signMessage&&"publicKey"in w&&"object"==typeof w&&w.publicKey&&"toBase58"in w.publicKey&&"function"==typeof w.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${y.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),...f?["",f,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(n=null===(r=null==g?void 0:g.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==n?n:(new Date).toISOString()}`,...(null===(s=null==g?void 0:g.signInWithSolana)||void 0===s?void 0:s.notBefore)?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...(null===(i=null==g?void 0:g.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...(null===(o=null==g?void 0:g.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...(null===(a=null==g?void 0:g.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...(null===(l=null==g?void 0:g.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...(null===(h=null===(c=null==g?void 0:g.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===h?void 0:h.length)?["Resources",...g.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await w.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=e}}try{const{data:t,error:r}=await nr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:Lt(m)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:sr});if(r)throw r;if(!t||!t.session||!t.user){const e=new yt;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await qt(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new kt;const{data:t,error:s}=await nr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:sr});if(await Mt(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!t||!t.session||!t.user){const e=new yt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=n?n:null}),error:s})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:r,token:n,access_token:s,nonce:i}=e,o=await nr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:sr}),{data:a,error:l}=o;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a||!a.session||!a.user){const e=new yt;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:l})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,n,s,i;try{if("email"in e){const{email:n,options:s}=e;let i=null,o=null;"pkce"===this.flowType&&([i,o]=await Jt(this.storage,this.storageKey));const{error:a}=await nr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:n,data:null!==(t=null==s?void 0:s.data)&&void 0!==t?t:{},create_user:null===(r=null==s?void 0:s.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},code_challenge:i,code_challenge_method:o},redirectTo:null==s?void 0:s.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){const{phone:t,options:r}=e,{data:o,error:a}=await nr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(n=null==r?void 0:r.data)&&void 0!==n?n:{},create_user:null===(s=null==r?void 0:r.shouldCreateUser)||void 0===s||s,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(i=null==r?void 0:r.channel)&&void 0!==i?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a})}throw new bt("You must provide either an email or phone number.")}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let n,s;"options"in e&&(n=null===(t=e.options)||void 0===t?void 0:t.redirectTo,s=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:i,error:o}=await nr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:sr});if(o)throw o;if(!i){throw new Error("An error occurred on token verification.")}const a=i.session,l=i.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,n,s,i;try{let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Jt(this.storage,this.storageKey));const l=await nr(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:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(n=null==e?void 0:e.options)||void 0===n?void 0:n.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:a}),headers:this.headers,xform:ar});return(null===(s=l.data)||void 0===s?void 0:s.url)&&Ut()&&!(null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new wt;const{error:n}=await nr(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:n,options:s}=e,{error:i}=await nr(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},redirectTo:null==s?void 0:s.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){const{phone:r,type:n,options:s}=e,{data:i,error:o}=await nr(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:o})}throw new bt("You must provide either an email or phone number and a type")}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){await this.initializePromise;return await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}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{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await qt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<at;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await qt(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=Qt()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,r,n)=>{if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){const t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,n)}return t.value||"string"!=typeof r||(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."),t.value=!0),Reflect.get(e,r,n)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await nr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:or}):await this._useSession(async e=>{var t,r,n;const{data:s,error:i}=e;if(i)throw i;return(null===(t=s.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await nr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(n=null===(r=s.session)||void 0===r?void 0:r.access_token)&&void 0!==n?n:void 0,xform:or}):{data:{user:null},error:new wt}})}catch(e){if(pt(e))return function(e){return pt(e)&&"AuthSessionMissingError"===e.name}(e)&&(await this._removeSession(),await Mt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:n,error:s}=r;if(s)throw s;if(!n.session)throw new wt;const i=n.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await Jt(this.storage,this.storageKey));const{data:l,error:c}=await nr(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:i.access_token,xform:or});if(c)throw c;return i.user=l.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new wt;const t=Date.now()/1e3;let r=t,n=!0,s=null;const{payload:i}=Kt(e.access_token);if(i.exp&&(r=i.exp,n=r<=t),n){const{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};s=t}else{const{data:n,error:i}=await this._getUser(e.access_token);if(i)throw i;s={access_token:e.access_token,refresh_token:e.refresh_token,user:n.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(e){if(pt(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:n,error:s}=t;if(s)throw s;e=null!==(r=n.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new wt;const{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!Ut())throw new vt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new vt(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("pkce"===this.flowType)throw new _t("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new vt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new _t("No code detected.");const{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;const n=new URL(window.location.href);return n.searchParams.delete("code"),window.history.replaceState(window.history.state,"",n.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:o,expires_at:a,token_type:l}=e;if(!(s&&o&&i&&l))throw new vt("No session defined in URL");const c=Math.round(Date.now()/1e3),h=parseInt(o);let u=c+h;a&&(u=parseInt(a));const d=u-c;1e3*d<=ot&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${h}s`);const p=u-h;c-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,c):c-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,c);const{data:m,error:f}=await this._getUser(s);if(f)throw f;const g={provider_token:r,provider_refresh_token:n,access_token:s,expires_in:h,expires_at:u,refresh_token:i,token_type:l,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:g,redirectType:e.type},error:null})}catch(e){if(pt(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await qt(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({error:s});const i=null===(r=n.session)||void 0===r?void 0:r.access_token;if(i){const{error:t}=await this.admin.signOut(i,e);if(t&&(!function(e){return pt(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await Mt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),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,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,n;try{const{data:{session:n},error:s}=t;if(s)throw s;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(t){await(null===(n=this.stateChangeEmitters.get(e))||void 0===n?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,n=null;"pkce"===this.flowType&&([r,n]=await Jt(this.storage,this.storageKey,!0));try{return await nr(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:n}=await this._useSession(async t=>{var r,n,s,i,o;const{data:a,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(n=e.options)||void 0===n?void 0:n.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:!0});return await nr(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(o=null===(i=a.session)||void 0===i?void 0:i.access_token)&&void 0!==o?o:void 0})});if(n)throw n;return Ut()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(pt(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:n,data:{session:s}}=t;if(n)throw n;const{options:i,provider:o,token:a,access_token:l,nonce:c}=e,h=await nr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==s?void 0:s.access_token)&&void 0!==r?r:void 0,body:{provider:o,id_token:a,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:sr}),{data:u,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:d})):this._returnResult({data:{user:null,session:null},error:new yt})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,n;const{data:s,error:i}=t;if(i)throw i;return await nr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(n=null===(r=s.session)||void 0===r?void 0:r.access_token)&&void 0!==n?n:void 0})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await nr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:sr})),n=(e,t)=>{const r=200*Math.pow(2,e);return t&&St(t)&&Date.now()+r-s<ot},new Promise((e,t)=>{(async()=>{for(let s=0;s<1/0;s++)try{const t=await r(s);if(!n(s,null,t))return void e(t)}catch(e){if(!n(s,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),pt(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var r,n}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Ut()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const n=await qt(this.storage,this.storageKey);if(n&&this.userStorage){let t=await qt(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:n.user},await Bt(this.userStorage,this.storageKey+"-user",t)),n.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:Qt()}else if(n&&!n.user&&!n.user){const e=await qt(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(n.user=e.user,await Mt(this.storage,this.storageKey+"-user"),await Bt(this.storage,this.storageKey,n)):n.user=Qt()}if(this._debug(r,"session from storage",n),!this._isValidSession(n))return this._debug(r,"session is not valid"),void(null!==n&&await this._removeSession());const s=1e3*(null!==(t=n.expires_at)&&void 0!==t?t:1/0)-Date.now()<at;if(this._debug(r,`session has${s?"":" not"} expired with margin of 90000s`),s){if(this.autoRefreshToken&&n.refresh_token){const{error:e}=await this._callRefreshToken(n.refresh_token);e&&(console.error(e),St(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(n.user&&!0===n.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(n.access_token);!t&&(null==e?void 0:e.user)?(n.user=e.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(e){return this._debug(r,"error",e),void console.error(e)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new wt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Wt;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new wt;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const n={data:t.session,error:null};return this.refreshingDeferred.resolve(n),n}catch(e){if(this._debug(n,"error",e),pt(e)){const r={data:null,error:e};return St(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,r=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],s=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){n.push(e)}});if(await Promise.all(s),n.length>0){for(let e=0;e<n.length;e+=1)console.error(n[e]);throw n[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Mt(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await Bt(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const n=Zt(e);await Bt(this.storage,this.storageKey,n)}else{const e=Zt(t);await Bt(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Mt(this.storage,this.storageKey),await Mt(this.storage,this.storageKey+"-code-verifier"),await Mt(this.storage,this.storageKey+"-user"),this.userStorage&&await Mt(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ut()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),ot);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const n=Math.floor((1e3*r.expires_at-e)/ot);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),n<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof mr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ut()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const n=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&n.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&n.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await Jt(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});n.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);n.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&n.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;return s?this._returnResult({data:null,error:s}):await nr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,n;const{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:l}=await nr(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===a.type&&(null===(n=null==a?void 0:a.totp)||void 0===n?void 0:n.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({data:null,error:s});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Tr(e.webauthn.credential_response):Cr(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await nr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return a?this._returnResult({data:null,error:a}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:a}))})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:s}=t;if(s)return this._returnResult({data:null,error:s});const i=await nr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});if(i.error)return i;const{data:o}=i;if("webauthn"!==o.type)return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Sr(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Er(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{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;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const n={all:[],phone:[],totp:[],webauthn:[]};for(const r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])n.all.push(r),"verified"===r.status&&n[r.factor_type].push(r);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:n}=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:s}=Kt(r.access_token);let i=null;s.aal&&(i=s.aal);let o=i;(null!==(t=null===(e=r.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(o="aal2");return{data:{currentLevel:i,nextLevel:o,currentAuthenticationMethods:s.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?await nr(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new wt})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new wt});const i=await nr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&Ut()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new wt});const i=await nr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&Ut()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await nr(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new wt})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?(await nr(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 wt})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const n=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>n)return r;const{data:s,error:i}=await nr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return s.keys&&0!==s.keys.length?(this.jwks=s,this.jwks_cached_at=n,r=s.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let r=e;if(!r){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}const{header:n,payload:s,signature:i,raw:{header:o,payload:a}}=Kt(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(s.exp);const l=n.alg&&!n.alg.startsWith("HS")&&n.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(n.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!l){const{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:s,header:n,signature:i},error:null}}const c=function(e){switch(e){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")}}(n.alg),h=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,h,i,Pt(`${o}.${a}`)))throw new Tt("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}}Ur.nextInstanceID={};const zr=Ur;let Dr="";Dr="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const Hr={headers:{"X-Client-Info":`supabase-js-${Dr}/2.90.1`}},Br={schema:"public"},qr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Mr={};function Wr(e){return(Wr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Kr(e){var t=function(e,t){if("object"!=Wr(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=Wr(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Wr(t)?t:t+""}function Fr(e,t,r){return(t=Kr(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Vr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function Jr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Vr(Object(r),!0).forEach(function(t){Fr(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Vr(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const Gr=(e,t,r)=>{const n=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),s=Headers;return async(r,i)=>{var o;const a=null!==(o=await t())&&void 0!==o?o:e;let l=new s(null==i?void 0:i.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${a}`),n(r,Jr(Jr({},i),{},{headers:l}))}};var Xr=class extends zr{constructor(e){super(e)}},Yr=class{constructor(e,t,r){var n,s;this.supabaseUrl=e,this.supabaseKey=t;const i=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((r=t).endsWith("/")?r:r+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var r}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a=function(e,t){var r,n;const{db:s,auth:i,realtime:o,global:a}=e,{db:l,auth:c,realtime:h,global:u}=t,d={db:Jr(Jr({},l),s),auth:Jr(Jr({},c),i),realtime:Jr(Jr({},h),o),storage:{},global:Jr(Jr(Jr({},u),a),{},{headers:Jr(Jr({},null!==(r=null==u?void 0:u.headers)&&void 0!==r?r:{}),null!==(n=null==a?void 0:a.headers)&&void 0!==n?n:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:Br,realtime:Mr,auth:Jr(Jr({},qr),{},{storageKey:o}),global:Hr});var l;(this.storageKey=null!==(n=a.auth.storageKey)&&void 0!==n?n:"",this.headers=null!==(s=a.global.headers)&&void 0!==s?s:{},a.accessToken)?(this.accessToken=a.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(l=a.auth)&&void 0!==l?l:{},this.headers,a.global.fetch);this.fetch=Gr(t,this._getAccessToken.bind(this),a.global.fetch),this.realtime=this._initRealtimeClient(Jr({headers:this.headers,accessToken:this._getAccessToken.bind(this)},a.realtime)),this.accessToken&&this.accessToken().then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new S(new URL("rest/v1",i).href,{headers:this.headers,schema:a.db.schema,fetch:this.fetch}),this.storage=new st(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),a.accessToken||this._listenForAuthEvents()}get functions(){return new w(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t,r=this;if(r.accessToken)return await r.accessToken();const{data:n}=await r.auth.getSession();return null!==(e=null===(t=n.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,u){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Xr({url:this.authUrl.href,headers:Jr(Jr({},d),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:c,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new ie(this.realtimeUrl.href,Jr(Jr({},e),{},{params:Jr(Jr({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};(function(){if("undefined"!=typeof window)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(null==t)return!1;const r=t.match(/^v(\d+)\./);return!!r&&parseInt(r[1],10)<=18})()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Qr={position:"bottom-right",defaultOpen:!1,theme:"dark",features:["prompts","timeline","deployments","elements","captures"],captureConsole:!0,captureNetwork:!0,hotkey:"ctrl+shift+o",apiUrl:"https://orquesta.live"};class Zr{constructor(){this.listeners=new Set,this.state=this.getInitialState()}getInitialState(){return{isConnected:!1,isConnecting:!1,connectionError:null,projectId:null,projectName:null,agentOnline:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,currentPrompt:null,promptHistory:[],isSubmitting:!1,outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}setConnected(e,t,r){this.setState({isConnected:!0,isConnecting:!1,connectionError:null,projectId:e,projectName:t,agentOnline:r})}setConnectionError(e){this.setState({isConnected:!1,isConnecting:!1,connectionError:e})}setOpen(e){this.setState({isOpen:e})}toggle(){this.setState({isOpen:!this.state.isOpen})}setActiveTab(e){this.setState({activeTab:e})}setCurrentPrompt(e){this.setState({currentPrompt:e}),e&&!this.state.promptHistory.find(t=>t.id===e.id)&&this.setState({promptHistory:[e,...this.state.promptHistory].slice(0,50)})}updatePrompt(e,t){this.state.currentPrompt?.id===e&&this.setState({currentPrompt:{...this.state.currentPrompt,...t}}),this.setState({promptHistory:this.state.promptHistory.map(r=>r.id===e?{...r,...t}:r)})}addOutputLine(e){const t={...e,id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`};this.setState({outputLines:[...this.state.outputLines,t]})}clearOutput(){this.setState({outputLines:[]})}storePromptOutput(e){this.state.outputLines.length>0&&this.setState({promptOutputs:{...this.state.promptOutputs,[e]:[...this.state.outputLines]}})}setSelectedElement(e){this.setState({selectedElement:e,isSelectingElement:!1})}startElementSelection(){this.setState({isSelectingElement:!0})}cancelElementSelection(){this.setState({isSelectingElement:!1,selectedElement:null})}setOverlayMode(e){this.setState({overlayMode:e}),"off"===e&&this.setState({highlightedPromptId:null})}setHighlightedPromptId(e){this.setState({highlightedPromptId:e})}setElementMarkers(e){this.setState({elementMarkers:e})}setCommentsForPrompt(e,t){this.setState({comments:{...this.state.comments,[e]:t}})}addComment(e,t){const r=this.state.comments[e]||[];this.setState({comments:{...this.state.comments,[e]:[...r,t]}}),this.setState({promptHistory:this.state.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)})}setExpandedPromptId(e){this.setState({expandedPromptId:e})}setLoadingComments(e){this.setState({isLoadingComments:e})}addConsoleLogs(e){this.setState({consoleLogs:[...this.state.consoleLogs,...e].slice(-100)})}addNetworkLogs(e){this.setState({networkLogs:[...this.state.networkLogs,...e].slice(-100)})}toggleIncludeConsole(){this.setState({includeConsole:!this.state.includeConsole})}toggleIncludeNetwork(){this.setState({includeNetwork:!this.state.includeNetwork})}reset(){this.state=this.getInitialState(),this.notify()}}class en{constructor(){this.buffer=[],this.maxSize=100,this.originalConsole=null,this.errorHandler=null,this.rejectionHandler=null,this.listeners=new Set}start(){if(this.originalConsole)return;this.originalConsole={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};const e=e=>(...t)=>{const r=this.createEntry(e,t);this.addEntry(r),this.originalConsole?.[e](...t)};console.log=e("log"),console.info=e("info"),console.warn=e("warn"),console.error=e("error"),this.errorHandler=e=>{const t=this.createEntry("error",[e.message],e.error?.stack);this.addEntry(t)},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{const t=e.reason instanceof Error?e.reason.message:String(e.reason),r=e.reason instanceof Error?e.reason.stack:void 0,n=this.createEntry("error",[`Unhandled Promise Rejection: ${t}`],r);this.addEntry(n)},window.addEventListener("unhandledrejection",this.rejectionHandler)}stop(){this.originalConsole&&(console.log=this.originalConsole.log,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null),this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null)}createEntry(e,t,r){return{timestamp:Date.now(),level:e,message:t.map(e=>"object"==typeof e?JSON.stringify(e,null,2):String(e)).join(" "),args:t,stack:r}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>"error"===e.level||"warn"===e.level)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getRecent(20);return 0===t.length?"":t.map(e=>`${`[${new Date(e.timestamp).toISOString()}] [${e.level.toUpperCase()}]`} ${e.message}${e.stack?`\n${e.stack}`:""}`).join("\n")}}class tn{constructor(){this.buffer=[],this.maxSize=100,this.originalFetch=null,this.originalXHROpen=null,this.originalXHRSend=null,this.listeners=new Set}start(){this.originalFetch||(this.patchFetch(),this.patchXHR())}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXHROpen&&this.originalXHRSend&&(XMLHttpRequest.prototype.open=this.originalXHROpen,XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHROpen=null,this.originalXHRSend=null)}patchFetch(){this.originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{const r="string"==typeof e?e:e instanceof URL?e.href:e.url,n=t?.method||"GET",s=Date.now(),i={timestamp:s,method:n,url:r,requestBody:t?.body};try{const r=await this.originalFetch(e,t);if(i.status=r.status,i.duration=Date.now()-s,!r.ok)try{const e=r.clone();i.responseBody=await e.text()}catch{}return this.addEntry(i),r}catch(e){throw i.duration=Date.now()-s,i.error=e instanceof Error?e.message:String(e),this.addEntry(i),e}}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;const e=this,t=new WeakMap;XMLHttpRequest.prototype.open=function(r,n,...s){return t.set(this,{method:r,url:"string"==typeof n?n:n.href,startTime:0}),e.originalXHROpen.apply(this,[r,n,...s])},XMLHttpRequest.prototype.send=function(r){const n=t.get(this);return n&&(n.startTime=Date.now(),this.addEventListener("loadend",()=>{const t={timestamp:n.startTime,method:n.method,url:n.url,status:this.status,duration:Date.now()-n.startTime};if(this.status>=400||0===this.status){t.error=this.statusText||"Request failed";try{t.responseBody=this.responseText}catch{}}e.addEntry(t)})),e.originalXHRSend.call(this,r)}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>e.status&&e.status>=400||e.error)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getErrors();return 0===t.length?"":t.map(e=>{const t=new Date(e.timestamp).toISOString(),r=e.status?`[${e.status}]`:"[FAILED]";return`[${t}] ${e.method} ${e.url} ${r}${e.error?` - ${e.error}`:""}`}).join("\n")}}class rn{constructor(){this.overlay=null,this.highlight=null,this.selectedHighlight=null,this.selectedElement=null,this.isActive=!1,this.onSelect=null,this.onCancel=null,this.globalRightClickHandler=null,this.globalRightClickCallback=null,this.globalRightClickWithPositionCallback=null,this.selectedElementScrollHandler=null,this.handleMouseMove=e=>{if(!this.isActive||!this.highlight)return;const t=document.elementFromPoint(e.clientX,e.clientY);if(!t||t.id?.startsWith("orquesta-"))return;this.selectedElement=t;const r=t.getBoundingClientRect();this.highlight.style.display="block",this.highlight.style.top=`${r.top}px`,this.highlight.style.left=`${r.left}px`,this.highlight.style.width=`${r.width}px`,this.highlight.style.height=`${r.height}px`;const n=this.highlight.querySelector("#orquesta-element-label");if(n){const e=t.tagName.toLowerCase(),r=t.id?`#${t.id}`:"",s=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`<${e}${r}${s}>`}},this.handleClick=e=>{if(!this.isActive)return;const t=e.target;if(!t.id?.startsWith("orquesta-")&&(e.preventDefault(),e.stopPropagation(),this.selectedElement)){const e=this.getElementContext(this.selectedElement);this.deactivate(),this.onSelect?.(e)}},this.handleKeyDown=e=>{"Escape"===e.key&&this.isActive&&(this.deactivate(),this.onCancel?.())},this.promptHighlightScrollHandler=null}setupGlobalRightClick(e){return this.globalRightClickCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const r=this.getElementContext(t);this.globalRightClickCallback?.(r)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickCallback=null)}}setupGlobalRightClickWithPosition(e){return this.globalRightClickWithPositionCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const r=this.getElementContext(t),n={x:e.clientX,y:e.clientY};this.globalRightClickWithPositionCallback?.(r,n)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickWithPositionCallback=null)}}highlightSelectedElement(e){try{const t=document.querySelector(e);if(!t)return null;this.removeSelectedHighlight(),this.selectedHighlight=document.createElement("div"),this.selectedHighlight.id="orquesta-selected-element-highlight",this.selectedHighlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #3b82f6;\n background: rgba(59, 130, 246, 0.15);\n z-index: 2147483640;\n transition: all 0.15s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25), 0 0 20px rgba(59, 130, 246, 0.3);\n ",document.body.appendChild(this.selectedHighlight);const r=document.createElement("div");r.id="orquesta-selected-element-label",r.style.cssText='\n position: absolute;\n top: -28px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 8px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ';const n=t.tagName.toLowerCase(),s=t.id?`#${t.id}`:"",i=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";r.textContent=`Selected: <${n}${s}${i}>`,this.selectedHighlight.appendChild(r);const o=()=>{if(!this.selectedHighlight)return;const e=t.getBoundingClientRect();this.selectedHighlight.style.top=e.top-3+"px",this.selectedHighlight.style.left=e.left-3+"px",this.selectedHighlight.style.width=`${e.width+6}px`,this.selectedHighlight.style.height=`${e.height+6}px`};return o(),this.selectedElementScrollHandler=o,window.addEventListener("scroll",this.selectedElementScrollHandler,!0),window.addEventListener("resize",this.selectedElementScrollHandler),t}catch{return null}}removeSelectedHighlight(){this.selectedHighlight&&(this.selectedHighlight.remove(),this.selectedHighlight=null),this.selectedElementScrollHandler&&(window.removeEventListener("scroll",this.selectedElementScrollHandler,!0),window.removeEventListener("resize",this.selectedElementScrollHandler),this.selectedElementScrollHandler=null)}activate(e,t){this.isActive||(this.isActive=!0,this.onSelect=e,this.onCancel=t||null,this.createOverlay(),this.addListeners(),document.body.style.cursor="crosshair")}deactivate(){this.isActive&&(this.isActive=!1,this.removeListeners(),this.removeOverlay(),this.selectedElement=null,document.body.style.cursor="")}isSelecting(){return this.isActive}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="orquesta-element-selector-overlay",this.overlay.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483646;\n pointer-events: none;\n ",document.body.appendChild(this.overlay),this.highlight=document.createElement("div"),this.highlight.id="orquesta-element-highlight",this.highlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 2px solid #3b82f6;\n background: rgba(59, 130, 246, 0.1);\n z-index: 2147483646;\n transition: all 0.1s ease;\n display: none;\n ",document.body.appendChild(this.highlight);const e=document.createElement("div");e.id="orquesta-element-label",e.style.cssText="\n position: absolute;\n bottom: -24px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: monospace;\n padding: 2px 6px;\n border-radius: 2px;\n white-space: nowrap;\n ",this.highlight.appendChild(e)}removeOverlay(){this.overlay?.remove(),this.highlight?.remove(),this.overlay=null,this.highlight=null}addListeners(){document.addEventListener("mousemove",this.handleMouseMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown,!0)}removeListeners(){document.removeEventListener("mousemove",this.handleMouseMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("keydown",this.handleKeyDown,!0)}highlightElement(e){try{const t=document.querySelector(e);if(!t)return null;this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null);let r=document.getElementById("orquesta-prompt-highlight");r||(r=document.createElement("div"),r.id="orquesta-prompt-highlight",r.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #8b5cf6;\n background: rgba(139, 92, 246, 0.15);\n z-index: 2147483640;\n transition: top 0.1s ease, left 0.1s ease, width 0.1s ease, height 0.1s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2), 0 0 20px rgba(139, 92, 246, 0.3);\n ",document.body.appendChild(r));let n=r.querySelector("#orquesta-prompt-highlight-label");n||(n=document.createElement("div"),n.id="orquesta-prompt-highlight-label",n.style.cssText='\n position: absolute;\n top: -30px;\n left: 0;\n background: #8b5cf6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 10px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ',r.appendChild(n));const s=t.tagName.toLowerCase(),i=t.id?`#${t.id}`:"",o=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`Highlighted: <${s}${i}${o}>`;const a=()=>{const e=t.getBoundingClientRect();r.style.display="block",r.style.top=e.top-3+"px",r.style.left=e.left-3+"px",r.style.width=`${e.width+6}px`,r.style.height=`${e.height+6}px`};a(),this.promptHighlightScrollHandler=a,window.addEventListener("scroll",this.promptHighlightScrollHandler,!0),window.addEventListener("resize",this.promptHighlightScrollHandler);const l=t.getBoundingClientRect();return(l.top<0||l.bottom>window.innerHeight)&&t.scrollIntoView({behavior:"smooth",block:"center"}),t}catch{return null}}removeHighlight(){const e=document.getElementById("orquesta-prompt-highlight");e&&(e.style.display="none"),this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null)}findElement(e,t){try{let r=document.querySelector(e);if(r)return r;if(t&&(r=document.getElementById(t),r))return r;const n=e.match(/^([a-z]+)\.([a-z0-9_-]+)/i);if(n){const[,e,t]=n;if(r=document.querySelector(`${e}.${t}`),r)return r}return null}catch{return null}}getElementContext(e){const t=e.getBoundingClientRect(),r={};for(const t of e.attributes)t.name.startsWith("data-")||"class"===t.name||"id"===t.name||(r[t.name]=t.value);return{selector:this.generateSelector(e),tag:e.tagName.toLowerCase(),id:e.id||void 0,className:"string"==typeof e.className?e.className:void 0,textContent:e.textContent?.trim().slice(0,200)||void 0,boundingRect:t,attributes:Object.keys(r).length>0?r:void 0}}generateSelector(e){if(e.id)return`#${e.id}`;const t=[];let r=e;for(;r&&r!==document.body;){let e=r.tagName.toLowerCase();if(r.id){e=`#${r.id}`,t.unshift(e);break}if(r.className&&"string"==typeof r.className){const t=r.className.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}const n=r.parentElement;if(n){const t=Array.from(n.children).filter(e=>e.tagName===r.tagName);if(t.length>1){e+=`:nth-child(${t.indexOf(r)+1})`}}t.unshift(e),r=r.parentElement}return t.join(" > ")}}const nn=!1,sn="prompts",on="dark";const an=new class{constructor(){this.projectId=null}setProjectId(e){this.projectId=e}getKey(e){const t=`orquesta_embed_${e}`;return this.projectId?`${t}_${this.projectId}`:t}get(e){try{const t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):null}catch{return null}}set(e,t){try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch{}}remove(e){try{localStorage.removeItem(this.getKey(e))}catch{}}getState(){return{isOpen:this.get("isOpen")??nn,position:this.get("position"),size:this.get("size"),activeTab:this.get("activeTab")??sn,theme:this.get("theme")??on}}setState(e){Object.entries(e).forEach(([e,t])=>{void 0!==t&&this.set(e,t)})}clear(){["isOpen","position","size","activeTab","theme"].forEach(e=>this.remove(e))}};class ln{constructor(e){this.supabase=null,this.channel=null,this.projectId=null,this.hotkeyHandler=null,this.config={...Qr,...e},this.state=new Zr,this.consoleCapture=new en,this.networkCapture=new tn,this.elementSelector=new rn}async connect(){if(!this.config.token)throw new Error("Embed token is required");this.state.setState({isConnecting:!0});try{const n=await fetch(`${this.config.apiUrl}/api/embed/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.token})});if(!n.ok){const e=await n.json();throw new Error(e.error||"Failed to validate token")}const s=await n.json();if(!s.valid)throw new Error("Invalid embed token");this.projectId=s.projectId,an.setProjectId(s.projectId),this.supabase=(e=s.supabaseUrl,t=s.supabaseAnonKey,new Yr(e,t,r)),this.channel=this.supabase.channel(s.channelName),this.channel.on("broadcast",{event:"output"},({payload:e})=>{this.handleOutput(e)}).on("broadcast",{event:"complete"},({payload:e})=>{this.handleComplete(e)}).on("broadcast",{event:"error"},({payload:e})=>{this.handleError(e)}).subscribe(e=>{if("SUBSCRIBED"===e){this.state.setConnected(s.projectId,s.project?.name||"Project",s.project?.agent_online||!1),this.config.captureConsole&&(this.consoleCapture.start(),this.consoleCapture.subscribe(e=>{this.state.addConsoleLogs([e])})),this.config.captureNetwork&&(this.networkCapture.start(),this.networkCapture.subscribe(e=>{this.state.addNetworkLogs([e])})),this.setupHotkey(),this.loadTimeline();const e=an.getState();this.state.setState({isOpen:this.config.defaultOpen??e.isOpen,activeTab:e.activeTab}),this.config.onReady?.()}else"CHANNEL_ERROR"!==e&&"TIMED_OUT"!==e||this.state.setConnectionError("Failed to connect to channel")})}catch(e){const t=e instanceof Error?e.message:"Connection failed";throw this.state.setConnectionError(t),this.config.onError?.(e instanceof Error?e:new Error(t)),e}var e,t,r}disconnect(){this.channel&&(this.supabase?.removeChannel(this.channel),this.channel=null),this.consoleCapture.stop(),this.networkCapture.stop(),this.elementSelector.deactivate(),this.removeHotkey(),this.state.reset(),this.supabase=null,this.projectId=null}setupHotkey(){if(!this.config.hotkey)return;const e=this.config.hotkey.toLowerCase().split("+"),t=e.pop(),r=new Set(e);this.hotkeyHandler=e=>{const n=r.has("ctrl")===(e.ctrlKey||e.metaKey),s=r.has("shift")===e.shiftKey,i=r.has("alt")===e.altKey,o=e.key.toLowerCase()===t;n&&s&&i&&o&&(e.preventDefault(),this.toggle())},document.addEventListener("keydown",this.hotkeyHandler)}removeHotkey(){this.hotkeyHandler&&(document.removeEventListener("keydown",this.hotkeyHandler),this.hotkeyHandler=null)}handleOutput(e){if(!this.state.getState().currentPrompt)return;let t,r="stdout",n=e.data;"stderr"===e.type?r="stderr":e.data.includes("Tool:")||e.data.includes("tool_call")?r="tool":(e.data.includes("thinking")||e.data.includes("Thinking"))&&(r="thinking");try{const s=JSON.parse(e.data);s.type&&(r=s.type,n=s.content||s.message||e.data,t=s)}catch{}this.state.addOutputLine({timestamp:e.timestamp||Date.now(),type:r,content:n,details:t})}handleComplete(e){const t=this.state.getState();t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:0===e.exitCode?"completed":"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1})}handleError(e){const t=this.state.getState();this.state.addOutputLine({timestamp:Date.now(),type:"stderr",content:`Error: ${e.error}`}),t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1})}async submitPrompt(e,t){if(!this.projectId)throw new Error("Not connected");const r=this.state.getState();if(r.isSubmitting)throw new Error("A prompt is already running");this.state.setState({isSubmitting:!0}),this.state.clearOutput();let n=e;const s=t?.elementContext||r.selectedElement;if(s&&(n+=`\n\n--- Element Context ---\nSelector: ${s.selector}\nTag: <${s.tag}>\n${s.id?`ID: ${s.id}`:""}\n${s.className?`Classes: ${s.className}`:""}\n${s.textContent?`Text: ${s.textContent}`:""}\n${s.attributes?`Attributes: ${JSON.stringify(s.attributes)}`:""}`),t?.includeConsole??r.includeConsole){const e=this.consoleCapture.formatForPrompt();e&&(n+=`\n\n--- Console Logs ---\n${e}`)}if(t?.includeNetwork??r.includeNetwork){const e=this.networkCapture.formatForPrompt();e&&(n+=`\n\n--- Network Errors ---\n${e}`)}try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({projectId:this.projectId,content:n,elementContext:s})});if(!e.ok){const t=await e.json();throw new Error(t.error||"Failed to submit prompt")}const t=(await e.json()).prompt;return this.state.setCurrentPrompt(t),this.state.setSelectedElement(null),this.config.onPromptSubmit?.(t.id),t.id}catch(e){throw this.state.setState({isSubmitting:!1}),e}}async loadTimeline(){if(this.projectId)try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts?projectId=${this.projectId}&limit=50`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(e.ok){const t=await e.json();this.state.setState({promptHistory:t.prompts||[]})}}catch{}}open(){this.state.setOpen(!0),an.set("isOpen",!0)}close(){this.state.setOpen(!1),an.set("isOpen",!1)}toggle(){const e=!this.state.getState().isOpen;this.state.setOpen(e),an.set("isOpen",e)}startElementSelection(){this.state.startElementSelection(),this.elementSelector.activate(e=>this.state.setSelectedElement(e),()=>this.state.cancelElementSelection())}getState(){return this.state.getState()}subscribe(e){return this.state.subscribe(e)}getConsoleCapture(){return this.consoleCapture}getNetworkCapture(){return this.networkCapture}getElementSelector(){return this.elementSelector}async loadComments(e){if(this.projectId){this.state.setLoadingComments(!0);try{const t=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(t.ok){const r=await t.json();this.state.setCommentsForPrompt(e,r.comments||[])}}catch{}finally{this.state.setLoadingComments(!1)}}}async addComment(e,t){if(this.projectId)try{const r=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({content:t})});if(r.ok){const t=await r.json();t.comment&&this.state.addComment(e,t.comment)}}catch(e){throw console.error("Failed to add comment:",e),e}}setOverlayMode(e){if(this.state.setOverlayMode(e),"off"===e)this.elementSelector.removeHighlight(),this.state.setHighlightedPromptId(null);else if("all"===e){const e=this.state.getState().promptHistory.filter(e=>e.element_context?.selector).map(e=>({promptId:e.id,selector:e.element_context.selector,rect:null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}));this.state.setElementMarkers(e)}else this.state.setElementMarkers([])}highlightPromptElement(e){if(!e.element_context?.selector)return void console.warn("Prompt has no element context");this.elementSelector.highlightElement(e.element_context.selector)?(this.state.setHighlightedPromptId(e.id),this.state.setOverlayMode("single")):console.warn("Element not found for prompt:",e.id)}setupGlobalRightClick(e){return this.elementSelector.setupGlobalRightClick(e)}setupGlobalRightClickWithPosition(e){return this.elementSelector.setupGlobalRightClickWithPosition(e)}}function cn({variant:r="primary",size:n="md",loading:s=!1,disabled:i,className:o="",children:a,...l}){return e("button",{className:`inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-zinc-900 disabled:opacity-50 disabled:cursor-not-allowed ${{primary:"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",secondary:"bg-zinc-700 text-white hover:bg-zinc-600 focus:ring-zinc-500",ghost:"bg-transparent text-zinc-300 hover:bg-zinc-800 hover:text-white focus:ring-zinc-500",danger:"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500"}[r]} ${{sm:"px-2.5 py-1.5 text-xs",md:"px-3 py-2 text-sm",lg:"px-4 py-2.5 text-base"}[n]} ${o}`,disabled:i||s,...l,children:[s&&e("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),a]})}function hn({label:r,error:n,className:s="",...i}){return e("div",{className:"w-full",children:[r&&t("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:r}),t("input",{className:`w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-md text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed ${n?"border-red-500":""} ${s}`,...i}),n&&t("p",{className:"mt-1.5 text-sm text-red-400",children:n})]})}const un=n.forwardRef(function({label:r,error:n,className:s="",...i},o){return e("div",{className:"w-full",children:[r&&t("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:r}),t("textarea",{ref:o,className:`w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-md text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed resize-none ${n?"border-red-500":""} ${s}`,...i}),n&&t("p",{className:"mt-1.5 text-sm text-red-400",children:n})]})});function dn({variant:e="default",size:r="md",children:n,className:s=""}){return t("span",{className:`inline-flex items-center font-medium rounded-full ${{default:"bg-zinc-700 text-zinc-300",success:"bg-green-900/50 text-green-400",warning:"bg-yellow-900/50 text-yellow-400",error:"bg-red-900/50 text-red-400",info:"bg-blue-900/50 text-blue-400"}[e]} ${{sm:"px-1.5 py-0.5 text-xs",md:"px-2 py-1 text-xs"}[r]} ${s}`,children:n})}function pn({status:e,className:r=""}){return t("span",{className:`inline-block w-2 h-2 rounded-full ${{online:"bg-green-500",offline:"bg-zinc-500",pending:"bg-yellow-500",running:"bg-blue-500 animate-pulse",completed:"bg-green-500",failed:"bg-red-500"}[e]} ${r}`})}const mn=s(null);function fn(){const e=o(mn);if(!e)throw new Error("Tabs components must be used within a Tabs provider");return e}function gn({defaultValue:e="",value:r,onChange:n,children:s,className:o=""}){const[a,l]=i(e),c=r??a??"";return t(mn.Provider,{value:{activeTab:c,setActiveTab:e=>{void 0===r&&l(e),n?.(e)}},children:t("div",{className:o,children:s})})}function wn({children:e,className:r=""}){return t("div",{className:`flex items-center gap-1 p-1 bg-zinc-800 rounded-lg ${r}`,children:e})}function yn({value:e,children:r,className:n=""}){const{activeTab:s,setActiveTab:i}=fn();return t("button",{onClick:()=>i(e),className:`flex-1 px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${s===e?"bg-zinc-700 text-white":"text-zinc-400 hover:text-zinc-300"} ${n}`,children:r})}function bn({value:e,children:r,className:n=""}){const{activeTab:s}=fn();return s!==e?null:t("div",{className:n,children:r})}function vn({onSubmit:r,isSubmitting:n,selectedElement:s,includeConsole:o,includeNetwork:c,onToggleConsole:h,onToggleNetwork:u,onSelectElement:d,onClearElement:p,agentOnline:m}){const[f,g]=i(""),w=a(null);l(()=>{w.current?.focus()},[]);const y=e=>{e.preventDefault(),f.trim()&&!n&&m&&(r(f.trim(),s),g(""))};return e("form",{onSubmit:y,className:"orquesta-prompt-input",children:[t(un,{ref:w,value:f,onChange:e=>g(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&y(e)},placeholder:m?"What would you like to do?":"Agent is offline...",disabled:n||!m,rows:3,className:"min-h-[80px]"}),e("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[s&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-blue-900/30 text-blue-400 text-xs rounded-md",children:[t("span",{children:"🎯"}),e("span",{className:"font-mono",children:["<",s.tag,">"]}),t("button",{type:"button",onClick:p,className:"ml-1 hover:text-blue-300",children:"×"})]}),o&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-yellow-900/30 text-yellow-400 text-xs rounded-md",children:[t("span",{children:"📋"}),t("span",{children:"Console logs"}),t("button",{type:"button",onClick:h,className:"ml-1 hover:text-yellow-300",children:"×"})]}),c&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-red-900/30 text-red-400 text-xs rounded-md",children:[t("span",{children:"🌐"}),t("span",{children:"Network errors"}),t("button",{type:"button",onClick:u,className:"ml-1 hover:text-red-300",children:"×"})]})]}),e("div",{className:"flex items-center justify-between mt-3",children:[e("div",{className:"flex items-center gap-1.5",children:[e("button",{type:"button",onClick:d,disabled:n,title:"Select an element to include context",className:`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all border ${s?"bg-blue-500/20 text-blue-300 border-blue-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-sm",children:"🎯"}),t("span",{children:"Element"})]}),e("button",{type:"button",onClick:h,disabled:n,title:"Include recent console logs",className:`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all border ${o?"bg-yellow-500/20 text-yellow-300 border-yellow-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-sm",children:"📋"}),t("span",{children:"Logs"}),o&&t("span",{className:"text-yellow-400",children:"✓"})]}),e("button",{type:"button",onClick:u,disabled:n,title:"Include network errors",className:`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all border ${c?"bg-red-500/20 text-red-300 border-red-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-sm",children:"🌐"}),t("span",{children:"Network"}),c&&t("span",{className:"text-red-400",children:"✓"})]})]}),t(cn,{type:"submit",variant:"primary",size:"sm",loading:n,disabled:!f.trim()||!m,children:n?"Running...":"Submit"})]}),!m&&t("p",{className:"mt-2 text-xs text-yellow-400",children:"⚠️ Agent is offline. Start the agent to submit prompts."})]})}function _n({lines:r,isRunning:n}){const s=a(null);if(l(()=>{s.current&&(s.current.scrollTop=s.current.scrollHeight)},[r]),0===r.length&&!n)return t("div",{className:"flex items-center justify-center h-32 text-zinc-500 text-sm",children:"Output will appear here when running prompts"});const i=e=>{switch(e){case"stderr":return"text-red-400";case"tool":return"text-blue-400";case"thinking":return"text-zinc-500 italic";case"system":return"text-yellow-400";default:return"text-zinc-300"}},o=e=>{switch(e){case"stderr":return"✕";case"tool":return"🔧";case"thinking":return"💭";case"system":return"ℹ";default:return"›"}};return e("div",{ref:s,className:"orquesta-log-stream overflow-y-auto max-h-[200px] font-mono text-xs",children:[r.map(r=>e("div",{className:`flex items-start gap-2 py-0.5 ${i(r.type)}`,children:[t("span",{className:"flex-shrink-0 w-4 text-center opacity-50",children:o(r.type)}),t("span",{className:"flex-1 whitespace-pre-wrap break-all",children:r.content})]},r.id)),n&&e("div",{className:"flex items-center gap-2 py-1 text-blue-400 animate-pulse",children:[t("span",{className:"w-4 text-center",children:"●"}),t("span",{children:"Running..."})]})]})}function kn({author:r,size:n="sm",showName:s=!1,className:i=""}){const o={sm:"w-5 h-5 text-[10px]",md:"w-6 h-6 text-xs",lg:"w-8 h-8 text-sm"};return e("div",{className:`flex items-center gap-1.5 ${i}`,children:[r?.avatar_url?t("img",{src:r.avatar_url,alt:r.full_name||"User",className:`${o[n]} rounded-full object-cover ring-1 ring-zinc-700`}):t("div",{className:`${o[n]} ${(e=>{if(!e)return"bg-zinc-600";const t=["bg-blue-600","bg-green-600","bg-purple-600","bg-orange-600","bg-pink-600","bg-cyan-600","bg-indigo-600","bg-teal-600"];return t[e.split("").reduce((e,t)=>e+t.charCodeAt(0),0)%t.length]})(r?.id)} rounded-full flex items-center justify-center font-medium text-white ring-1 ring-zinc-700`,children:(e=>{if(!e)return"?";const t=e.trim().split(" ");return 1===t.length?t[0][0]?.toUpperCase()||"?":(t[0][0]+t[t.length-1][0]).toUpperCase()})(r?.full_name)}),s&&r?.full_name&&t("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:r.full_name})]})}function xn({sha:r,url:n,branch:s,className:i=""}){if(!r)return null;const o=r.slice(0,7),a=e("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 bg-zinc-800 rounded text-[10px] font-mono text-zinc-400 hover:bg-zinc-700 hover:text-zinc-300 transition-colors ${i}`,children:[t("svg",{className:"w-3 h-3",fill:"currentColor",viewBox:"0 0 16 16",children:t("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"})}),o,s&&e("span",{className:"text-zinc-500",children:["(",s,")"]})]});return n?t("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"inline-flex",onClick:e=>e.stopPropagation(),children:a}):a}function Sn(e){const t=new Date(e),r=(new Date).getTime()-t.getTime(),n=Math.floor(r/6e4),s=Math.floor(n/60),i=Math.floor(s/24);return n<1?"just now":n<60?`${n}m`:s<24?`${s}h`:i<7?`${i}d`:t.toLocaleDateString()}function En({comments:r,isLoading:n=!1,className:s=""}){return n?t("div",{className:`space-y-2 ${s}`,children:[1,2].map(r=>e("div",{className:"flex gap-2 animate-pulse",children:[t("div",{className:"w-5 h-5 bg-zinc-700 rounded-full"}),e("div",{className:"flex-1 space-y-1",children:[t("div",{className:"h-3 bg-zinc-700 rounded w-20"}),t("div",{className:"h-3 bg-zinc-700 rounded w-full"})]})]},r))}):0===r.length?t("div",{className:`text-center text-xs text-zinc-500 py-3 ${s}`,children:"No comments yet"}):t("div",{className:`space-y-3 ${s}`,children:r.map(r=>e("div",{className:"flex gap-2",children:[t(kn,{author:r.author,size:"sm"}),e("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs font-medium text-zinc-300 truncate",children:r.author?.full_name||"Unknown"}),t("span",{className:"text-[10px] text-zinc-500",children:Sn(r.created_at)})]}),t("p",{className:"text-xs text-zinc-400 mt-0.5 break-words",children:r.content})]})]},r.id))})}function Tn({onSubmit:r,placeholder:n="Add a comment...",disabled:s=!1,className:o=""}){const[a,l]=i(""),[c,h]=i(!1),u=async e=>{if(e.preventDefault(),a.trim()&&!c&&!s){h(!0);try{await r(a.trim()),l("")}finally{h(!1)}}};return e("form",{onSubmit:u,className:`flex gap-2 ${o}`,children:[t("input",{type:"text",value:a,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),u(e))},placeholder:n,disabled:s||c,className:"flex-1 px-2 py-1.5 bg-zinc-800 border border-zinc-700 rounded text-xs text-white placeholder:text-zinc-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"}),t("button",{type:"submit",disabled:!a.trim()||c||s,className:"px-2 py-1.5 bg-blue-600 text-white text-xs rounded hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:c?e("svg",{className:"w-3 h-3 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):"Post"})]})}function Cn({prompts:r,currentPromptId:n,expandedPromptId:s,comments:o={},isLoadingComments:c=!1,promptOutputs:h={},onSelectPrompt:u,onExpandPrompt:d,onHighlightElement:p,onLoadComments:m,onAddComment:f}){const[g,w]=i(null),[y,b]=i(null),v=a(null),_=a(r.length);if(l(()=>{r.length>_.current&&v.current&&(v.current.scrollTop=0),_.current=r.length},[r.length]),0===r.length)return t("div",{className:"flex items-center justify-center h-32 text-zinc-500 text-sm",children:"No prompts yet. Right-click any element to start!"});const k=e=>{const t=new Date(e),r=(new Date).getTime()-t.getTime(),n=Math.floor(r/6e4),s=Math.floor(r/36e5),i=Math.floor(r/864e5);return n<1?"Just now":n<60?`${n}m ago`:s<24?`${s}h ago`:i<7?`${i}d ago`:t.toLocaleDateString()},x=e=>{switch(e){case"completed":return"success";case"failed":return"error";case"running":return"info";default:return"default"}};return t("div",{ref:v,className:"orquesta-timeline space-y-2 overflow-y-auto max-h-[400px]",children:r.map(r=>{const i=s===r.id,a=r.id===n,l=g===r.id,v=o[r.id]||[],_=h[r.id]||[],S=y===r.id;return e("div",{className:"rounded-lg border transition-all "+(a?"bg-zinc-800 border-blue-500":"bg-zinc-900 border-zinc-800 hover:border-zinc-700"),onMouseEnter:()=>w(r.id),onMouseLeave:()=>w(null),children:[t("button",{onClick:()=>(e=>{u?.(e),e.element_context&&p&&p(e)})(r),className:"w-full text-left p-3",children:e("div",{className:"flex items-start gap-2",children:[t(kn,{author:r.author,size:"sm"}),e("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:[t("span",{className:"text-xs font-medium text-zinc-300 truncate",children:r.author?.full_name||"Unknown"}),t("span",{className:"text-[10px] text-zinc-500",children:k(r.created_at)})]}),e("p",{className:"text-sm text-zinc-200 line-clamp-2",children:[r.content.slice(0,100),r.content.length>100&&"..."]}),e("div",{className:"flex items-center gap-2 mt-2 flex-wrap",children:[r.git_commit_sha&&t(xn,{sha:r.git_commit_sha,url:r.git_commit_url,branch:r.git_branch}),r.element_context&&e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 border border-blue-500/30 rounded-md text-[10px] text-blue-400 font-medium",children:[t("span",{children:"🎯"}),e("span",{children:["<",r.element_context.tag,">"]}),r.element_context.textContent&&e("span",{className:"text-blue-300/70 max-w-[60px] truncate",children:['"',r.element_context.textContent.slice(0,15),'..."']})]}),(r.comment_count||0)>0&&e("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 bg-zinc-800 rounded text-[10px] text-zinc-400",children:["💬 ",r.comment_count]})]})]}),e("div",{className:"flex-shrink-0 flex items-center gap-1.5",children:[t(pn,{status:r.status}),t(dn,{variant:x(r.status),size:"sm",children:r.status})]})]})}),e("div",{className:"flex items-center gap-2 px-3 pb-2 -mt-1 "+(l||r.element_context||i||"completed"===r.status||"failed"===r.status?"":"hidden"),children:[r.element_context&&e("button",{onClick:e=>{e.stopPropagation(),p?.(r)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-purple-600/20 border border-purple-500/40 rounded-md text-[11px] text-purple-300 font-medium hover:bg-purple-600/30 hover:border-purple-500/60 transition-all",children:[e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]}),t("span",{children:"Show on page"})]}),("completed"===r.status||"failed"===r.status)&&e("button",{onClick:e=>{e.stopPropagation(),b(S?null:r.id)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium transition-all "+(S?"bg-zinc-600 border border-zinc-500 text-zinc-100":"bg-zinc-700/50 border border-zinc-600/50 text-zinc-300 hover:bg-zinc-700 hover:border-zinc-500"),children:[t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})}),t("span",{children:S?"Hide output":"View output"})]}),t("button",{onClick:e=>{e.stopPropagation(),(async e=>{s===e?d?.(null):(d?.(e),m&&!o[e]&&await m(e))})(r.id)},className:"inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium transition-all ml-auto "+(i?"bg-zinc-700 text-zinc-200":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-300"),children:i?"Hide comments":(r.comment_count||0)>0?`💬 ${r.comment_count}`:"+ Comment"})]}),S&&t("div",{className:"px-3 pb-3 border-t border-zinc-800",children:t("div",{className:"mt-2 bg-zinc-950 rounded-md p-2 max-h-[150px] overflow-y-auto",children:_.length>0?t("div",{className:"font-mono text-[11px] space-y-0.5",children:_.slice(-20).map((e,r)=>t("div",{className:""+("stderr"===e.type?"text-red-400":"tool"===e.type?"text-blue-400":"thinking"===e.type?"text-zinc-500 italic":"system"===e.type?"text-yellow-400":"text-zinc-300"),children:e.content},r))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No output recorded for this prompt"})})}),i&&e("div",{className:"px-3 pb-3 pt-1 border-t border-zinc-800 space-y-3",children:[t(En,{comments:v,isLoading:c}),f&&t(Tn,{onSubmit:e=>f(r.id,e),placeholder:"Add a comment..."})]})]},r.id)})})}const On=400,Rn=500;function Nn({state:r,position:n,onClose:s,onMinimize:o,onSubmitPrompt:h,onSelectElement:u,onClearElement:d,onToggleConsole:p,onToggleNetwork:m,onTabChange:f,onExpandPrompt:g,onHighlightElement:w,onLoadComments:y,onAddComment:b,onOverlayModeChange:v}){const _=a(null),[k,x]=i(!1),[S,E]=i(!1),[T,C]=i(()=>an.get("position")||function(e){const t=20;switch(e){case"bottom-right":return{x:window.innerWidth-On-t,y:window.innerHeight-Rn-t};case"bottom-left":return{x:t,y:window.innerHeight-Rn-t};case"top-right":return{x:window.innerWidth-On-t,y:t};case"top-left":return{x:t,y:t}}}(n)),[O,R]=i(()=>an.get("size")||{width:On,height:Rn}),N=a({x:0,y:0}),$=a({width:0,height:0,x:0,y:0});const j=c(e=>{e.target.closest("button")||(x(!0),N.current={x:e.clientX-T.x,y:e.clientY-T.y})},[T]),I=c(e=>{e.stopPropagation(),E(!0),$.current={width:O.width,height:O.height,x:e.clientX,y:e.clientY}},[O]);return l(()=>{const e=e=>{if(k){const t=Math.max(0,Math.min(window.innerWidth-O.width,e.clientX-N.current.x)),r=Math.max(0,Math.min(window.innerHeight-O.height,e.clientY-N.current.y));C({x:t,y:r})}else if(S){const t=e.clientX-$.current.x,r=e.clientY-$.current.y,n=Math.max(320,$.current.width+t),s=Math.max(400,$.current.height+r);R({width:n,height:s})}},t=()=>{k&&(x(!1),an.set("position",T)),S&&(E(!1),an.set("size",O))};return(k||S)&&(document.addEventListener("mousemove",e),document.addEventListener("mouseup",t)),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[k,S,T,O]),e("div",{ref:_,className:"orquesta-embed-panel fixed z-[2147483647] bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl flex flex-col overflow-hidden",style:{left:T.x,top:T.y,width:O.width,height:O.height},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700 cursor-move select-none",onMouseDown:j,children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-lg",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"}),r.projectName&&e("span",{className:"text-xs text-zinc-400",children:["• ",r.projectName]})]}),e("div",{className:"flex items-center gap-1",children:[t(pn,{status:r.agentOnline?"online":"offline"}),e("div",{className:"flex items-center gap-0.5 mx-1 bg-zinc-800 rounded p-0.5",children:[t("button",{onClick:()=>v?.("off"),className:"p-1 rounded text-xs "+("off"===r.overlayMode?"bg-zinc-700 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Overlay off",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"})})}),t("button",{onClick:()=>v?.("single"),className:"p-1 rounded text-xs "+("single"===r.overlayMode?"bg-blue-600 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Show selected prompt on page",children:e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})}),t("button",{onClick:()=>v?.("all"),className:"p-1 rounded text-xs "+("all"===r.overlayMode?"bg-purple-600 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Show all prompts on page",children:e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 11a3 3 0 11-6 0 3 3 0 016 0z"})]})})]}),t("button",{onClick:o,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Minimize",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),t("button",{onClick:s,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Close",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),e(gn,{value:r.activeTab,onChange:e=>f(e),className:"flex-1 flex flex-col overflow-hidden",children:[t("div",{className:"px-3 py-2 border-b border-zinc-800",children:e(wn,{className:"w-full",children:[t(yn,{value:"prompts",children:"Prompts"}),t(yn,{value:"timeline",children:"Timeline"})]})}),e("div",{className:"flex-1 overflow-y-auto p-3",children:[e(bn,{value:"prompts",className:"h-full flex flex-col",children:[t(vn,{onSubmit:h,isSubmitting:r.isSubmitting,selectedElement:r.selectedElement,includeConsole:r.includeConsole,includeNetwork:r.includeNetwork,onToggleConsole:p,onToggleNetwork:m,onSelectElement:u,onClearElement:d,agentOnline:r.agentOnline}),(r.currentPrompt||r.outputLines.length>0)&&e("div",{className:"mt-4 pt-4 border-t border-zinc-800",children:[r.currentPrompt&&e("div",{className:"flex items-center gap-2 mb-2",children:[t(pn,{status:r.currentPrompt.status}),e("span",{className:"text-xs text-zinc-400 line-clamp-1",children:[r.currentPrompt.content.slice(0,50),"..."]})]}),t(_n,{lines:r.outputLines,isRunning:r.isSubmitting})]})]}),t(bn,{value:"timeline",children:t(Cn,{prompts:r.promptHistory,currentPromptId:r.currentPrompt?.id,expandedPromptId:r.expandedPromptId,comments:r.comments,isLoadingComments:r.isLoadingComments,promptOutputs:r.promptOutputs,onExpandPrompt:g,onHighlightElement:w,onLoadComments:y,onAddComment:b})})]})]}),t("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-se-resize",onMouseDown:I,children:t("svg",{className:"w-full h-full text-zinc-600",viewBox:"0 0 16 16",fill:"currentColor",children:t("path",{d:"M14 14H10V10H14V14ZM14 8H12V6H14V8ZM8 14H6V12H8V14Z"})})})]})}function $n({isActive:r,onCancel:n}){const s=a(null);return l(()=>{const e=e=>{"Escape"===e.key&&r&&n()};return r&&document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[r,n]),r?t("div",{ref:s,className:"orquesta-element-inspector fixed inset-0 z-[2147483645] pointer-events-none",children:t("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 pointer-events-auto",children:e("div",{className:"flex items-center gap-3 px-4 py-2 bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl",children:[t("span",{className:"text-sm text-zinc-300",children:"Click on any element to select it, or right-click for options"}),t(cn,{variant:"ghost",size:"sm",onClick:n,children:"Cancel (Esc)"})]})})}):null}function jn({markers:r,onMarkerClick:n}){const[s,o]=i([]),[h,u]=i(null),d=a(null),p=c(()=>{d.current&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{const e=window.innerHeight,t=window.innerWidth,n=[];for(const s of r)try{const r=document.querySelector(s.selector);if(r){const i=r.getBoundingClientRect(),o=i.left+i.width/2,a=i.top+i.height/2,l=i.top<e&&i.bottom>0&&i.left<t&&i.right>0;n.push({promptId:s.promptId,x:o,y:a,visible:!0,inViewport:l})}else n.push({promptId:s.promptId,x:0,y:0,visible:!1,inViewport:!1})}catch{n.push({promptId:s.promptId,x:0,y:0,visible:!1,inViewport:!1})}o(n)})},[r]);l(()=>{p();let e=!1;const t=()=>{e||(e=!0,requestAnimationFrame(()=>{p(),e=!1}))};window.addEventListener("scroll",t,!0),window.addEventListener("resize",t);const r=new MutationObserver(t);return r.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),()=>{window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t),r.disconnect(),d.current&&cancelAnimationFrame(d.current)}},[p]);const m=h?r.find(e=>e.promptId===h):null,f=h?s.find(e=>e.promptId===h):null;return e("div",{className:"orquesta-markers-overlay fixed inset-0 pointer-events-none z-[2147483646]",children:[s.map((s,i)=>{if(!s.visible||!s.inViewport)return null;const o=r.find(e=>e.promptId===s.promptId);if(!o)return null;const a=h===s.promptId;return e("div",{className:"absolute pointer-events-auto",style:{left:s.x,top:s.y,transform:"translate(-50%, -50%)"},children:[e("button",{onClick:()=>n?.(s.promptId),onMouseEnter:()=>u(s.promptId),onMouseLeave:()=>u(null),className:"relative flex items-center gap-1.5 px-2 py-1 rounded-full border-2 shadow-lg transition-all "+(a?"bg-purple-500 border-white scale-110":"bg-purple-600 border-white/80 hover:scale-105"),children:[t("span",{className:"w-5 h-5 flex items-center justify-center bg-white/20 rounded-full text-white text-[10px] font-bold",children:i+1}),e("span",{className:"text-white text-[11px] font-medium max-w-[120px] truncate",children:[o.content.slice(0,25),o.content.length>25?"...":""]})]}),t("div",{className:"absolute inset-0 -z-10 animate-ping rounded-full bg-purple-500/30",style:{animationDuration:"2s"}})]},s.promptId)}),m&&f&&f.visible&&f.inViewport&&e("div",{className:"fixed pointer-events-none bg-zinc-900 border border-zinc-600 rounded-xl shadow-2xl p-4 z-20",style:{...(e=>{let t=e.x+20,r=e.y+20;return t+280>window.innerWidth-20&&(t=e.x-280-20),r+180>window.innerHeight-20&&(r=e.y-180-20),{left:t,top:r}})(f),width:280},children:[e("div",{className:"flex items-center justify-between mb-3",children:[e("div",{className:"flex items-center gap-2",children:[t(kn,{author:m.author,size:"sm"}),t("span",{className:"text-xs font-medium text-zinc-200",children:m.author?.full_name||"Unknown"})]}),e("span",{className:"px-2 py-0.5 bg-blue-500/20 border border-blue-500/30 rounded text-[10px] text-blue-400 font-mono",children:["🎯 ",m.selector.split(" ").pop()?.split(".")[0]||"element"]})]}),e("p",{className:"text-sm text-zinc-200 mb-3 line-clamp-3",children:[m.content.slice(0,150),m.content.length>150&&"..."]}),e("div",{className:"flex items-center gap-3 text-[10px] text-zinc-500",children:[m.gitCommitSha&&e("span",{className:"inline-flex items-center gap-1 font-mono bg-zinc-800 px-1.5 py-0.5 rounded",children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})}),m.gitCommitSha.slice(0,7)]}),m.commentCount>0&&e("span",{className:"inline-flex items-center gap-1",children:["💬 ",m.commentCount," comments"]})]}),t("div",{className:"mt-3 pt-2 border-t border-zinc-800 text-[10px] text-zinc-500 text-center",children:"Click to view in timeline"})]})]})}function In({isOpen:r,position:n,element:s,agentOnline:o,includeConsole:c,includeNetwork:h,onSubmit:u,onClose:d,onToggleConsole:p,onToggleNetwork:m,onOpenPanel:f}){const[g,w]=i(""),[y,b]=i(!1),v=a(null),_=a(null);if(l(()=>{r&&_.current&&setTimeout(()=>_.current?.focus(),50)},[r]),l(()=>{if(r&&v.current){const e=v.current,t=e.getBoundingClientRect(),r=window.innerWidth,n=window.innerHeight;t.right>r-20&&(e.style.left=`${Math.max(20,r-t.width-20)}px`),t.bottom>n-20&&(e.style.top=`${Math.max(20,n-t.height-20)}px`)}},[r,n]),l(()=>{if(!r)return;const e=e=>{v.current&&!v.current.contains(e.target)&&d()},t=e=>{"Escape"===e.key&&d()};return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)}},[r,d]),l(()=>{r&&(w(""),b(!1))},[r]),!r||!s)return null;const k=async e=>{e.preventDefault(),g.trim()&&!y&&o&&(b(!0),u(g.trim()),w(""),setTimeout(()=>{d()},100))};return e("div",{ref:v,id:"orquesta-context-menu",style:{position:"fixed",zIndex:2147483647,backgroundColor:"#18181b",border:"1px solid #52525b",borderRadius:"12px",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.5)",overflow:"hidden",left:n.x,top:n.y,width:340,maxWidth:"calc(100vw - 40px)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',color:"#ffffff"},onClick:e=>e.stopPropagation(),children:[e("div",{style:{padding:"10px 12px",backgroundColor:"#27272a",borderBottom:"1px solid #3f3f46"},children:[e("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"6px"},children:[t("div",{style:{width:"24px",height:"24px",borderRadius:"6px",backgroundColor:"rgba(37, 99, 235, 0.2)",border:"1px solid rgba(59, 130, 246, 0.3)",display:"flex",alignItems:"center",justifyContent:"center"},children:t("span",{style:{color:"#60a5fa",fontSize:"14px"},children:"🎯"})}),t("span",{style:{fontSize:"14px",fontWeight:500,color:"#ffffff"},children:"Selected Element"})]}),t("div",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",color:"#a1a1aa",backgroundColor:"rgba(24, 24, 27, 0.5)",padding:"6px 8px",borderRadius:"6px",wordBreak:"break-all"},children:(()=>{const e=[];if(e.push(`<${s.tag}`),s.id&&e.push(` id="${s.id}"`),s.className){const t=s.className.split(" ").slice(0,2).join(" ");e.push(` class="${t}${s.className.split(" ").length>2?"...":""}"`)}if(e.push(">"),s.textContent){const t=s.textContent.slice(0,30);e.push(t+(s.textContent.length>30?"...":""))}return e.push(`</${s.tag}>`),e.join("")})()})]}),e("form",{onSubmit:k,style:{padding:"12px"},children:[t("textarea",{ref:_,value:g,onChange:e=>w(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&k(e)},placeholder:o?"What do you want to do with this element?":"Agent is offline...",disabled:y||!o,rows:3,style:{width:"100%",padding:"8px 10px",backgroundColor:"#09090b",border:"1px solid #3f3f46",borderRadius:"6px",color:"#ffffff",fontSize:"13px",fontFamily:"inherit",resize:"vertical",outline:"none",boxSizing:"border-box"}}),e("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:[e("button",{type:"button",onClick:p,style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"all 0.15s ease",backgroundColor:c?"rgba(234, 179, 8, 0.2)":"#27272a",color:c?"#fde047":"#a1a1aa",border:c?"1px solid rgba(234, 179, 8, 0.3)":"1px solid #3f3f46"},children:[t("span",{children:"📋"}),t("span",{children:"Logs"}),c&&t("span",{style:{marginLeft:"2px",color:"#facc15"},children:"✓"})]}),e("button",{type:"button",onClick:m,style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"all 0.15s ease",backgroundColor:h?"rgba(239, 68, 68, 0.2)":"#27272a",color:h?"#fca5a5":"#a1a1aa",border:h?"1px solid rgba(239, 68, 68, 0.3)":"1px solid #3f3f46"},children:[t("span",{children:"🌐"}),t("span",{children:"Network"}),h&&t("span",{style:{marginLeft:"2px",color:"#f87171"},children:"✓"})]})]}),e("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:"12px",paddingTop:"12px",borderTop:"1px solid #27272a"},children:[t("button",{type:"button",onClick:f,style:{fontSize:"12px",color:"#a1a1aa",background:"none",border:"none",cursor:"pointer",padding:0},children:"Open full panel →"}),e("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t("button",{type:"button",onClick:d,style:{padding:"6px 12px",borderRadius:"6px",fontSize:"12px",fontWeight:500,cursor:"pointer",backgroundColor:"transparent",color:"#d4d4d8",border:"none"},children:"Cancel"}),t("button",{type:"submit",disabled:!g.trim()||!o||y,style:{padding:"6px 12px",borderRadius:"6px",fontSize:"12px",fontWeight:500,cursor:g.trim()&&o&&!y?"pointer":"not-allowed",backgroundColor:g.trim()&&o&&!y?"#2563eb":"#3f3f46",color:"#ffffff",border:"none",opacity:g.trim()&&o&&!y?1:.5},children:y?"Submitting...":"Submit"})]})]}),e("div",{style:{marginTop:"8px",fontSize:"10px",color:"#71717a",textAlign:"center"},children:["Press ",t("kbd",{style:{padding:"2px 4px",backgroundColor:"#27272a",borderRadius:"4px"},children:"⌘/Ctrl + Enter"})," to submit"]})]})]})}function An({isConnected:r,agentOnline:n,projectName:s,currentPrompt:o,isSubmitting:a,lastCompletedPrompt:c,onClose:h}){const[u,d]=i(!0),[p,m]=i(!1),f=r?n?a||"running"===o?.status?"running":"completed"===o?.status?"completed":"failed"===o?.status?"failed":"idle":"offline":"connecting";if(l(()=>{"running"!==f&&"completed"!==f&&"failed"!==f||(d(!0),m(!1))},[f]),l(()=>{if("completed"===f||"failed"===f){const e=setTimeout(()=>{m(!0)},5e3);return()=>clearTimeout(e)}},[f,o?.id]),!u)return null;const g=(()=>{switch(f){case"connecting":return{bg:"#27272a",border:"#3f3f46",icon:"⟳",iconBg:"#3f3f46",text:"Connecting to Orquesta...",pulse:!0};case"offline":return{bg:"#27272a",border:"#ef4444",icon:"○",iconBg:"#7f1d1d",text:"Agent offline",pulse:!1};case"running":return{bg:"#172554",border:"#3b82f6",icon:"⟳",iconBg:"#1d4ed8",text:`Running: ${o?.content.slice(0,50)}${(o?.content.length||0)>50?"...":""}`,pulse:!0};case"completed":return{bg:"#14532d",border:"#22c55e",icon:"✓",iconBg:"#15803d",text:"Completed"+(o?.git_commit_sha?` • Commit ${o.git_commit_sha.slice(0,7)}`:""),pulse:!1};case"failed":return{bg:"#450a0a",border:"#ef4444",icon:"✕",iconBg:"#b91c1c",text:"Prompt failed",pulse:!1};default:return{bg:"#18181b",border:"#3f3f46",icon:"⬡",iconBg:"#27272a",text:s?`${s} • Ready`:"Orquesta Ready",pulse:!1}}})();return e("div",p?{id:"orquesta-status-bar-minimized",onClick:()=>m(!1),style:{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:2147483646,display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:g.bg,border:`1px solid ${g.border}`,borderRadius:"20px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",cursor:"pointer",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',transition:"all 0.2s ease"},children:[t("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"completed"===f?"#22c55e":"failed"===f?"#ef4444":"running"===f?"#3b82f6":"#71717a",animation:g.pulse?"pulse 2s infinite":"none"}}),t("span",{style:{fontSize:"11px",color:"#d4d4d8",fontWeight:500},children:"Orquesta"}),t("style",{children:"\n @keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n "})]}:{id:"orquesta-status-bar",style:{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:2147483646,display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px 8px 10px",backgroundColor:g.bg,border:`1px solid ${g.border}`,borderRadius:"10px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',maxWidth:"calc(100vw - 40px)",transition:"all 0.3s ease"},children:[t("div",{style:{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:g.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t("span",{style:{fontSize:"14px",color:"#ffffff",animation:g.pulse?"spin 1s linear infinite":"none"},children:g.icon})}),e("div",{style:{flex:1,minWidth:0},children:[t("div",{style:{fontSize:"12px",fontWeight:500,color:"#ffffff",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"400px"},children:g.text}),"running"===f&&t("div",{style:{marginTop:"4px",height:"3px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"2px",overflow:"hidden"},children:t("div",{style:{height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",animation:"progress 2s ease-in-out infinite"}})})]}),"completed"===f&&o?.git_branch&&e("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"4px",flexShrink:0},children:[t("svg",{style:{width:"12px",height:"12px",color:"#a1a1aa"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})}),t("span",{style:{fontSize:"11px",color:"#a1a1aa",fontFamily:"ui-monospace, monospace"},children:o.git_branch})]}),t("button",{onClick:()=>m(!0),style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",flexShrink:0},title:"Minimize",children:t("svg",{style:{width:"14px",height:"14px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),t("button",{onClick:()=>{d(!1),h()},style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",flexShrink:0},title:"Close",children:t("svg",{style:{width:"14px",height:"14px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),t("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes progress {\n 0% { width: 0%; margin-left: 0%; }\n 50% { width: 40%; margin-left: 30%; }\n 100% { width: 0%; margin-left: 100%; }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n "})]})}const Pn=[{id:"demo-1",full_name:"Sarah Chen",avatar_url:null},{id:"demo-2",full_name:"Mike Johnson",avatar_url:null},{id:"demo-3",full_name:"Alex Rivera",avatar_url:null}],Ln=[{id:"demo-prompt-1",content:'Change the "Shop Now" button color to green and add a hover animation',status:"completed",created_at:new Date(Date.now()-72e5).toISOString(),completed_at:new Date(Date.now()-72e5+45e3).toISOString(),user_id:"demo-1",source:"embed",element_context:{selector:"button.bg-blue-600",tag:"button",className:"px-6 py-3 bg-blue-600 text-white rounded-lg font-medium",textContent:"Shop Now"},author:Pn[0],git_branch:"main",git_commit_sha:"a1b2c3d",comment_count:2},{id:"demo-prompt-2",content:'Add a discount badge showing "20% OFF" to the Premium Headphones card',status:"completed",created_at:new Date(Date.now()-36e5).toISOString(),completed_at:new Date(Date.now()-36e5+32e3).toISOString(),user_id:"demo-2",source:"embed",element_context:{selector:"div.bg-gradient-to-br.from-purple-400",tag:"div",className:"bg-gradient-to-br from-purple-400 to-purple-600 h-48 relative",textContent:"Best Seller"},author:Pn[1],git_branch:"feature/product-badges",git_commit_sha:"e4f5g6h",comment_count:1},{id:"demo-prompt-3",content:"Make the contact form email field validate on blur and show error message",status:"completed",created_at:new Date(Date.now()-18e5).toISOString(),completed_at:new Date(Date.now()-18e5+28e3).toISOString(),user_id:"demo-3",source:"embed",element_context:{selector:'input[type="email"]',tag:"input",className:"w-full px-4 py-2 border border-gray-300 rounded-lg",textContent:""},author:Pn[2],git_branch:"main",git_commit_sha:"i7j8k9l",comment_count:0}],Un={"demo-prompt-1":[{id:"comment-1",content:"Looks great! The animation is smooth.",created_at:new Date(Date.now()-54e5).toISOString(),author:Pn[1]},{id:"comment-2",content:"Could we also add this to the Learn More button?",created_at:new Date(Date.now()-36e5).toISOString(),author:Pn[2]}],"demo-prompt-2":[{id:"comment-3",content:"Perfect placement for the badge!",created_at:new Date(Date.now()-27e5).toISOString(),author:Pn[0]}]};function zn(n){const{children:s,enableGlobalRightClick:o=!0,demoMode:h=!1,...u}=n,[d,p]=i(null),[m,f]=i(h?{isConnected:!0,isConnecting:!1,connectionError:null,projectId:"demo-project",projectName:"Demo Store",agentOnline:!0,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,currentPrompt:null,promptHistory:[...Ln],isSubmitting:!1,outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{...Un},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1}:null),[g,w]=i(!1),[y,b]=i(null),[v,_]=i({isOpen:!1,position:{x:0,y:0},element:null}),[k,x]=i(!0),[S,E]=i(null),T=a(null),C=a(null);a(null),l(()=>{"completed"!==m?.currentPrompt?.status&&"failed"!==m?.currentPrompt?.status||E(m.currentPrompt)},[m?.currentPrompt?.status,m?.currentPrompt]),l(()=>{if(h)return C.current=new rn,o&&C.current&&(T.current=C.current.setupGlobalRightClickWithPosition((e,t)=>{C.current&&C.current.highlightSelectedElement(e.selector),_({isOpen:!0,position:t,element:e})})),()=>{T.current&&(T.current(),T.current=null)}},[h,o]),l(()=>{if(h)return;const e=new ln(u);p(e);const t=e.subscribe(e=>{f(e)});return e.connect().catch(e=>{b(e.message)}),o&&(T.current=e.setupGlobalRightClickWithPosition((t,r)=>{e.getElementSelector().deactivate(),e.getElementSelector().highlightSelectedElement(t.selector),_({isOpen:!0,position:r,element:t})})),()=>{t(),T.current&&(T.current(),T.current=null),e.disconnect()}},[u.token,o,h]);const O=c(()=>{h?f(e=>e?{...e,isOpen:!1}:null):d?.close()},[d,h]),R=c(()=>{w(!0)},[]),N=c(()=>{w(!1),h?f(e=>e?{...e,isOpen:!0}:null):d?.open()},[d,h]),$=c(async(e,t)=>{if(h){const r=t||m?.selectedElement||void 0,n={id:`demo-prompt-${Date.now()}`,content:e,status:"running",created_at:(new Date).toISOString(),user_id:"demo-user",source:"embed",element_context:r,author:{id:"demo-user",full_name:"Demo User",avatar_url:null},comment_count:0};f(e=>e?{...e,isSubmitting:!0,currentPrompt:n,outputLines:[],promptHistory:[n,...e.promptHistory]}:null);return[{delay:200,type:"system",content:"Starting Claude CLI session..."},{delay:600,type:"thinking",content:"Analyzing the request..."},{delay:1e3,type:"stdout",content:`Processing: "${e.slice(0,50)}${e.length>50?"...":""}"`},{delay:1400,type:"tool",content:"Tool: Edit file"},{delay:1800,type:"stdout",content:"Changes applied successfully."}].forEach(({delay:e,type:t,content:r})=>{setTimeout(()=>{f(e=>e?{...e,outputLines:[...e.outputLines,{id:`output-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,timestamp:Date.now(),type:t,content:r}]}:null)},e)}),void setTimeout(()=>{f(e=>{if(!e)return null;const t={...n,status:"completed",completed_at:(new Date).toISOString(),git_branch:"main",git_commit_sha:Math.random().toString(36).slice(2,9)},r=[...e.outputLines,{id:`output-${Date.now()}-complete`,timestamp:Date.now(),type:"system",content:"Prompt completed successfully."}];return{...e,isSubmitting:!1,currentPrompt:t,selectedElement:null,outputLines:r,promptOutputs:{...e.promptOutputs,[n.id]:r},promptHistory:e.promptHistory.map(e=>e.id===n.id?t:e)}})},2200)}if(d)try{await d.submitPrompt(e,{elementContext:t||void 0})}catch(e){console.error("Failed to submit prompt:",e)}},[d,h,m?.selectedElement]),j=c(()=>{h?(f(e=>e?{...e,isSelectingElement:!0}:null),C.current?.activate(e=>{f(t=>t?{...t,selectedElement:e,isSelectingElement:!1}:null)},()=>{f(e=>e?{...e,isSelectingElement:!1}:null)})):d?.startElementSelection()},[d,h]),I=c(()=>{h?(f(e=>e?{...e,selectedElement:null}:null),C.current?.deactivate(),C.current?.removeSelectedHighlight()):d&&(f(e=>e?{...e,selectedElement:null}:null),d.getElementSelector().deactivate(),d.getElementSelector().removeSelectedHighlight())},[d,h]),A=c(()=>{m&&f(e=>e?{...e,includeConsole:!e.includeConsole}:null)},[m]),P=c(()=>{m&&f(e=>e?{...e,includeNetwork:!e.includeNetwork}:null)},[m]),L=c(e=>{m&&(f(t=>t?{...t,activeTab:e}:null),an.set("activeTab",e))},[m]),U=c(()=>{h?(C.current?.deactivate(),f(e=>e?{...e,isSelectingElement:!1}:null)):d?.getElementSelector().deactivate()},[d,h]),z=c(e=>{m&&f(t=>t?{...t,expandedPromptId:e}:null)},[m]),D=c(e=>{h?e.element_context?.selector&&(C.current?.highlightElement(e.element_context.selector),f(t=>t?{...t,overlayMode:"single",highlightedPromptId:e.id}:null)):d?.highlightPromptElement(e)},[d,h]),H=c(async e=>{h||d&&await d.loadComments(e)},[d,h]),B=c(async(e,t)=>{if(h){const r={id:`comment-${Date.now()}`,content:t,created_at:(new Date).toISOString(),author:{id:"demo-user",full_name:"Demo User",avatar_url:null}};return void f(t=>{if(!t)return null;const n=t.comments[e]||[];return{...t,comments:{...t.comments,[e]:[...n,r]},promptHistory:t.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)}})}d&&await d.addComment(e,t)},[d,h]),q=c(e=>{h?f(t=>{if(!t)return null;let r=t.elementMarkers;return"all"===e?r=t.promptHistory.filter(e=>e.element_context?.selector).map(e=>{const t=document.querySelector(e.element_context.selector);return{promptId:e.id,selector:e.element_context.selector,rect:t?.getBoundingClientRect()||null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}}):"off"===e&&(C.current?.removeHighlight(),r=[]),{...t,overlayMode:e,highlightedPromptId:"off"===e?null:t.highlightedPromptId,elementMarkers:r}}):d?.setOverlayMode(e)},[d,h]),M=c(e=>{m&&f(t=>t?{...t,activeTab:"timeline",expandedPromptId:e}:null)},[m]),W=c(()=>{_(e=>({...e,isOpen:!1})),h&&C.current?C.current.removeSelectedHighlight():d&&d.getElementSelector().removeSelectedHighlight()},[d,h]),K=c(async e=>{v.element&&(f(e=>e?{...e,selectedElement:v.element,isOpen:!0,activeTab:"prompts"}:null),w(!1),await $(e,v.element||void 0),_(e=>({...e,isOpen:!1})))},[v.element,$]),F=c(()=>{v.element&&(f(e=>e?{...e,selectedElement:v.element,isOpen:!0,activeTab:"prompts"}:null),w(!1),_(e=>({...e,isOpen:!1})))},[v.element]);return y?e("div",{className:"orquesta-embed-error fixed bottom-4 right-4 z-[2147483647] p-4 bg-red-900/90 border border-red-700 rounded-lg text-white text-sm max-w-xs",children:[t("div",{className:"font-semibold mb-1",children:"Orquesta Error"}),t("div",{className:"text-red-200",children:y})]}):!m||m.isConnecting?t("div",{className:"orquesta-embed-loading fixed bottom-4 right-4 z-[2147483647] p-4 bg-zinc-900 border border-zinc-700 rounded-lg text-white text-sm",children:e("div",{className:"flex items-center gap-2",children:[e("svg",{className:"animate-spin h-4 w-4",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{children:"Connecting to Orquesta..."})]})}):e(r,{children:[k&&t(An,{isConnected:m.isConnected,agentOnline:m.agentOnline,projectName:m.projectName,currentPrompt:m.currentPrompt,isSubmitting:m.isSubmitting,lastCompletedPrompt:S,onClose:()=>x(!1)}),(g||!m.isOpen)&&e("button",{onClick:N,className:"orquesta-embed-trigger fixed z-[2147483647] p-3 bg-zinc-900 border border-zinc-700 rounded-full shadow-xl hover:bg-zinc-800 transition-colors",style:{[u.position?.includes("right")?"right":"left"]:"20px",[u.position?.includes("top")?"top":"bottom"]:"20px"},title:"Open Orquesta",children:[t("span",{className:"text-xl",children:"⬡"}),m.agentOnline&&t("span",{className:"absolute top-1 right-1 w-2 h-2 bg-green-500 rounded-full"})]}),m.isOpen&&!g&&t(Nn,{state:m,position:u.position||"bottom-right",onClose:O,onMinimize:R,onSubmitPrompt:$,onSelectElement:j,onClearElement:I,onToggleConsole:A,onToggleNetwork:P,onTabChange:L,onExpandPrompt:z,onHighlightElement:D,onLoadComments:H,onAddComment:B,onOverlayModeChange:q}),t($n,{isActive:m.isSelectingElement,onCancel:U}),"all"===m.overlayMode&&m.elementMarkers.length>0&&t(jn,{markers:m.elementMarkers,onMarkerClick:M}),t(In,{isOpen:v.isOpen,position:v.position,element:v.element,agentOnline:m.agentOnline,includeConsole:m.includeConsole,includeNetwork:m.includeNetwork,onSubmit:K,onClose:W,onToggleConsole:A,onToggleNetwork:P,onOpenPanel:F}),s]})}export{kn as AuthorAvatar,dn as Badge,cn as Button,Tn as CommentInput,En as CommentList,en as ConsoleCapture,$n as ElementInspector,jn as ElementMarkers,rn as ElementSelector,Nn as EmbedPanel,xn as GitCommitLink,hn as Input,_n as LogStream,tn as NetworkCapture,zn as OrquestaEmbed,ln as OrquestaEmbedClient,vn as PromptInput,Zr as StateManager,pn as StatusDot,gn as Tabs,bn as TabsContent,wn as TabsList,yn as TabsTrigger,un as Textarea,Cn as Timeline,an as storage};
|
|
1
|
+
import{jsxs as e,jsx as t,Fragment as r}from"react/jsx-runtime";import s,{createContext as n,useState as i,useContext as o,useRef as a,useEffect as l,useCallback as c}from"react";function h(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(r[s[n]]=e[s[n]])}return r}function u(e,t,r,s){return new(r||(r=Promise))(function(n,i){function o(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}l((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class d extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class p extends d{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class m extends d{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class g extends d{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var f;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(f||(f={}));class w{constructor(e,{headers:t={},customFetch:r,region:s=f.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return u(this,arguments,void 0,function*(e,t={}){var r;let s,n;try{const{headers:i,method:o,body:a,signal:l,timeout:c}=t;let h={},{region:u}=t;u||(u=this.region);const d=new URL(`${this.url}/${e}`);let f;u&&"any"!==u&&(h["x-region"]=u,d.searchParams.set("forceFunctionRegion",u)),a&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)?"undefined"!=typeof Blob&&a instanceof Blob||a instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",f=a):"string"==typeof a?(h["Content-Type"]="text/plain",f=a):"undefined"!=typeof FormData&&a instanceof FormData?f=a:(h["Content-Type"]="application/json",f=JSON.stringify(a)):f=!a||"string"==typeof a||"undefined"!=typeof Blob&&a instanceof Blob||a instanceof ArrayBuffer||"undefined"!=typeof FormData&&a instanceof FormData?a:JSON.stringify(a);let w=l;c&&(n=new AbortController,s=setTimeout(()=>n.abort(),c),l?(w=n.signal,l.addEventListener("abort",()=>n.abort())):w=n.signal);const y=yield this.fetch(d.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),i),body:f,signal:w}).catch(e=>{throw new p(e)}),b=y.headers.get("x-relay-error");if(b&&"true"===b)throw new m(y);if(!y.ok)throw new g(y);let v,_=(null!==(r=y.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return v="application/json"===_?yield y.json():"application/octet-stream"===_||"application/pdf"===_?yield y.blob():"text/event-stream"===_?y:"multipart/form-data"===_?yield y.formData():yield y.text(),{data:v,error:null,response:y}}catch(e){return{data:null,error:e,response:e instanceof g||e instanceof m?e.context:void 0}}finally{s&&clearTimeout(s)}})}}var y=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},b=class{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let s=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,s=null,n=null,i=e.status,o=e.statusText;if(e.ok){var a,l;if("HEAD"!==r.method){var c;const t=await e.text();""===t||(s="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null===(c=r.headers.get("Accept"))||void 0===c?void 0:c.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}const h=null===(a=r.headers.get("Prefer"))||void 0===a?void 0:a.match(/count=(exact|planned|estimated)/),u=null===(l=e.headers.get("content-range"))||void 0===l?void 0:l.split("/");h&&u&&u.length>1&&(n=parseInt(u[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(s)&&(s.length>1?(t={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,o="Not Acceptable"):s=1===s.length?s[0]:null)}else{var h;const n=await e.text();try{t=JSON.parse(n),Array.isArray(t)&&404===e.status&&(s=[],t=null,i=200,o="OK")}catch(r){404===e.status&&""===n?(i=204,o="No Content"):t={message:n}}if(t&&r.isMaybeSingle&&(null==t||null===(h=t.details)||void 0===h?void 0:h.includes("0 rows"))&&(t=null,i=200,o="OK"),t&&r.shouldThrowOnError)throw new y(t)}return{error:t,data:s,count:n,status:i,statusText:o}});return this.shouldThrowOnError||(s=s.catch(e=>{var t;let r="";const s=null==e?void 0:e.cause;if(s){var n,i,o,a;const t=null!==(n=null==s?void 0:s.message)&&void 0!==n?n:"",l=null!==(i=null==s?void 0:s.code)&&void 0!==i?i:"";r=`${null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(a=null==s?void 0:s.name)&&void 0!==a?a:"Error"}: ${t}`,l&&(r+=` (${l})`),(null==s?void 0:s.stack)&&(r+=`\n${s.stack}`)}else{var l;r=null!==(l=null==e?void 0:e.stack)&&void 0!==l?l:""}return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},v=class extends b{select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){const n=void 0===s?"offset":`${s}.offset`,i=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.get("Accept"))&&void 0!==o?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const _=new RegExp("[,()]");var k=class extends v{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&_.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&_.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let n="";"plain"===s?n="pl":"phrase"===s?n="ph":"websearch"===s&&(n="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},x=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:s}=null!=t?t:{},n=r?"HEAD":"GET";let i=!1;const o=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),s&&l.append("Prefer",`count=${s}`),new k({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;const{url:n,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);n.searchParams.set("columns",e.join(","))}}return new k({method:"POST",url:n,headers:i,schema:this.schema,body:e,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const{url:o,headers:a}=this.cloneRequestState();if(a.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&o.searchParams.set("on_conflict",t),s&&a.append("Prefer",`count=${s}`),n||a.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);o.searchParams.set("columns",e.join(","))}}return new k({method:"POST",url:o,headers:a,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}update(e,{count:t}={}){var r;const{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new k({method:"PATCH",url:s,headers:n,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var t;const{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new k({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch})}},S=class e{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new x(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:n}={}){var i;let o;const a=new URL(`${this.url}/rpc/${e}`);let l;const c=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(c)),h=r&&Object.values(t).some(c);h?(o="POST",l=t):r||s?(o=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{a.searchParams.append(e,t)})):(o="POST",l=t);const u=new Headers(this.headers);return h?u.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&u.set("Prefer",`count=${n}`),new k({method:o,url:a,headers:u,schema:this.schemaName,body:l,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}};class E{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const t=globalThis.process;if(t){const e=t.versions;if(e&&e.node){const t=e.node,r=parseInt(t.replace(/^v/,"").split(".")[0]);return r>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const T="1.0.0",C=T,O=1e4;var R,N,A,$,j,I;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(R||(R={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(N||(N={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(A||(A={})),function(e){e.websocket="websocket"}($||($={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(j||(j={}));class P{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},n=(new TextEncoder).encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,r){var s,n;const i=e.topic,o=null!==(s=e.ref)&&void 0!==s?s:"",a=null!==(n=e.join_ref)&&void 0!==n?n:"",l=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(c).length?"":JSON.stringify(c);if(a.length>255)throw new Error(`joinRef length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+o.length+i.length+l.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+u);let p=new DataView(d),m=0;p.setUint8(m++,this.KINDS.userBroadcastPush),p.setUint8(m++,a.length),p.setUint8(m++,o.length),p.setUint8(m++,i.length),p.setUint8(m++,l.length),p.setUint8(m++,h.length),p.setUint8(m++,t),Array.from(a,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(o,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(i,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(l,e=>p.setUint8(m++,e.charCodeAt(0))),Array.from(h,e=>p.setUint8(m++,e.charCodeAt(0)));var g=new Uint8Array(d.byteLength+r.byteLength);return g.set(new Uint8Array(d),0),g.set(new Uint8Array(r),d.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const r=JSON.parse(e),[s,n,i,o,a]=r;return t({join_ref:s,ref:n,topic:i,event:o,payload:a})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){const s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),o=t.getUint8(4);let a=this.HEADER_LENGTH+4;const l=r.decode(e.slice(a,a+s));a+=s;const c=r.decode(e.slice(a,a+n));a+=n;const h=r.decode(e.slice(a,a+i));a+=i;const u=e.slice(a,e.byteLength),d=o===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:c,payload:d};return i>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class L{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(I||(I={}));const U=(e,t,r={})=>{var s;const n=null!==(s=r.skipTypes)&&void 0!==s?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=z(s,e,t,n),r),{}):{}},z=(e,t,r,s)=>{const n=t.find(t=>t.name===e),i=null==n?void 0:n.type,o=r[e];return i&&!s.includes(i)?D(i,o):H(o)},D=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return W(t,r)}switch(e){case I.bool:return q(t);case I.float4:case I.float8:case I.int2:case I.int4:case I.int8:case I.numeric:case I.oid:return B(t);case I.json:case I.jsonb:return M(t);case I.timestamp:return K(t);case I.abstime:case I.date:case I.daterange:case I.int4range:case I.int8range:case I.money:case I.reltime:case I.text:case I.time:case I.timestamptz:case I.timetz:case I.tsrange:case I.tstzrange:default:return H(t)}},H=e=>e,q=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},B=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},M=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},W=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;const n=e.slice(1,r);try{s=JSON.parse("["+n+"]")}catch(e){s=n?n.split(","):[]}return s.map(e=>D(t,e))}return e},K=e=>"string"==typeof e?e.replace(" ","T"):e,F=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class V{constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var J,G,X,Y;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(J||(J={}));class Q{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Q.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=Q.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=Q.syncDiff(this.state,e,t,r),s())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const n=this.cloneDeep(e),i=this.transformState(t),o={},a={};return this.map(n,(e,t)=>{i[e]||(a[e]=t)}),this.map(i,(e,t)=>{const r=n[e];if(r){const s=t.map(e=>e.presence_ref),n=r.map(e=>e.presence_ref),i=t.filter(e=>n.indexOf(e.presence_ref)<0),l=r.filter(e=>s.indexOf(e.presence_ref)<0);i.length>0&&(o[e]=i),l.length>0&&(a[e]=l)}else o[e]=t}),this.syncDiff(n,{joins:o,leaves:a},r,s)}static syncDiff(e,t,r,s){const{joins:n,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(t,s)=>{var n;const i=null!==(n=e[t])&&void 0!==n?n:[];if(e[t]=this.cloneDeep(s),i.length>0){const r=e[t].map(e=>e.presence_ref),s=i.filter(e=>r.indexOf(e.presence_ref)<0);e[t].unshift(...s)}r(t,i,s)}),this.map(i,(t,r)=>{let n=e[t];if(!n)return;const i=r.map(e=>e.presence_ref);n=n.filter(e=>i.indexOf(e.presence_ref)<0),e[t]=n,s(t,n,r),0===n.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return t[r]="metas"in s?s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(G||(G={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(X||(X={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(Y||(Y={}));class Z{constructor(e,t={config:{}},r){var s,n;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=N.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new V(this,A.join,this.params,this.timeout),this.rejoinTimer=new L(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=N.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=N.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=N.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=N.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=N.errored,this.rejoinTimer.scheduleTimeout())}),this._on(A.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Q(this),this.broadcastEndpointURL=F(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(n=null===(s=this.params.config)||void 0===s?void 0:s.broadcast)||void 0===n?void 0:n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,n;if(this.socket.isConnected()||this.socket.connect(),this.state==N.closed){const{config:{broadcast:i,presence:o,private:a}}=this.params,l=null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==s?s:[],c=!!this.bindings[X.PRESENCE]&&this.bindings[X.PRESENCE].length>0||!0===(null===(n=this.params.config.presence)||void 0===n?void 0:n.enabled),h={},u={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(Y.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(Y.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket._isManualToken()||this.socket.setAuth(),void 0!==t){const s=this.bindings.postgres_changes,n=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,i=[];for(let r=0;r<n;r++){const n=s[r],{filter:{event:o,schema:a,table:l,filter:c}}=n,h=t&&t[r];if(!(h&&h.event===o&&Z.isFilterValueEqual(h.schema,a)&&Z.isFilterValueEqual(h.table,l)&&Z.isFilterValueEqual(h.filter,c)))return this.unsubscribe(),this.state=N.errored,void(null==e||e(Y.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));i.push(Object.assign(Object.assign({},n),{id:h.id}))}return this.bindings.postgres_changes=i,void(e&&e(Y.SUBSCRIBED))}null==e||e(Y.SUBSCRIBED)}).receive("error",t=>{this.state=N.errored,null==e||e(Y.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(Y.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===N.joined&&e===X.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var s;if(null==t)return Promise.reject("Payload is required for httpSend()");const n={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(n.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:n,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!==(s=r.timeout)&&void 0!==s?s:this.timeout);if(202===o.status)return{success:!0};let a=o.statusText;try{const e=await o.json();a=e.error||e.message||a}catch(e){}return Promise.reject(new Error(a))}async send(e,t={}){var r,s;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,n,i;const o=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(n=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===n?void 0:n.broadcast)||void 0===i?void 0:i.ack)||r("ok"),o.receive("ok",()=>r("ok")),o.receive("error",()=>r("error")),o.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:n,payload:i}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:i,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(s=e.body)||void 0===s?void 0:s.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=N.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(A.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new V(this,A.leave,{},e),r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=N.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const s=new AbortController,n=setTimeout(()=>s.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),i}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new V(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;const i=e.toLocaleLowerCase(),{close:o,error:a,leave:l,join:c}=A;if(r&&[o,a,l,c].indexOf(i)>=0&&r!==this._joinRef())return;let h=this._onMessage(i,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null===(s=this.bindings.postgres_changes)||void 0===s||s.filter(e=>{var t,r,s;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(s=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===s?void 0:s.toLocaleLowerCase())===i}).map(e=>e.callback(h,r)):null===(n=this.bindings[i])||void 0===n||n.filter(e=>{var r,s,n,o,a,l,c,h;if(["broadcast","presence","postgres_changes"].includes(i)){if("id"in e){const i=e.id,l=null===(r=e.filter)||void 0===r?void 0:r.event;return i&&(null===(s=t.ids)||void 0===s?void 0:s.includes(i))&&("*"===l||(null==l?void 0:l.toLocaleLowerCase())===(null===(n=t.data)||void 0===n?void 0:n.type.toLocaleLowerCase()))&&(!(null===(o=e.filter)||void 0===o?void 0:o.table)||e.filter.table===(null===(a=t.data)||void 0===a?void 0:a.table))}{const r=null===(c=null===(l=null==e?void 0:e.filter)||void 0===l?void 0:l.event)||void 0===c?void 0:c.toLocaleLowerCase();return"*"===r||r===(null===(h=null==t?void 0:t.event)||void 0===h?void 0:h.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===i}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.data,{schema:t,table:r,commit_timestamp:s,type:n,errors:i}=e,o={schema:t,table:r,commit_timestamp:s,eventType:n,new:{},old:{},errors:i};h=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===N.closed}_isJoined(){return this.state===N.joined}_isJoining(){return this.state===N.joining}_isLeaving(){return this.state===N.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var s;return!((null===(s=e.type)||void 0===s?void 0:s.toLocaleLowerCase())===r&&Z.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(A.close,{},e)}_onError(e){this._on(A.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=N.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=U(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=U(e.columns,e.old_record)),t}}const ee=()=>{},te=25e3,re=10,se=100,ne=[1e3,2e3,5e3,1e4];class ie{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=O,this.transport=null,this.heartbeatIntervalMs=te,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ee,this.ref=0,this.reconnectTimer=null,this.vsn=C,this.logger=ee,this.conn=null,this.sendBuffer=[],this.serializer=new P,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${$.websocket}`,this.httpEndpoint=F(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=E.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case R.connecting:return j.Connecting;case R.open:return j.Open;case R.closing:return j.Closing;default:return j.Closed}}isConnected(){return this.connectionState()===j.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{const r=new Z(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){const{topic:t,event:r,payload:s,ref:n}=e,i=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${r} (${n})`,s),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},se)}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){const t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:t,event:r,payload:s,ref:n}=e,i=n?`(${n})`:"",o=s.status||"";this.log("receive",`${o} ${t} ${r} ${i}`.trim(),s),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,s,n)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===R.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===R.open||this.conn.readyState===R.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`);(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(A.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const r={access_token:t,version:"realtime-js/2.90.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(A.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new L(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},re)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,n,i,o,a,l,c,h,u,d;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(r=null==e?void 0:e.timeout)&&void 0!==r?r:O,this.heartbeatIntervalMs=null!==(s=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==s?s:te,this.worker=null!==(n=null==e?void 0:e.worker)&&void 0!==n&&n,this.accessToken=null!==(i=null==e?void 0:e.accessToken)&&void 0!==i?i:null,this.heartbeatCallback=null!==(o=null==e?void 0:e.heartbeatCallback)&&void 0!==o?o:ee,this.vsn=null!==(a=null==e?void 0:e.vsn)&&void 0!==a?a:C,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(l=null==e?void 0:e.reconnectAfterMs)&&void 0!==l?l:e=>ne[e-1]||1e4,this.vsn){case T:this.encode=null!==(c=null==e?void 0:e.encode)&&void 0!==c?c:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:(e,t)=>t(JSON.parse(e));break;case"2.0.0":this.encode=null!==(u=null==e?void 0:e.encode)&&void 0!==u?u:this.serializer.encode.bind(this.serializer),this.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}var oe=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function ae(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:o}){const a=function(e,t,r){const s=new URL(t,e);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,n),l=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),c=await t(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),h=await c.text(),u=(c.headers.get("content-type")||"").includes("application/json"),d=u&&h?JSON.parse(h):h;if(!c.ok){const e=u?d:void 0,t=e?.error;throw new oe(t?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:c.status,headers:c.headers,data:d}}}}function le(e){return e.join("")}var ce=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:le(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${le(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${le(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${le(e.namespace)}`}),!0}catch(e){if(e instanceof oe&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof oe&&409===e.status)return;throw e}}};function he(e){return e.join("")}var ue=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${he(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof oe&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof oe&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},de=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=ae({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new ce(this.client,t),this.tableOps=new ue(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},pe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function me(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var ge=class extends pe{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},fe=class extends pe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};const we=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),ye=e=>{if(Array.isArray(e))return e.map(e=>ye(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const s=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[s]=ye(r)}),t};function be(e){return(be="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ve(e){var t=function(e,t){if("object"!=be(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t);if("object"!=be(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==be(t)?t:t+""}function _e(e,t,r){return(t=ve(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ke(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function xe(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ke(Object(r),!0).forEach(function(t){_e(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ke(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const Se=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)},Ee=async(e,t,r)=>{e instanceof await Response&&!(null==r?void 0:r.noResolveJson)?e.json().then(r=>{const s=e.status||500,n=(null==r?void 0:r.statusCode)||s+"";t(new ge(Se(r),s,n))}).catch(e=>{t(new fe(Se(e),e))}):t(new fe(Se(e),e))},Te=(e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(n.headers=xe({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s)):n.body=s,(null==t?void 0:t.duplex)&&(n.duplex=t.duplex),xe(xe({},n),r)):n};async function Ce(e,t,r,s,n,i){return new Promise((o,a)=>{e(r,Te(t,s,n,i)).then(e=>{if(!e.ok)throw e;return(null==s?void 0:s.noResolveJson)?e:e.json()}).then(e=>o(e)).catch(e=>Ee(e,a,s))})}async function Oe(e,t,r,s){return Ce(e,"GET",t,r,s)}async function Re(e,t,r,s,n){return Ce(e,"POST",t,s,n,r)}async function Ne(e,t,r,s,n){return Ce(e,"PUT",t,s,n,r)}async function Ae(e,t,r,s,n){return Ce(e,"DELETE",t,s,n,r)}var $e=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}};let je;je=Symbol.toStringTag;var Ie=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[je]="BlobDownloadBuilder",this.promise=null}asStream(){return new $e(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}};const Pe={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Le={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Ue=class{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=we(s)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(e,t,r,s){var n=this;try{let i;const o=xe(xe({},Le),s);let a=xe(xe({},n.headers),"POST"===e&&{"x-upsert":String(o.upsert)});const l=o.metadata;"undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!o.duplex&&(o.duplex="half")),(null==s?void 0:s.headers)&&(a=xe(xe({},a),s.headers));const c=n._removeEmptyFolders(t),h=n._getFinalPath(c),u=await("PUT"==e?Ne:Re)(n.fetch,`${n.url}/object/${h}`,i,xe({headers:a},(null==o?void 0:o.duplex)?{duplex:o.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var n=this;const i=n._removeEmptyFolders(e),o=n._getFinalPath(i),a=new URL(n.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let e;const t=xe({upsert:Le.upsert},s),o=xe(xe({},n.headers),{"x-upsert":String(t.upsert)});return"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,o["cache-control"]=`max-age=${t.cacheControl}`,o["content-type"]=t.contentType),{data:{path:i,fullPath:(await Ne(n.fetch,a.toString(),e,{headers:o})).Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async createSignedUploadUrl(e,t){var r=this;try{let s=r._getFinalPath(e);const n=xe({},r.headers);(null==t?void 0:t.upsert)&&(n["x-upsert"]="true");const i=await Re(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new pe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;try{return{data:await Re(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async copy(e,t,r){var s=this;try{return{data:{path:(await Re(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers})).Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async createSignedUrl(e,t,r){var s=this;try{let n=s._getFinalPath(e),i=await Re(s.fetch,`${s.url}/object/sign/${n}`,xe({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:s.headers});const o=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${s.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async createSignedUrls(e,t,r){var s=this;try{const n=await Re(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:n.map(e=>xe(xe({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}download(e,t){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=s?`?${s}`:"",i=this._getFinalPath(e);return new Ie(()=>Oe(this.fetch,`${this.url}/${r}/${i}${n}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}async info(e){var t=this;const r=t._getFinalPath(e);try{return{data:ye(await Oe(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async exists(e){var t=this;const r=t._getFinalPath(e);try{return await async function(e,t,r,s){return Ce(e,"HEAD",t,xe(xe({},r),{},{noResolveJson:!0}),s)}(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e)&&e instanceof fe){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],n=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==n&&s.push(n);const i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&s.push(o);let a=s.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}async remove(e){var t=this;try{return{data:await Ae(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async list(e,t,r){var s=this;try{const n=xe(xe(xe({},Pe),t),{},{prefix:e||""});return{data:await Re(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async listV2(e,t){var r=this;try{const s=xe({},e);return{data:await Re(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};const ze="2.90.1",De={"X-Client-Info":`storage-js/${ze}`};var He=class{constructor(e,t={},r,s){this.shouldThrowOnError=!1;const n=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href.replace(/\/$/,""),this.headers=xe(xe({},De),t),this.fetch=we(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(e){var t=this;try{const r=t.listBucketOptionsToQueryString(e);return{data:await Oe(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await Oe(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){var r=this;try{return{data:await Re(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async updateBucket(e,t){var r=this;try{return{data:await Ne(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async emptyBucket(e){var t=this;try{return{data:await Re(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await Ae(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},qe=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=xe(xe({},De),t),this.fetch=we(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await Re(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async listBuckets(e){var t=this;try{const r=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&r.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);const s=r.toString(),n=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return{data:await Oe(t.fetch,n,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await Ae(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(me(e))return{data:null,error:e};throw e}}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e)&&!(0===e.length||e.length>100)&&e.trim()===e&&!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new pe("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new de({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){const r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}};const Be={"X-Client-Info":`storage-js/${ze}`,"Content-Type":"application/json"};var Me=class extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function We(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}var Ke=class extends Me{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Fe=class extends Me{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}};const Ve=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Je=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Ge=(e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(n.headers=xe({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s)):n.body=s,xe(xe({},n),r)):n};async function Xe(e,t,r,s,n,i){return new Promise((o,a)=>{e(r,Ge(t,s,n,i)).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>o(e)).catch(e=>(async(e,t,r)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){const r=e.status||500,s=e;if("function"==typeof s.json)s.json().then(e=>{const s=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new Ke(Je(e),r,s))}).catch(()=>{const e=r+"";t(new Ke(s.statusText||`HTTP ${r} error`,r,e))});else{const e=r+"";t(new Ke(s.statusText||`HTTP ${r} error`,r,e))}}else t(new Fe(Je(e),e))})(e,a,s))})}async function Ye(e,t,r,s,n){return Xe(e,"POST",t,s,n,r)}var Qe=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=xe(xe({},Be),t),this.fetch=Ve(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async getIndex(e,t){var r=this;try{return{data:await Ye(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async listIndexes(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async deleteIndex(e,t){var r=this;try{return{data:await Ye(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}},Ze=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=xe(xe({},Be),t),this.fetch=Ve(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(e){var t=this;try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:await Ye(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async getVectors(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async listVectors(e){var t=this;try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:await Ye(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async queryVectors(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async deleteVectors(e){var t=this;try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:await Ye(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}},et=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=xe(xe({},Be),t),this.fetch=Ve(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async listBuckets(e={}){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(We(e))return{data:null,error:e};throw e}}},tt=class extends et{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new rt(this.url,this.headers,e,this.fetch)}async createBucket(e){return(()=>super.createBucket)().call(this,e)}async getBucket(e){return(()=>super.getBucket)().call(this,e)}async listBuckets(e={}){return(()=>super.listBuckets)().call(this,e)}async deleteBucket(e){return(()=>super.deleteBucket)().call(this,e)}},rt=class extends Qe{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,xe(xe({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,xe(xe({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return(()=>super.getIndex)().call(this,this.vectorBucketName,e)}async deleteIndex(e){return(()=>super.deleteIndex)().call(this,this.vectorBucketName,e)}index(e){return new st(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},st=class extends Ze{constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,xe(xe({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},nt=class extends He{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new Ue(this.url,this.headers,e,this.fetch)}get vectors(){return new tt(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new qe(this.url+"/iceberg",this.headers,this.fetch)}};const it="2.90.1",ot=3e4,at=9e4,lt={"X-Client-Info":`gotrue-js/${it}`},ct="X-Supabase-Api-Version",ht={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},ut=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class dt extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function pt(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class mt extends dt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class gt extends dt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class ft extends dt{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class wt extends ft{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class yt extends ft{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class bt extends ft{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class vt extends ft{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class _t extends ft{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class kt extends ft{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class xt extends ft{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function St(e){return pt(e)&&"AuthRetryableFetchError"===e.name}class Et extends ft{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class Tt extends ft{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ot=" \t\n\r=".split(""),Rt=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Ot.length;t+=1)e[Ot[t].charCodeAt(0)]=-2;for(let t=0;t<Ct.length;t+=1)e[Ct[t].charCodeAt(0)]=t;return e})();function Nt(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(Ct[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(Ct[e]),t.queuedBits-=6}}function At(e,t,r){const s=Rt[e];if(!(s>-1)){if(-2===s)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function $t(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t<e.length;t+=1)At(e.charCodeAt(t),n,i);return t.join("")}function jt(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function It(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)At(e.charCodeAt(t),r,s);return new Uint8Array(t)}function Pt(e){const t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){const t=1024*(s-55296)&65535;s=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}jt(s,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function Lt(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>Nt(e,r,s)),Nt(null,r,s),t.join("")}const Ut=()=>"undefined"!=typeof window&&"undefined"!=typeof document,zt={tested:!1,writable:!1},Dt=()=>{if(!Ut())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(zt.tested)return zt.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),zt.tested=!0,zt.writable=!0}catch(e){zt.tested=!0,zt.writable=!1}return zt.writable};const Ht=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),qt=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},Bt=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},Mt=async(e,t)=>{await e.removeItem(t)};class Wt{constructor(){this.promise=new Wt.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function Kt(e){const t=e.split(".");if(3!==t.length)throw new Tt("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!ut.test(t[e]))throw new Tt("JWT not in base64url format");return{header:JSON.parse($t(t[0])),payload:JSON.parse($t(t[1])),signature:It(t[2]),raw:{header:t[0],payload:t[1]}}}function Ft(e){return("0"+e.toString(16)).substr(-2)}async function Vt(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Jt(e,t,r=!1){const s=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,Ft).join("")}();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await qt(e,`${t}-code-verifier`,n);const i=await Vt(s);return[i,s===i?"plain":"s256"]}Wt.promiseConstructor=Promise;const Gt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const Xt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Yt(e){if(!Xt.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Qt(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)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 Zt(e){return JSON.parse(JSON.stringify(e))}const er=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tr=[502,503,504];async function rr(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new xt(er(e),0);if(tr.includes(e.status))throw new xt(er(e),e.status);let s,n;try{s=await e.json()}catch(e){throw new gt(er(e),e)}const i=function(e){const t=e.headers.get(ct);if(!t)return null;if(!t.match(Gt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=ht.timestamp&&"object"==typeof s&&s&&"string"==typeof s.code?n=s.code:"object"==typeof s&&s&&"string"==typeof s.error_code&&(n=s.error_code),n){if("weak_password"===n)throw new Et(er(s),e.status,(null===(t=s.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===n)throw new wt}else if("object"==typeof s&&s&&"object"==typeof s.weak_password&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new Et(er(s),e.status,s.weak_password.reasons);throw new mt(er(s),e.status||500,n)}async function sr(e,t,r,s){var n;const i=Object.assign({},null==s?void 0:s.headers);i[ct]||(i[ct]=ht.name),(null==s?void 0:s.jwt)&&(i.Authorization=`Bearer ${s.jwt}`);const o=null!==(n=null==s?void 0:s.query)&&void 0!==n?n:{};(null==s?void 0:s.redirectTo)&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await async function(e,t,r,s,n,i){const o=((e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))})(t,s,n,i);let a;try{a=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new xt(er(e),0)}a.ok||await rr(a);if(null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await rr(e)}}(e,t,r+a,{headers:i,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}function nr(e){var t;let r=null;var s;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(s=e.expires_in,Math.round(Date.now()/1e3)+s)));return{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ir(e){const t=nr(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function or(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ar(e){return{data:e,error:null}}function lr(e){const{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=e,o=h(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},user:Object.assign({},o)},error:null}}function cr(e){return e}const hr=["global","local","others"];class ur{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Ht(r),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)}}async signOut(e,t=hr[0]){if(hr.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${hr.join(", ")}`);try{return await sr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(pt(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await sr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,r=h(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await sr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:lr,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(pt(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await sr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,n,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await sr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:cr});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(pt(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Yt(e);try{return await sr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Yt(e);try{return await sr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Yt(e);try{return await sr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:or})}catch(e){if(pt(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Yt(e.userId);try{const{data:t,error:r}=await sr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Yt(e.userId),Yt(e.id);try{return{data:await sr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,n,i,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await sr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:cr});if(c.error)throw c.error;const h=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(a=null===(o=c.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(pt(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await sr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await sr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await sr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await sr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(pt(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await sr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pt(e))return{data:null,error:e};throw e}}}function dr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const pr=!!(globalThis&&Dt()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class mr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class gr extends mr{}async function fr(e,t,r){pr&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const s=new globalThis.AbortController;return t>0&&setTimeout(()=>{s.abort(),pr&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async s=>{if(!s){if(0===t)throw pr&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new gr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(pr)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}pr&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{pr&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}))}function wr(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function yr(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class br extends Error{constructor({message:e,code:t,cause:r,name:s}){var n;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(n=null!=s?s:r instanceof Error?r.name:void 0)&&void 0!==n?n:"Unknown Error",this.code=t}}class vr extends br{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function _r({error:e,options:t}){var r,s,n;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new br({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new br({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new br({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new br({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new br({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new br({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new br({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new br({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!Or(t))return new br({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new br({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new br({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new br({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new br({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function kr({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new br({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new br({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Or(t))return new br({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new br({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new br({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new br({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const xr=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Sr(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:r,excludeCredentials:s}=e,n=h(e,["challenge","user","excludeCredentials"]),i=It(t).buffer,o=Object.assign(Object.assign({},r),{id:It(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(s&&s.length>0){a.excludeCredentials=new Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];a.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:It(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return a}function Er(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:r}=e,s=h(e,["challenge","allowCredentials"]),n=It(t).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];i.allowCredentials[e]=Object.assign(Object.assign({},t),{id:It(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}function Tr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:Lt(new Uint8Array(e.response.attestationObject)),clientDataJSON:Lt(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Cr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e,s=e.getClientExtensionResults(),n=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Lt(new Uint8Array(n.authenticatorData)),clientDataJSON:Lt(new Uint8Array(n.clientDataJSON)),signature:Lt(new Uint8Array(n.signature)),userHandle:n.userHandle?Lt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Or(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Rr(){var e,t;return!!(Ut()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const Nr={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Ar={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function $r(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(const n of e)if(n)for(const e in n){const i=n[e];if(void 0!==i)if(Array.isArray(i))s[e]=i;else if(r(i))s[e]=i;else if(t(i)){const r=s[e];t(r)?s[e]=$r(r,i):s[e]=$r(i)}else s[e]=i}return s}class jr{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},n){try{const{data:i,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:o};const a=null!=s?s:xr.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return $r(Nr,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.create),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:_r({error:t,options:e})}}}({publicKey:t,signal:a});return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}case"request":{const t=function(e,t){return $r(Ar,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.request),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:kr({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:a}));return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(e){return pt(e)?{data:null,error:e}:{data:null,error:new gt("Unexpected error in challenge",e)}}}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=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new dt("rpId is required for WebAuthn authentication")};try{if(!Rr())return{data:null,error:new gt("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:n});if(!i)return{data:null,error:o};const{webauthn:a}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:r,credential_response:a.credential_response}})}catch(e){return pt(e)?{data:null,error:e}:{data:null,error:new gt("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new dt("rpId is required for WebAuthn registration")};try{if(!Rr())return{data:null,error:new gt("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:o};const{data:a,error:l}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:n});return a?this._verify({factorId:i.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:r,type:a.webauthn.type,credential_response:a.webauthn.credential_response}}):{data:null,error:l}}catch(e){return pt(e)?{data:null,error:e}:{data:null,error:new gt("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Ir={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:lt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Pr(e,t,r){return await r()}const Lr={};class Ur{get jwks(){var e,t;return null!==(t=null===(e=Lr[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Lr[this.storageKey]=Object.assign(Object.assign({},Lr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Lr[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Lr[this.storageKey]=Object.assign(Object.assign({},Lr[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.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const n=Object.assign(Object.assign({},Ir),e);if(this.storageKey=n.storageKey,this.instanceID=null!==(t=Ur.nextInstanceID[this.storageKey])&&void 0!==t?t:0,Ur.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.instanceID>0&&Ut()){const e=`${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(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.admin=new ur({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=Ht(n.fetch),this.lock=n.lock||Pr,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,this.throwOnError=n.throwOnError,this.lockAcquireTimeout=n.lockAcquireTimeout,n.lock?this.lock=n.lock:this.persistSession&&Ut()&&(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===r?void 0:r.locks)?this.lock=fr:this.lock=Pr,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 jr(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.persistSession?(n.storage?this.storage=n.storage:Dt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=dr(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=dr(this.memoryStorage)),Ut()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${it}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(Ut()&&(t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),Ut()&&this.detectSessionInUrl&&"none"!==r){const{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),function(e){return pt(e)&&"AuthImplicitGrantRedirectError"===e.name}(n)){const t=null===(e=n.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:n}}return{error:n}}const{session:i,redirectType:o}=s;return this._debug("#_initialize()","detected session in URL",i,"redirect type",o),await this._saveSession(i),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return pt(e)?this._returnResult({error:e}):this._returnResult({error:new gt("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const n=await sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken}},xform:nr}),{data:i,error:o}=n;if(o||!i)return this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let n;if("email"in e){const{email:r,password:s,options:i}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Jt(this.storage,this.storageKey)),n=await sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:o,code_challenge_method:a},xform:nr})}else{if(!("phone"in e))throw new bt("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:o}=e;n=await sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{},channel:null!==(s=null==o?void 0:o.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:nr})}}const{data:i,error:o}=n;if(o||!i)return await Mt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const a=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:s,options:n}=e;t=await sr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:ir})}else{if(!("phone"in e))throw new bt("You must provide either an email or phone number and a password");{const{phone:r,password:s,options:n}=e;t=await sr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:ir})}}const{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const e=new yt;return this._returnResult({data:{user:null,session:null},error:e})}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(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(n=e.options)||void 0===n?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{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,n,i,o,a,l,c,h,u;let d,p;if("message"in e)d=e.message,p=e.signature;else{const{chain:h,wallet:u,statement:m,options:g}=e;let f;if(Ut())if("object"==typeof u)f=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)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.");f=e.ethereum}else{if("object"!=typeof u||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");f=u}const w=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),y=await f.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!y||0===y.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const b=wr(y[0]);let v=null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!v){const e=await f.request({method:"eth_chainId"});v=parseInt(e,16)}d=function(e){var t;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:u,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)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(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const p=`${h?`${h}://${s}`:s} wants you to sign in with your Ethereum account:\n${wr(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let m=`URI: ${u}\nVersion: ${d}\nChain ID: ${r}${o?`\nNonce: ${o}`:""}\nIssued At: ${i.toISOString()}`;if(n&&(m+=`\nExpiration Time: ${n.toISOString()}`),a&&(m+=`\nNot Before: ${a.toISOString()}`),l&&(m+=`\nRequest ID: ${l}`),c){let e="\nResources:";for(const t of c){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}m+=e}return`${p}\n${m}`}({domain:w.host,address:b,statement:m,uri:w.href,version:"1",chainId:v,nonce:null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.nonce,issuedAt:null!==(i=null===(n=null==g?void 0:g.signInWithEthereum)||void 0===n?void 0:n.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.expirationTime,notBefore:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.notBefore,requestId:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==g?void 0:g.signInWithEthereum)||void 0===c?void 0:c.resources}),p=await f.request({method:"personal_sign",params:[yr(d),b]})}try{const{data:t,error:r}=await sr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:nr});if(r)throw r;if(!t||!t.session||!t.user){const e=new yt;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,n,i,o,a,l,c,h,u,d;let p,m;if("message"in e)p=e.message,m=e.signature;else{const{chain:u,wallet:d,statement:g,options:f}=e;let w;if(Ut())if("object"==typeof d)w=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))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.");w=e.solana}else{if("object"!=typeof d||!(null==f?void 0:f.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=d}const y=new URL(null!==(t=null==f?void 0:f.url)&&void 0!==t?t:window.location.href);if("signIn"in w&&w.signIn){const e=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==f?void 0:f.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),g?{statement:g}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),m=t.signature}else{if(!("signMessage"in w&&"function"==typeof w.signMessage&&"publicKey"in w&&"object"==typeof w&&w.publicKey&&"toBase58"in w.publicKey&&"function"==typeof w.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${y.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(s=null===(r=null==f?void 0:f.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==s?s:(new Date).toISOString()}`,...(null===(n=null==f?void 0:f.signInWithSolana)||void 0===n?void 0:n.notBefore)?[`Not Before: ${f.signInWithSolana.notBefore}`]:[],...(null===(i=null==f?void 0:f.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${f.signInWithSolana.expirationTime}`]:[],...(null===(o=null==f?void 0:f.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${f.signInWithSolana.chainId}`]:[],...(null===(a=null==f?void 0:f.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${f.signInWithSolana.nonce}`]:[],...(null===(l=null==f?void 0:f.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${f.signInWithSolana.requestId}`]:[],...(null===(h=null===(c=null==f?void 0:f.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===h?void 0:h.length)?["Resources",...f.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await w.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=e}}try{const{data:t,error:r}=await sr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:Lt(m)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:nr});if(r)throw r;if(!t||!t.session||!t.user){const e=new yt;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await Bt(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new kt;const{data:t,error:n}=await sr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:nr});if(await Mt(this.storage,`${this.storageKey}-code-verifier`),n)throw n;if(!t||!t.session||!t.user){const e=new yt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:n})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:r,token:s,access_token:n,nonce:i}=e,o=await sr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:nr}),{data:a,error:l}=o;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a||!a.session||!a.user){const e=new yt;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:l})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,n,i;try{if("email"in e){const{email:s,options:n}=e;let i=null,o=null;"pkce"===this.flowType&&([i,o]=await Jt(this.storage,this.storageKey));const{error:a}=await sr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},create_user:null===(r=null==n?void 0:n.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:i,code_challenge_method:o},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){const{phone:t,options:r}=e,{data:o,error:a}=await sr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(n=null==r?void 0:r.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(i=null==r?void 0:r.channel)&&void 0!==i?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a})}throw new bt("You must provide either an email or phone number.")}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,n=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:i,error:o}=await sr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:nr});if(o)throw o;if(!i){throw new Error("An error occurred on token verification.")}const a=i.session,l=i.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),this._returnResult({data:{user:l,session:a},error:null})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,n,i;try{let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Jt(this.storage,this.storageKey));const l=await sr(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:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:a}),headers:this.headers,xform:ar});return(null===(n=l.data)||void 0===n?void 0:n.url)&&Ut()&&!(null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new wt;const{error:s}=await sr(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(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:n}=e,{error:i}=await sr(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){const{phone:r,type:s,options:n}=e,{data:i,error:o}=await sr(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:o})}throw new bt("You must provide either an email or phone number and a type")}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){await this.initializePromise;return await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}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{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await Bt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<at;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await Bt(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=Qt()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,r,s)=>{if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){const t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,s)}return t.value||"string"!=typeof r||(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."),t.value=!0),Reflect.get(e,r,s)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{session:null},error:n}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await sr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:or}):await this._useSession(async e=>{var t,r,s;const{data:n,error:i}=e;if(i)throw i;return(null===(t=n.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await sr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0,xform:or}):{data:{user:null},error:new wt}})}catch(e){if(pt(e))return function(e){return pt(e)&&"AuthSessionMissingError"===e.name}(e)&&(await this._removeSession(),await Mt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new wt;const i=s.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await Jt(this.storage,this.storageKey));const{data:l,error:c}=await sr(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:i.access_token,xform:or});if(c)throw c;return i.user=l.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new wt;const t=Date.now()/1e3;let r=t,s=!0,n=null;const{payload:i}=Kt(e.access_token);if(i.exp&&(r=i.exp,s=r<=t),s){const{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};n=t}else{const{data:s,error:i}=await this._getUser(e.access_token);if(i)throw i;n={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return this._returnResult({data:{user:n.user,session:n},error:null})}catch(e){if(pt(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:s,error:n}=t;if(n)throw n;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new wt;const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{user:null,session:null},error:n}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!Ut())throw new vt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new vt(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("pkce"===this.flowType)throw new _t("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new vt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new _t("No code detected.");const{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;const s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:i,expires_in:o,expires_at:a,token_type:l}=e;if(!(n&&o&&i&&l))throw new vt("No session defined in URL");const c=Math.round(Date.now()/1e3),h=parseInt(o);let u=c+h;a&&(u=parseInt(a));const d=u-c;1e3*d<=ot&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${h}s`);const p=u-h;c-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,c):c-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,c);const{data:m,error:g}=await this._getUser(n);if(g)throw g;const f={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:h,expires_at:u,refresh_token:i,token_type:l,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:f,redirectType:e.type},error:null})}catch(e){if(pt(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await Bt(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({error:n});const i=null===(r=s.session)||void 0===r?void 0:r.access_token;if(i){const{error:t}=await this.admin.signOut(i,e);if(t&&(!function(e){return pt(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await Mt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),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,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{const{data:{session:s},error:n}=t;if(n)throw n;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await Jt(this.storage,this.storageKey,!0));try{return await sr(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:t.redirectTo})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:s}=await this._useSession(async t=>{var r,s,n,i,o;const{data:a,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:!0});return await sr(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(o=null===(i=a.session)||void 0===i?void 0:i.access_token)&&void 0!==o?o:void 0})});if(s)throw s;return Ut()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(pt(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:s,data:{session:n}}=t;if(s)throw s;const{options:i,provider:o,token:a,access_token:l,nonce:c}=e,h=await sr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==n?void 0:n.access_token)&&void 0!==r?r:void 0,body:{provider:o,id_token:a,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:nr}),{data:u,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:d})):this._returnResult({data:{user:null,session:null},error:new yt})}catch(e){if(await Mt(this.storage,`${this.storageKey}-code-verifier`),pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)throw i;return await sr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const n=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await sr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:nr})),s=(e,t)=>{const r=200*Math.pow(2,e);return t&&St(t)&&Date.now()+r-n<ot},new Promise((e,t)=>{(async()=>{for(let n=0;n<1/0;n++)try{const t=await r(n);if(!s(n,null,t))return void e(t)}catch(e){if(!s(n,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),pt(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var r,s}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Ut()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const s=await Bt(this.storage,this.storageKey);if(s&&this.userStorage){let t=await Bt(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:s.user},await qt(this.userStorage,this.storageKey+"-user",t)),s.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:Qt()}else if(s&&!s.user&&!s.user){const e=await Bt(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await Mt(this.storage,this.storageKey+"-user"),await qt(this.storage,this.storageKey,s)):s.user=Qt()}if(this._debug(r,"session from storage",s),!this._isValidSession(s))return this._debug(r,"session is not valid"),void(null!==s&&await this._removeSession());const n=1e3*(null!==(t=s.expires_at)&&void 0!==t?t:1/0)-Date.now()<at;if(this._debug(r,`session has${n?"":" not"} expired with margin of 90000s`),n){if(this.autoRefreshToken&&s.refresh_token){const{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),St(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){return this._debug(r,"error",e),void console.error(e)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new wt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Wt;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new wt;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),pt(e)){const r={data:null,error:e};return St(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const s=[],n=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(n),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Mt(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await qt(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const s=Zt(e);await qt(this.storage,this.storageKey,s)}else{const e=Zt(t);await qt(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Mt(this.storage,this.storageKey),await Mt(this.storage,this.storageKey+"-code-verifier"),await Mt(this.storage,this.storageKey+"-user"),this.userStorage&&await Mt(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ut()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),ot);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-e)/ot);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof mr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ut()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await Jt(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;return n?this._returnResult({data:null,error:n}):await sr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:l}=await sr(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===a.type&&(null===(s=null==a?void 0:a.totp)||void 0===s?void 0:s.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Tr(e.webauthn.credential_response):Cr(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await sr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return a?this._returnResult({data:null,error:a}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:a}))})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=await sr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});if(i.error)return i;const{data:o}=i;if("webauthn"!==o.type)return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Sr(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Er(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{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;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:s}=await this.getSession();if(s)return this._returnResult({data:null,error:s});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:n}=Kt(r.access_token);let i=null;n.aal&&(i=n.aal);let o=i;(null!==(t=null===(e=r.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(o="aal2");return{data:{currentLevel:i,nextLevel:o,currentAuthenticationMethods:n.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await sr(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new wt})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new wt});const i=await sr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&Ut()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new wt});const i=await sr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&Ut()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await sr(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new wt})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await sr(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 wt})})}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>s)return r;const{data:n,error:i}=await sr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return n.keys&&0!==n.keys.length?(this.jwks=n,this.jwks_cached_at=s,r=n.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let r=e;if(!r){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}const{header:s,payload:n,signature:i,raw:{header:o,payload:a}}=Kt(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(n.exp);const l=s.alg&&!s.alg.startsWith("HS")&&s.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(s.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!l){const{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:n,header:s,signature:i},error:null}}const c=function(e){switch(e){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")}}(s.alg),h=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,h,i,Pt(`${o}.${a}`)))throw new Tt("Invalid JWT signature");return{data:{claims:n,header:s,signature:i},error:null}}catch(e){if(pt(e))return this._returnResult({data:null,error:e});throw e}}}Ur.nextInstanceID={};const zr=Ur;let Dr="";Dr="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const Hr={headers:{"X-Client-Info":`supabase-js-${Dr}/2.90.1`}},qr={schema:"public"},Br={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Mr={};function Wr(e){return(Wr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Kr(e){var t=function(e,t){if("object"!=Wr(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t);if("object"!=Wr(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Wr(t)?t:t+""}function Fr(e,t,r){return(t=Kr(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Vr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function Jr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Vr(Object(r),!0).forEach(function(t){Fr(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Vr(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const Gr=(e,t,r)=>{const s=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),n=Headers;return async(r,i)=>{var o;const a=null!==(o=await t())&&void 0!==o?o:e;let l=new n(null==i?void 0:i.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${a}`),s(r,Jr(Jr({},i),{},{headers:l}))}};var Xr=class extends zr{constructor(e){super(e)}},Yr=class{constructor(e,t,r){var s,n;this.supabaseUrl=e,this.supabaseKey=t;const i=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((r=t).endsWith("/")?r:r+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var r}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a=function(e,t){var r,s;const{db:n,auth:i,realtime:o,global:a}=e,{db:l,auth:c,realtime:h,global:u}=t,d={db:Jr(Jr({},l),n),auth:Jr(Jr({},c),i),realtime:Jr(Jr({},h),o),storage:{},global:Jr(Jr(Jr({},u),a),{},{headers:Jr(Jr({},null!==(r=null==u?void 0:u.headers)&&void 0!==r?r:{}),null!==(s=null==a?void 0:a.headers)&&void 0!==s?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:qr,realtime:Mr,auth:Jr(Jr({},Br),{},{storageKey:o}),global:Hr});var l;(this.storageKey=null!==(s=a.auth.storageKey)&&void 0!==s?s:"",this.headers=null!==(n=a.global.headers)&&void 0!==n?n:{},a.accessToken)?(this.accessToken=a.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(l=a.auth)&&void 0!==l?l:{},this.headers,a.global.fetch);this.fetch=Gr(t,this._getAccessToken.bind(this),a.global.fetch),this.realtime=this._initRealtimeClient(Jr({headers:this.headers,accessToken:this._getAccessToken.bind(this)},a.realtime)),this.accessToken&&this.accessToken().then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new S(new URL("rest/v1",i).href,{headers:this.headers,schema:a.db.schema,fetch:this.fetch}),this.storage=new nt(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),a.accessToken||this._listenForAuthEvents()}get functions(){return new w(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t,r=this;if(r.accessToken)return await r.accessToken();const{data:s}=await r.auth.getSession();return null!==(e=null===(t=s.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,u){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Xr({url:this.authUrl.href,headers:Jr(Jr({},d),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:l,throwOnError:c,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new ie(this.realtimeUrl.href,Jr(Jr({},e),{},{params:Jr(Jr({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};(function(){if("undefined"!=typeof window)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(null==t)return!1;const r=t.match(/^v(\d+)\./);return!!r&&parseInt(r[1],10)<=18})()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Qr={position:"bottom-right",defaultOpen:!1,theme:"dark",features:["prompts","timeline","deployments","elements","captures"],captureConsole:!0,captureNetwork:!0,hotkey:"ctrl+shift+o",apiUrl:"https://orquesta.live"};class Zr{constructor(){this.listeners=new Set,this.state=this.getInitialState()}getInitialState(){return{isConnected:!1,isConnecting:!1,connectionError:null,projectId:null,projectName:null,agentOnline:!1,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,currentPrompt:null,promptHistory:[],isSubmitting:!1,outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}setConnected(e,t,r){this.setState({isConnected:!0,isConnecting:!1,connectionError:null,projectId:e,projectName:t,agentOnline:r})}setConnectionError(e){this.setState({isConnected:!1,isConnecting:!1,connectionError:e})}setOpen(e){this.setState({isOpen:e})}toggle(){this.setState({isOpen:!this.state.isOpen})}setActiveTab(e){this.setState({activeTab:e})}setCurrentPrompt(e){this.setState({currentPrompt:e}),e&&!this.state.promptHistory.find(t=>t.id===e.id)&&this.setState({promptHistory:[e,...this.state.promptHistory].slice(0,50)})}updatePrompt(e,t){this.state.currentPrompt?.id===e&&this.setState({currentPrompt:{...this.state.currentPrompt,...t}}),this.setState({promptHistory:this.state.promptHistory.map(r=>r.id===e?{...r,...t}:r)})}addOutputLine(e){const t={...e,id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`};this.setState({outputLines:[...this.state.outputLines,t]})}clearOutput(){this.setState({outputLines:[]})}storePromptOutput(e){this.state.outputLines.length>0&&this.setState({promptOutputs:{...this.state.promptOutputs,[e]:[...this.state.outputLines]}})}setSelectedElement(e){this.setState({selectedElement:e,isSelectingElement:!1})}startElementSelection(){this.setState({isSelectingElement:!0})}cancelElementSelection(){this.setState({isSelectingElement:!1,selectedElement:null})}setOverlayMode(e){this.setState({overlayMode:e}),"off"===e&&this.setState({highlightedPromptId:null})}setHighlightedPromptId(e){this.setState({highlightedPromptId:e})}setElementMarkers(e){this.setState({elementMarkers:e})}setCommentsForPrompt(e,t){this.setState({comments:{...this.state.comments,[e]:t}})}addComment(e,t){const r=this.state.comments[e]||[];this.setState({comments:{...this.state.comments,[e]:[...r,t]}}),this.setState({promptHistory:this.state.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)})}setExpandedPromptId(e){this.setState({expandedPromptId:e})}setLoadingComments(e){this.setState({isLoadingComments:e})}addConsoleLogs(e){this.setState({consoleLogs:[...this.state.consoleLogs,...e].slice(-100)})}addNetworkLogs(e){this.setState({networkLogs:[...this.state.networkLogs,...e].slice(-100)})}toggleIncludeConsole(){this.setState({includeConsole:!this.state.includeConsole})}toggleIncludeNetwork(){this.setState({includeNetwork:!this.state.includeNetwork})}setAuth(e,t){this.setState({user:e,isAuthenticated:t,isAuthenticating:!1,authError:null})}setAuthenticating(e){this.setState({isAuthenticating:e})}setAuthError(e){this.setState({authError:e,isAuthenticating:!1})}setRequireAuth(e){this.setState({requireAuth:e})}reset(){this.state=this.getInitialState(),this.notify()}}class es{constructor(){this.buffer=[],this.maxSize=100,this.originalConsole=null,this.errorHandler=null,this.rejectionHandler=null,this.listeners=new Set}start(){if(this.originalConsole)return;this.originalConsole={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};const e=e=>(...t)=>{const r=this.createEntry(e,t);this.addEntry(r),this.originalConsole?.[e](...t)};console.log=e("log"),console.info=e("info"),console.warn=e("warn"),console.error=e("error"),this.errorHandler=e=>{const t=this.createEntry("error",[e.message],e.error?.stack);this.addEntry(t)},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{const t=e.reason instanceof Error?e.reason.message:String(e.reason),r=e.reason instanceof Error?e.reason.stack:void 0,s=this.createEntry("error",[`Unhandled Promise Rejection: ${t}`],r);this.addEntry(s)},window.addEventListener("unhandledrejection",this.rejectionHandler)}stop(){this.originalConsole&&(console.log=this.originalConsole.log,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null),this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null)}createEntry(e,t,r){return{timestamp:Date.now(),level:e,message:t.map(e=>"object"==typeof e?JSON.stringify(e,null,2):String(e)).join(" "),args:t,stack:r}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>"error"===e.level||"warn"===e.level)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getRecent(20);return 0===t.length?"":t.map(e=>`${`[${new Date(e.timestamp).toISOString()}] [${e.level.toUpperCase()}]`} ${e.message}${e.stack?`\n${e.stack}`:""}`).join("\n")}}class ts{constructor(){this.buffer=[],this.maxSize=100,this.originalFetch=null,this.originalXHROpen=null,this.originalXHRSend=null,this.listeners=new Set}start(){this.originalFetch||(this.patchFetch(),this.patchXHR())}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXHROpen&&this.originalXHRSend&&(XMLHttpRequest.prototype.open=this.originalXHROpen,XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHROpen=null,this.originalXHRSend=null)}patchFetch(){this.originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{const r="string"==typeof e?e:e instanceof URL?e.href:e.url,s=t?.method||"GET",n=Date.now(),i={timestamp:n,method:s,url:r,requestBody:t?.body};try{const r=await this.originalFetch(e,t);if(i.status=r.status,i.duration=Date.now()-n,!r.ok)try{const e=r.clone();i.responseBody=await e.text()}catch{}return this.addEntry(i),r}catch(e){throw i.duration=Date.now()-n,i.error=e instanceof Error?e.message:String(e),this.addEntry(i),e}}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;const e=this,t=new WeakMap;XMLHttpRequest.prototype.open=function(r,s,...n){return t.set(this,{method:r,url:"string"==typeof s?s:s.href,startTime:0}),e.originalXHROpen.apply(this,[r,s,...n])},XMLHttpRequest.prototype.send=function(r){const s=t.get(this);return s&&(s.startTime=Date.now(),this.addEventListener("loadend",()=>{const t={timestamp:s.startTime,method:s.method,url:s.url,status:this.status,duration:Date.now()-s.startTime};if(this.status>=400||0===this.status){t.error=this.statusText||"Request failed";try{t.responseBody=this.responseText}catch{}}e.addEntry(t)})),e.originalXHRSend.call(this,r)}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>e.status&&e.status>=400||e.error)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getErrors();return 0===t.length?"":t.map(e=>{const t=new Date(e.timestamp).toISOString(),r=e.status?`[${e.status}]`:"[FAILED]";return`[${t}] ${e.method} ${e.url} ${r}${e.error?` - ${e.error}`:""}`}).join("\n")}}class rs{constructor(){this.overlay=null,this.highlight=null,this.selectedHighlight=null,this.selectedElement=null,this.isActive=!1,this.onSelect=null,this.onCancel=null,this.globalRightClickHandler=null,this.globalRightClickCallback=null,this.globalRightClickWithPositionCallback=null,this.selectedElementScrollHandler=null,this.handleMouseMove=e=>{if(!this.isActive||!this.highlight)return;const t=document.elementFromPoint(e.clientX,e.clientY);if(!t||t.id?.startsWith("orquesta-"))return;this.selectedElement=t;const r=t.getBoundingClientRect();this.highlight.style.display="block",this.highlight.style.top=`${r.top}px`,this.highlight.style.left=`${r.left}px`,this.highlight.style.width=`${r.width}px`,this.highlight.style.height=`${r.height}px`;const s=this.highlight.querySelector("#orquesta-element-label");if(s){const e=t.tagName.toLowerCase(),r=t.id?`#${t.id}`:"",n=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";s.textContent=`<${e}${r}${n}>`}},this.handleClick=e=>{if(!this.isActive)return;const t=e.target;if(!t.id?.startsWith("orquesta-")&&(e.preventDefault(),e.stopPropagation(),this.selectedElement)){const e=this.getElementContext(this.selectedElement);this.deactivate(),this.onSelect?.(e)}},this.handleKeyDown=e=>{"Escape"===e.key&&this.isActive&&(this.deactivate(),this.onCancel?.())},this.promptHighlightScrollHandler=null}setupGlobalRightClick(e){return this.globalRightClickCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const r=this.getElementContext(t);this.globalRightClickCallback?.(r)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickCallback=null)}}setupGlobalRightClickWithPosition(e){return this.globalRightClickWithPositionCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const r=this.getElementContext(t),s={x:e.clientX,y:e.clientY};this.globalRightClickWithPositionCallback?.(r,s)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickWithPositionCallback=null)}}highlightSelectedElement(e){try{const t=document.querySelector(e);if(!t)return null;this.removeSelectedHighlight(),this.selectedHighlight=document.createElement("div"),this.selectedHighlight.id="orquesta-selected-element-highlight",this.selectedHighlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #3b82f6;\n background: rgba(59, 130, 246, 0.15);\n z-index: 2147483640;\n transition: all 0.15s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25), 0 0 20px rgba(59, 130, 246, 0.3);\n ",document.body.appendChild(this.selectedHighlight);const r=document.createElement("div");r.id="orquesta-selected-element-label",r.style.cssText='\n position: absolute;\n top: -28px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 8px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ';const s=t.tagName.toLowerCase(),n=t.id?`#${t.id}`:"",i=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";r.textContent=`Selected: <${s}${n}${i}>`,this.selectedHighlight.appendChild(r);const o=()=>{if(!this.selectedHighlight)return;const e=t.getBoundingClientRect();this.selectedHighlight.style.top=e.top-3+"px",this.selectedHighlight.style.left=e.left-3+"px",this.selectedHighlight.style.width=`${e.width+6}px`,this.selectedHighlight.style.height=`${e.height+6}px`};return o(),this.selectedElementScrollHandler=o,window.addEventListener("scroll",this.selectedElementScrollHandler,!0),window.addEventListener("resize",this.selectedElementScrollHandler),t}catch{return null}}removeSelectedHighlight(){this.selectedHighlight&&(this.selectedHighlight.remove(),this.selectedHighlight=null),this.selectedElementScrollHandler&&(window.removeEventListener("scroll",this.selectedElementScrollHandler,!0),window.removeEventListener("resize",this.selectedElementScrollHandler),this.selectedElementScrollHandler=null)}activate(e,t){this.isActive||(this.isActive=!0,this.onSelect=e,this.onCancel=t||null,this.createOverlay(),this.addListeners(),document.body.style.cursor="crosshair")}deactivate(){this.isActive&&(this.isActive=!1,this.removeListeners(),this.removeOverlay(),this.selectedElement=null,document.body.style.cursor="")}isSelecting(){return this.isActive}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="orquesta-element-selector-overlay",this.overlay.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483646;\n pointer-events: none;\n ",document.body.appendChild(this.overlay),this.highlight=document.createElement("div"),this.highlight.id="orquesta-element-highlight",this.highlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 2px solid #3b82f6;\n background: rgba(59, 130, 246, 0.1);\n z-index: 2147483646;\n transition: all 0.1s ease;\n display: none;\n ",document.body.appendChild(this.highlight);const e=document.createElement("div");e.id="orquesta-element-label",e.style.cssText="\n position: absolute;\n bottom: -24px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: monospace;\n padding: 2px 6px;\n border-radius: 2px;\n white-space: nowrap;\n ",this.highlight.appendChild(e)}removeOverlay(){this.overlay?.remove(),this.highlight?.remove(),this.overlay=null,this.highlight=null}addListeners(){document.addEventListener("mousemove",this.handleMouseMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown,!0)}removeListeners(){document.removeEventListener("mousemove",this.handleMouseMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("keydown",this.handleKeyDown,!0)}highlightElement(e){try{const t=document.querySelector(e);if(!t)return null;this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null);let r=document.getElementById("orquesta-prompt-highlight");r||(r=document.createElement("div"),r.id="orquesta-prompt-highlight",r.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #8b5cf6;\n background: rgba(139, 92, 246, 0.15);\n z-index: 2147483640;\n transition: top 0.1s ease, left 0.1s ease, width 0.1s ease, height 0.1s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2), 0 0 20px rgba(139, 92, 246, 0.3);\n ",document.body.appendChild(r));let s=r.querySelector("#orquesta-prompt-highlight-label");s||(s=document.createElement("div"),s.id="orquesta-prompt-highlight-label",s.style.cssText='\n position: absolute;\n top: -30px;\n left: 0;\n background: #8b5cf6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 10px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ',r.appendChild(s));const n=t.tagName.toLowerCase(),i=t.id?`#${t.id}`:"",o=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";s.textContent=`Highlighted: <${n}${i}${o}>`;const a=()=>{const e=t.getBoundingClientRect();r.style.display="block",r.style.top=e.top-3+"px",r.style.left=e.left-3+"px",r.style.width=`${e.width+6}px`,r.style.height=`${e.height+6}px`};a(),this.promptHighlightScrollHandler=a,window.addEventListener("scroll",this.promptHighlightScrollHandler,!0),window.addEventListener("resize",this.promptHighlightScrollHandler);const l=t.getBoundingClientRect();return(l.top<0||l.bottom>window.innerHeight)&&t.scrollIntoView({behavior:"smooth",block:"center"}),t}catch{return null}}removeHighlight(){const e=document.getElementById("orquesta-prompt-highlight");e&&(e.style.display="none"),this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null)}findElement(e,t){try{let r=document.querySelector(e);if(r)return r;if(t&&(r=document.getElementById(t),r))return r;const s=e.match(/^([a-z]+)\.([a-z0-9_-]+)/i);if(s){const[,e,t]=s;if(r=document.querySelector(`${e}.${t}`),r)return r}return null}catch{return null}}getElementContext(e){const t=e.getBoundingClientRect(),r={};for(const t of e.attributes)t.name.startsWith("data-")||"class"===t.name||"id"===t.name||(r[t.name]=t.value);return{selector:this.generateSelector(e),tag:e.tagName.toLowerCase(),id:e.id||void 0,className:"string"==typeof e.className?e.className:void 0,textContent:e.textContent?.trim().slice(0,200)||void 0,boundingRect:t,attributes:Object.keys(r).length>0?r:void 0}}generateSelector(e){if(e.id)return`#${e.id}`;const t=[];let r=e;for(;r&&r!==document.body;){let e=r.tagName.toLowerCase();if(r.id){e=`#${r.id}`,t.unshift(e);break}if(r.className&&"string"==typeof r.className){const t=r.className.trim().split(/\s+/).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}const s=r.parentElement;if(s){const t=Array.from(s.children).filter(e=>e.tagName===r.tagName);if(t.length>1){e+=`:nth-child(${t.indexOf(r)+1})`}}t.unshift(e),r=r.parentElement}return t.join(" > ")}}class ss{constructor(e,t){this.listeners=new Set,this.popupWindow=null,this.messageHandler=null,this.token=e,this.apiUrl=t,this.state=this.getInitialState()}getInitialState(){return{isAuthenticated:!1,isAuthenticating:!1,user:null,sessionToken:null,expiresAt:null,authError:null}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}getStorageKey(){return`orquesta_embed_session_${this.token.slice(-8)}`}saveSession(e){try{localStorage.setItem(this.getStorageKey(),JSON.stringify(e))}catch{}}loadSession(){try{const e=localStorage.getItem(this.getStorageKey());if(!e)return null;const t=JSON.parse(e);return t.expiresAt&&new Date(t.expiresAt)<new Date?(this.clearSession(),null):t}catch{return null}}clearSession(){try{localStorage.removeItem(this.getStorageKey())}catch{}}async checkSession(){const e=this.loadSession();if(!e)return!1;try{const t=await fetch(`${this.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})});if(!t.ok)return this.clearSession(),!1;const r=await t.json();return r.valid?(this.setState({isAuthenticated:!0,user:r.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0):(this.clearSession(),!1)}catch{return this.setState({isAuthenticated:!0,user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0}}login(){return new Promise((e,t)=>{this.setState({isAuthenticating:!0,authError:null});const r=Math.random().toString(36).slice(2),s=window.location.origin,n=new URL(`${this.apiUrl}/embed/auth`);n.searchParams.set("token",this.token),n.searchParams.set("origin",s),n.searchParams.set("state",r);const i=window.screenX+(window.innerWidth-500)/2,o=window.screenY+(window.innerHeight-600)/2;if(this.popupWindow=window.open(n.toString(),"orquesta_auth",`width=500,height=600,left=${i},top=${o},popup=yes`),!this.popupWindow)return this.setState({isAuthenticating:!1,authError:"Popup blocked"}),void t(new Error("Popup blocked. Please allow popups for this site."));this.messageHandler=r=>{if(r.origin!==new URL(this.apiUrl).origin)return;const{type:s,payload:n}=r.data||{};"orquesta_auth_success"===s?(this.handleAuthSuccess(n),e(n),this.cleanup()):"orquesta_auth_error"===s?(this.handleAuthError(n),t(new Error(n.message||"Authentication failed")),this.cleanup()):"orquesta_auth_closed"===s&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup())},window.addEventListener("message",this.messageHandler);const a=setInterval(()=>{this.popupWindow?.closed&&(clearInterval(a),this.state.isAuthenticating&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup()))},500)})}handleAuthSuccess(e){const t={user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt};this.saveSession(t),this.setState({isAuthenticated:!0,isAuthenticating:!1,user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null})}handleAuthError(e){this.setState({isAuthenticating:!1,authError:e.message})}cleanup(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.popupWindow&&!this.popupWindow.closed&&this.popupWindow.close(),this.popupWindow=null}async logout(){const e=this.loadSession();if(e?.sessionToken)try{await fetch(`${this.apiUrl}/api/embed/session`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})})}catch{}this.clearSession(),this.setState(this.getInitialState())}getUser(){return this.state.user}getSessionToken(){return this.state.sessionToken}destroy(){this.cleanup(),this.listeners.clear()}}const ns=!1,is="prompts",os="dark";const as=new class{constructor(){this.projectId=null}setProjectId(e){this.projectId=e}getKey(e){const t=`orquesta_embed_${e}`;return this.projectId?`${t}_${this.projectId}`:t}get(e){try{const t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):null}catch{return null}}set(e,t){try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch{}}remove(e){try{localStorage.removeItem(this.getKey(e))}catch{}}getState(){return{isOpen:this.get("isOpen")??ns,position:this.get("position"),size:this.get("size"),activeTab:this.get("activeTab")??is,theme:this.get("theme")??os}}setState(e){Object.entries(e).forEach(([e,t])=>{void 0!==t&&this.set(e,t)})}clear(){["isOpen","position","size","activeTab","theme"].forEach(e=>this.remove(e))}};class ls{constructor(e){this.supabase=null,this.channel=null,this.projectId=null,this.authManager=null,this.hotkeyHandler=null,this.config={...Qr,...e},this.state=new Zr,this.consoleCapture=new es,this.networkCapture=new ts,this.elementSelector=new rs,this.config.requireAuth&&(this.state.setRequireAuth(!0),this.authManager=new ss(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}))}async connect(){if(!this.config.token)throw new Error("Embed token is required");this.state.setState({isConnecting:!0});try{this.authManager&&await this.authManager.checkSession();const s=await fetch(`${this.config.apiUrl}/api/embed/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.token})});if(!s.ok){const e=await s.json();throw new Error(e.error||"Failed to validate token")}const n=await s.json();if(!n.valid)throw new Error("Invalid embed token");this.projectId=n.projectId,as.setProjectId(n.projectId),this.supabase=(e=n.supabaseUrl,t=n.supabaseAnonKey,new Yr(e,t,r)),this.channel=this.supabase.channel(n.channelName),this.channel.on("broadcast",{event:"output"},({payload:e})=>{this.handleOutput(e)}).on("broadcast",{event:"complete"},({payload:e})=>{this.handleComplete(e)}).on("broadcast",{event:"error"},({payload:e})=>{this.handleError(e)}).subscribe(e=>{if("SUBSCRIBED"===e){this.state.setConnected(n.projectId,n.project?.name||"Project",n.project?.agent_online||!1),this.config.captureConsole&&(this.consoleCapture.start(),this.consoleCapture.subscribe(e=>{this.state.addConsoleLogs([e])})),this.config.captureNetwork&&(this.networkCapture.start(),this.networkCapture.subscribe(e=>{this.state.addNetworkLogs([e])})),this.setupHotkey(),this.loadTimeline();const e=as.getState();this.state.setState({isOpen:this.config.defaultOpen??e.isOpen,activeTab:e.activeTab}),this.config.onReady?.()}else"CHANNEL_ERROR"!==e&&"TIMED_OUT"!==e||this.state.setConnectionError("Failed to connect to channel")})}catch(e){const t=e instanceof Error?e.message:"Connection failed";throw this.state.setConnectionError(t),this.config.onError?.(e instanceof Error?e:new Error(t)),e}var e,t,r}disconnect(){this.channel&&(this.supabase?.removeChannel(this.channel),this.channel=null),this.consoleCapture.stop(),this.networkCapture.stop(),this.elementSelector.deactivate(),this.removeHotkey(),this.authManager&&this.authManager.destroy(),this.state.reset(),this.supabase=null,this.projectId=null}setupHotkey(){if(!this.config.hotkey)return;const e=this.config.hotkey.toLowerCase().split("+"),t=e.pop(),r=new Set(e);this.hotkeyHandler=e=>{const s=r.has("ctrl")===(e.ctrlKey||e.metaKey),n=r.has("shift")===e.shiftKey,i=r.has("alt")===e.altKey,o=e.key.toLowerCase()===t;s&&n&&i&&o&&(e.preventDefault(),this.toggle())},document.addEventListener("keydown",this.hotkeyHandler)}removeHotkey(){this.hotkeyHandler&&(document.removeEventListener("keydown",this.hotkeyHandler),this.hotkeyHandler=null)}handleOutput(e){if(!this.state.getState().currentPrompt)return;let t,r="stdout",s=e.data;"stderr"===e.type?r="stderr":e.data.includes("Tool:")||e.data.includes("tool_call")?r="tool":(e.data.includes("thinking")||e.data.includes("Thinking"))&&(r="thinking");try{const n=JSON.parse(e.data);n.type&&(r=n.type,s=n.content||n.message||e.data,t=n)}catch{}this.state.addOutputLine({timestamp:e.timestamp||Date.now(),type:r,content:s,details:t})}handleComplete(e){const t=this.state.getState();t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:0===e.exitCode?"completed":"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1})}handleError(e){const t=this.state.getState();this.state.addOutputLine({timestamp:Date.now(),type:"stderr",content:`Error: ${e.error}`}),t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1})}async submitPrompt(e,t){if(!this.projectId)throw new Error("Not connected");if(this.config.requireAuth&&!this.state.getState().isAuthenticated)throw new Error("Authentication required. Please log in first.");const r=this.state.getState();if(r.isSubmitting)throw new Error("A prompt is already running");this.state.setState({isSubmitting:!0}),this.state.clearOutput();let s=e;const n=t?.elementContext||r.selectedElement;if(n&&(s+=`\n\n--- Element Context ---\nSelector: ${n.selector}\nTag: <${n.tag}>\n${n.id?`ID: ${n.id}`:""}\n${n.className?`Classes: ${n.className}`:""}\n${n.textContent?`Text: ${n.textContent}`:""}\n${n.attributes?`Attributes: ${JSON.stringify(n.attributes)}`:""}`),t?.includeConsole??r.includeConsole){const e=this.consoleCapture.formatForPrompt();e&&(s+=`\n\n--- Console Logs ---\n${e}`)}if(t?.includeNetwork??r.includeNetwork){const e=this.networkCapture.formatForPrompt();e&&(s+=`\n\n--- Network Errors ---\n${e}`)}try{const e={"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},t=this.authManager?.getSessionToken();t&&(e["X-Session-Token"]=t);const r=await fetch(`${this.config.apiUrl}/api/embed/prompts`,{method:"POST",headers:e,body:JSON.stringify({projectId:this.projectId,content:s,elementContext:n})});if(!r.ok){const e=await r.json();throw new Error(e.error||"Failed to submit prompt")}const i=(await r.json()).prompt;return this.state.setCurrentPrompt(i),this.state.setSelectedElement(null),this.config.onPromptSubmit?.(i.id),i.id}catch(e){throw this.state.setState({isSubmitting:!1}),e}}async loadTimeline(){if(this.projectId)try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts?projectId=${this.projectId}&limit=50`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(e.ok){const t=await e.json();this.state.setState({promptHistory:t.prompts||[]})}}catch{}}open(){this.state.setOpen(!0),as.set("isOpen",!0)}close(){this.state.setOpen(!1),as.set("isOpen",!1)}toggle(){const e=!this.state.getState().isOpen;this.state.setOpen(e),as.set("isOpen",e)}startElementSelection(){this.state.startElementSelection(),this.elementSelector.activate(e=>this.state.setSelectedElement(e),()=>this.state.cancelElementSelection())}getState(){return this.state.getState()}subscribe(e){return this.state.subscribe(e)}getConsoleCapture(){return this.consoleCapture}getNetworkCapture(){return this.networkCapture}getElementSelector(){return this.elementSelector}async loadComments(e){if(this.projectId){this.state.setLoadingComments(!0);try{const t=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(t.ok){const r=await t.json();this.state.setCommentsForPrompt(e,r.comments||[])}}catch{}finally{this.state.setLoadingComments(!1)}}}async addComment(e,t){if(this.projectId)try{const r=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({content:t})});if(r.ok){const t=await r.json();t.comment&&this.state.addComment(e,t.comment)}}catch(e){throw console.error("Failed to add comment:",e),e}}setOverlayMode(e){if(this.state.setOverlayMode(e),"off"===e)this.elementSelector.removeHighlight(),this.state.setHighlightedPromptId(null);else if("all"===e){const e=this.state.getState().promptHistory.filter(e=>e.element_context?.selector).map(e=>({promptId:e.id,selector:e.element_context.selector,rect:null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}));this.state.setElementMarkers(e)}else this.state.setElementMarkers([])}highlightPromptElement(e){if(!e.element_context?.selector)return void console.warn("Prompt has no element context");this.elementSelector.highlightElement(e.element_context.selector)?(this.state.setHighlightedPromptId(e.id),this.state.setOverlayMode("single")):console.warn("Element not found for prompt:",e.id)}setupGlobalRightClick(e){return this.elementSelector.setupGlobalRightClick(e)}setupGlobalRightClickWithPosition(e){return this.elementSelector.setupGlobalRightClickWithPosition(e)}async login(){if(!this.authManager)throw new Error("Authentication is not enabled. Set requireAuth: true in config.");try{const e=await this.authManager.login();return this.config.onLogin?.(e.user),e.user}catch(e){throw e}}async logout(){if(!this.authManager)throw new Error("Authentication is not enabled.");await this.authManager.logout(),this.config.onLogout?.()}isAuthenticated(){return this.state.getState().isAuthenticated}getUser(){return this.state.getState().user}isAuthRequired(){return this.config.requireAuth||!1}}function cs({variant:r="primary",size:s="md",loading:n=!1,disabled:i,className:o="",children:a,...l}){return e("button",{className:`inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-zinc-900 disabled:opacity-50 disabled:cursor-not-allowed ${{primary:"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",secondary:"bg-zinc-700 text-white hover:bg-zinc-600 focus:ring-zinc-500",ghost:"bg-transparent text-zinc-300 hover:bg-zinc-800 hover:text-white focus:ring-zinc-500",danger:"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500"}[r]} ${{sm:"px-2.5 py-1.5 text-xs",md:"px-3 py-2 text-sm",lg:"px-4 py-2.5 text-base"}[s]} ${o}`,disabled:i||n,...l,children:[n&&e("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),a]})}function hs({label:r,error:s,className:n="",...i}){return e("div",{className:"w-full",children:[r&&t("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:r}),t("input",{className:`w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-md text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed ${s?"border-red-500":""} ${n}`,...i}),s&&t("p",{className:"mt-1.5 text-sm text-red-400",children:s})]})}const us=s.forwardRef(function({label:r,error:s,className:n="",...i},o){return e("div",{className:"w-full",children:[r&&t("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:r}),t("textarea",{ref:o,className:`w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-md text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed resize-none ${s?"border-red-500":""} ${n}`,...i}),s&&t("p",{className:"mt-1.5 text-sm text-red-400",children:s})]})});function ds({variant:e="default",size:r="md",children:s,className:n=""}){return t("span",{className:`inline-flex items-center font-medium rounded-full ${{default:"bg-zinc-700 text-zinc-300",success:"bg-green-900/50 text-green-400",warning:"bg-yellow-900/50 text-yellow-400",error:"bg-red-900/50 text-red-400",info:"bg-blue-900/50 text-blue-400"}[e]} ${{sm:"px-1.5 py-0.5 text-xs",md:"px-2 py-1 text-xs"}[r]} ${n}`,children:s})}function ps({status:e,className:r=""}){return t("span",{className:`inline-block w-2 h-2 rounded-full ${{online:"bg-green-500",offline:"bg-zinc-500",pending:"bg-yellow-500",running:"bg-blue-500 animate-pulse",completed:"bg-green-500",failed:"bg-red-500"}[e]} ${r}`})}const ms=n(null);function gs(){const e=o(ms);if(!e)throw new Error("Tabs components must be used within a Tabs provider");return e}function fs({defaultValue:e="",value:r,onChange:s,children:n,className:o=""}){const[a,l]=i(e),c=r??a??"";return t(ms.Provider,{value:{activeTab:c,setActiveTab:e=>{void 0===r&&l(e),s?.(e)}},children:t("div",{className:o,children:n})})}function ws({children:e,className:r=""}){return t("div",{className:`flex items-center gap-1 p-1 bg-zinc-800 rounded-lg ${r}`,children:e})}function ys({value:e,children:r,className:s=""}){const{activeTab:n,setActiveTab:i}=gs();return t("button",{onClick:()=>i(e),className:`flex-1 px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${n===e?"bg-zinc-700 text-white":"text-zinc-400 hover:text-zinc-300"} ${s}`,children:r})}function bs({value:e,children:r,className:s=""}){const{activeTab:n}=gs();return n!==e?null:t("div",{className:s,children:r})}function vs({onSubmit:r,isSubmitting:s,selectedElement:n,includeConsole:o,includeNetwork:c,onToggleConsole:h,onToggleNetwork:u,onSelectElement:d,onClearElement:p,agentOnline:m}){const[g,f]=i(""),w=a(null);l(()=>{w.current?.focus()},[]);const y=e=>{e.preventDefault(),g.trim()&&!s&&m&&(r(g.trim(),n),f(""))};return e("form",{onSubmit:y,className:"orquesta-prompt-input",children:[t(us,{ref:w,value:g,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&y(e)},placeholder:m?"What would you like to do?":"Agent is offline...",disabled:s||!m,rows:3,className:"min-h-[80px]"}),e("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[n&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-blue-900/30 text-blue-400 text-xs rounded-md",children:[t("span",{children:"🎯"}),e("span",{className:"font-mono",children:["<",n.tag,">"]}),t("button",{type:"button",onClick:p,className:"ml-1 hover:text-blue-300",children:"×"})]}),o&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-yellow-900/30 text-yellow-400 text-xs rounded-md",children:[t("span",{children:"📋"}),t("span",{children:"Console logs"}),t("button",{type:"button",onClick:h,className:"ml-1 hover:text-yellow-300",children:"×"})]}),c&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-red-900/30 text-red-400 text-xs rounded-md",children:[t("span",{children:"🌐"}),t("span",{children:"Network errors"}),t("button",{type:"button",onClick:u,className:"ml-1 hover:text-red-300",children:"×"})]})]}),e("div",{className:"flex items-center justify-between mt-3",children:[e("div",{className:"flex items-center gap-1.5",children:[e("button",{type:"button",onClick:d,disabled:s,title:"Select an element to include context",className:`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all border ${n?"bg-blue-500/20 text-blue-300 border-blue-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-sm",children:"🎯"}),t("span",{children:"Element"})]}),e("button",{type:"button",onClick:h,disabled:s,title:"Include recent console logs",className:`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all border ${o?"bg-yellow-500/20 text-yellow-300 border-yellow-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-sm",children:"📋"}),t("span",{children:"Logs"}),o&&t("span",{className:"text-yellow-400",children:"✓"})]}),e("button",{type:"button",onClick:u,disabled:s,title:"Include network errors",className:`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all border ${c?"bg-red-500/20 text-red-300 border-red-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-sm",children:"🌐"}),t("span",{children:"Network"}),c&&t("span",{className:"text-red-400",children:"✓"})]})]}),t(cs,{type:"submit",variant:"primary",size:"sm",loading:s,disabled:!g.trim()||!m,children:s?"Running...":"Submit"})]}),!m&&t("p",{className:"mt-2 text-xs text-yellow-400",children:"⚠️ Agent is offline. Start the agent to submit prompts."})]})}function _s({lines:r,isRunning:s}){const n=a(null);if(l(()=>{n.current&&(n.current.scrollTop=n.current.scrollHeight)},[r]),0===r.length&&!s)return t("div",{className:"flex items-center justify-center h-32 text-zinc-500 text-sm",children:"Output will appear here when running prompts"});const i=e=>{switch(e){case"stderr":return"text-red-400";case"tool":return"text-blue-400";case"thinking":return"text-zinc-500 italic";case"system":return"text-yellow-400";default:return"text-zinc-300"}},o=e=>{switch(e){case"stderr":return"✕";case"tool":return"🔧";case"thinking":return"💭";case"system":return"ℹ";default:return"›"}};return e("div",{ref:n,className:"orquesta-log-stream overflow-y-auto max-h-[200px] font-mono text-xs",children:[r.map(r=>e("div",{className:`flex items-start gap-2 py-0.5 ${i(r.type)}`,children:[t("span",{className:"flex-shrink-0 w-4 text-center opacity-50",children:o(r.type)}),t("span",{className:"flex-1 whitespace-pre-wrap break-all",children:r.content})]},r.id)),s&&e("div",{className:"flex items-center gap-2 py-1 text-blue-400 animate-pulse",children:[t("span",{className:"w-4 text-center",children:"●"}),t("span",{children:"Running..."})]})]})}function ks({author:r,size:s="sm",showName:n=!1,className:i=""}){const o={sm:"w-5 h-5 text-[10px]",md:"w-6 h-6 text-xs",lg:"w-8 h-8 text-sm"};return e("div",{className:`flex items-center gap-1.5 ${i}`,children:[r?.avatar_url?t("img",{src:r.avatar_url,alt:r.full_name||"User",className:`${o[s]} rounded-full object-cover ring-1 ring-zinc-700`}):t("div",{className:`${o[s]} ${(e=>{if(!e)return"bg-zinc-600";const t=["bg-blue-600","bg-green-600","bg-purple-600","bg-orange-600","bg-pink-600","bg-cyan-600","bg-indigo-600","bg-teal-600"];return t[e.split("").reduce((e,t)=>e+t.charCodeAt(0),0)%t.length]})(r?.id)} rounded-full flex items-center justify-center font-medium text-white ring-1 ring-zinc-700`,children:(e=>{if(!e)return"?";const t=e.trim().split(" ");return 1===t.length?t[0][0]?.toUpperCase()||"?":(t[0][0]+t[t.length-1][0]).toUpperCase()})(r?.full_name)}),n&&r?.full_name&&t("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:r.full_name})]})}function xs({sha:r,url:s,branch:n,className:i=""}){if(!r)return null;const o=r.slice(0,7),a=e("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 bg-zinc-800 rounded text-[10px] font-mono text-zinc-400 hover:bg-zinc-700 hover:text-zinc-300 transition-colors ${i}`,children:[t("svg",{className:"w-3 h-3",fill:"currentColor",viewBox:"0 0 16 16",children:t("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"})}),o,n&&e("span",{className:"text-zinc-500",children:["(",n,")"]})]});return s?t("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"inline-flex",onClick:e=>e.stopPropagation(),children:a}):a}function Ss(e){const t=new Date(e),r=(new Date).getTime()-t.getTime(),s=Math.floor(r/6e4),n=Math.floor(s/60),i=Math.floor(n/24);return s<1?"just now":s<60?`${s}m`:n<24?`${n}h`:i<7?`${i}d`:t.toLocaleDateString()}function Es({comments:r,isLoading:s=!1,className:n=""}){return s?t("div",{className:`space-y-2 ${n}`,children:[1,2].map(r=>e("div",{className:"flex gap-2 animate-pulse",children:[t("div",{className:"w-5 h-5 bg-zinc-700 rounded-full"}),e("div",{className:"flex-1 space-y-1",children:[t("div",{className:"h-3 bg-zinc-700 rounded w-20"}),t("div",{className:"h-3 bg-zinc-700 rounded w-full"})]})]},r))}):0===r.length?t("div",{className:`text-center text-xs text-zinc-500 py-3 ${n}`,children:"No comments yet"}):t("div",{className:`space-y-3 ${n}`,children:r.map(r=>e("div",{className:"flex gap-2",children:[t(ks,{author:r.author,size:"sm"}),e("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs font-medium text-zinc-300 truncate",children:r.author?.full_name||"Unknown"}),t("span",{className:"text-[10px] text-zinc-500",children:Ss(r.created_at)})]}),t("p",{className:"text-xs text-zinc-400 mt-0.5 break-words",children:r.content})]})]},r.id))})}function Ts({onSubmit:r,placeholder:s="Add a comment...",disabled:n=!1,className:o=""}){const[a,l]=i(""),[c,h]=i(!1),u=async e=>{if(e.preventDefault(),a.trim()&&!c&&!n){h(!0);try{await r(a.trim()),l("")}finally{h(!1)}}};return e("form",{onSubmit:u,className:`flex gap-2 ${o}`,children:[t("input",{type:"text",value:a,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),u(e))},placeholder:s,disabled:n||c,className:"flex-1 px-2 py-1.5 bg-zinc-800 border border-zinc-700 rounded text-xs text-white placeholder:text-zinc-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"}),t("button",{type:"submit",disabled:!a.trim()||c||n,className:"px-2 py-1.5 bg-blue-600 text-white text-xs rounded hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:c?e("svg",{className:"w-3 h-3 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):"Post"})]})}function Cs({prompts:r,currentPromptId:s,expandedPromptId:n,comments:o={},isLoadingComments:c=!1,promptOutputs:h={},onSelectPrompt:u,onExpandPrompt:d,onHighlightElement:p,onLoadComments:m,onAddComment:g}){const[f,w]=i(null),[y,b]=i(null),v=a(null),_=a(r.length);if(l(()=>{r.length>_.current&&v.current&&(v.current.scrollTop=0),_.current=r.length},[r.length]),0===r.length)return t("div",{className:"flex items-center justify-center h-32 text-zinc-500 text-sm",children:"No prompts yet. Right-click any element to start!"});const k=e=>{const t=new Date(e),r=(new Date).getTime()-t.getTime(),s=Math.floor(r/6e4),n=Math.floor(r/36e5),i=Math.floor(r/864e5);return s<1?"Just now":s<60?`${s}m ago`:n<24?`${n}h ago`:i<7?`${i}d ago`:t.toLocaleDateString()},x=e=>{switch(e){case"completed":return"success";case"failed":return"error";case"running":return"info";default:return"default"}};return t("div",{ref:v,className:"orquesta-timeline space-y-2 overflow-y-auto max-h-[400px]",children:r.map(r=>{const i=n===r.id,a=r.id===s,l=f===r.id,v=o[r.id]||[],_=h[r.id]||[],S=y===r.id;return e("div",{className:"rounded-lg border transition-all "+(a?"bg-zinc-800 border-blue-500":"bg-zinc-900 border-zinc-800 hover:border-zinc-700"),onMouseEnter:()=>w(r.id),onMouseLeave:()=>w(null),children:[t("button",{onClick:()=>(e=>{u?.(e),e.element_context&&p&&p(e)})(r),className:"w-full text-left p-3",children:e("div",{className:"flex items-start gap-2",children:[t(ks,{author:r.author,size:"sm"}),e("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:[t("span",{className:"text-xs font-medium text-zinc-300 truncate",children:r.author?.full_name||"Unknown"}),t("span",{className:"text-[10px] text-zinc-500",children:k(r.created_at)})]}),e("p",{className:"text-sm text-zinc-200 line-clamp-2",children:[r.content.slice(0,100),r.content.length>100&&"..."]}),e("div",{className:"flex items-center gap-2 mt-2 flex-wrap",children:[r.git_commit_sha&&t(xs,{sha:r.git_commit_sha,url:r.git_commit_url,branch:r.git_branch}),r.element_context&&e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 border border-blue-500/30 rounded-md text-[10px] text-blue-400 font-medium",children:[t("span",{children:"🎯"}),e("span",{children:["<",r.element_context.tag,">"]}),r.element_context.textContent&&e("span",{className:"text-blue-300/70 max-w-[60px] truncate",children:['"',r.element_context.textContent.slice(0,15),'..."']})]}),(r.comment_count||0)>0&&e("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 bg-zinc-800 rounded text-[10px] text-zinc-400",children:["💬 ",r.comment_count]})]})]}),e("div",{className:"flex-shrink-0 flex items-center gap-1.5",children:[t(ps,{status:r.status}),t(ds,{variant:x(r.status),size:"sm",children:r.status})]})]})}),e("div",{className:"flex items-center gap-2 px-3 pb-2 -mt-1 "+(l||r.element_context||i||"completed"===r.status||"failed"===r.status?"":"hidden"),children:[r.element_context&&e("button",{onClick:e=>{e.stopPropagation(),p?.(r)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-purple-600/20 border border-purple-500/40 rounded-md text-[11px] text-purple-300 font-medium hover:bg-purple-600/30 hover:border-purple-500/60 transition-all",children:[e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]}),t("span",{children:"Show on page"})]}),("completed"===r.status||"failed"===r.status)&&e("button",{onClick:e=>{e.stopPropagation(),b(S?null:r.id)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium transition-all "+(S?"bg-zinc-600 border border-zinc-500 text-zinc-100":"bg-zinc-700/50 border border-zinc-600/50 text-zinc-300 hover:bg-zinc-700 hover:border-zinc-500"),children:[t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})}),t("span",{children:S?"Hide output":"View output"})]}),t("button",{onClick:e=>{e.stopPropagation(),(async e=>{n===e?d?.(null):(d?.(e),m&&!o[e]&&await m(e))})(r.id)},className:"inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium transition-all ml-auto "+(i?"bg-zinc-700 text-zinc-200":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-300"),children:i?"Hide comments":(r.comment_count||0)>0?`💬 ${r.comment_count}`:"+ Comment"})]}),S&&t("div",{className:"px-3 pb-3 border-t border-zinc-800",children:t("div",{className:"mt-2 bg-zinc-950 rounded-md p-2 max-h-[150px] overflow-y-auto",children:_.length>0?t("div",{className:"font-mono text-[11px] space-y-0.5",children:_.slice(-20).map((e,r)=>t("div",{className:""+("stderr"===e.type?"text-red-400":"tool"===e.type?"text-blue-400":"thinking"===e.type?"text-zinc-500 italic":"system"===e.type?"text-yellow-400":"text-zinc-300"),children:e.content},r))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No output recorded for this prompt"})})}),i&&e("div",{className:"px-3 pb-3 pt-1 border-t border-zinc-800 space-y-3",children:[t(Es,{comments:v,isLoading:c}),g&&t(Ts,{onSubmit:e=>g(r.id,e),placeholder:"Add a comment..."})]})]},r.id)})})}const Os=400,Rs=500;function Ns({state:s,position:n,onClose:o,onMinimize:h,onSubmitPrompt:u,onSelectElement:d,onClearElement:p,onToggleConsole:m,onToggleNetwork:g,onTabChange:f,onExpandPrompt:w,onHighlightElement:y,onLoadComments:b,onAddComment:v,onOverlayModeChange:_,onLogin:k,onLogout:x}){const S=a(null),[E,T]=i(!1),[C,O]=i(!1),[R,N]=i(()=>as.get("position")||function(e){const t=20;switch(e){case"bottom-right":return{x:window.innerWidth-Os-t,y:window.innerHeight-Rs-t};case"bottom-left":return{x:t,y:window.innerHeight-Rs-t};case"top-right":return{x:window.innerWidth-Os-t,y:t};case"top-left":return{x:t,y:t}}}(n)),[A,$]=i(()=>as.get("size")||{width:Os,height:Rs}),j=a({x:0,y:0}),I=a({width:0,height:0,x:0,y:0});const P=c(e=>{e.target.closest("button")||(T(!0),j.current={x:e.clientX-R.x,y:e.clientY-R.y})},[R]),L=c(e=>{e.stopPropagation(),O(!0),I.current={width:A.width,height:A.height,x:e.clientX,y:e.clientY}},[A]);return l(()=>{const e=e=>{if(E){const t=Math.max(0,Math.min(window.innerWidth-A.width,e.clientX-j.current.x)),r=Math.max(0,Math.min(window.innerHeight-A.height,e.clientY-j.current.y));N({x:t,y:r})}else if(C){const t=e.clientX-I.current.x,r=e.clientY-I.current.y,s=Math.max(320,I.current.width+t),n=Math.max(400,I.current.height+r);$({width:s,height:n})}},t=()=>{E&&(T(!1),as.set("position",R)),C&&(O(!1),as.set("size",A))};return(E||C)&&(document.addEventListener("mousemove",e),document.addEventListener("mouseup",t)),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[E,C,R,A]),e("div",{ref:S,className:"orquesta-embed-panel fixed z-[2147483647] bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl flex flex-col overflow-hidden",style:{left:R.x,top:R.y,width:A.width,height:A.height},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700 cursor-move select-none",onMouseDown:P,children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-lg",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"}),s.projectName&&e("span",{className:"text-xs text-zinc-400",children:["• ",s.projectName]})]}),e("div",{className:"flex items-center gap-1",children:[s.requireAuth&&(s.isAuthenticated&&s.user?e("div",{className:"flex items-center gap-1.5 mr-2",children:[s.user.avatar_url?t("img",{src:s.user.avatar_url,alt:"",className:"w-5 h-5 rounded-full"}):t("div",{className:"w-5 h-5 rounded-full bg-zinc-600 flex items-center justify-center text-xs text-white",children:s.user.full_name?.[0]?.toUpperCase()||"?"}),t("span",{className:"text-xs text-zinc-300 max-w-20 truncate",children:s.user.full_name||"User"}),t("button",{onClick:x,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Sign out",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})})]}):t("button",{onClick:k,disabled:s.isAuthenticating,className:"flex items-center gap-1 px-2 py-1 mr-2 text-xs bg-blue-600 hover:bg-blue-500 disabled:bg-blue-800 text-white rounded transition-colors",children:s.isAuthenticating?e(r,{children:[e("svg",{className:"animate-spin w-3 h-3",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{children:"Signing in..."})]}):e(r,{children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"})}),t("span",{children:"Sign in"})]})})),t(ps,{status:s.agentOnline?"online":"offline"}),e("div",{className:"flex items-center gap-0.5 mx-1 bg-zinc-800 rounded p-0.5",children:[t("button",{onClick:()=>_?.("off"),className:"p-1 rounded text-xs "+("off"===s.overlayMode?"bg-zinc-700 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Overlay off",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"})})}),t("button",{onClick:()=>_?.("single"),className:"p-1 rounded text-xs "+("single"===s.overlayMode?"bg-blue-600 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Show selected prompt on page",children:e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})}),t("button",{onClick:()=>_?.("all"),className:"p-1 rounded text-xs "+("all"===s.overlayMode?"bg-purple-600 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Show all prompts on page",children:e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 11a3 3 0 11-6 0 3 3 0 016 0z"})]})})]}),t("button",{onClick:h,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Minimize",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),t("button",{onClick:o,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Close",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),e(fs,{value:s.activeTab,onChange:e=>f(e),className:"flex-1 flex flex-col overflow-hidden",children:[t("div",{className:"px-3 py-2 border-b border-zinc-800",children:e(ws,{className:"w-full",children:[t(ys,{value:"prompts",children:"Prompts"}),t(ys,{value:"timeline",children:"Timeline"})]})}),e("div",{className:"flex-1 overflow-y-auto p-3",children:[s.requireAuth&&!s.isAuthenticated&&e("div",{className:"h-full flex flex-col items-center justify-center text-center p-4",children:[t("div",{className:"w-16 h-16 rounded-full bg-zinc-800 flex items-center justify-center mb-4",children:t("svg",{className:"w-8 h-8 text-zinc-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"})})}),t("h3",{className:"text-white font-semibold mb-2",children:"Sign in to continue"}),t("p",{className:"text-zinc-400 text-sm mb-4",children:"You need to sign in to submit prompts to this project."}),s.authError&&t("div",{className:"mb-4 px-3 py-2 bg-red-900/30 border border-red-800 rounded text-red-300 text-xs",children:s.authError}),t("button",{onClick:k,disabled:s.isAuthenticating,className:"flex items-center gap-2 px-4 py-2 bg-white text-gray-800 rounded-lg font-medium hover:bg-gray-100 disabled:bg-gray-300 transition-colors",children:s.isAuthenticating?e(r,{children:[e("svg",{className:"animate-spin w-4 h-4",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{children:"Signing in..."})]}):e(r,{children:[e("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",children:[t("path",{fill:"currentColor",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),t("path",{fill:"currentColor",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),t("path",{fill:"currentColor",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),t("path",{fill:"currentColor",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),t("span",{children:"Continue with Google"})]})}),t("p",{className:"text-zinc-500 text-xs mt-4",children:"You must be a member of this project's organization."})]}),(!s.requireAuth||s.isAuthenticated)&&e(r,{children:[e(bs,{value:"prompts",className:"h-full flex flex-col",children:[t(vs,{onSubmit:u,isSubmitting:s.isSubmitting,selectedElement:s.selectedElement,includeConsole:s.includeConsole,includeNetwork:s.includeNetwork,onToggleConsole:m,onToggleNetwork:g,onSelectElement:d,onClearElement:p,agentOnline:s.agentOnline}),(s.currentPrompt||s.outputLines.length>0)&&e("div",{className:"mt-4 pt-4 border-t border-zinc-800",children:[s.currentPrompt&&e("div",{className:"flex items-center gap-2 mb-2",children:[t(ps,{status:s.currentPrompt.status}),e("span",{className:"text-xs text-zinc-400 line-clamp-1",children:[s.currentPrompt.content.slice(0,50),"..."]})]}),t(_s,{lines:s.outputLines,isRunning:s.isSubmitting})]})]}),t(bs,{value:"timeline",children:t(Cs,{prompts:s.promptHistory,currentPromptId:s.currentPrompt?.id,expandedPromptId:s.expandedPromptId,comments:s.comments,isLoadingComments:s.isLoadingComments,promptOutputs:s.promptOutputs,onExpandPrompt:w,onHighlightElement:y,onLoadComments:b,onAddComment:v})})]})]})]}),t("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-se-resize",onMouseDown:L,children:t("svg",{className:"w-full h-full text-zinc-600",viewBox:"0 0 16 16",fill:"currentColor",children:t("path",{d:"M14 14H10V10H14V14ZM14 8H12V6H14V8ZM8 14H6V12H8V14Z"})})})]})}function As({isActive:r,onCancel:s}){const n=a(null);return l(()=>{const e=e=>{"Escape"===e.key&&r&&s()};return r&&document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[r,s]),r?t("div",{ref:n,className:"orquesta-element-inspector fixed inset-0 z-[2147483645] pointer-events-none",children:t("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 pointer-events-auto",children:e("div",{className:"flex items-center gap-3 px-4 py-2 bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl",children:[t("span",{className:"text-sm text-zinc-300",children:"Click on any element to select it, or right-click for options"}),t(cs,{variant:"ghost",size:"sm",onClick:s,children:"Cancel (Esc)"})]})})}):null}function $s({markers:r,onMarkerClick:s}){const[n,o]=i([]),[h,u]=i(null),d=a(null),p=c(()=>{d.current&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{const e=window.innerHeight,t=window.innerWidth,s=[];for(const n of r)try{const r=document.querySelector(n.selector);if(r){const i=r.getBoundingClientRect(),o=i.left+i.width/2,a=i.top+i.height/2,l=i.top<e&&i.bottom>0&&i.left<t&&i.right>0;s.push({promptId:n.promptId,x:o,y:a,visible:!0,inViewport:l})}else s.push({promptId:n.promptId,x:0,y:0,visible:!1,inViewport:!1})}catch{s.push({promptId:n.promptId,x:0,y:0,visible:!1,inViewport:!1})}o(s)})},[r]);l(()=>{p();let e=!1;const t=()=>{e||(e=!0,requestAnimationFrame(()=>{p(),e=!1}))};window.addEventListener("scroll",t,!0),window.addEventListener("resize",t);const r=new MutationObserver(t);return r.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),()=>{window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t),r.disconnect(),d.current&&cancelAnimationFrame(d.current)}},[p]);const m=h?r.find(e=>e.promptId===h):null,g=h?n.find(e=>e.promptId===h):null;return e("div",{className:"orquesta-markers-overlay fixed inset-0 pointer-events-none z-[2147483646]",children:[n.map((n,i)=>{if(!n.visible||!n.inViewport)return null;const o=r.find(e=>e.promptId===n.promptId);if(!o)return null;const a=h===n.promptId;return e("div",{className:"absolute pointer-events-auto",style:{left:n.x,top:n.y,transform:"translate(-50%, -50%)"},children:[e("button",{onClick:()=>s?.(n.promptId),onMouseEnter:()=>u(n.promptId),onMouseLeave:()=>u(null),className:"relative flex items-center gap-1.5 px-2 py-1 rounded-full border-2 shadow-lg transition-all "+(a?"bg-purple-500 border-white scale-110":"bg-purple-600 border-white/80 hover:scale-105"),children:[t("span",{className:"w-5 h-5 flex items-center justify-center bg-white/20 rounded-full text-white text-[10px] font-bold",children:i+1}),e("span",{className:"text-white text-[11px] font-medium max-w-[120px] truncate",children:[o.content.slice(0,25),o.content.length>25?"...":""]})]}),t("div",{className:"absolute inset-0 -z-10 animate-ping rounded-full bg-purple-500/30",style:{animationDuration:"2s"}})]},n.promptId)}),m&&g&&g.visible&&g.inViewport&&e("div",{className:"fixed pointer-events-none bg-zinc-900 border border-zinc-600 rounded-xl shadow-2xl p-4 z-20",style:{...(e=>{let t=e.x+20,r=e.y+20;return t+280>window.innerWidth-20&&(t=e.x-280-20),r+180>window.innerHeight-20&&(r=e.y-180-20),{left:t,top:r}})(g),width:280},children:[e("div",{className:"flex items-center justify-between mb-3",children:[e("div",{className:"flex items-center gap-2",children:[t(ks,{author:m.author,size:"sm"}),t("span",{className:"text-xs font-medium text-zinc-200",children:m.author?.full_name||"Unknown"})]}),e("span",{className:"px-2 py-0.5 bg-blue-500/20 border border-blue-500/30 rounded text-[10px] text-blue-400 font-mono",children:["🎯 ",m.selector.split(" ").pop()?.split(".")[0]||"element"]})]}),e("p",{className:"text-sm text-zinc-200 mb-3 line-clamp-3",children:[m.content.slice(0,150),m.content.length>150&&"..."]}),e("div",{className:"flex items-center gap-3 text-[10px] text-zinc-500",children:[m.gitCommitSha&&e("span",{className:"inline-flex items-center gap-1 font-mono bg-zinc-800 px-1.5 py-0.5 rounded",children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})}),m.gitCommitSha.slice(0,7)]}),m.commentCount>0&&e("span",{className:"inline-flex items-center gap-1",children:["💬 ",m.commentCount," comments"]})]}),t("div",{className:"mt-3 pt-2 border-t border-zinc-800 text-[10px] text-zinc-500 text-center",children:"Click to view in timeline"})]})]})}function js({isOpen:r,position:s,element:n,agentOnline:o,includeConsole:c,includeNetwork:h,onSubmit:u,onClose:d,onToggleConsole:p,onToggleNetwork:m,onOpenPanel:g}){const[f,w]=i(""),[y,b]=i(!1),v=a(null),_=a(null);if(l(()=>{r&&_.current&&setTimeout(()=>_.current?.focus(),50)},[r]),l(()=>{if(r&&v.current){const e=v.current,t=e.getBoundingClientRect(),r=window.innerWidth,s=window.innerHeight;t.right>r-20&&(e.style.left=`${Math.max(20,r-t.width-20)}px`),t.bottom>s-20&&(e.style.top=`${Math.max(20,s-t.height-20)}px`)}},[r,s]),l(()=>{if(!r)return;const e=e=>{v.current&&!v.current.contains(e.target)&&d()},t=e=>{"Escape"===e.key&&d()};return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)}},[r,d]),l(()=>{r&&(w(""),b(!1))},[r]),!r||!n)return null;const k=async e=>{e.preventDefault(),f.trim()&&!y&&o&&(b(!0),u(f.trim()),w(""),setTimeout(()=>{d()},100))};return e("div",{ref:v,id:"orquesta-context-menu",style:{position:"fixed",zIndex:2147483647,backgroundColor:"#18181b",border:"1px solid #52525b",borderRadius:"12px",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.5)",overflow:"hidden",left:s.x,top:s.y,width:340,maxWidth:"calc(100vw - 40px)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',color:"#ffffff"},onClick:e=>e.stopPropagation(),children:[e("div",{style:{padding:"10px 12px",backgroundColor:"#27272a",borderBottom:"1px solid #3f3f46"},children:[e("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"6px"},children:[t("div",{style:{width:"24px",height:"24px",borderRadius:"6px",backgroundColor:"rgba(37, 99, 235, 0.2)",border:"1px solid rgba(59, 130, 246, 0.3)",display:"flex",alignItems:"center",justifyContent:"center"},children:t("span",{style:{color:"#60a5fa",fontSize:"14px"},children:"🎯"})}),t("span",{style:{fontSize:"14px",fontWeight:500,color:"#ffffff"},children:"Selected Element"})]}),t("div",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",color:"#a1a1aa",backgroundColor:"rgba(24, 24, 27, 0.5)",padding:"6px 8px",borderRadius:"6px",wordBreak:"break-all"},children:(()=>{const e=[];if(e.push(`<${n.tag}`),n.id&&e.push(` id="${n.id}"`),n.className){const t=n.className.split(" ").slice(0,2).join(" ");e.push(` class="${t}${n.className.split(" ").length>2?"...":""}"`)}if(e.push(">"),n.textContent){const t=n.textContent.slice(0,30);e.push(t+(n.textContent.length>30?"...":""))}return e.push(`</${n.tag}>`),e.join("")})()})]}),e("form",{onSubmit:k,style:{padding:"12px"},children:[t("textarea",{ref:_,value:f,onChange:e=>w(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&k(e)},placeholder:o?"What do you want to do with this element?":"Agent is offline...",disabled:y||!o,rows:3,style:{width:"100%",padding:"8px 10px",backgroundColor:"#09090b",border:"1px solid #3f3f46",borderRadius:"6px",color:"#ffffff",fontSize:"13px",fontFamily:"inherit",resize:"vertical",outline:"none",boxSizing:"border-box"}}),e("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:[e("button",{type:"button",onClick:p,style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"all 0.15s ease",backgroundColor:c?"rgba(234, 179, 8, 0.2)":"#27272a",color:c?"#fde047":"#a1a1aa",border:c?"1px solid rgba(234, 179, 8, 0.3)":"1px solid #3f3f46"},children:[t("span",{children:"📋"}),t("span",{children:"Logs"}),c&&t("span",{style:{marginLeft:"2px",color:"#facc15"},children:"✓"})]}),e("button",{type:"button",onClick:m,style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"all 0.15s ease",backgroundColor:h?"rgba(239, 68, 68, 0.2)":"#27272a",color:h?"#fca5a5":"#a1a1aa",border:h?"1px solid rgba(239, 68, 68, 0.3)":"1px solid #3f3f46"},children:[t("span",{children:"🌐"}),t("span",{children:"Network"}),h&&t("span",{style:{marginLeft:"2px",color:"#f87171"},children:"✓"})]})]}),e("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:"12px",paddingTop:"12px",borderTop:"1px solid #27272a"},children:[t("button",{type:"button",onClick:g,style:{fontSize:"12px",color:"#a1a1aa",background:"none",border:"none",cursor:"pointer",padding:0},children:"Open full panel →"}),e("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t("button",{type:"button",onClick:d,style:{padding:"6px 12px",borderRadius:"6px",fontSize:"12px",fontWeight:500,cursor:"pointer",backgroundColor:"transparent",color:"#d4d4d8",border:"none"},children:"Cancel"}),t("button",{type:"submit",disabled:!f.trim()||!o||y,style:{padding:"6px 12px",borderRadius:"6px",fontSize:"12px",fontWeight:500,cursor:f.trim()&&o&&!y?"pointer":"not-allowed",backgroundColor:f.trim()&&o&&!y?"#2563eb":"#3f3f46",color:"#ffffff",border:"none",opacity:f.trim()&&o&&!y?1:.5},children:y?"Submitting...":"Submit"})]})]}),e("div",{style:{marginTop:"8px",fontSize:"10px",color:"#71717a",textAlign:"center"},children:["Press ",t("kbd",{style:{padding:"2px 4px",backgroundColor:"#27272a",borderRadius:"4px"},children:"⌘/Ctrl + Enter"})," to submit"]})]})]})}function Is({isConnected:r,agentOnline:s,projectName:n,currentPrompt:o,isSubmitting:a,lastCompletedPrompt:c,onClose:h}){const[u,d]=i(!0),[p,m]=i(!1),g=r?s?a||"running"===o?.status?"running":"completed"===o?.status?"completed":"failed"===o?.status?"failed":"idle":"offline":"connecting";if(l(()=>{"running"!==g&&"completed"!==g&&"failed"!==g||(d(!0),m(!1))},[g]),l(()=>{if("completed"===g||"failed"===g){const e=setTimeout(()=>{m(!0)},5e3);return()=>clearTimeout(e)}},[g,o?.id]),!u)return null;const f=(()=>{switch(g){case"connecting":return{bg:"#27272a",border:"#3f3f46",icon:"⟳",iconBg:"#3f3f46",text:"Connecting to Orquesta...",pulse:!0};case"offline":return{bg:"#27272a",border:"#ef4444",icon:"○",iconBg:"#7f1d1d",text:"Agent offline",pulse:!1};case"running":return{bg:"#172554",border:"#3b82f6",icon:"⟳",iconBg:"#1d4ed8",text:`Running: ${o?.content.slice(0,50)}${(o?.content.length||0)>50?"...":""}`,pulse:!0};case"completed":return{bg:"#14532d",border:"#22c55e",icon:"✓",iconBg:"#15803d",text:"Completed"+(o?.git_commit_sha?` • Commit ${o.git_commit_sha.slice(0,7)}`:""),pulse:!1};case"failed":return{bg:"#450a0a",border:"#ef4444",icon:"✕",iconBg:"#b91c1c",text:"Prompt failed",pulse:!1};default:return{bg:"#18181b",border:"#3f3f46",icon:"⬡",iconBg:"#27272a",text:n?`${n} • Ready`:"Orquesta Ready",pulse:!1}}})();return e("div",p?{id:"orquesta-status-bar-minimized",onClick:()=>m(!1),style:{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:2147483646,display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:f.bg,border:`1px solid ${f.border}`,borderRadius:"20px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",cursor:"pointer",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',transition:"all 0.2s ease"},children:[t("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"completed"===g?"#22c55e":"failed"===g?"#ef4444":"running"===g?"#3b82f6":"#71717a",animation:f.pulse?"pulse 2s infinite":"none"}}),t("span",{style:{fontSize:"11px",color:"#d4d4d8",fontWeight:500},children:"Orquesta"}),t("style",{children:"\n @keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n "})]}:{id:"orquesta-status-bar",style:{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:2147483646,display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px 8px 10px",backgroundColor:f.bg,border:`1px solid ${f.border}`,borderRadius:"10px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',maxWidth:"calc(100vw - 40px)",transition:"all 0.3s ease"},children:[t("div",{style:{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:f.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t("span",{style:{fontSize:"14px",color:"#ffffff",animation:f.pulse?"spin 1s linear infinite":"none"},children:f.icon})}),e("div",{style:{flex:1,minWidth:0},children:[t("div",{style:{fontSize:"12px",fontWeight:500,color:"#ffffff",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"400px"},children:f.text}),"running"===g&&t("div",{style:{marginTop:"4px",height:"3px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"2px",overflow:"hidden"},children:t("div",{style:{height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",animation:"progress 2s ease-in-out infinite"}})})]}),"completed"===g&&o?.git_branch&&e("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"4px",flexShrink:0},children:[t("svg",{style:{width:"12px",height:"12px",color:"#a1a1aa"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})}),t("span",{style:{fontSize:"11px",color:"#a1a1aa",fontFamily:"ui-monospace, monospace"},children:o.git_branch})]}),t("button",{onClick:()=>m(!0),style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",flexShrink:0},title:"Minimize",children:t("svg",{style:{width:"14px",height:"14px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),t("button",{onClick:()=>{d(!1),h()},style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",flexShrink:0},title:"Close",children:t("svg",{style:{width:"14px",height:"14px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),t("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes progress {\n 0% { width: 0%; margin-left: 0%; }\n 50% { width: 40%; margin-left: 30%; }\n 100% { width: 0%; margin-left: 100%; }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n "})]})}const Ps=[{id:"demo-1",full_name:"Sarah Chen",avatar_url:null},{id:"demo-2",full_name:"Mike Johnson",avatar_url:null},{id:"demo-3",full_name:"Alex Rivera",avatar_url:null}],Ls=[{id:"demo-prompt-1",content:'Change the "Shop Now" button color to green and add a hover animation',status:"completed",created_at:new Date(Date.now()-72e5).toISOString(),completed_at:new Date(Date.now()-72e5+45e3).toISOString(),user_id:"demo-1",source:"embed",element_context:{selector:"button.bg-blue-600",tag:"button",className:"px-6 py-3 bg-blue-600 text-white rounded-lg font-medium",textContent:"Shop Now"},author:Ps[0],git_branch:"main",git_commit_sha:"a1b2c3d",comment_count:2},{id:"demo-prompt-2",content:'Add a discount badge showing "20% OFF" to the Premium Headphones card',status:"completed",created_at:new Date(Date.now()-36e5).toISOString(),completed_at:new Date(Date.now()-36e5+32e3).toISOString(),user_id:"demo-2",source:"embed",element_context:{selector:"div.bg-gradient-to-br.from-purple-400",tag:"div",className:"bg-gradient-to-br from-purple-400 to-purple-600 h-48 relative",textContent:"Best Seller"},author:Ps[1],git_branch:"feature/product-badges",git_commit_sha:"e4f5g6h",comment_count:1},{id:"demo-prompt-3",content:"Make the contact form email field validate on blur and show error message",status:"completed",created_at:new Date(Date.now()-18e5).toISOString(),completed_at:new Date(Date.now()-18e5+28e3).toISOString(),user_id:"demo-3",source:"embed",element_context:{selector:'input[type="email"]',tag:"input",className:"w-full px-4 py-2 border border-gray-300 rounded-lg",textContent:""},author:Ps[2],git_branch:"main",git_commit_sha:"i7j8k9l",comment_count:0}],Us={"demo-prompt-1":[{id:"comment-1",content:"Looks great! The animation is smooth.",created_at:new Date(Date.now()-54e5).toISOString(),author:Ps[1]},{id:"comment-2",content:"Could we also add this to the Learn More button?",created_at:new Date(Date.now()-36e5).toISOString(),author:Ps[2]}],"demo-prompt-2":[{id:"comment-3",content:"Perfect placement for the badge!",created_at:new Date(Date.now()-27e5).toISOString(),author:Ps[0]}]};function zs(s){const{children:n,enableGlobalRightClick:o=!0,demoMode:h=!1,...u}=s,[d,p]=i(null),[m,g]=i(h?{isConnected:!0,isConnecting:!1,connectionError:null,projectId:"demo-project",projectName:"Demo Store",agentOnline:!0,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,currentPrompt:null,promptHistory:[...Ls],isSubmitting:!1,outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{...Us},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1}:null),[f,w]=i(!1),[y,b]=i(null),[v,_]=i({isOpen:!1,position:{x:0,y:0},element:null}),[k,x]=i(!0),[S,E]=i(null),T=a(null),C=a(null);a(null),l(()=>{"completed"!==m?.currentPrompt?.status&&"failed"!==m?.currentPrompt?.status||E(m.currentPrompt)},[m?.currentPrompt?.status,m?.currentPrompt]),l(()=>{if(h)return C.current=new rs,o&&C.current&&(T.current=C.current.setupGlobalRightClickWithPosition((e,t)=>{C.current&&C.current.highlightSelectedElement(e.selector),_({isOpen:!0,position:t,element:e})})),()=>{T.current&&(T.current(),T.current=null)}},[h,o]),l(()=>{if(h)return;const e=new ls(u);p(e);const t=e.subscribe(e=>{g(e)});return e.connect().catch(e=>{b(e.message)}),o&&(T.current=e.setupGlobalRightClickWithPosition((t,r)=>{e.getElementSelector().deactivate(),e.getElementSelector().highlightSelectedElement(t.selector),_({isOpen:!0,position:r,element:t})})),()=>{t(),T.current&&(T.current(),T.current=null),e.disconnect()}},[u.token,o,h]);const O=c(()=>{h?g(e=>e?{...e,isOpen:!1}:null):d?.close()},[d,h]),R=c(()=>{w(!0)},[]),N=c(()=>{w(!1),h?g(e=>e?{...e,isOpen:!0}:null):d?.open()},[d,h]),A=c(async(e,t)=>{if(h){const r=t||m?.selectedElement||void 0,s={id:`demo-prompt-${Date.now()}`,content:e,status:"running",created_at:(new Date).toISOString(),user_id:"demo-user",source:"embed",element_context:r,author:{id:"demo-user",full_name:"Demo User",avatar_url:null},comment_count:0};g(e=>e?{...e,isSubmitting:!0,currentPrompt:s,outputLines:[],promptHistory:[s,...e.promptHistory]}:null);return[{delay:200,type:"system",content:"Starting Claude CLI session..."},{delay:600,type:"thinking",content:"Analyzing the request..."},{delay:1e3,type:"stdout",content:`Processing: "${e.slice(0,50)}${e.length>50?"...":""}"`},{delay:1400,type:"tool",content:"Tool: Edit file"},{delay:1800,type:"stdout",content:"Changes applied successfully."}].forEach(({delay:e,type:t,content:r})=>{setTimeout(()=>{g(e=>e?{...e,outputLines:[...e.outputLines,{id:`output-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,timestamp:Date.now(),type:t,content:r}]}:null)},e)}),void setTimeout(()=>{g(e=>{if(!e)return null;const t={...s,status:"completed",completed_at:(new Date).toISOString(),git_branch:"main",git_commit_sha:Math.random().toString(36).slice(2,9)},r=[...e.outputLines,{id:`output-${Date.now()}-complete`,timestamp:Date.now(),type:"system",content:"Prompt completed successfully."}];return{...e,isSubmitting:!1,currentPrompt:t,selectedElement:null,outputLines:r,promptOutputs:{...e.promptOutputs,[s.id]:r},promptHistory:e.promptHistory.map(e=>e.id===s.id?t:e)}})},2200)}if(d)try{await d.submitPrompt(e,{elementContext:t||void 0})}catch(e){console.error("Failed to submit prompt:",e)}},[d,h,m?.selectedElement]),$=c(()=>{h?(g(e=>e?{...e,isSelectingElement:!0}:null),C.current?.activate(e=>{g(t=>t?{...t,selectedElement:e,isSelectingElement:!1}:null)},()=>{g(e=>e?{...e,isSelectingElement:!1}:null)})):d?.startElementSelection()},[d,h]),j=c(()=>{h?(g(e=>e?{...e,selectedElement:null}:null),C.current?.deactivate(),C.current?.removeSelectedHighlight()):d&&(g(e=>e?{...e,selectedElement:null}:null),d.getElementSelector().deactivate(),d.getElementSelector().removeSelectedHighlight())},[d,h]),I=c(()=>{m&&g(e=>e?{...e,includeConsole:!e.includeConsole}:null)},[m]),P=c(()=>{m&&g(e=>e?{...e,includeNetwork:!e.includeNetwork}:null)},[m]),L=c(e=>{m&&(g(t=>t?{...t,activeTab:e}:null),as.set("activeTab",e))},[m]),U=c(()=>{h?(C.current?.deactivate(),g(e=>e?{...e,isSelectingElement:!1}:null)):d?.getElementSelector().deactivate()},[d,h]),z=c(e=>{m&&g(t=>t?{...t,expandedPromptId:e}:null)},[m]),D=c(e=>{h?e.element_context?.selector&&(C.current?.highlightElement(e.element_context.selector),g(t=>t?{...t,overlayMode:"single",highlightedPromptId:e.id}:null)):d?.highlightPromptElement(e)},[d,h]),H=c(async e=>{h||d&&await d.loadComments(e)},[d,h]),q=c(async(e,t)=>{if(h){const r={id:`comment-${Date.now()}`,content:t,created_at:(new Date).toISOString(),author:{id:"demo-user",full_name:"Demo User",avatar_url:null}};return void g(t=>{if(!t)return null;const s=t.comments[e]||[];return{...t,comments:{...t.comments,[e]:[...s,r]},promptHistory:t.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)}})}d&&await d.addComment(e,t)},[d,h]),B=c(e=>{h?g(t=>{if(!t)return null;let r=t.elementMarkers;return"all"===e?r=t.promptHistory.filter(e=>e.element_context?.selector).map(e=>{const t=document.querySelector(e.element_context.selector);return{promptId:e.id,selector:e.element_context.selector,rect:t?.getBoundingClientRect()||null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}}):"off"===e&&(C.current?.removeHighlight(),r=[]),{...t,overlayMode:e,highlightedPromptId:"off"===e?null:t.highlightedPromptId,elementMarkers:r}}):d?.setOverlayMode(e)},[d,h]),M=c(e=>{m&&g(t=>t?{...t,activeTab:"timeline",expandedPromptId:e}:null)},[m]),W=c(()=>{_(e=>({...e,isOpen:!1})),h&&C.current?C.current.removeSelectedHighlight():d&&d.getElementSelector().removeSelectedHighlight()},[d,h]),K=c(async e=>{v.element&&(g(e=>e?{...e,selectedElement:v.element,isOpen:!0,activeTab:"prompts"}:null),w(!1),await A(e,v.element||void 0),_(e=>({...e,isOpen:!1})))},[v.element,A]),F=c(()=>{v.element&&(g(e=>e?{...e,selectedElement:v.element,isOpen:!0,activeTab:"prompts"}:null),w(!1),_(e=>({...e,isOpen:!1})))},[v.element]),V=c(async()=>{if(h){const e={id:"demo-user-id",full_name:"Demo User",avatar_url:null};return g(t=>t?{...t,isAuthenticated:!0,user:e,authError:null}:null),void u.onLogin?.(e)}if(d)try{await d.login()}catch(e){console.error("Login failed:",e)}},[d,h,u]),J=c(async()=>{if(h)return g(e=>e?{...e,isAuthenticated:!1,user:null}:null),void u.onLogout?.();if(d)try{await d.logout()}catch(e){console.error("Logout failed:",e)}},[d,h,u]);return y?e("div",{className:"orquesta-embed-error fixed bottom-4 right-4 z-[2147483647] p-4 bg-red-900/90 border border-red-700 rounded-lg text-white text-sm max-w-xs",children:[t("div",{className:"font-semibold mb-1",children:"Orquesta Error"}),t("div",{className:"text-red-200",children:y})]}):!m||m.isConnecting?t("div",{className:"orquesta-embed-loading fixed bottom-4 right-4 z-[2147483647] p-4 bg-zinc-900 border border-zinc-700 rounded-lg text-white text-sm",children:e("div",{className:"flex items-center gap-2",children:[e("svg",{className:"animate-spin h-4 w-4",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{children:"Connecting to Orquesta..."})]})}):e(r,{children:[k&&t(Is,{isConnected:m.isConnected,agentOnline:m.agentOnline,projectName:m.projectName,currentPrompt:m.currentPrompt,isSubmitting:m.isSubmitting,lastCompletedPrompt:S,onClose:()=>x(!1)}),(f||!m.isOpen)&&e("button",{onClick:N,className:"orquesta-embed-trigger fixed z-[2147483647] p-3 bg-zinc-900 border border-zinc-700 rounded-full shadow-xl hover:bg-zinc-800 transition-colors",style:{[u.position?.includes("right")?"right":"left"]:"20px",[u.position?.includes("top")?"top":"bottom"]:"20px"},title:"Open Orquesta",children:[t("span",{className:"text-xl",children:"⬡"}),m.agentOnline&&t("span",{className:"absolute top-1 right-1 w-2 h-2 bg-green-500 rounded-full"})]}),m.isOpen&&!f&&t(Ns,{state:m,position:u.position||"bottom-right",onClose:O,onMinimize:R,onSubmitPrompt:A,onSelectElement:$,onClearElement:j,onToggleConsole:I,onToggleNetwork:P,onTabChange:L,onExpandPrompt:z,onHighlightElement:D,onLoadComments:H,onAddComment:q,onOverlayModeChange:B,onLogin:V,onLogout:J}),t(As,{isActive:m.isSelectingElement,onCancel:U}),"all"===m.overlayMode&&m.elementMarkers.length>0&&t($s,{markers:m.elementMarkers,onMarkerClick:M}),t(js,{isOpen:v.isOpen,position:v.position,element:v.element,agentOnline:m.agentOnline,includeConsole:m.includeConsole,includeNetwork:m.includeNetwork,onSubmit:K,onClose:W,onToggleConsole:I,onToggleNetwork:P,onOpenPanel:F}),n]})}export{ss as AuthManager,ks as AuthorAvatar,ds as Badge,cs as Button,Ts as CommentInput,Es as CommentList,es as ConsoleCapture,As as ElementInspector,$s as ElementMarkers,rs as ElementSelector,Ns as EmbedPanel,xs as GitCommitLink,hs as Input,_s as LogStream,ts as NetworkCapture,zs as OrquestaEmbed,ls as OrquestaEmbedClient,vs as PromptInput,Zr as StateManager,ps as StatusDot,fs as Tabs,bs as TabsContent,ws as TabsList,ys as TabsTrigger,us as Textarea,Cs as Timeline,as as storage};
|