1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-DlEwjg-E.js","assets/vendor-CxUIEUfi.js"])))=>i.map(i=>d[i]); 2import{j as i,A as Ce,m as S}from"./animations-BVA_raEK.js";import{a as Ho,r as v,g as Ko,R as Gi,b as Xo,c as Ie}from"./vendor-CxUIEUfi.js";import{X as Ve,L as Us,E as zn,a as Bn,A as lt,M as bn,b as Vn,U as Yi,K as Go,H as pr,c as Ks,S as Yo,I as ls,B as gr,d as Rt,Q as Qo,e as ms,C as Zo,f as el,g as Qi,h as vn,T as _t,i as tl,V as Wn,j as Gr,k as Yr,l as Qr,m as Zr,Z as ei,n as zt,F as sl,o as nl,p as rl,q as il,r as al,s as ol,R as qn,t as ll,P as cl,u as ti,v as si,w as dl,x as ul,y as hl,z as fl,D as ml,G as pl,J as gl,N as wl}from"./icons-BvFkly_Y.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const a of r)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function t(r){const a={};return r.integrity&&(a.integrity=r.integrity),r.referrerPolicy&&(a.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?a.credentials="include":r.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function s(r){if(r.ep)return;r.ep=!0;const a=t(r);fetch(r.href,a)}})();var Zi,ni=Ho;Zi=ni.createRoot,ni.hydrateRoot;var ri={},xl="@vercel/analytics",yl="1.5.0",bl=()=>{window.va||(window.va=function(...e){(window.vaq=window.vaq||[]).push(e)})};function ea(){return typeof window<"u"}function ta(){try{const n="production"}catch{}return"production"}function vl(n="auto"){if(n==="auto"){window.vam=ta();return}window.vam=n}function _l(){return(ea()?window.vam:ta())||"production"}function Jn(){return _l()==="development"}function jl(n){return n.scriptSrc?n.scriptSrc:Jn()?"https://va.vercel-scripts.com/v1/script.debug.js":n.basePath?`${n.basePath}/insights/script.js`:"/_vercel/insights/script.js"}function kl(n={debug:!0}){var e;if(!ea())return;vl(n.mode),bl(),n.beforeSend&&((e=window.va)==null||e.call(window,"beforeSend",n.beforeSend));const t=jl(n);if(document.head.querySelector(`script[src*="${t}"]`))return;const s=document.createElement("script");s.src=t,s.defer=!0,s.dataset.sdkn=xl+(n.framework?`/${n.framework}`:""),s.dataset.sdkv=yl,n.disableAutoTrack&&(s.dataset.disableAutoTrack="1"),n.endpoint?s.dataset.endpoint=n.endpoint:n.basePath&&(s.dataset.endpoint=`${n.basePath}/insights`),n.dsn&&(s.dataset.dsn=n.dsn),s.onerror=()=>{const r=Jn()?"Please check if any ad blockers are enabled and try again.":"Be sure to enable Web Analytics for your project and deploy again. See https://vercel.com/docs/analytics/quickstart for more information.";console.log(`[Vercel Web Analytics] Failed to load script from ${t}. ${r}`)},Jn()&&n.debug===!1&&(s.dataset.debug="false"),document.head.appendChild(s)}function Nl({route:n,path:e}){var t;(t=window.va)==null||t.call(window,"pageview",{route:n,path:e})}function Sl(){if(!(typeof process>"u"||typeof ri>"u"))return ri.REACT_APP_VERCEL_OBSERVABILITY_BASEPATH}function Pl(n){return v.useEffect(()=>{var e;n.beforeSend&&((e=window.va)==null||e.call(window,"beforeSend",n.beforeSend))},[n.beforeSend]),v.useEffect(()=>{kl({framework:n.framework||"react",basePath:n.basePath??Sl(),...n.route!==void 0&&{disableAutoTrack:!0},...n})},[]),v.useEffect(()=>{n.route&&n.path&&Nl({route:n.route,path:n.path})},[n.route,n.path]),null}const El={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_OPENAI_API_KEY:"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",VITE_SUPABASE_ANON_KEY:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxhaHpybHlob2p5ZmFkamFzZHJjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Mzk0NzUwNDAsImV4cCI6MjA1NTA1MTA0MH0.0IwuqcrHrPS6AqJKVYbNVhP1gjKTh4sP_BPDF8TKHiY",VITE_SUPABASE_URL:"https://lahzrlyhojyfadjasdrc.supabase.co"},ii=n=>{let e;const t=new Set,s=(u,m)=>{const f=typeof u=="function"?u(e):u;if(!Object.is(f,e)){const p=e;e=m??(typeof f!="object"||f===null)?f:Object.assign({},e,f),t.forEach(g=>g(e,p))}},r=()=>e,c={setState:s,getState:r,getInitialState:()=>d,subscribe:u=>(t.add(u),()=>t.delete(u)),destroy:()=>{(El?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),t.clear()}},d=e=n(s,r,c);return c},Cl=n=>n?ii(n):ii;var sa={exports:{}},na={},ra={exports:{}},ia={};/** 3 * @license React 4 * use-sync-external-store-shim.production.js 5 * 6 * Copyright (c) Meta Platforms, Inc. and affiliates. 7 * 8 * This source code is licensed under the MIT license found in the 9 * LICENSE file in the root directory of this source tree. 10 */var Bt=v;function Al(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var $l=typeof Object.is=="function"?Object.is:Al,Tl=Bt.useState,Rl=Bt.useEffect,Il=Bt.useLayoutEffect,Ol=Bt.useDebugValue;function Dl(n,e){var t=e(),s=Tl({inst:{value:t,getSnapshot:e}}),r=s[0].inst,a=s[1];return Il(function(){r.value=t,r.getSnapshot=e,_n(r)&&a({inst:r})},[n,t,e]),Rl(function(){return _n(r)&&a({inst:r}),n(function(){_n(r)&&a({inst:r})})}
vendor: 2,458 bytes, lines 10-18
10,[n]),Ol(t),t}function _n(n){var e=n.getSnapshot;n=n.value;try{var t=e();return!$l(n,t)}catch{return!0}}function Ml(n,e){return e()}var Ll=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Ml:Dl;ia.useSyncExternalStore=Bt.useSyncExternalStore!==void 0?Bt.useSyncExternalStore:Ll;ra.exports=ia;var Fl=ra.exports;/** 11 * @license React 12 * use-sync-external-store-shim/with-selector.production.js 13 * 14 * Copyright (c) Meta Platforms, Inc. and affiliates. 15 * 16 * This source code is licensed under the MIT license found in the 17 * LICENSE file in the root directory of this source tree. 18 */var en=v,Ul=Fl;function zl(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var Bl=typeof Object.is=="function"?Object.is:zl,Vl=Ul.useSyncExternalStore,Wl=en.useRef,ql=en.useEffect,Jl=en.useMemo,Hl=en.useDebugValue;na.useSyncExternalStoreWithSelector=function(n,e,t,s,r){var a=Wl(null);if(a.current===null){var o={hasValue:!1,value:null};a.current=o}else o=a.current;a=Jl(function(){function c(p){if(!d){if(d=!0,u=p,p=s(p),r!==void 0&&o.hasValue){var g=o.value;if(r(g,p))return m=g}return m=p}if(g=m,Bl(u,p))return g;var w=s(p);return r!==void 0&&r(g,w)?(u=p,g):(u=p,m=w)}var d=!1,u,m,f=t===void 0?null:t;return[function(){return c(e())},f===null?void 0:function(){return c(f())}]},[e,t,s,r]);var l=Vl(n,a[0],a[1]);return ql(function(){o.hasValue=!0,o.value=l},[l]),Hl(l),l};sa.exports=na;var Kl=sa.exports;const Xl=Ko(Kl),aa={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_OPENAI_API_KEY:"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",VITE_SUPABASE_ANON_KEY:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxhaHpybHlob2p5ZmFkamFzZHJjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Mzk0NzUwNDAsImV4cCI6MjA1NTA1MTA0MH0.0IwuqcrHrPS6AqJKVYbNVhP1gjKTh4sP_BPDF8TKHiY",VITE_SUPABASE_URL:"https://lahzrlyhojyfadjasdrc.supabase.co"},{useDebugValue:Gl}=Gi,{useSyncExternalStoreWithSelector:Yl}=Xl;let ai=!1;const Ql=n=>n;function Zl(n,e=Ql,t){(aa?"production":void 0)!=="production"&&t&&!ai&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),ai=!0);const s=Yl(n.subscribe,n.getState,n.getServerState||n.getInitialState,e,t);
18return Gl(s),s}const oi=n=>{(aa?"production":void 0)!=="production"&&typeof n!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof n=="function"?Cl(n):n,t=(s,r)=>Zl(e,s,r);return Object.assign(t,e),t},ec=n=>n?oi(n):oi,tc="modulepreload",sc=function(n){return"/"+n},li={},Vt=function(e,t,s){let r=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");r=Promise.allSettled(t.map(c=>{if(c=sc(c),c in li)return;li[c]=!0;const d=c.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":tc,d||(m.as="script"),m.crossOrigin="",m.href=c,l&&m.setAttribute("nonce",l),document.head.appendChild(m),d)return new Promise((f,p)=>{m.addEventListener("load",f),m.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${c}`)))})}))}function a(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return r.then(o=>{for(const l of o||[])l.status==="rejected"&&a(l.reason);return e().catch(a)})},nc=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>Vt(async()=>{const{default:s}=await Promise.resolve().then(()=>Jt);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};class wr extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class rc extends wr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class ic extends wr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class ac extends wr{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Hn;(function(n){n.Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2"})(Hn||(Hn={}));var oc=function(n,e,t,s){function r(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(u){try{d(s.next(u))}catch(m){o(m)}}function c(u){try{d(s.throw(u))}catch(m){o(m)}}function d(u){u.done?a(u.value):r(u.value).then(l,c)}d((s=s.apply(n,e||[])).next())})};class lc{constructor(e,{headers:t={},customFetch:s,region:r=Hn.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=nc(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return oc(this,void 0,void 0,function*(){try{const{headers:r,method:a,body:o}=t;let l={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(l["x-region"]=c);let d;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",d=o):typeof o=="string"?(l["Content-Type"]="text/plain",d=o):typeof FormData<"u"&&o instanceof FormData?d=o:(l["Content-Type"]="application/json",d=JSON.stringify(o)));const u=yield this.fetch(`${this.url}/${e}`,{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),r),body:d}).catch(g=>{throw new rc(g)}),m=u.headers.get("x-relay-error");if(m&&m==="true")throw new ic(u);if(!u.ok)throw new ac(u);let f=((s=u.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return f==="application/json"?p=yield u.json():f==="application/octet-stream"?p=yield u.blob():f==="text/event-stream"?p=u:f==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(r){return{data:null,error:r}}})}}var ve={},xr={},tn={},xs={},sn={},nn={},cc=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},Wt=cc();const dc=Wt.fetch,oa=Wt.fetch.bind(Wt),la=Wt.Headers,uc=Wt.Request,hc=Wt.Response,Jt=Object.freeze(Object.defineProperty({__proto__:null,Headers:la,Request:uc,Response:hc,default:oa,fetch:dc},Symbol.toStringTag,{value:"Module"})),fc=Xo(Jt);var rn={};Object.defineProperty(rn,"__esModule",{value:!0});
18let mc=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};rn.default=mc;var ca=Ie&&Ie.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(nn,"__esModule",{value:!0});const pc=ca(fc),gc=ca(rn);let wc=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=pc.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Object.assign({},this.headers),this.headers[e]=t,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const s=this.fetch;let r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{var o,l,c;let d=null,u=null,m=null,f=a.status,p=a.statusText;if(a.ok){if(this.method!=="HEAD"){const N=await a.text();N===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=N:u=JSON.parse(N))}const w=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),y=(l=a.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");w&&y&&y.length>1&&(m=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,m=null,f=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const w=await a.text();try{d=JSON.parse(w),Array.isArray(d)&&a.status===404&&(u=[],d=null,f=200,p="OK")}catch{a.status===404&&w===""?(f=204,p="No Content"):d={message:w}}if(d&&this.isMaybeSingle&&(!((c=d?.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,f=200,p="OK"),d&&this.shouldThrowOnError)throw new gc.default(d)}return{error:d,data:u,count:m,status:f,statusText:p}});return this.shouldThrowOnError||(r=r.catch(a=>{var o,l,c;return{error:{message:`${(o=a?.name)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:`${(l=a?.stack)!==null&&l!==void 0?l:""}`,hint:"",code:`${(c=a?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}returns(){return this}overrideTypes(){return this}};nn.default=wc;var xc=Ie&&Ie.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(sn,"__esModule",{value:!0});const yc=xc(nn);let bc=class extends yc.default{select(e){let t=!1;const s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:a=r}={}){const o=a?`${a}.order`:"order",l=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${l?`${l},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){const a=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}
18explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:a=!1,format:o="text"}={}){var l;const c=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,a?"wal":null].filter(Boolean).join("|"),d=(l=this.headers.Accept)!==null&&l!==void 0?l:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${d}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};sn.default=bc;var vc=Ie&&Ie.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(xs,"__esModule",{value:!0});const _c=vc(sn);let jc=class extends _c.default{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}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const s=Array.from(new Set(t)).map(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?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 typeof t=="string"?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 typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let a="";r==="plain"?a="pl":r==="phrase"?a="ph":r==="websearch"&&(a="w");const o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${a}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){const r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};xs.default=jc;var kc=Ie&&Ie.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(tn,"__esModule",{value:!0});const Yt=kc(xs);let Nc=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){const r=t?"HEAD":"GET";let a=!1;const o=(e??"*").split("").map(l=>/\s/.test(l)&&!a?"":(l==='"'&&(a=!a),l)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new Yt.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){const r="POST",a=[];if(this.headers.Prefer&&a.push(this.headers.Prefer),t&&a.push(`count=${t}`),s||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){const o=e.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(o.length>0){const l=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",l.join(","))}}return new Yt.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:a=!0}={}){const o="POST",l=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&l.push(this.headers.Prefer),r&&l.push(`count=${r}`),a||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(e)){const c=e.reduce((d,u)=>d.concat(Object.keys(u)),[]);if(c.length>0){const d=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",d.join(","))}}return new Yt.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){const s="PATCH",r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new Yt.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new Yt.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};tn.default=Nc;var an={},on={};Object.defineProperty(on,"__esModule",{value:!0});on.version=void 0;on.version="0.0.0-automated";Object.defineProperty(an,"__esModule",{value:!0});an.DEFAULT_HEADERS=void 0;const Sc=on;an.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Sc.version}`};var da=Ie&&Ie.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};
18Object.defineProperty(xr,"__esModule",{value:!0});const Pc=da(tn),Ec=da(xs),Cc=an;let Ac=class ua{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},Cc.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){const t=new URL(`${this.url}/${e}`);return new Pc.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new ua(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:a}={}){let o;const l=new URL(`${this.url}/rpc/${e}`);let c;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([u,m])=>m!==void 0).map(([u,m])=>[u,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([u,m])=>{l.searchParams.append(u,m)})):(o="POST",c=t);const d=Object.assign({},this.headers);return a&&(d.Prefer=`count=${a}`),new Ec.default({method:o,url:l,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};xr.default=Ac;var Ht=Ie&&Ie.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};
18Object.defineProperty(ve,"__esModule",{value:!0});ve.PostgrestError=ve.PostgrestBuilder=ve.PostgrestTransformBuilder=ve.PostgrestFilterBuilder=ve.PostgrestQueryBuilder=ve.PostgrestClient=void 0;const ha=Ht(xr);ve.PostgrestClient=ha.default;const fa=Ht(tn);ve.PostgrestQueryBuilder=fa.default;const ma=Ht(xs);ve.PostgrestFilterBuilder=ma.default;const pa=Ht(sn);ve.PostgrestTransformBuilder=pa.default;const ga=Ht(nn);ve.PostgrestBuilder=ga.default;const wa=Ht(rn);ve.PostgrestError=wa.default;var $c=ve.default={PostgrestClient:ha.default,PostgrestQueryBuilder:fa.default,PostgrestFilterBuilder:ma.default,PostgrestTransformBuilder:pa.default,PostgrestBuilder:ga.default,PostgrestError:wa.default};const{PostgrestClient:Tc,PostgrestQueryBuilder:Wf,PostgrestFilterBuilder:qf,PostgrestTransformBuilder:Jf,PostgrestBuilder:Hf,PostgrestError:Kf}=$c,Rc="2.11.2",Ic={"X-Client-Info":`realtime-js/${Rc}`},Oc="1.0.0",xa=1e4,Dc=1e3;var Lt;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(Lt||(Lt={}));var Pe;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(Pe||(Pe={}));var Be;(function(n){n.close="phx_close",n.error="phx_error",n.join="phx_join",n.reply="phx_reply",n.leave="phx_leave",n.access_token="access_token"})(Be||(Be={}));var Kn;(function(n){n.websocket="websocket"})(Kn||(Kn={}));var bt;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(bt||(bt={}));class Mc{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const r=t.getUint8(1),a=t.getUint8(2);let o=this.HEADER_LENGTH+2;const l=s.decode(e.slice(o,o+r));o=o+r;const c=s.decode(e.slice(o,o+a));o=o+a;const d=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:l,event:c,payload:d}}}class ya{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)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var te;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(te||(te={}));const ci=(n,e,t={})=>{var s;const r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((a,o)=>(a[o]=Lc(o,n,e,r),a),{})},Lc=(n,e,t,s)=>{const r=e.find(l=>
18l.name===n),a=r?.type,o=t[n];return a&&!s.includes(a)?ba(a,o):Xn(o)},ba=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return Bc(e,t)}switch(n){case te.bool:return Fc(e);case te.float4:case te.float8:case te.int2:case te.int4:case te.int8:case te.numeric:case te.oid:return Uc(e);case te.json:case te.jsonb:return zc(e);case te.timestamp:return Vc(e);case te.abstime:case te.date:case te.daterange:case te.int4range:case te.int8range:case te.money:case te.reltime:case te.text:case te.time:case te.timestamptz:case te.timetz:case te.tsrange:case te.tstzrange:return Xn(e);default:return Xn(e)}},Xn=n=>n,Fc=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},Uc=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},zc=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch(e){return console.log(`JSON parse error: ${e}`),n}return n},Bc=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,s=n[t];if(n[0]==="{"&&s==="}"){let a;const o=n.slice(1,t);try{a=JSON.parse("["+o+"]")}catch{a=o?o.split(","):[]}return a.map(l=>ba(e,l))}return n},Vc=n=>typeof n=="string"?n.replace(" ","T"):n,va=n=>{let e=n;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class jn{constructor(e,t,s={},r=xa){this.channel=e,this.event=t,this.payload=s,this.timeout=r,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 s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.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);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},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(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var di;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(di||(di={}));class cs{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{const{onJoin:a,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=cs.syncState(this.state,r,a,o),this.pendingDiffs.forEach(c=>{this.state=cs.syncDiff(this.state,c,a,o)}),this.pendingDiffs=[],l()}),this.channel._on(s.diff,{},r=>{const{onJoin:a,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=cs.syncDiff(this.state,r,a,o),l())}),this.onJoin((r,a,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:a,newPresences:o})}),this.onLeave((r,a,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:a,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){const a=this.cloneDeep(e),o=this.transformState(t),l={},c={};return this.map(a,(d,u)=>{o[d]||(c[d]=u)}),this.map(o,(d,u)=>{const m=a[d];if(m){const f=u.map(y=>y.presence_ref),p=m.map(y=>y.presence_ref),g=u.filter(y=>p.indexOf(y.presence_ref)<0),w=m.filter(y=>f.indexOf(y.presence_ref)<0);g.length>0&&(l[d]=g),w.length>0&&(c[d]=w)}else l[d]=u}),this.syncDiff(a,{joins:l,leaves:c},s,r)}static syncDiff(e,t,s,r){const{joins:a,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(a,(l,c)=>{var d;const u=(d=e[l])!==null&&d!==void 0?d:[];if(e[l]=this.cloneDeep(c),u.length>0){const m=e[l].map(p=>p.presence_ref),f=u.filter(p=>m.indexOf(p.presence_ref)<0);e[l].unshift(...f)}s(l,u,c)}),this.map(o,(l,c)=>{let d=e[l];
18if(!d)return;const u=c.map(m=>m.presence_ref);d=d.filter(m=>u.indexOf(m.presence_ref)<0),e[l]=d,r(l,d,c),d.length===0&&delete e[l]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const r=e[s];return"metas"in r?t[s]=r.metas.map(a=>(a.presence_ref=a.phx_ref,delete a.phx_ref,delete a.phx_ref_prev,a)):t[s]=r,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()}}var ui;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(ui||(ui={}));var hi;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes",n.SYSTEM="system"})(hi||(hi={}));var et;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(et||(et={}));class yr{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=Pe.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new jn(this,Be.join,this.params,this.timeout),this.rejoinTimer=new ya(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Pe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Pe.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=Pe.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Pe.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Be.reply,{},(r,a)=>{this._trigger(this._replyEventName(a),r)}),this.presence=new cs(this),this.broadcastEndpointURL=va(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:a,presence:o,private:l}}=this.params;this._onError(u=>e?.(et.CHANNEL_ERROR,u)),this._onClose(()=>e?.(et.CLOSED));const c={},d={broadcast:a,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(u=>u.filter))!==null&&r!==void 0?r:[],private:l};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:d},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:u})=>{var m;if(this.socket.setAuth(),u===void 0){e?.(et.SUBSCRIBED);return}else{const f=this.bindings.postgres_changes,p=(m=f?.length)!==null&&m!==void 0?m:0,g=[];for(let w=0;w<p;w++){const y=f[w],{filter:{event:N,schema:_,table:L,filter:T}}=y,B=u&&u[w];if(B&&B.event===N&&B.schema===_&&B.table===L&&B.filter===T)g.push(Object.assign(Object.assign({},y),{id:B.id}));else{this.unsubscribe(),e?.(et.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=g,e&&e(et.SUBSCRIBED);return}}).receive("error",u=>{e?.(et.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e?.(et.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,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){const{event:a,payload:o}=e,c={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:o,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=d.body)===null||r===void 0?void 0:r.cancel()),d.ok?"ok":"error"}catch(d){return d.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var o,l,c;const d=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||c===void 0)&&c.ack)&&a("ok"),d.receive("ok",()=>a("ok")),d.receive("error",()=>
18a("error")),d.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=Pe.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Be.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{const r=new jn(this,Be.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",{})})}async _fetchWithTimeout(e,t,s){const r=new AbortController,a=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(a),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new jn(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,a;const o=e.toLocaleLowerCase(),{close:l,error:c,leave:d,join:u}=Be;if(s&&[l,c,d,u].indexOf(o)>=0&&s!==this._joinRef())return;let f=this._onMessage(o,t,s);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(p=>{var g,w,y;return((g=p.filter)===null||g===void 0?void 0:g.event)==="*"||((y=(w=p.filter)===null||w===void 0?void 0:w.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(p=>p.callback(f,s)):(a=this.bindings[o])===null||a===void 0||a.filter(p=>{var g,w,y,N,_,L;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){const T=p.id,B=(g=p.filter)===null||g===void 0?void 0:g.event;return T&&((w=t.ids)===null||w===void 0?void 0:w.includes(T))&&(B==="*"||B?.toLocaleLowerCase()===((y=t.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{const T=(_=(N=p?.filter)===null||N===void 0?void 0:N.event)===null||_===void 0?void 0:_.toLocaleLowerCase();return T==="*"||T===((L=t?.event)===null||L===void 0?void 0:L.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){const g=f.data,{schema:w,table:y,commit_timestamp:N,type:_,errors:L}=g;f=Object.assign(Object.assign({},{schema:w,table:y,commit_timestamp:N,eventType:_,new:{},old:{},errors:L}),this._getPayloadRecords(g))}p.callback(f,s)})}_isClosed(){return this.state===Pe.closed}_isJoined(){return this.state===Pe.joined}_isJoining(){return this.state===Pe.joining}_isLeaving(){return this.state===Pe.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const r=e.toLocaleLowerCase(),a={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(a):this.bindings[r]=[a],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var a;return!(((a=r.type)===null||a===void 0?void 0:a.toLocaleLowerCase())===s&&yr.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Be.close,{},e)}_onError(e){this._on(Be.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Pe.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=ci(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=ci(e.columns,e.old_record)),t}}const Wc=()=>{},qc=typeof WebSocket<"u",Jc=` 19 addEventListener("message", (e) => { 20 if (e.data.event === "start") { 21 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 22 } 23 });`;class Hc{constructor(e,t){var s;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ic,this.params={},this.timeout=xa,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Wc,this.conn=null,this.sendBuffer=[],this.serializer
23=new Mc,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=a=>{let o;return a?o=a:typeof fetch>"u"?o=(...l)=>Vt(async()=>{const{default:c}=await Promise.resolve().then(()=>Jt);return{default:c}},void 0).then(({default:c})=>c(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${e}/${Kn.websocket}`,this.httpEndpoint=va(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const r=(s=t?.params)===null||s===void 0?void 0:s.apikey;if(r&&(this.accessTokenValue=r,this.apiKey=r),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:a=>[1e3,2e3,5e3,1e4][a-1]||1e4,this.encode=t?.encode?t.encode:(a,o)=>o(JSON.stringify(a)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ya(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch),t?.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=t?.worker||!1,this.workerUrl=t?.workerUrl}this.accessToken=t?.accessToken||null}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers});return}if(qc){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new Kc(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Vt(async()=>{const{default:e}=await import("./browser-DlEwjg-E.js").then(t=>t.b);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{this.conn=new e(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Oc}))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case Lt.connecting:return bt.Connecting;case Lt.open:return bt.Open;case Lt.closing:return bt.Closing;default:return bt.Closed}}isConnected(){return this.connectionState()===bt.Open}channel(e,t={config:{}}){const s=new yr(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){const{topic:t,event:s,payload:r,ref:a}=e,o=()=>{this.encode(e,l=>{var c;(c=this.conn)===null||c===void 0||c.send(l)})};this.log("push",`${t} ${s} (${a})`,r),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;if(t){let s=null;try{s=JSON.parse(atob(t.split(".")[1]))}catch{}if(s&&s.exp&&!(Math.floor(Date.now()/1e3)-s.exp<0))return this.log("auth",`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${s.exp}`),Promise.reject(`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${s.exp}`);this.accessTokenValue=t,this.channels.forEach(r=>{t&&r.updateJoinPayload({access_token:t}),r.joinedOnce&&r._isJoined()&&r._push(Be.access_token,{access_token:t})})}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Dc,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth()}}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(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>
23this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:a,ref:o}=t;o&&o===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${a.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,a),this.channels.filter(l=>l._isMember(s)).forEach(l=>l._trigger(r,a,o)),this.stateChangeCallbacks.message.forEach(l=>l(t))})}async _onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{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=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(Be.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_workerObjectUrl(e){let t;if(e)t=e;else{const s=new Blob([Jc],{type:"application/javascript"});t=URL.createObjectURL(s)}return t}}class Kc{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Lt.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}}class br extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function de(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class Xc extends br{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class Gn extends br{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var Gc=function(n,e,t,s){function r(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(u){try{d(s.next(u))}catch(m){o(m)}}function c(u){try{d(s.throw(u))}catch(m){o(m)}}function d(u){u.done?a(u.value):r(u.value).then(l,c)}d((s=s.apply(n,e||[])).next())})};const _a=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>Vt(async()=>{const{default:s}=await Promise.resolve().then(()=>Jt);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Yc=()=>Gc(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Vt(()=>Promise.resolve().then(()=>Jt),void 0)).Response:Response}),Yn=n=>{if(Array.isArray(n))return n.map(t=>Yn(t));if(typeof n=="function"||n!==Object(n))return n;const e={};return Object.entries(n).forEach(([t,s])=>{const r=t.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[r]=Yn(s)}),e};var kt=function(n,e,t,s){function r(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(u){try{d(s.next(u))}catch(m){o(m)}}function c(u){try{d(s.throw(u))}catch(m){o(m)}}function d(u){u.done?a(u.value):r(u.value).then(l,c)}d((s=s.apply(n,e||[])).next())})};const kn=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),Qc=(n,e,t)=>kt(void 0,void 0,void 0,function*(){const s=yield Yc();n instanceof s&&!t?.noResolveJson?n.json().then(r=>{e(new Xc(kn(r),n.status||500))}).catch(r=>{e(new Gn(kn(r),r))}):e(new Gn(kn(n),n))}),Zc=(n,e,t,s)=>{const r={method:n,headers:e?.headers||{}};return n==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s&&(r.body=JSON.stringify(s)),Object.assign(Object.assign({},r),t))};function ys(n,e,t,s,r,a){return kt(this,void 0,void 0,function*(){return new Promise((o,l)=>{n(t,Zc(e,s,r,a)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Qc(c,l,s))})})}function Xs(n,e,t,s){return kt(this,void 0,void 0,function*(){return ys(n,"GET",e,t,s)})}function at(n,e,t,s,r){return kt(this,void 0,void 0,function*(){return ys(n,"POST",e,s,r,t)})}function ed(n,e,t,s,r){return kt(this,void 0,void 0,function*(){return ys(n,"PUT",e,s,r,t)})}function td(n,e,t,s){return kt(this,void 0,void 0,function*(){return ys(n,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function ja(n,e,t,s,r){return kt(this,void 0,void 0,function*(){return ys(n,"DELETE",e,s,r,t)})}var ye=function(n,e,t,s){function r(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(u){try{d(s.next(u))}catch(m){o(m)}}function c(u){try{d(s.throw(u))}catch(m){o(m)}}function d(u){u.done?a(u.value):r(u.value).then(l,c)}d((s=s.apply(n,e||[])).next())})};const sd={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},fi={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};
23class nd{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=_a(r)}uploadOrUpdate(e,t,s,r){return ye(this,void 0,void 0,function*(){try{let a;const o=Object.assign(Object.assign({},fi),r);let l=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const c=o.metadata;typeof Blob<"u"&&s instanceof Blob?(a=new FormData,a.append("cacheControl",o.cacheControl),c&&a.append("metadata",this.encodeMetadata(c)),a.append("",s)):typeof FormData<"u"&&s instanceof FormData?(a=s,a.append("cacheControl",o.cacheControl),c&&a.append("metadata",this.encodeMetadata(c))):(a=s,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType,c&&(l["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),r?.headers&&(l=Object.assign(Object.assign({},l),r.headers));const d=this._removeEmptyFolders(t),u=this._getFinalPath(d),m=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:a,headers:l},o?.duplex?{duplex:o.duplex}:{})),f=yield m.json();return m.ok?{data:{path:d,id:f.Id,fullPath:f.Key},error:null}:{data:null,error:f}}catch(a){if(de(a))return{data:null,error:a};throw a}})}upload(e,t,s){return ye(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return ye(this,void 0,void 0,function*(){const a=this._removeEmptyFolders(e),o=this._getFinalPath(a),l=new URL(this.url+`/object/upload/sign/${o}`);l.searchParams.set("token",t);try{let c;const d=Object.assign({upsert:fi.upsert},r),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",d.cacheControl)):(c=s,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType);const m=yield this.fetch(l.toString(),{method:"PUT",body:c,headers:u}),f=yield m.json();return m.ok?{data:{path:a,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(de(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return ye(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");const a=yield at(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+a.url),l=o.searchParams.get("token");if(!l)throw new br("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:l},error:null}}catch(s){if(de(s))return{data:null,error:s};throw s}})}update(e,t,s){return ye(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return ye(this,void 0,void 0,function*(){try{return{data:yield at(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,de
23stinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(de(r))return{data:null,error:r};throw r}})}copy(e,t,s){return ye(this,void 0,void 0,function*(){try{return{data:{path:(yield at(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(de(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return ye(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),a=yield at(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers});const o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return a={signedUrl:encodeURI(`${this.url}${a.signedURL}${o}`)},{data:a,error:null}}catch(r){if(de(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return ye(this,void 0,void 0,function*(){try{const r=yield at(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),a=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${a}`):null})),error:null}}catch(r){if(de(r))return{data:null,error:r};throw r}})}download(e,t){return ye(this,void 0,void 0,function*(){const r=typeof t?.transform<"u"?"render/image/authenticated":"object",a=this.transformOptsToQueryString(t?.transform||{}),o=a?`?${a}`:"";try{const l=this._getFinalPath(e);return{data:yield(yield Xs(this.fetch,`${this.url}/${r}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(de(l))return{data:null,error:l};throw l}})}info(e){return ye(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield Xs(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Yn(s),error:null}}catch(s){if(de(s))return{data:null,error:s};throw s}})}exists(e){return ye(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield td(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(de(s)&&s instanceof Gn){const r=s.originalError;if([400,404].includes(r?.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],a=t?.download?`download=${t.download===!0?"":t.download}`:"";a!==""&&r.push(a);const l=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&r.push(c);let d=r.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${l}/public/${s}${d}`)}}}remove(e){return ye(this,void 0,void 0,function*(){try{return{data:yield ja(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(de(t))return{data:null,error:t};throw t}})}list(e,t,s){return ye(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},sd),t),{prefix:e||""});return{data:yield at(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(de(r))return{data:null,error:r};throw r}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e}`}_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 rd="2.7.1",id={"X-Client-Info":`storage-js/${rd}`};var Nt=function(n,e,t,s){function r(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(u){try{d(s.next(u))}catch(m){o(m)}}function c(u){try{d(s.throw(u))}catch(m){o(m)}}function d(u){u.done?a(u.value):r(u.value).then(l,c)}d((s=s.apply(n,e||[])).next())})};class ad{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({}
23,id),t),this.fetch=_a(s)}listBuckets(){return Nt(this,void 0,void 0,function*(){try{return{data:yield Xs(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(de(e))return{data:null,error:e};throw e}})}getBucket(e){return Nt(this,void 0,void 0,function*(){try{return{data:yield Xs(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(de(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Nt(this,void 0,void 0,function*(){try{return{data:yield at(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(de(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Nt(this,void 0,void 0,function*(){try{return{data:yield ed(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(de(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Nt(this,void 0,void 0,function*(){try{return{data:yield at(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(de(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Nt(this,void 0,void 0,function*(){try{return{data:yield ja(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(de(t))return{data:null,error:t};throw t}})}}class od extends ad{constructor(e,t={},s){super(e,t,s)}from(e){return new nd(this.url,this.headers,e,this.fetch)}}const ld="2.49.4";let ts="";typeof Deno<"u"?ts="deno":typeof document<"u"?ts="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ts="react-native":ts="node";const cd={"X-Client-Info":`supabase-js-${ts}/${ld}`},dd={headers:cd},ud={schema:"public"},hd={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},fd={};var md=function(n,e,t,s){function r(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(u){try{d(s.next(u))}catch(m){o(m)}}function c(u){try{d(s.throw(u))}catch(m){o(m)}}function d(u){u.done?a(u.value):r(u.value).then(l,c)}d((s=s.apply(n,e||[])).next())})};const pd=n=>{let e;return n?e=n:typeof fetch>"u"?e=oa:e=fetch,(...t)=>e(...t)},gd=()=>typeof Headers>"u"?la:Headers,wd=(n,e,t)=>{const s=pd(t),r=gd();return(a,o)=>md(void 0,void 0,void 0,function*(){var l;const c=(l=yield e())!==null&&l!==void 0?l:n;let d=new r(o?.headers);return d.has("apikey")||d.set("apikey",n),d.has("Authorization")||d.set("Authorization",`Bearer ${c}`),s(a,Object.assign(Object.assign({},o),{headers:d}))})};var xd=function(n,e,t,s){function r(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(u){try{d(s.next(u))}catch(m){o(m)}}function c(u){try{d(s.throw(u))}catch(m){o(m)}}function d(u){u.done?a(u.value):r(u.value).then(l,c)}d((s=s.apply(n,e||[])).next())})};function yd(n){return n.replace(/\/$/,"")}function bd(n,e){const{db:t,auth:s,realtime:r,global:a}=n,{db:o,auth:l,realtime:c,global:d}=e,u={db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},l),s),realtime:Object.assign(Object.assign({},c),r),global:Object.assign(Object.assign({},d),a),accessToken:()=>xd(this,void 0,void 0,function*(){return""})};return n.accessToken?u.accessToken=n.accessToken:delete u.accessToken,u}const ka="2.69.1",It=30*1e3,Qn=3,Nn=Qn*It,vd="http://localhost:9999",_d="supabase.auth.token",jd={"X-Client-Info":`gotrue-js/${ka}`},Zn="X-Supabase-Api-Version",Na={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},kd=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Nd=6e5;class vr extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function z(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class Sd extends vr{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function Pd(n){return z(n)&&n.name==="AuthApiError"}class Sa extends vr{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class dt extends vr{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class rt extends dt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Ed(n){return z(n)&&n.name==="AuthSessionMissingError"}class Sn extends dt{constructor(){super("Auth session or user missing","AuthInvalidToken
23ResponseError",500,void 0)}}class Ns extends dt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Ss extends dt{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}}}function Cd(n){return z(n)&&n.name==="AuthImplicitGrantRedirectError"}class mi extends dt{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 er extends dt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Pn(n){return z(n)&&n.name==="AuthRetryableFetchError"}class pi extends dt{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class ds extends dt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const gi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),wi=` 24\r=`.split(""),Ad=(()=>{const n=new Array(128);for(let e=0;e<n.length;e+=1)n[e]=-1;for(let e=0;e<wi.length;e+=1)n[wi[e].charCodeAt(0)]=-2;for(let e=0;e<gi.length;e+=1)n[gi[e].charCodeAt(0)]=e;return n})();function Pa(n,e,t){const s=Ad[n];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function xi(n){const e=[],t=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},r={queue:0,queuedBits:0},a=o=>{Rd(o,s,t)};for(let o=0;o<n.length;o+=1)Pa(n.charCodeAt(o),r,a);return e.join("")}function $d(n,e){if(n<=127){e(n);return}else if(n<=2047){e(192|n>>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function Td(n,e){for(let t=0;t<n.length;t+=1){let s=n.charCodeAt(t);if(s>55295&&s<=56319){const r=(s-55296)*1024&65535;s=(n.charCodeAt(t+1)-56320&65535|r)+65536,t+=1}$d(s,e)}}function Rd(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let s=1;s<6;s+=1)if(!(n>>7-s&1)){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function Id(n){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};for(let r=0;r<n.length;r+=1)Pa(n.charCodeAt(r),t,s);return new Uint8Array(e)}function Od(n){const e=[];return Td(n,t=>e.push(t)),new Uint8Array(e)}function Dd(n){return Math.round(Date.now()/1e3)+n}function Md(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){const e=Math.random()*16|0;return(n=="x"?e:e&3|8).toString(16)})}const Ke=()=>typeof window<"u"&&typeof document<"u",gt={tested:!1,writable:!1},us=()=>{if(!Ke())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(gt.tested)return gt.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),gt.tested=!0,gt.writable=!0}catch{gt.tested=!0,gt.writable=!1}return gt.writable};function Ld(n){const e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,a)=>{e[a]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}const Ea=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>Vt(async()=>{const{default:s}=await Promise.resolve().then(()=>Jt);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Fd=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",Ca=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},Ps=async(n,e)=>{const t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Es=async(n,e)=>{await n.removeItem(e)};class ln{constructor(){this.promise=new ln.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}ln.promiseConstructor=Promise;function En(n){const e=n.split(".");if(e.length!==3)throw new ds("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!kd.test(e[s]))throw new ds("JWT not in base64url format");return{header:JSON.parse(xi(e[0])),payload:JSON.parse(xi(e[1])),signature:Id(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ud(n){return await new Promise(e=>{setTimeout(()=>e(null),n)})}function zd(n,e){return new Promise((s,r)=>{(async()=>{for(let a=0;a<1/0;a++)try{const o=await n(a);if(!e(a,null,o)){s(o);return}}catch(o){if(!e(a,o)){r(o);return}}})()})}function Bd(n){return("0"+n.toString(16)).substr(-2)}function Vd(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length;let r="";for(let a=0;a<56;a++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,Bd).join("")}async function Wd(n){const t=new TextEncoder().encode(n),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(a=>String.fromCharCode(a)).join("")}async function qd(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code
24challenge method will default to use plain instead of sha256."),n;const t=await Wd(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function St(n,e,t=!1){const s=Vd();let r=s;t&&(r+="/PASSWORD_RECOVERY"),await Ca(n,`${e}-code-verifier`,r);const a=await qd(s);return[a,s===a?"plain":"s256"]}const Jd=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Hd(n){const e=n.headers.get(Zn);if(!e||!e.match(Jd))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Kd(n){if(!n)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function Xd(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Gd=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(t[s[r]]=n[s[r]]);return t};const xt=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),Yd=[502,503,504];async function yi(n){var e;if(!Fd(n))throw new er(xt(n),0);if(Yd.includes(n.status))throw new er(xt(n),n.status);let t;try{t=await n.json()}catch(a){throw new Sa(xt(a),a)}let s;const r=Hd(n);if(r&&r.getTime()>=Na["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new pi(xt(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new rt}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((a,o)=>a&&typeof o=="string",!0))throw new pi(xt(t),n.status,t.weak_password.reasons);throw new Sd(xt(t),n.status||500,s)}const Qd=(n,e,t,s)=>{const r={method:n,headers:e?.headers||{}};return n==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function H(n,e,t,s){var r;const a=Object.assign({},s?.headers);a[Zn]||(a[Zn]=Na["2024-01-01"].name),s?.jwt&&(a.Authorization=`Bearer ${s.jwt}`);const o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Zd(n,e,t+l,{headers:a,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Zd(n,e,t,s,r,a){const o=Qd(e,s,r,a);let l;try{l=await n(t,Object.assign({},o))}catch(c){throw console.error(c),new er(xt(c),0)}if(l.ok||await yi(l),s?.noResolveJson)return l;try{return await l.json()}catch(c){await yi(c)}}function it(n){var e;let t=null;nu(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Dd(n.expires_in)));const s=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:s},error:null}}function bi(n){const e=it(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=n.weak_password),e}function ot(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function eu(n){return{data:n,error:null}}function tu(n){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:a}=n,o=Gd(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:a},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function su(n){return n}function nu(n){return n.access_token&&n.refresh_token&&n.expires_in}var ru=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(t[s[r]]=n[s[r]]);return t};class iu{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Ea(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await H(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(z(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await H(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ot})}catch(s){if(z(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:t}=e,s=ru(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await H(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:tu,redirectTo:t?.redirectTo})}catch(t){if(z(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await H(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ot})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,a,o,l,c;try{const d={nextPage:null,lastPage:0,total:0},u=await H(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(a=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&a!==void 0?a:""},xform:su});if(u.error)throw u.error;const m=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return p.length>
240&&(p.forEach(g=>{const w=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(g.split(";")[1].split("=")[1]);d[`${y}Page`]=w}),d.total=parseInt(f)),{data:Object.assign(Object.assign({},m),d),error:null}}catch(d){if(z(d))return{data:{users:[]},error:d};throw d}}async getUserById(e){try{return await H(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ot})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await H(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ot})}catch(s){if(z(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await H(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ot})}catch(s){if(z(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{const{data:t,error:s}=await H(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(z(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await H(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}}const au={getItem:n=>us()?globalThis.localStorage.getItem(n):null,setItem:(n,e)=>{us()&&globalThis.localStorage.setItem(n,e)},removeItem:n=>{us()&&globalThis.localStorage.removeItem(n)}};function vi(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}function ou(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const Pt={debug:!!(globalThis&&us()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};
vendor: 15,395 bytes, line 24
24class Aa extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class lu extends Aa{}async function cu(n,e,t){Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",n,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",n)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(n,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",n,r.name);try{return await t()}finally{Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",n,r.name)}}else{if(e===0)throw Pt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",n),new lu(`Acquiring an exclusive Navigator LockManager lock "${n}" immediately failed`);if(Pt.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}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 t()}}))}ou();const du={url:vd,storageKey:_d,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:jd,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function _i(n,e,t){return await t()}class ps{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=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,this.instanceID=ps.nextInstanceID,ps.nextInstanceID+=1,this.instanceID>0&&Ke()&&console.warn("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.");const r=Object.assign(Object.assign({},du),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new iu({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=Ea(r.fetch),this.lock=r.lock||_i,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:Ke()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=cu:this.lock=_i,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)},this.persistSession?r.storage?this.storage=r.storage:us()?this.storage=au:(this.memoryStorage={},this.storage=vi(this.memoryStorage)):(this.memoryStorage={},this.storage=vi(this.memoryStorage)),Ke()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),await this._notifyAllSubscribers(a.data.event,a.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${ka}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const t=Ld(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),Ke()&&this.detectSessionInUrl&&s!=="none"){const{data:r,error:a}=await this._getSessionFromURL(t,s);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),Cd(a)){const c=(e=a.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:a}}return await this._removeSession(),{error:a}}const{session:o,redirectType:l}=r;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return z(t)?{error:t}:{error:new Sa("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const a=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:it}),{data:o,error:l}=a;if(l||!o)return{data:{user:null,session:null},error:l};const c=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:d,session:c},error:null}}catch(a){if(z(a))return{data:{user:null,session:null},error:a};throw a}}async signUp(e){var t,s,r;try{let a;if("email"in e){const{email:u,password:m,options:f}=e;let p=null,g=null;this.flowType==="pkce"&&([p,g]=await St(this.storage,this.storageKey)),a=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:m,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:p,code_challenge_method:g},xform:it})}else if("phone"in e){const{phone:u,password:m,options:f}=e;a=await H(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:m,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(r=f?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:it})}else throw new Ns("You must provide either an email or phone number and a password");const{data:o,error:l}=a;if(l||!o)return{data:{user:null,session:null},error:l};const c=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:d,session:c},error:null}}catch(a){if(z(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithPassword(e){try{let t;if("email"in e){const{email:a,password:o,options:l}=e;t=await H(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:bi})}else if("phone"in e){const{phone:a,password:o,options:l}=e;t=await H(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:bi})}else throw new Ns("You must provide either an email or phone number and a password");const{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Sn}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,a;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){const t=await Ps(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/");try{const{data:a,error:o}=await H(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:it});if(await Es(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!a||!a.session||!a.user?{data:{user:null,session:null,redirectType:null},error:new Sn}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:Object.assign(Object.assign({},a),{redirectType:r??null}),error:o})}catch(a){if(z(a))return{data:{user:null,session:null,redirectType:null},error:a};throw a}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:a,nonce:o}=e,l=await H(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:a,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:it}),{data:c,error:d}=l;return d?{data:{user:null,session:null},error:d}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Sn}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,a,o;try{if("email"in e){const{email:l,options:c}=e;let d=null,u=null;this.flowType==="pkce"&&([d,u]=await St(this.storage,this.storageKey));const{error:m}=await H(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:d,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in e){const{phone:l,options:c}=e,{data:d,error:u}=await H(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(r=c?.data)!==null&&r!==void 0?r:{},create_user:(a=c?.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:d?.message_id},error:u}}throw new Ns("You must provide either an email or phone number.")}catch(l){if(z(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(e){var t,s;try{let r,a;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,a=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:l}=await H(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:r,xform:it});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const c=o.session,d=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:d,session:c},error:null}}catch(r){if(z(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let a=null,o=null;return this.flowType==="pkce"&&([a,o]=await St(this.storage,this.storageKey)),await H(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:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:eu})}catch(a){if(z(a))return{data:null,error:a};throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new rt;const{error:r}=await H(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(z(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:a}=e,{error:o}=await H(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:a?.captchaToken}},redirectTo:a?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:s,type:r,options:a}=e,{data:o,error:l}=await H(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:l}}throw new Ns("You must provide either an email or phone number and a type")}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),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 s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}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 Ps(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not val
24id"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Nn:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,d,u)=>(!o&&d==="user"&&(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."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,d,u))})}return{data:{session:e},error:null}}const{session:r,error:a}=await this._callRefreshToken(e.refresh_token);return a?{data:{session:null},error:a}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await H(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ot}):await this._useSession(async t=>{var s,r,a;const{data:o,error:l}=t;if(l)throw l;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new rt}:await H(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&a!==void 0?a:void 0,xform:ot})})}catch(t){if(z(t))return Ed(t)&&(await this._removeSession(),await Es(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:r,error:a}=s;
24if(a)throw a;if(!r.session)throw new rt;const o=r.session;let l=null,c=null;this.flowType==="pkce"&&e.email!=null&&([l,c]=await St(this.storage,this.storageKey));const{data:d,error:u}=await H(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:c}),jwt:o.access_token,xform:ot});if(u)throw u;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(z(s))return{data:{user:null},error:s};throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new rt;const t=Date.now()/1e3;let s=t,r=!0,a=null;const{payload:o}=En(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){const{session:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!l)return{data:{user:null,session:null},error:null};a=l}else{const{data:l,error:c}=await this._getUser(e.access_token);if(c)throw c;a={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return{data:{user:a.user,session:a},error:null}}catch(t){if(z(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){const{data:o,error:l}=t;if(l)throw l;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new rt;const{session:r,error:a}=await this._callRefreshToken(e.refresh_token);return a?{data:{user:null,session:null},error:a}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!Ke())throw new Ss("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ss(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new mi("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ss("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new mi("No code detected.");const{data:_,error:L}=await this._exchangeCodeForSession(e.code);if(L)throw L;const T=new URL(window.location.href);return T.searchParams.delete("code"),window.history.replaceState(window.history.state,"",T.toString()),{data:{session:_.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:a,refresh_token:o,expires_in:l,expires_at:c,token_type:d}=e;if(!a||!l||!o||!d)throw new Ss("No session defined in URL");const u=Math.round(Date.now()/1e3),m=parseInt(l);let f=u+m;c&&(f=parseInt(c));const p=f-u;p*1e3<=It&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${m}s`);const g=f-m;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,f,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,f,u);const{data:w,error:y}=await this._getUser(a);if(y)throw y;const N={provider_token:s,provider_refresh_token:r,access_token:a,expires_in:m,expires_at:f,refresh_token:o,token_type:d,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:N,redirectType:e.type},error:null}}catch(s){if(z(s))return{data:{session:null,redirectType:null},error:s};throw s}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await Ps(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;const{data:r,error:a}=t;if(a)return{error:a};const o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);
24if(l&&!(Pd(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return e!=="others"&&(await this._removeSession(),await Es(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=Md(),s={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,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{const{data:{session:a},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a),console.error(a)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await St(this.storage,this.storageKey,!0));try{return await H(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(a){if(z(a))return{data:null,error:a};throw a}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{const{data:s,error:r}=await this._useSession(async a=>{var o,l,c,d,u;const{data:m,error:f}=a;if(f)throw f;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await H(this.fetch,"GET",p,{headers:this.headers,jwt:(u=(d=m.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(r)throw r;return Ke()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(z(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;const{data:a,error:o}=t;if(o)throw o;return await H(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await zd(async r=>(r>0&&await Ud(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await H(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:it})),(r,a)=>{const o=200*Math.pow(2,r);return a&&Pn(a)&&Date.now()+o-s<It})}catch(s){if(this._debug(t,"error",s),z(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const s=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",s),Ke()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;const t="#_recoverAndRefresh()";this._debug(t,"begin");try{const s=await Ps(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not val
24id"),s!==null&&await this._removeSession();return}const r=((e=s.expires_at)!==null&&e!==void 0?e:1/0)*1e3-Date.now()<Nn;if(this._debug(t,`session has${r?"":" not"} expired with margin of ${Nn}s`),r){if(this.autoRefreshToken&&s.refresh_token){const{error:a}=await this._callRefreshToken(s.refresh_token);a&&(console.error(a),Pn(a)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new rt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new ln;const{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new rt;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const l={session:a.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(a){if(this._debug(r,"error",a),z(a)){const o={session:null,error:a};return Pn(a)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(a),a}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const a=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){a.push(c)}});if(await Promise.all(o),a.length>0){for(let l=0;l<a.length;l+=1)console.error(a[l]);throw a[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ca(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Es(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ke()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),It);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}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:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const r=Math.floor((s.expires_at*1e3-e)/It);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${It}ms, refresh threshold is ${Qn} ticks`),r<=Qn&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Aa)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ke()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),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),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(
24await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){const r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[a,o]=await St(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(l.toString())}if(s?.queryParams){const a=new URLSearchParams(s.queryParams);r.push(a.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:r,error:a}=t;return a?{data:null,error:a}:await H(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;const{data:a,error:o}=t;if(o)return{data:null,error:o};const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:c,error:d}=await H(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(s=a?.session)===null||s===void 0?void 0:s.access_token});return d?{data:null,error:d}:(e.factorType==="totp"&&(!((r=c?.totp)===null||r===void 0)&&r.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:a}=t;if(a)return{data:null,error:a};const{data:o,error:l}=await H(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:a}=t;return a?{data:null,error:a}:await H(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const s=e?.factors||[],r=s.filter(o=>o.factor_type==="totp"&&o.status==="verified"),a=s.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:s,totp:r,phone:a},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;const{data:{session:r},error:a}=e;if(a)return{data:null,error:a};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=En(r.access_token);let l=null;o.aal&&(l=o.aal);let c=l;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");const u=o.amr||[];return{data:{currentLevel:l,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(o=>o.kid===e);if(s||(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+Nd>Date.now()))return s;const{data:r,error:a}=await H(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;if(!r.keys||r.keys.length===0)throw new ds("JWKS is empty");if(this.jwks=r,this.jwks_cached_at=Date.now(),s=r.keys.find(o=>o.kid===e),!s)throw new ds("No matching signing key found in JWKS");return s}async getClaims(e,t={keys:[]}){try{let s=e;if(!s){const{data:p,error:g}
24=await this.getSession();if(g||!p.session)return{data:null,error:g};s=p.session.access_token}const{header:r,payload:a,signature:o,raw:{header:l,payload:c}}=En(s);if(Kd(a.exp),!r.kid||r.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:p}=await this.getUser(s);if(p)throw p;return{data:{claims:a,header:r,signature:o},error:null}}const d=Xd(r.alg),u=await this.fetchJwk(r.kid,t),m=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,m,o,Od(`${l}.${c}`)))throw new ds("Invalid JWT signature");return{data:{claims:a,header:r,signature:o},error:null}}catch(s){if(z(s))return{data:null,error:s};throw s}}}ps.nextInstanceID=0;const uu=ps;class hu extends uu{constructor(e){super(e)}}var fu=function(n,e,t,s){function r(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(u){try{d(s.next(u))}catch(m){o(m)}}function c(u){try{d(s.throw(u))}catch(m){o(m)}}function d(u){u.done?a(u.value):r(u.value).then(l,c)}d((s=s.apply(n,e||[])).next())})};class mu{constructor(e,t,s){var r,a,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const l=yd(e);this.realtimeUrl=`${l}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${l}/auth/v1`,this.storageUrl=`${l}/storage/v1`,this.functionsUrl=`${l}/functions/v1`;const c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,d={db:ud,realtime:fd,auth:Object.assign(Object.assign({},hd),{storageKey:c}),global:dd},u=bd(s??{},d);this.storageKey=(r=u.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(a=u.global.headers)!==null&&a!==void 0?a:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(m,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=wd(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},u.realtime)),this.rest=new Tc(`${l}/rest/v1`,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),u.accessToken||this._listenForAuthEvents()}get functions(){return new lc(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new od(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}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()}_getAccessToken(){var e,t;return fu(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:a,flowType:o,lock:l,debug:c},d,u){const m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new hu({url:this.authUrl,headers:Object.assign(Object.assign({},m),d),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,lock:l,debug:c,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new Hc(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?this.changedAccessToken=s:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const pu=(n,e,t)=>new mu(n,e,t),gu="https://lahzrlyhojyfadjasdrc.supabase.co",wu="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxhaHpybHlob2p5ZmFkamFzZHJjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Mzk0NzUwNDAsImV4cCI6MjA1NTA1MTA0MH0.0IwuqcrHrPS6AqJKVYbNVhP1gjKTh4sP_BPDF8TKHiY",I=pu(gu,wu),ut=ec((n,e)=>({user:null,isAuthenticated:!1,currentSession:null,magazine:{currentPage:0,pages:[...Array.from({length:13},(t,s)=>`/January/${s+1}.webp`)],comments:[],likes:[]},fabricPoll:{userVote:null,totalVotes:{redRoseViscoseSilkCrepe:0,floralViscoseChiffon:0},hasVoted:!1},initializeSession:async()=>{try{const{data:{session:t}}=await I.auth.getSession();if(t?.user){const{data:s}=await I.from("profiles").select().eq("id",t.user.id).single();if(s){const{data:r}=await I.from("sessions").insert({user_id:s.id,started_at:new Date().toISOString(),last_active_at:new Date().toISOString()}).select().single();n({user:s,isAuthenticated:!0,currentSession:r||null}),await e().fetchLikes(),await e().fetchAllComments(),await e().fetchFabricPollResults()}else await I.auth.signOut(),n({user:null,isAuthenticated:!1,currentSession:null})}}catch(t){console.error("Session initialization error:",t),n({user:null,isAuthenticated:!1,currentSession:null})}},trackPageView:async t=>{const{user:s,currentSession:r}=e();if(!(!s||!r))try{await I.from("page_views").insert({session_id:r.id,user_id:s.id,page_index:t,created_at:new Date().toISOString()})}catch(a){console.error("Error tracking page view:",a)}},trackDownload:async t=>{const{user:s,currentSession:r}=e();if(!(!s||!r))try{await I.from("downloads").insert({session_id:r.id,user_id:s.id,download_type:t,created_at:new Date().toISOString()})}catch(a){console.error("Error tracking download:",a)}},updateSessionActivity:async()=>{const{user:t,currentSession:s}=e();if(!(!t||!s))try{await I.from("sessions").update({last_active_at:new Date().toISOString()}).eq("id",s.id)}catch(r){console.error("Error updating session activity:",r)}},login:async(t,s)=>{try{console.log("Attempting to log in with email:",t);const{data:r,error:a}=await I.auth.signInWithPassword({email:t,password:s});if(a)return console.error("Sign in error:",a.message),{success:!1,error:a.message};const o=r.user;if(!o?.id)return console.error("No user returned from sign in"),{success:!1,error:"Authentication failed. Please check your credentials."};console.log("User authenticated, fetching profile for ID:",o.id);const{data:l,error:c}
24=await I.from("profiles").select().eq("id",o.id).single();if(c)return console.error("Profile fetch error:",c),{success:!1,error:"Failed to retrieve user profile."};console.log("Profile fetched successfully:",l.username);const{data:d,error:u}=await I.from("sessions").insert({user_id:o.id,started_at:new Date().toISOString(),last_active_at:new Date().toISOString()}).select().single();return u&&console.error("Failed to create analytics session:",u.message),n({user:l,isAuthenticated:!0,currentSession:d||null}),await e().fetchLikes(),await e().fetchAllComments(),console.log("Login complete, user is authenticated"),{success:!0}}catch(r){return console.error("Login error:",r),{success:!1,error:r instanceof Error?r.message:"An unexpected error occurred during login. Please try again."}}},register:async(t,s,r,a)=>{if(a!=="Community2025")return{success:!1,error:"Invalid community key. Please try again."};try{const o=t.toLowerCase().trim(),l=s.toLowerCase().trim();console.log("Starting registration for:",o,l);const{data:c}=await I.from("profiles").select().eq("username",o).single();if(c)return console.log("Username already exists:",o),{success:!1,error:"This username is already taken. Please choose another one."};if(r.length<6)return{success:!1,error:"Password must be at least 6 characters long."};console.log("Attempting to sign up user with Supabase...");const{data:d,error:u}=await I.auth.signUp({email:l,password:r,options:{data:{username:o}}});if(console.log("Sign up response:",d?"Success":"Failed",u?u.message:"No error"),u){if(u.message.includes("already registered"))return{success:!1,error:"This email is already registered. Please use a different email or try logging in."};throw u}const m=d.user;if(!m?.id)throw console.error("Failed to create user, no user ID returned"),new Error("Failed to create user account");console.log("User created successfully, ID:",m.id),await new Promise(y=>setTimeout(y,1e3));const{data:f,error:p}=await I.from("profiles").select().eq("id",m.id).single();if(console.log("Profile fetch result:",f?"Found":"Not found",p?p.message:"No error"),p||!f){console.log("Creating profile manually as trigger might have failed");const{data:y,error:N}=await I.from("profiles").insert({id:m.id,username:o,email:l,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).select().single();if(N)throw console.error("Manual profile creation failed:",N.message),N;console.log("Manual profile created:",y?"Success":"Failed"),n({user:y,isAuthenticated:!0})}else console.log("Using automatically created profile"),n({user:f,isAuthenticated:!0});console.log("Creating analytics session");const{data:g,error:w}=await I.from("sessions").insert({user_id:m.id,started_at:new Date().toISOString(),last_active_at:new Date().toISOString()}).select().single();return w&&console.error("Failed to create analytics session:",w.message),n({currentSession:g||null}),await e().fetchLikes(),await e().fetchAllComments(),console.log("Registration complete, user is logged in"),{success:!0}}catch(o){return console.error("Registration error:",o),{success:!1,error:o instanceof Error?o.message:"An unexpected error occurred during registration. Please try again."}}},logout:async()=>{const{currentSession:t}=e();if(t)try{await I.from("sessions").update({ended_at:new Date().toISOString()}).eq("id",t.id)}catch(s){console.error("Error ending session:",s)}await I.auth.signOut(),n({user:null,isAuthenticated:!1,currentSession:null})},addComment:async(t,s)=>{const{user:r}=e();if(r)try{const{data:a,error:o}=await I.from("comments").insert({user_id:r.id,page_index:s,content:t,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}).select().single();if(o)throw console.error("Supabase error adding comment:",o),o;if(!a){console.error("No comment returned from insert operation");return}const l={...a,profile:{username:r.username}};console.log("Comment added with profile:",l),n(c=>({magazine:{...c.magazine,comments:[...c.magazine.comments,l]}})),console.log("Comment added successfully to state")}catch(a){console.error("Error adding comment:",a),a instanceof Error&&console.error("Error details:",a.message)}},toggleLike:async t=>{const{user:s}=e();if(s){console.log(`Toggling like for page ${t} by user ${s.id}`);try{const r=e().magazine.likes.find(a=>a.user_id===s.id&&a.page_index===t);if(r){console.log(`Found existing like ${r.id}, removing it`);const{error:a}=await I.from("likes").delete().eq("id",r.id);if(a)throw console.error("Error deleting like:",a),a;n(o=>(console.log("Removing like from state"),{magazine:{...o.magazine,likes:o.magazine.likes.filter(l=>l.id!==r.id)}}))}else{console.log("No existing like found, creating new like");const{data:a,error:o}=await I.from("likes").insert({user_id:s.id,page_index:t,created_at:new Date().toISOString()}).select().single();if(o)throw console.error("Error creating like:",o),o;console.log("New like created:",a),n(l=>(console.log("Adding like to state"),{magazine:{...l.magazine,likes:[...l.magazine.likes,a]}}))}}catch(r){console.error("Error toggling like:",r)}}},fetchComments:async t=>{console.log(`Fetching comments for page index: ${t}`);try{const{data:s,error:r}=await I.from("comments").select(` 25 *, 26 profiles:profiles(username) 27 `).eq("page_index",t).order("created_at",{ascending:!0});if(r)throw console.error("Error fetching comments:",r),r;if(!s||s.length===0)return console.log(`No comments found for page ${t}`),[];console.log(`Received ${s.length} raw comments for page ${t}`);const a=s.map(o=>o.profiles&&o.profiles.username?{...o,profile:{username:o.profiles.username},profiles:void 0}:o.username?{...o,profile:{username:o.username}}:{...o,profile:{username:"Anonymous"}});return n(o=>{const l=o.magazine.comments.filter(d=>d.page_index===t);if(l.length===a.length&&l.every(d=>a.some(u=>u.id===d.id)))return console.log(`Comments for page ${t} unchanged, skipping state update`),o;const c=o.magazine.comments.filter(d=>d.page_index!==t);return{magazine:{...o.magazine,comments:[...c,...a]}}}),a}catch(s){return console.error("Error fetching comments:",s),[]}},fetchAllComments:async()=>{console.log("Fetching comments for all pages");try{const{data:t,error:s}=await I.from("comments").select(` 28 *, 29 profiles:profiles(username) 30 `).order("created_at",{ascending:!0});if(s)throw console.error("Error fetching all comments:",s),s;console.log(`Received all raw comments (${t?.length||0}):`,t);const r=t?.map(a=>a.profiles&&a.profiles.username?{...a,profile:{username:a.profiles.username},profiles:void 0}:a.username?{...a,profile:{username:a.username}}:{...a,profile:{username:"Anonymous"}});console.log("Transformed all comments:",r),n(a=>({magazine:{...a.magazine,comments:r||[]}}))}catch(t){console.error("Error fetching all comments:",t)}},fetchLikes:async()=>{try{const{data:t,error:s}=await I.from("likes").select().order("created_at",{ascending:!0});if(s)throw s;n(r=>({magazine:{...r.magazine,likes:t||[]}}))}
30catch(t){console.error("Error fetching likes:",t)}},trackInteraction:async(t,s)=>{const{user:r,currentSession:a}=e();if(!(!r||!a))try{await I.from("interactions").insert({session_id:a.id,user_id:r.id,interaction_type:t,metadata:s||{},created_at:new Date().toISOString()})}catch(o){console.error("Error tracking interaction:",o)}},checkAllComments:async()=>{console.log("Checking all comments in database...");try{const{data:t,error:s}=await I.from("comments").select("*, profile:profiles(*)").order("created_at",{ascending:!0});return s?(console.error("Error checking all comments:",s),[]):(console.log(`Found ${t?.length||0} total comments in database:`,t),t||[])}catch(t){return console.error("Error checking all comments:",t),[]}},submitFabricVote:async t=>{const{user:s}=e();if(!s)return console.error("User not authenticated"),!1;try{const{data:r,error:a}=await I.from("fabric_poll").upsert({user_id:s.id,fabric_choice:t,updated_at:new Date().toISOString()},{onConflict:"user_id"}).select().single();return a?(console.error("Error submitting fabric vote:",a),!1):(n(o=>({fabricPoll:{...o.fabricPoll,userVote:t,hasVoted:!0}})),await e().fetchFabricPollResults(),!0)}catch(r){return console.error("Error submitting fabric vote:",r),!1}},fetchFabricPollResults:async()=>{try{const{data:t,error:s}=await I.from("fabric_poll").select("fabric_choice");if(s){console.error("Error fetching fabric poll results:",s);return}const r=t?.reduce((c,d)=>(d.fabric_choice==="redRoseViscoseSilkCrepe"?c.redRoseViscoseSilkCrepe+=1:d.fabric_choice==="floralViscoseChiffon"&&(c.floralViscoseChiffon+=1),c),{redRoseViscoseSilkCrepe:0,floralViscoseChiffon:0})||{redRoseViscoseSilkCrepe:0,floralViscoseChiffon:0},{user:a}=e();let o=null,l=!1;if(a){const{data:c}=await I.from("fabric_poll").select("fabric_choice").eq("user_id",a.id).single();c&&(o=c.fabric_choice,l=!0)}n(c=>({fabricPoll:{...c.fabricPoll,totalVotes:r,userVote:o,hasVoted:l}}))}catch(t){console.error("Error fetching fabric poll results:",t)}}}));ut.getState().checkAllComments();const ji=({isPasswordResetMode:n})=>{const{login:e,register:t}=ut(),[s,r]=v.useState(""),[a,o]=v.useState(""),[l,c]=v.useState(""),[d,u]=v.useState(""),[m,f]=v.useState(null),[p,g]=v.useState(!1),[w,y]=v.useState(!0),[N,_]=v.useState(!1),[L,T]=v.useState(""),[B,Y]=v.useState(!1),[K,Q]=v.useState(""),[ee,W]=v.useState(!1),[J,le]=v.useState(n||!1),[re,Ae]=v.useState(""),[ne,$e]=v.useState("");v.useEffect(()=>{const F=window.location.hash,U=!!(F&&(F.includes("type=recovery")||F.includes("access_token="))),xe=sessionStorage.getItem("has_reset_token")==="true";(U||xe)&&(console.log("DIRECT CHECK: Password reset token found in URL or sessionStorage"),le(!0),(async()=>{try{const{data:ie}=await I.auth.getSession();ie.session?console.log("Active session found for password reset, ready to proceed"):console.log(U?"No active session yet but token in URL, should be processed on form submit":"Warning: Reset mode active but no token or session found")}catch(ie){console.error("Error checking session in direct hash check:",ie)}})())},[]),v.useEffect(()=>{n!==void 0&&(console.log("External password reset mode changed:",n),le(n),n&&(async()=>{try{const{data:F}=await I.auth.getSession();if(F.session)console.log("Active session found for password reset");else{console.log("No active session found for password reset, may need to refresh token");const U=window.location.hash;U&&(U.includes("type=recovery")||U.includes("access_token="))?console.log("Recovery token found in URL, but no session - this is expected"):f("Password reset session not found. Please try again or request a new reset link.")}}catch(F){console.error("Error checking session for password reset:",F)}})())},[n]),v.useEffect(()=>{if(n){console.log("Password reset mode already set by parent component");return}return(async()=>{const U=window.location.hash;if(new URL(window.location.href).hostname,U&&(U.includes("type=recovery")||U.includes("access_token="))){console.log("Recovery token detected in URL"),le(!0);try{const{data:ie}=await I.auth.getSession();if(ie.session){console.log("Recovery session detected, keeping the page in password reset mode");const Te=ie.session.user.id;console.log("User ID from recovery session:",Te)}else console.log("No recovery session detected"),f("Invalid or expired recovery link. Please request a new one."),le(!1)}catch(ie){console.error("Error processing recovery token:",ie),f("There was a problem with your password reset link. Please try again."),le(!1)}}})(),()=>{}},[]);const ge=F=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(F),Oe=F=>/^[a-zA-Z0-9_-]+$/.test(F),De=async F=>{if(F.preventDefault(),f(null),w){if(!L){f("Please enter your email");return}if(!ge(L)){f("Please enter a valid email address");return}if(!l){f("Password is required");return}}else{if(!s){f("Username is required");return}if(!Oe(s)){f("Username can only contain letters, numbers, underscores, and hyphens");return}if(!a){f("Email is required");return}if(!ge(a)){f("Please enter a valid email address");return}if(!l){f("Password is required");return}if(l.length<6){f("Password must be at least 6 characters long");return}if(!d){f("Community key is required for registration");return}}g(!0),console.log(`Attempting to ${w?"login":"register"} user`);try{if(w){console.log("Using identifier:",L);const U=await e(L,l);
30console.log("Login result:",U),U.success||f(U.error||"Login failed. Please try again.")}else{console.log("Registering with:",{username:s,email:a});const U=await t(s,a,l,d);console.log("Registration result:",U),U.success||f(U.error||"Registration failed. Please try again.")}}catch(U){console.error("Auth error:",U),f(U instanceof Error?U.message:"An unexpected error occurred")}finally{g(!1)}},je=async F=>{if(F.preventDefault(),f(null),W(!1),!K){f("Please enter your email address");return}if(!ge(K)){f("Please enter a valid email address");return}g(!0);try{console.log("Sending password reset email to:",K);const ie=await fetch("https://lahzrlyhojyfadjasdrc.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxhaHpybHlob2p5ZmFkamFzZHJjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Mzk0NzUwNDAsImV4cCI6MjA1NTA1MTA0MH0.0IwuqcrHrPS6AqJKVYbNVhP1gjKTh4sP_BPDF8TKHiY"},body:JSON.stringify({email:K})}),Te=await ie.json();if(!ie.ok)throw new Error(Te.error||"Failed to send password reset email");W(!0),f(null),console.log("Password reset email sent successfully via Edge Function")}catch(U){console.error("Password reset error:",U),f(U instanceof Error?U.message:"An unexpected error occurred")}finally{g(!1)}},we=F=>{Y(F),f(null),W(!1),F&&Q(L)},qe=()=>{y(!w),f(null),T(""),r(""),o(""),c(""),Y(!1),W(!1)},Me=async F=>{if(F.preventDefault(),f(null),!re){f("Please enter a new password");return}if(re.length<6){f("Password must be at least 6 characters long");return}if(re!==ne){f("Passwords do not match");return}g(!0);try{const U=window.location.hash,xe=!!(U&&(U.includes("type=recovery")||U.includes("access_token="))),ie=sessionStorage.getItem("has_reset_token")==="true";console.log("Processing password reset with:",{hasToken:xe,hasStoredToken:ie,hashLength:U?U.length:0});const{data:Te}=await I.auth.getSession();if(!Te?.session&&!xe){console.error("No active session or recovery token found"),f("No valid recovery session found. Please request a new password reset link."),g(!1);return}console.log("Updating password...");const{error:ke}=await I.auth.updateUser({password:re});if(ke)console.error("Password update error:",ke),ke.message.includes("expired")||ke.message.includes("invalid")||ke.status===401?(f("Your password reset link has expired. Please request a new one."),sessionStorage.removeItem("has_reset_token"),sessionStorage.removeItem("reset_token_processed")):f(ke.message);else{console.log("Password updated successfully"),sessionStorage.removeItem("has_reset_token"),sessionStorage.removeItem("reset_token_processed"),window.history.replaceState(null,document.title,window.location.pathname);const Le=document.createElement("div");Le.className="fixed inset-0 flex items-center justify-center z-50 bg-black/70 backdrop-blur-sm",Le.innerHTML=` 31 <div class="bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-auto border-4 border-green-400"> 32 <div class="text-center mb-4"> 33 <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4"> 34 <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"> 35 <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /> 36 </svg> 37 </div> 38 <h2 class="text-2xl font-bold text-gray-800">Password Reset Successful!</h2> 39 <p class="mt-2 text-gray-600">Your password has been updated successfully.</p> 40 </div> 41 <div class="bg-blue-50 p-4 rounded-xl mb-4 text-sm text-blue-800"> 42 <p class="font-medium mb-2">What's Next?</p> 43 <ol class="list-decimal pl-5 space-y-1"> 44 <li>You'll be redirected to the login page</li> 45 <li>Sign in with your email and new password</li> 46 <li>Enjoy access to your Rosys Patterns account</li> 47 </ol> 48 </div> 49 <button id="successDismissBtn" class="w-full bg-gradient-to-r from-pink-500 to-rose-500 text-white py-3 rounded-xl font-medium hover:shadow-lg transition-all transform hover:scale-[1.02] active:scale-[0.98]"> 50 Continue to Login 51 </button> 52 </div> 53 `,document.body.appendChild(Le),document.getElementById("successDismissBtn")?.addEventListener("click",()=>{document.body.removeChild(Le),I.auth.signOut(),le(!1),y(!0),Ae(""),$e(""),f(null)})}}catch(U){console.error("Password update error:",U),f("An unexpected error occurred. Please try again or request a new reset link.")}finally{g(!1)}};return console.log("Login rendering decision:",{isResetPasswordMode:J,forgotPasswordMode:B,hash:window.location.hash,hasResetToken:!!(window.location.hash&&(window.location.hash.includes("type=recovery")||window.location.hash.includes("access_token=")))}),J?(console.log("Rendering password reset form (from recovery link)"),i.jsx("div",{className:"fixed inset-0 flex items-center justify-center z-40 p-4 bg-black/40 backdrop-blur-sm overflow-y-auto",children:i.jsx("div",{className:"relative w-full max-w-md mx-auto",children:i.jsxs("div",{className:`bg-white rounded-2xl shadow-lg px-6 py-8 ${J?"border-4 border-amber-400 bg-amber-50/30":""}`,children:[i.jsxs("div",{className:"text-center mb-5",children:[i.jsx("h2",{className:"text-xl font-bold text-[#4a3f35]",children:"Reset Your Password"}),i.jsx("p",{className:"text-[#4a3f35]/70 text-sm mt-1",children:"Enter a new secure password for your account"}),i.jsx("div",{className:"mt-2 bg-amber-100 text-amber-800 p-2 rounded-lg text-xs",children:"Your password reset link is active. Please create a new password below."})]}),m&&i.jsxs("div",{className:"bg-red-50 text-red-500 p-2.5 rounded-xl flex items-center justify-between text-xs",children:[i.jsx("span",{children:m}),i.jsx("button",{onClick:()=>f(null),className:"p-1 hover:bg-red-100 rounded-full transition-colors flex-shrink-0",children:i.jsx(Ve,{className:"w-3.5 h-3.5"})})]}),i.jsxs("form",{onSubmit:Me,className:"space-y-3",children:[i.jsxs("div",{className:"space-y-1",children:[i.jsx("label",{htmlFor:"newPassword",className:"block text-xs font-medium text-[#4a3f35]",children:"New Password (min 6 characters)"}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400",children:i.jsx(Us,{className:"w-4 h-4"})}),i.jsx("input",{id:"newPassword",type:N?"text":"password",value:re,onChange:F=>Ae(F.target.value),placeholder:"Enter new password",className:"w-full pl-8 px-3 py-2 rounded-xl border border-[#4a3f35]/10 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-pink-500/20 focus:border-pink-500 transition-all pr-10 text-sm leading-tight",required:!0,disabled:p,autoComplete:"new-password"}),i.jsx("button",{type:"button",className:"absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700",onClick:()=>_(!N),children:N?i.jsx(zn,{size:16}):i.jsx(Bn,{size:16})})]})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("label",{htmlFor:"newPasswordConfirm",className:"block text-xs font-medium text-[#4a3f35]",children:"Confirm New Password"}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400",children:i.jsx(Us,{className:"w-4 h-4"})}),i.jsx("input",{id:"newPasswordConfirm",type:N?"text":"password",value:ne,onChange:F=>$e(F.target.value),placeholder:"Confirm new password",className:"w-full pl-8 px-3 py-2 rounded-xl border border-[#4a3f35]/10 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-pink-500/20 focus:border-pink-500 transition-all pr-10 text-sm leading-tight",required:!0,disabled:p,autoComplete:"new-password"})]})]}),i.jsx("button",{type:"submit",disabled:p||!re||!ne,className:`mt-1 w-full bg-gradient-to-r from-pink-500 to-rose-500 text-white py-2 rounded-xl font-medium transition-all transform hover:scale-[1.02] active:scale-[0.98] text-sm ${p||!re||!ne?"opacity-50 cursor-not-allowed":"hover:shadow-lg"}`,children:p?i.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[i.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),i.jsx("span",{children:"Updating..."})]}):"Update Password"})]}),i.jsx("div",{className:"flex flex-col items-center space-y-2 pt-1",children:i.jsxs("div",{className:"text-center w-full",children:[i.jsx("div",{className:"relative w-full h-px bg-gray-200 mb-2",children:i.jsx("span",{className:"absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white px-2 text-xs text-gray-400",children:"OR"})}),i.jsxs("button",{type:"button",onClick:()=>{le(!1),y(!0)},className:"w-full py-2 border transition-all flex items-center justify-center gap-1 text-xs font-medium rounded-xl border-gray-300 text-gray-700 hover:bg-gray-50",children:[i.jsx(lt,{className:"w-3 h-3"}),i.jsx("span",{children:"Back to Login"})]})]})})]})})})):B?i.jsx("div",{className:"min-h-screen overflow-y-auto bg-[#f5f1eb]",children:i.jsxs("div",{className:"flex flex-col items-center py-6 px-4 sm:px-6 sm:py-8 pb-12",children:[i.jsxs("div",{className:"mb-5 sm:mb-6 text-center",children:[i.jsx("img",{src:"/logowhite.png",alt:"Rosys Patterns Logo",className:"w-14 h-14 sm:w-20 sm:h-20 mx-auto mb-2 object-contain"}),i.jsx("div",{className:"font-serif italic",children:i.jsx("p",{className:"text-[#4a3f35]/70 tracking-widest text-xs sm:text-sm",children:"Jan & Feb 26' Edition"})})]}),i.jsxs("div",{className:"w-full max-w-sm md:max-w-md bg-white/95 rounded-2xl shadow-2xl p-4 sm:p-6 space-y-3 sm:space-y-4 mb-6",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("h1",{className:"text-xl sm:text-3xl font-bold text-[#4a3f35] mb-1 sm:mb-2",children:"Reset Password"}),i.jsx("p",{className:"text-[#4a3f35]/60 text-sm",children:"Enter your email and we'll send you a link to reset your password"}),i.jsxs("p",{className:"text-xs text-amber-600 mt-1 bg-amber-50 p-2 rounded-lg",children:[i.jsx("b",{children:"Tip:"})," The reset link now works both on localhost and on the deployed site. No manual changes required."]})]}),m&&i.jsxs("div",{className:"bg-red-50 text-red-500 p-2.5 rounded-xl flex items-center justify-between text-xs",children:[i.jsx("span",{children:m}),i.jsx("button",{onClick:()=>f(null),className:"p-1 hover:bg-red-100 rounded-full transition-colors flex-shrink-0",children:i.jsx(Ve,{className:"w-3.5 h-3.5"})})]}),ee&&i.jsxs("div",{className:"bg-green-50 text-green-600 p-2.5 rounded-xl flex flex-col items-start justify-between text-xs space-y-2",children:[i.jsxs("div",{className:"flex w-full justify-between",children:[i.jsx("span",{className:"font-medium",children:"Password reset email sent!"}),i.jsx("button",{onClick:()=>W(!1),className:"p-1 hover:bg-green-100 rounded-full transition-colors flex-shrink-0",children:i.jsx(Ve,{className:"w-3.5 h-3.5"})})]}),i.jsx("p",{children:"Please check your inbox for the reset link. If you don't see it, check your spam folder."})]}),i.jsxs("form",{onSubmit:je,className:"space-y-3",children:[i.jsxs("div",{className:"space-y-1",children:[i.jsx("label",{htmlFor:"resetEmail",className:"block text-xs font-medium text-[#4a3f35]",children:"Email"}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400",children:i.jsx(bn,{className:"w-4 h-4"})}),i.jsx("input",{id:"resetEmail",type:"email",value:K,onChange:F=>Q(F.target.value),placeholder:"Enter your email",className:"w-full pl-8 px-3 py-2 rounded-xl border border-[#4a3f35]/10 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-pink-500/20 focus:border-pink-500 transition-all text-sm leading-tight",required:!0,disabled:p,autoComplete:"email"})]})]}),i.jsx("button",{type:"submit",disabled:p||!K,className:`mt-1 w-full bg-gradient-to-r from-pink-500 to-rose-500 text-white py-2 rounded-xl font-medium transition-all transform hover:scale-[1.02] active:scale-[0.98] text-sm ${p||!K?"opacity-50 cursor-not-allowed":"hover:shadow-lg"}`,children:p?i.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[i.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),i.jsx("span",{children:"Sending..."})]}):"Send Reset Link"})]}),i.jsx("div",{className:"flex flex-col items-center space-y-2 pt-1",children:i.jsxs("div",{className:"text-center w-full",children:[i.jsx("div",{className:"relative w-full h-px bg-gray-200 mb-2",children:i.jsx("span",{className:"absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white px-2 text-xs text-gray-400",children:"REMEMBER YOUR PASSWORD?"})}),i.jsxs("button",{type:"button",onClick:()=>we(!1),className:"w-full py-2 border transition-all flex items-center justify-center gap-1 text-xs font-medium rounded-xl border-gray-300 text-gray-700 hover:bg-gray-50",children:[i.jsx(lt,{className:"w-3 h-3"}),i.jsx("span",{children:"Back to Login"})]})]})})]})]})}):i.jsx("div",{className:"min-h-screen overflow-y-auto bg-[#f5f1eb]",children:i.jsxs("div",{className:"flex flex-col items-center py-6 px-4 sm:px-6 sm:py-8 pb-12",children:[i.jsxs("div",{className:"mb-5 sm:mb-6 text-center",children:[i.jsx("img",{src:"/logowhite.png",alt:"Rosys Patterns Logo",className:"w-14 h-14 sm:w-20 sm:h-20 mx-auto mb-2 object-contain"}),i.jsx("div",{className:"font-serif italic",children:i.jsx("p",{className:"text-[#4a3f35]/70 tracking-widest text-xs sm:text-sm",children:"July & Aug 25' Edition"})})]}),i.jsxs("div",{className:"w-full max-w-sm md:max-w-md bg-white/95 rounded-2xl shadow-2xl p-4 sm:p-6 space-y-3 sm:space-y-4 mb-6",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("h1",{className:"text-xl sm:text-3xl font-bold text-[#4a3f35] mb-1 sm:mb-2",children:w?"Welcome Back":"Join Us"}),i.jsx("p",{className:"text-[#4a3f35]/60 text-sm",children:w?"Sign in to enjoy June's Edition":"Create an account to join our community"})]}),i.jsxs("div",{className:"bg-pink-50 border border-pink-200 rounded-xl p-3 text-center",children:[i.jsx("h3",{className:"font-bold text-pink-800 text-sm",children:"â ï¸ Important Notice â ï¸"}),i.jsxs("p",{className:"text-xs text-pink-700 mt-1",children:["Starting with Jan & Feb 26' Edition, ",i.jsx("span",{className:"font-semibold",children:"all users"})," need to sign in with email and password."]}),w&&i.jsxs("button",{onClick:qe,className:"mt-2 bg-pink-600 hover:bg-pink-700 text-white text-xs py-1.5 px-3 rounded-lg inline-flex items-center",children:[i.jsx("span",{children:"Create New Account"}),i.jsx(Vn,{className:"w-3 h-3 ml-1"})]})]}),m&&i.jsxs("div",{className:"bg-red-50 text-red-500 p-2.5 rounded-xl flex items-center justify-between text-xs",children:[i.jsx("span",{children:m}),i.jsx("button",{onClick:()=>f(null),className:"p-1 hover:bg-red-100 rounded-full transition-colors flex-shrink-0",children:i.jsx(Ve,{className:"w-3.5 h-3.5"})})]}),i.jsxs("form",{onSubmit:De,className:"space-y-3",children:[i.jsx("input",{type:"text",autoComplete:"email",style:{display:"none"},"aria-hidden":"true",value:w?L:s,readOnly:!0}),w?i.jsxs("div",{className:"space-y-1",children:[i.jsx("label",{htmlFor:"identifier",className:"block text-xs font-medium text-[#4a3f35]",children:"Email"}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400",children:i.jsx(bn,{className:"w-4 h-4"})}),i.jsx("input",{id:"identifier",type:"email",value:L,onChange:F=>T(F.target.value),placeholder:"Enter your email",className:"w-full pl-8 px-3 py-2 rounded-xl border border-[#4a3f35]/10 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-pink-500/20 focus:border-pink-500 transition-all text-sm leading-tight",required:!0,disabled:p,autoComplete:"email",inputMode:"email"})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-1",children:[i.jsx("label",{htmlFor:"username",className:"block text-xs font-medium text-[#4a3f35]",children:"Username *"}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute inset-y-0 left
53-0 pl-3 flex items-center pointer-events-none text-gray-400",children:i.jsx(Yi,{className:"w-4 h-4"})}),i.jsx("input",{id:"username",type:"text",value:s,onChange:F=>r(F.target.value),placeholder:"Choose a username",pattern:"[a-zA-Z0-9_-]*",title:"Only letters, numbers, underscores, and hyphens are allowed",className:"w-full pl-8 px-3 py-2 rounded-xl border border-[#4a3f35]/10 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-pink-500/20 focus:border-pink-500 transition-all text-sm leading-tight",required:!0,disabled:p,autoComplete:"username",name:"username",inputMode:"text"})]}),i.jsx("p",{className:"text-xs text-[#4a3f35]/60",children:"Only letters, numbers, underscores, and hyphens"})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("label",{htmlFor:"email",className:"block text-xs font-medium text-[#4a3f35]",children:"Email *"}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400",children:i.jsx(bn,{className:"w-4 h-4"})}),i.jsx("input",{id:"email",type:"email",value:a,onChange:F=>o(F.target.value),placeholder:"Enter your email",className:"w-full pl-8 px-3 py-2 rounded-xl border border-[#4a3f35]/10 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-pink-500/20 focus:border-pink-500 transition-all text-sm leading-tight",required:!0,disabled:p,autoComplete:"email",inputMode:"email",name:"email"})]})]})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("div",{className:"flex items-center justify-between",children:i.jsxs("label",{htmlFor:"password",className:"block text-xs font-medium text-[#4a3f35]",children:["Password ",!w&&"(min 6 characters)*"]})}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400",children:i.jsx(Us,{className:"w-4 h-4"})}),i.jsx("input",{id:"password",type:N?"text":"password",value:l,onChange:F=>c(F.target.value),placeholder:"Enter your password",className:"w-full pl-8 px-3 py-2 rounded-xl border border-[#4a3f35]/10 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-pink-500/20 focus:border-pink-500 transition-all pr-10 text-sm leading-tight",required:!0,disabled:p,autoComplete:w?"current-password":"new-password",name:w?"current-password":"new-password"}),i.jsx("button",{type:"button",className:"absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700",onClick:()=>_(!N),children:N?i.jsx(zn,{size:16}):i.jsx(Bn,{size:16})})]}),w&&!B&&i.jsx("div",{className:"flex justify-end mt-1",children:i.jsx("button",{type:"button",onClick:()=>we(!0),className:"text-xs text-pink-600 hover:text-pink-700 hover:underline focus:outline-none",children:"Forgot password?"})})]}),!w&&i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("label",{htmlFor:"key",className:"block text-xs font-medium text-[#4a3f35]",children:"Community Key *"}),i.jsx("a",{href:"https://chat.whatsapp.com/BhehU7Q0FjA6BtxYDPoPIn",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-green-600 hover:text-green-800 font-medium",children:"Get key on WhatsApp"})]}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400",children:i.jsx(Go,{className:"w-4 h-4"})}),i.jsx("input",{id:"key",type:"password",value:d,onChange:F=>u(F.target.value),placeholder:"Enter community key",className:"w-full pl-8 px-3 py-2 rounded-xl border border-[#4a3f35]/10 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-pink-500/20 focus:border-pink-500 transition-all text-sm leading-tight",autoComplete:"off",name:"key",required:!0,disabled:p,inputMode:"text"})]}),i.jsx("p",{className:"text-xs text-[#4a3f35]/60",children:"Join our WhatsApp community to get the key"})]}),i.jsx("button",{type:"submit",disabled:p||(w?!L||!l:!s||!a||!l||!d),className:`mt-1 w-full bg-gradient-to-r from-pink-500 to-rose-500 text-white py-2 rounded-xl font-medium transition-all transform hover:scale-[1.02] active:scale-[0.98] text-sm ${p||(w?!L||!l:!s||!a||!l||!d)?"opacity-50 cursor-not-allowed":"hover:shadow-lg"}`,children:p?i.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[i.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),i.jsx("span",{children:w?"Signing in...":"Creating account..."})]}):w?"Sign In":"Create Account"})]}),i.jsxs("div",{className:"flex flex-col items-center space-y-2 pt-1",children:[i.jsxs("div",{className:"text-center w-full",children:[i.jsx("div",{className:"relative w-full h-px bg-gray-200 mb-2",children:i.jsx("span",{className:"absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white px-2 text-xs text-gray-400",children:w?"NEW USER?":"ALREADY REGISTERED?"})}),i.jsx("button",{type:"button",onClick:qe,className:`w-full py-2 border transition-all flex items-center justify-center gap-1 text-xs font-medium rounded-xl ${w?"border-pink-500 text-pink-600 hover:bg-pink-50 bg-pink-50/50":"border-gray-300 text-gray-700 hover:bg-gray-50"}`,children:w?i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"Create a New Account"}),i.jsx(Vn,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-3 h-3"}),i.jsx("span",{children:"Back to Login"})]})})]}),i.jsx("p",{className:"text-xs text-[#4a3f35]/60 text-center",children:"* Required fields"}),w&&window.location.hash&&window.location.hash.includes("type=recovery")&&i.jsx("button",{type:"button",onClick:()=>{console.log("Manually entering password reset mode"),le(!0),sessionStorage.setItem("has_reset_token","true")},className:"mt-2 text-xs text-amber-600 hover:text-amber-700 bg-amber-50 hover:bg-amber-100 px-3 py-1.5 rounded-lg transition-colors",children:i.jsx("span",{children:"Reset Link Detected - Click to Enter Reset Mode"})})]})]}
53),i.jsxs("div",{className:"w-full max-w-sm md:max-w-md space-y-4",children:[i.jsxs("div",{className:"bg-white/95 p-4 rounded-2xl border border-green-200 shadow-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"#25D366",className:"flex-shrink-0",children:i.jsx("path",{d:"M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"font-bold text-green-800 text-sm",children:"Join Our WhatsApp Community!"}),i.jsx("p",{className:"text-xs text-green-700",children:w?"Connect with fellow enthusiasts and get updates":"Get your community key and join our sewing community"})]})]}),i.jsxs("a",{href:"https://chat.whatsapp.com/BhehU7Q0FjA6BtxYDPoPIn",target:"_blank",rel:"noopener noreferrer",className:"mt-2 w-full flex items-center justify-center gap-2 bg-green-600 hover:bg-green-700 text-white py-2 px-4 rounded-lg transition-colors text-sm",children:[i.jsx("span",{children:"Join Rosys Patterns on WhatsApp"}),i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"M5 12h14M12 5l7 7-7 7"})})]})]}),i.jsxs("div",{className:"bg-white/95 rounded-2xl p-4 border border-[#4a3f35]/10 shadow-lg",children:[i.jsx("h3",{className:"font-medium text-[#4a3f35] text-xs mb-2",children:"What you'll get with Rosys Patterns:"}),i.jsxs("ul",{className:"text-xs space-y-1.5 text-[#4a3f35]/80",children:[i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx("svg",{className:"w-4 h-4 text-pink-500 mt-0.5 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 13l4 4L19 7"})}),i.jsx("span",{children:"Monthly magazine with exclusive sewing patterns"})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx("svg",{className:"w-4 h-4 text-pink-500 mt-0.5 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 13l4 4L19 7"})}),i.jsx("span",{children:"DIY projects for all skill levels"})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx("svg",{className:"w-4 h-4 text-pink-500 mt-0.5 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 13l4 4L19 7"})}),i.jsx("span",{children:"Comprehensive pattern directory"})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx("svg",{className:"w-4 h-4 text-pink-500 mt-0.5 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 13l4 4L19 7"})}),i.jsx("span",{children:"Pro sewing tips & creative design inspirations"})]})]})]}),i.jsx("div",{className:"text-center text-xs text-[#4a3f35]/60 px-4 py-3 mx-auto",children:w?i.jsx("p",{className:"font-medium",children:"â ï¸ Starting with Jan & Feb 26' Edition, all users need to sign in with email and password."}):i.jsx("p",{children:"Free Sewing Patterns, DIY projects, and exclusive lifestyle content updated monthly!"})})]})]})})};function fe(n){const e=Object.prototype.toString.call(n);return n instanceof Date||typeof n=="object"&&e==="[object Date]"?new n.constructor(+n):typeof n=="number"||e==="[object Number]"||typeof n=="string"||e==="[object String]"?new Date(n):new Date(NaN)}function xu(n,e){return n instanceof Date?new n.constructor(e):new Date(e)}const Cs=43200,ki=1440;let yu={};function bu(){return yu}function Ni(n){const e=fe(n),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+n-+t}function zs(n,e){const t=fe(n),s=fe(e),r=t.getTime()-s.getTime();return r<0?-1:r>0?1:r}function vu(n){return xu(n,Date.now())}function _u(n,e){const t=fe(n),s=fe(e),r=t.getFullYear()-s.getFullYear(),a=t.getMonth()-s.getMonth();return r*12+a}function ju(n){return e=>{const s=(n?Math[n]:Math.trunc)(e);return s===0?0:s}}function ku(n,e){return+fe(n)-+fe(e)}function Nu(n){const e=fe(n);return e.setHours(23,59,59,999),e}function Su(n){const e=fe(n),t=e.getMonth();return e.setFullYear(e.getFullYear(),t+1,0),e.setHours(23,59,59,999),e}function Pu(n){const e=fe(n);return+Nu(e)==+Su(e)}function Eu(n,e){const t=fe(n),s=fe(e),r=zs(t,s),a=Math.abs(_u(t,s));let o;if(a<1)o=0;else{t.getMonth()===1&&t.getDate()>27&&t.setDate(30),t.setMonth(t.getMonth()-r*a);let l=zs(t,s)===-r;Pu(fe(n))&&a===1&&zs(n,s)===1&&(l=!1),o=r*(a-Number(l))}return o===0?0:o}function Cu(n,e,t){const s=ku(n,e)/1e3;return ju(t?.roundingMethod)(s)}const Au={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},$u=(n,e,t)=>{let s;const r=Au[n];return typeof r=="string"?s=r:e===1?s=r.one:s=r.other.replace("{{count}}",e.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+s:s+" ago":s};function Cn(n){return(e={})=>{const t=e.width?String(e.width):n.defaultWidth;return n.formats[t]||n.formats[n.defaultWidth]}}const Tu={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Ru={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Iu={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Ou={date:Cn({formats:Tu,defaultWidth:"full"}),time:Cn({formats:Ru,defaultWidth:"full"}),dateTime:Cn({formats:Iu,defaultWidth:"full"})},Du={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Mu=(n,e,t,s)=>Du[n];function Qt(n){return(e,t)=>{const s=t?.context?String(t.context):"standalone";let r;if(s==="formatting"&&n.formattingValues){const o=n.defaultFormattingWidth||n.defaultWidth,l=t?.width?String(t.width):o;r=n.formattingValues[l]||n.formattingValues[o]}else{const o=n.defaultWidth,l=t?.width?String(t.width):n.defaultWidth;r=n.values[l]||n.values[o]}const a=n.argumentCallback?n.argumentCallback(e):e;return r[a]}}const Lu={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Fu={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Uu={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},zu={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Frid
53ay","Saturday"]},Bu={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Vu={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Wu=(n,e)=>{const t=Number(n),s=t%100;if(s>20||s<10)switch(s%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},qu={ordinalNumber:Wu,era:Qt({values:Lu,defaultWidth:"wide"}),quarter:Qt({values:Fu,defaultWidth:"wide",argumentCallback:n=>n-1}),month:Qt({values:Uu,defaultWidth:"wide"}),day:Qt({values:zu,defaultWidth:"wide"}),dayPeriod:Qt({values:Bu,defaultWidth:"wide",formattingValues:Vu,defaultFormattingWidth:"wide"})};function Zt(n){return(e,t={})=>{const s=t.width,r=s&&n.matchPatterns[s]||n.matchPatterns[n.defaultMatchWidth],a=e.match(r);if(!a)return null;const o=a[0],l=s&&n.parsePatterns[s]||n.parsePatterns[n.defaultParseWidth],c=Array.isArray(l)?Hu(l,m=>m.test(o)):Ju(l,m=>m.test(o));let d;d=n.valueCallback?n.valueCallback(c):c,d=t.valueCallback?t.valueCallback(d):d;const u=e.slice(o.length);return{value:d,rest:u}}}function Ju(n,e){for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&e(n[t]))return t}function Hu(n,e){for(let t=0;t<n.length;t++)if(e(n[t]))return t}function Ku(n){return(e,t={})=>{const s=e.match(n.matchPattern);if(!s)return null;const r=s[0],a=e.match(n.parsePattern);if(!a)return null;let o=n.valueCallback?n.valueCallback(a[0]):a[0];o=t.valueCallback?t.valueCallback(o):o;const l=e.slice(r.length);return{value:o,rest:l}}}const Xu=/^(\d+)(th|st|nd|rd)?/i,Gu=/\d+/i,Yu={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Qu={any:[/^b/i,/^(a|c)/i]},Zu={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},eh={any:[/1/i,/2/i,/3/i,/4/i]},th={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},sh={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},nh={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},rh={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},ih={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},ah={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},oh={ordinalNumber:Ku({matchPattern:Xu,parsePattern:Gu,valueCallback:n=>parseInt(n,10)}),era:Zt({matchPatterns:Yu,defaultMatchWidth:"wide",parsePatterns:Qu,defaultParseWidth:"any"}),quarter:Zt({matchPatterns:Zu,defaultMatchWidth:"wide",parsePatterns:eh,defaultParseWidth:"any",valueCallback:n=>n+1}),month:Zt({matchPatterns:th,defaultMatchWidth:"wide",parsePatterns:sh,defaultParseWidth:"any"}),day:Zt({matchPatterns:nh,defaultMatchWidth:"wide",parsePatterns:rh,defaultParseWidth:"any"}),dayPeriod:Zt({matchPatterns:ih,defaultMatchWidth:"any",parsePatterns:ah,defaultParseWidth:"any"})},lh={code:"en-US",formatDistance:$u,formatLong:Ou,formatRelative:Mu,localize:qu,match:oh,options:{weekStartsOn:0,firstWeekContainsDate:1}};function ch(n,e,t){const s=bu(),r=t?.locale??s.locale??lh,a=2520,o=zs(n,e);if(isNaN(o))throw new RangeError("Invalid time value");const l=Object.assign({},t,{addSuffix:t?.addSuffix,comparison:o});let c,d;o>0?(c=fe(e),d=fe(n)):(c=fe(n),d=fe(e));const u=Cu(d,c),m=(Ni(d)-Ni(c))/1e3,f=Math.round((u-m)/60);let p;if(f<2)return t?.includeSeconds?u<5?r.formatDistance("lessThanXSeconds",5,l):u<10?r.formatDistance("lessThanXSeconds",10,l):u<20?r.formatDistance("lessThanXSeconds",20,l):u<40?r.formatDistance("halfAMinute",0,l):u<60?r.formatDistance("lessThanXMinutes",1,l):r.formatDistance("xMinutes",1,l):f===0?r.formatDistance("lessThanXMinutes",1,l):r.formatDistance("xMinutes",f,l);if(f<45)return r.formatDistance("xMinutes",f,l);if(f<90)return r.formatDistance("aboutXHours",1,l);if(f<ki){const g=Math.round(f/60);return r.formatDistance("aboutXHours",g,l)}else{if(f<a)return r.formatDistance("xDays",1,l);if(f<Cs){const g=Math.round(f/ki);return r.formatDistance("xDays",g,l)}else if(f<Cs*2)return p=Math.round(f/Cs),r.formatDistance("aboutXMonths",p,l)}if(p=Eu(d,c),p<12){const g=Math.round(f/Cs);return r.formatDistance("xMonths",g,l)}else{const g=p%12,w=Math.trunc(p/12);return g<3?r.formatDistance("aboutXYears",w,l):g<9?r.formatDistance("overXYears",w,l):r.formatDistance("almostXYears",w+1,l)}}function dh(n,e){return ch(n,vu(n),e)}const yt=new Map;function uh({isVisible:n,onClose:e,pageIndex:t}){const s=yt.get(t);return s?i.jsx(Ce,{children:n&&i.jsx(S.div,{initial:{opacity:0}
53,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/40",onClick:e,children:i.jsxs(S.div,{initial:{scale:.95,y:20},animate:{scale:1,y:0},exit:{scale:.95,y:20},className:"relative w-full max-w-[320px] bg-white rounded-xl overflow-hidden shadow-2xl",onClick:r=>r.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-2 border-b border-gray-100",children:[i.jsxs("div",{className:"flex items-center space-x-2",children:[i.jsx("div",{className:"w-7 h-7 rounded-full overflow-hidden ring-2 ring-pink-100",children:i.jsx("img",{src:s.profilePic,alt:s.username,className:"w-full h-full object-cover"})}),i.jsx("div",{children:i.jsx("h3",{className:"font-semibold text-sm",children:s.username})})]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-gray-100 rounded-full",children:i.jsx(Ve,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"aspect-square bg-black",children:i.jsx("img",{src:s.imageUrl,alt:"Post",className:"w-full h-full object-contain"})}),i.jsxs("div",{className:"p-2 border-b border-gray-100",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center space-x-3",children:[i.jsx("button",{className:"hover:text-pink-500 transition-colors",children:i.jsx(pr,{className:"w-5 h-5"})}),i.jsx("button",{className:"hover:text-blue-500 transition-colors",children:i.jsx(Ks,{className:"w-5 h-5"})}),i.jsx("button",{className:"hover:text-green-500 transition-colors",children:i.jsx(Yo,{className:"w-5 h-5"})})]}),i.jsx(ls,{className:"w-4 h-4 text-gray-400"})]}),i.jsx("div",{className:"mt-1",children:i.jsxs("p",{className:"font-semibold text-xs",children:[s.likes.toLocaleString()," likes"]})})]}),i.jsxs("div",{className:"p-2 space-y-1",children:[i.jsxs("p",{className:"text-xs leading-normal",children:[i.jsx("span",{className:"font-semibold",children:s.username})," ",s.caption]}),i.jsxs("p",{className:"text-xs text-gray-500",children:["View all ",s.comments," comments"]})]}),i.jsx("div",{className:"p-2 bg-gray-50 border-t border-gray-100",children:i.jsx("div",{className:"space-y-0.5",children:s.bio.map((r,a)=>i.jsx("p",{className:"text-xs text-gray-600",children:r},a))})}),i.jsx("a",{href:s.instagramUrl,target:"_blank",rel:"noopener noreferrer",className:"block w-full p-2 text-center bg-[#0095F6] text-white text-xs font-semibold hover:bg-[#1877F2] transition-colors",children:"Follow on Instagram"})]})})}):null}const Si=({onClick:n,position:e={top:"50%",left:"50%"}})=>{const t={...e};if(t.bottom){const r=parseInt(t.bottom||"0",10)+8;t.bottom=`${r}%`}return i.jsxs(S.button,{whileHover:{scale:1.1},whileTap:{scale:.95},onClick:n,style:{position:"absolute",transform:"translate(-50%, -50%)",...t},className:"group relative z-50 w-10 h-10 bg-amber-500/90 backdrop-blur-sm rounded-full shadow-lg flex items-center justify-center hover:shadow-xl transition-all",children:[i.jsx("div",{className:"text-white group-hover:scale-110 transition-transform",children:i.jsx(gr,{className:"w-5 h-5"})}),i.jsx("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-2 px-3 py-1.5 text-sm bg-white text-gray-800 rounded-full shadow-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap",children:"Book Recommendation: Amusing Ourselves to Death"})]})};function hh({isVisible:n,onClose:e}){return i.jsx(Ce,{children:n&&i.jsx(S.div,{initial:{opacity:0}
53,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[100] flex items-end sm:items-center justify-center p-0 sm:p-4 bg-black/40",onClick:e,children:i.jsxs(S.div,{initial:{y:"100%"},animate:{y:0},exit:{y:"100%"},transition:{type:"spring",damping:25,stiffness:300},className:"w-full max-w-lg bg-white rounded-t-2xl sm:rounded-2xl shadow-xl overflow-hidden",onClick:t=>t.stopPropagation(),children:[i.jsx("div",{className:"p-4 border-b border-gray-200",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center space-x-2",children:[i.jsx(gr,{className:"w-5 h-5 text-pink-600"}),i.jsx("h2",{className:"font-semibold text-gray-900",children:"Book Recommendation"})]}),i.jsx("button",{onClick:e,className:"p-2 text-gray-500 hover:text-gray-700 rounded-full hover:bg-gray-100 transition-colors",children:i.jsx(Ve,{className:"w-5 h-5"})})]})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"flex items-start space-x-4",children:i.jsxs("div",{className:"flex-1",children:[i.jsx("h3",{className:"font-semibold text-gray-900 text-lg",children:"Amusing Ourselves to Death"}),i.jsx("p",{className:"text-gray-600",children:"by Neil Postman"}),i.jsxs("div",{className:"flex items-center space-x-1 mt-1",children:[i.jsx(Rt,{className:"w-4 h-4 text-yellow-400 fill-current"}),i.jsx(Rt,{className:"w-4 h-4 text-yellow-400 fill-current"}),i.jsx(Rt,{className:"w-4 h-4 text-yellow-400 fill-current"}),i.jsx(Rt,{className:"w-4 h-4 text-yellow-400 fill-current"}),i.jsx(Rt,{className:"w-4 h-4 text-yellow-400 fill-current"}),i.jsx("span",{className:"text-sm text-gray-500 ml-1",children:"(4.4)"})]})]})}),i.jsx("div",{className:"space-y-3",children:i.jsxs("div",{className:"flex items-start space-x-2",children:[i.jsx(Qo,{className:"w-5 h-5 text-gray-400 flex-shrink-0 mt-1"}),i.jsx("p",{className:"text-gray-600 text-sm",children:"A sharp and still-relevant book on how entertainment logic can weaken public thinking â not by hiding information, but by turning everything into stimulation. Postman shows how a culture can become highly informed on the surface while slowly losing the capacity for depth, continuity, and real understanding."})]})}),i.jsx("div",{className:"pt-2",children:i.jsxs("a",{href:"https://www.amazon.com/Amusing-Ourselves-Death-Discourse-Business/dp/0670804541/ref=sr_1_1?crid=105LLHVRRBXJU&dib=eyJ2IjoiMSJ9.8p_5KQQaTsG8j7V_Y8079z9uHv5hIhI7otIPwOsayJiCQ9LGxCDR6XyXUskvk5z0tZCHMpFc5UpkSrySzgwilXN2aED9oMB6GyAMINCuR4E.cNRhiqINkgZZSN4-C_XXFbc6rXcmfuZ85A3yqV4tSNg&dib_tag=se&keywords=amusing+ourselves+to+death+hardcover&qid=1773680667&sprefix=amusing+ourselves+to%2Caps%2C595&sr=8-1",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center space-x-2 w-full bg-pink-600 text-white py-2 px-4 rounded-lg hover:bg-pink-700 transition-colors",children:[i.jsx("span",{children:"View on Amazon"}),i.jsx(ms,{className:"w-4 h-4"})]})})]})]})})})}function fh({isVisible:n,onClose:e}){const{trackInteraction:t}=ut();return v.useEffect(()=>{n&&t("profile_view",{profile_name:"Heather Riedel",profile_type:"photographer",page_index:11,source:"spotlight_bubble"})},[n,t]),i.jsx(Ce,{children:n&&i.jsx(S.div,{initial:{opacity:0}
53,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/40 p-0",onClick:e,children:i.jsxs(S.div,{initial:{scale:.9,y:20},animate:{scale:1,y:0},exit:{scale:.9,y:20},transition:{type:"spring",damping:25},className:"relative w-full h-full md:h-auto md:w-[600px] md:max-h-[85vh] bg-[#f5f1eb] overflow-hidden md:rounded-2xl shadow-2xl",onClick:s=>s.stopPropagation(),children:[i.jsx("button",{onClick:e,className:"absolute top-4 right-4 z-10 p-2 bg-white/90 backdrop-blur-sm rounded-full shadow-lg hover:bg-white transition-colors",children:i.jsx(Ve,{className:"w-5 h-5 text-[#4a3f35]"})}),i.jsxs("div",{className:"relative h-[40vh] md:h-[45vh] w-full bg-[#4a3f35] overflow-hidden",children:[i.jsx(S.img,{initial:{scale:1.2},animate:{scale:1},transition:{duration:1.5,ease:"easeOut"},src:"/heather.webp",alt:"Heather Riedel",className:"w-full h-full object-cover opacity-90"}),i.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#4a3f35] to-transparent"}),i.jsxs(S.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2},className:"absolute bottom-0 left-0 right-0 p-6 text-white",children:[i.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Heather Riedel"}),i.jsxs("div",{className:"flex items-center space-x-3 text-white/90",children:[i.jsx(Zo,{className:"w-4 h-4"}),i.jsx("span",{children:"Professional Photographer"})]})]})]}),i.jsxs("div",{className:"overflow-y-auto overscroll-contain",style:{maxHeight:"calc(100vh - 40vh)"},children:[i.jsxs("div",{className:"grid grid-cols-3 gap-2 p-4 bg-white/50",children:[i.jsxs(S.div,{whileHover:{scale:1.05},className:"flex flex-col items-center p-3 bg-white rounded-xl",children:[i.jsx(pr,{className:"w-5 h-5 text-pink-500 mb-1"}),i.jsx("span",{className:"text-xs text-[#4a3f35]/70",children:"Passion"}),i.jsx("span",{className:"text-sm font-medium text-[#4a3f35]",children:"Dog Photography"})]}),i.jsxs(S.div,{whileHover:{scale:1.05},className:"flex flex-col items-center p-3 bg-white rounded-xl",children:[i.jsx(el,{className:"w-5 h-5 text-pink-500 mb-1"}),i.jsx("span",{className:"text-xs text-[#4a3f35]/70",children:"Based in"}),i.jsx("span",{className:"text-sm font-medium text-[#4a3f35]",children:"Seattle"})]}),i.jsxs(S.div,{whileHover:{scale:1.05},className:"flex flex-col items-center p-3 bg-white rounded-xl",children:[i.jsx(Qi,{className:"w-5 h-5 text-pink-500 mb-1"}),i.jsx("span",{className:"text-xs text-[#4a3f35]/70",children:"Experience"}),i.jsx("span",{className:"text-sm font-medium text-[#4a3f35]",children:"5+ Years"})]})]}),i.jsx(S.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"p-4",children:i.jsx("div",{className:"bg-white/80 backdrop-blur-sm p-4 rounded-xl",children:i.jsx("p",{className:"text-[#4a3f35] italic text-base leading-relaxed",children:`"I love dog photography; it's the heart of my business! But I am also passionate about diving into various creative projects that keep things fun and exciting"`})})}),i.jsxs("div",{className:"px-4 pb-4",children:[i.jsx("h4",{className:"font-semibold text-[#4a3f35] mb-3",children:"Photography Style"}),i.jsx("div",{className:"space-y-2",children:["Natural, cinematic feel with soft lighting and rich colors","Dreamlike, ethereal atmosphere blending soft natural light","Deep, moody tones creating mystery and quiet strength"].map((s,r)=>i.jsxs(S.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.4+r*.1},className:"flex items-center space-x-2 bg-white/60 p-3 rounded-lg",children:[i.jsx(Rt,{className:"w-4 h-4 text-pink-500 flex-shrink-0"}),i.jsx("span",{className:"text-sm text-[#4a3f35]",children:s})]},r))})]}),i.jsxs("div",{className:"px-4 pb-4",children:[i.jsx("h4",{className:"font-semibold text-[#4a3f35] mb-3",children:"Featured Work"}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsx(S.div,{whileHover:{scale:1.03},className:"aspect-square rounded-xl overflow-hidden shadow-lg",children:i.jsx("img",{src:"/dog.png",alt:"Featured dog photography 1",className:"w-full h-full object-cover"})}),i.jsx(S.div,{whileHover:{scale:1.03},className:"aspect-square rounded-xl overflow-hidden shadow-lg",children:i.jsx("img",{src:"/dog2.png",alt:"Featured dog photography 2",className:"w-full h-full object-cover"})})]})]}),i.jsx("div",{className:"sticky bottom-0 p-4 bg-[#f5f1eb]/95 backdrop-blur-sm border-t border-[#4a3f35]/10",children:i.jsxs("div",{className:"space-y-3",children:[i.jsxs(S.a,{whileHover:{scale:1.02},whileTap:{scale:.98},href:"https://riedelphotography.com",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center space-x-2 bg-[#4a3f35] text-white w-full px-6 py-3.5 rounded-xl font-medium hover:bg-[#3a2f25] transition-colors group",children:[i.jsx("span",{children:"Visit Riedel Photography"}),i.jsx(ms,{className:"w-4 h-4 group-hover:translate-x-1 transition-transform"})]}),i.jsxs(S.a,{whileHover:{scale:1.02},whileTap:{scale:.98},href:"https://www.instagram.com/riedel.photography/",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center space-x-2 bg-gradient-to-r from-pink-500 to-rose-500 text-white w-full px-6 py-3.5 rounded-xl font-medium hover:from-pink-600 hover:to-rose-600 transition-colors group",children:[i.jsx(ls,{className:"w-4 h-4"}),i.jsx("span",{children:"Follow @riedel.photography"}),i.jsx(ms,{className:"w-4 h-4 group-hover:translate-x-1 transition-transform"})]})]})})]})]})})})}const tr=async(n,e)=>(console.log(`[MOCK] Tracking event: ${n}`,e),{success:!0}),mh=({onAuthenticate:n})=>{const[e,t]=v.useState(""),[s,r]=v.useState(""),[a,o]=v.useState(!1),l=v.useRef(null);v.useEffect(()=>{l.current&&l.current.focus()},[]);const c=async d=>{d.preventDefault(),o(!0),r(""),e==="JoviAdmin123!"?(o(!1),setTimeout(()=>{sessionStorage.setItem("voting_authenticated","true"),n()},300)):setTimeout(()=>{o(!1),r("Incorrect password"),tr("voting_password_failed",{})},500)};return i.jsx("div",{className:"fixed inset-0 bg-[#f5f1eb] z-50 flex items-center justify-center",children:i.jsxs("div",{className:"max-w-md w-full p-8 bg-white rounded-lg shadow-sm",children:[i.jsxs("div",{className:"mb-8 text-center",children:[i.jsx("h1",{className:"text-2xl font-semibold text-[#4a3f35] mb-2",children:"Voting Access"}),i.jsx("p",{className:"text-[#4a3f35]/70",children:"Enter the password to access the voting section"})]}),i.jsxs("form",{onSubmit:c,children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("input",{ref:l,type:"password",value:e,onCh
53ange:d=>t(d.target.value),placeholder:"Enter password",className:"w-full p-3 border border-[#e5e1da] rounded-md focus:outline-none focus:ring-2 focus:ring-[#b0a99f]",disabled:a}),s&&i.jsx("p",{className:"mt-2 text-red-500 text-sm",children:s})]}),i.jsx("button",{type:"submit",className:"w-full bg-[#4a3f35] text-white py-3 rounded-md hover:bg-[#3a2f25] transition-colors duration-200",disabled:a||!e,children:a?"Checking...":"Enter Voting Area"})]})]})})},ph=()=>i.jsx("style",{children:` 54 @keyframes pulse { 55 0% { opacity: 0.8; transform: scale(1); } 56 100% { opacity: 0; transform: scale(1.05); } 57 } 58 59 @keyframes bounce { 60 0%, 100% { transform: translateY(0); } 61 50% { transform: translateY(-3px); } 62 } 63 64 .vote-success-indicator { 65 position: absolute; 66 top: -5px; 67 right: -5px; 68 width: 20px; 69 height: 20px; 70 border-radius: 50%; 71 background-color: #4a3f35; 72 color: white; 73 font-size: 10px; 74 display: flex; 75 align-items: center; 76 justify-content: center; 77 opacity: 0; 78 transform: scale(0); 79 animation: vote-success 0.5s forwards; 80 } 81 82 @keyframes vote-success { 83 0% { opacity: 0; transform: scale(0); } 84 70% { opacity: 1; transform: scale(1.2); } 85 100% { opacity: 1; transform: scale(1); } 86 } 87 88 @keyframes glowing { 89 0% { box-shadow: 0 0 5px #ff69b4; } 90 50% { box-shadow: 0 0 20px #ff69b4; } 91 100% { box-shadow: 0 0 5px #ff69b4; } 92 } 93 94 @keyframes voted-flash { 95 0%, 100% { background-color: #ff69b4; } 96 50% { background-color: #ff4da6; } 97 } 98 99 @keyframes heartbeat { 100 0% { transform: scale(1); } 101 25% { transform: scale(1.1); } 102 50% { transform: scale(1); } 103 75% { transform: scale(1.1); } 104 100% { transform: scale(1); } 105 } 106 107 .voted-overlay { 108 position: absolute; 109 top: 0; 110 left: 0; 111 width: 100%; 112 height: 100%; 113 background-color: rgba(255,105,180,0.2); 114 pointer-events: none; 115 z-index: 5; 116 border-radius: 0.75rem; 117 } 118 119 .confetti { 120 position: absolute; 121 width: 10px; 122 height: 10px; 123 background-color: #ff69b4; 124 opacity: 0; 125 } 126 `}),gh=({onBack:n})=>{const{user:e}=ut(),[t,s]=v.useState([]),[r,a]=v.useState([]),[o,l]=v.useState(!0),[c,d]=v.useState(""),[u,m]=v.useState(null),[f,p]=v.useState(0),[g,w]=v.useState(!0),[y,N]=v.useState({hours:48,minutes:0,seconds:0}),[_,L]=v.useState(!1),[T,B]=v.useState({}),[Y,K]=v.useState([]),[Q,ee]=v.useState(!1),[W,J]=v.useState(null),[le,re]=v.useState(null),Ae=50,ne=5;v.useEffect(()=>{if(!g)return;const x=(()=>{try{const b=sessionStorage.getItem("user_votes");if(b){const P=JSON.parse(b);if(Array.isArray(P))return a(P),console.log("Loaded saved votes from session storage:",P),P}return[]}catch(b){return console.error("Error parsing saved votes:",b),[]}})();(async()=>{l(!0);try{const[b,P]=[$e(),De(x)];await Promise.all([b,P])}catch(b){console.error("Error initializing data:",b),d("Something went wrong. Some features may be limited.")}finally{l(!1)}})()},[g,e]);const $e=async()=>{try{const h=new Promise((b,P)=>setTimeout(()=>P(new Error("Timeout fetching voting period")),3e3)),x=I.from("voting_periods").select("*").eq("is_active",!0).order("end_time",{ascending:!0}).limit(1),{data:A}=await Promise.race([x,h]);if(A&&A.length>0){const b=A[0],k=new Date(b.end_time).getTime(),j=sessionStorage.getItem("voting_end_time");j&&parseInt(j,10)!==k&&(sessionStorage.removeItem("voting_end_time"),sessionStorage.removeItem("user_votes"),sessionStorage.removeItem("max_votes_per_user"),a([]),L(!1)),sessionStorage.setItem("voting_end_time",k.toString()),b.max_votes_per_user&&sessionStorage.setItem("max_votes_per_user",b.max_votes_per_user.toString()),Oe(k)}else{const b=sessionStorage.getItem("voting_end_time");b?Oe(parseInt(b,10)):(L(!0),N({hours:0,minutes:0,seconds:0}))}}catch(h){console.error("Error in timer initialization:",h);const x=sessionStorage.getItem("voting_end_time");x?Oe(parseInt(x,10)):ge()}},ge=()=>{const h=sessionStorage.getItem("voting_end_time");let x;h?x=parseInt(h,10):(x=Date.now()+48*60*60*1e3,sessionStorage.setItem("voting_end_time",x.toString())),Oe(x)},Oe=h=>{if(Date.now()>=h){L(!0),N({hours:0,minutes:0,seconds:0});return}const x=setInterval(()=>{const A=Date.now(),b=Math.max(0,h-A);if(b<=0){clearInterval(x),L(!0),N({hours:0,minutes:0,seconds:0});return}const P=Math.floor(b/(1e3*60*60)),k=Math.floor(b%(1e3*60*60)/(1e3*60)),j=Math.floor(b%(1e3*60)/1e3);N({hours:P,minutes:k,seconds:j})},1e3);return()=>clearInterval(x)},De=async h=>{if(_){console.log("Voting is closed - fetching only top 5 winners for efficiency");try{const P=I.from("accurate_design_votes").select("id, title, vote_count").order("vote_count",{ascending:!1}).limit(3),k=new Promise((M,O)=>setTimeout(()=>O(new Error("Timeout fetching rankings")),3e3)),{data:j,error:E}=await Promise.race([P,k]);if(!E&&j){const M=j.map((O,q)=>({rank:q+1,design_id:O.id||0,title:O.title||`Design ${O.id}`,vote_count:O.vote_count||0,images:[]}));K(M);for(const O of M)mt(O.design_id);console.log("Successfully loaded top 3 winners for closed voting");return}}catch(P){console.error("Error fetching top 5 winners for closed voting:",P),d("Unable to load voting results. Please refresh the page.");return}}const{count:x}=await I.from("voting_designs").select("id",{count:"exact",head:!0}),A=x||67,b=Array.from({length:A},(P,k)=>({id:k+1,title:`Design ${k+1}`,description:`Design option ${k+1}`,images:[],vote_count:0}));s(b);try{let P=[...h];if(e)try{const k=I.rpc("get_user_votes",{p_user_id:e.id}),j=new Promise((O,q)=>setTimeout(()=>q(new Error("Timeout fetching user votes")),3e3)),{data:E,error:M}=await Promise.race([k,j]);if(!M&&E){const O=E.map(q=>q.design_id);P=O,a(O),sessionStorage.setItem("user_votes",JSON.stringify(O)),console.log("Loaded user votes from database:",O)}}catch(k){console.error("Error or timeout fetching user votes:",k)}try{const k=I.from("accurate_design_votes").select("id, vote_count").order("id"),j=new Promise((O,q)=>setTimeout(()=>q(new Error("Timeout fetching vote counts")),3e3)),{data:E,error:M}=await Promise.race([k,j]);if(!M&&E&&E.length>0){console.log(`Loaded ${E.length} vote counts from database`);const O=new Map;
126E.forEach(G=>{O.set(G.id,G.vote_count)});const q=b.map(G=>({...G,vote_count:O.get(G.id)||0}));s(q)}}catch(k){console.error("Error fetching vote counts:",k)}try{const k=I.from("voting_designs").select("*").order("id"),j=new Promise((O,q)=>setTimeout(()=>q(new Error("Timeout fetching designs")),5e3)),{data:E,error:M}=await Promise.race([k,j]);if(!M&&E&&E.length>0){console.log(`Loaded ${E.length} designs from database`);const O=E.map(G=>({id:G.id,title:G.title||`Design ${G.id}`,description:G.description||`Design option ${G.id}`,vote_count:G.vote_count||0,images:G.image_url?[G.image_url]:[]}));s(G=>G.map(Je=>{const Fe=O.find(pt=>pt.id===Je.id);return Fe?{...Je,title:Fe.title,description:Fe.description,vote_count:Math.max(Je.vote_count,Fe.vote_count),images:Je.images.length>0?Je.images:Fe.images}:Je}));const q=O.slice(0,20);je(q,10),setTimeout(()=>{je(O.slice(20),5)},3e3)}}catch(k){console.error("Error or timeout fetching designs:",k),je(b,10)}try{const k=I.from("accurate_design_votes").select("id, title, vote_count").order("vote_count",{ascending:!1}).limit(3),j=new Promise((O,q)=>setTimeout(()=>q(new Error("Timeout fetching rankings")),3e3)),{data:E,error:M}=await Promise.race([k,j]);if(!M&&E){const O=E.map((q,G)=>({rank:G+1,design_id:q.id||0,title:q.title||`Design ${q.id}`,vote_count:q.vote_count||0,images:[]}));K(O);for(const q of O)mt(q.design_id)}}catch(k){console.error("Error or timeout fetching rankings:",k);try{const j=[...t].sort((E,M)=>M.vote_count-E.vote_count).slice(0,3).map((E,M)=>({rank:M+1,design_id:E.id,title:E.title,vote_count:E.vote_count,images:E.images}));j.length>0&&(K(j),console.log("Using fallback rankings from loaded designs"))}catch(j){console.error("Fallback ranking generation failed:",j)}}try{const{data:k}=await I.from("voting_options").select("*");if(!k||k.length===0){console.log("Attempting final fallback to count votes directly from user_votes table");const{data:j,error:E}=await I.from("user_votes").select("design_id");if(!E&&j&&j.length>0){const M=new Map;j.forEach(O=>{const q=M.get(O.design_id)||0;M.set(O.design_id,q+1)}),s(O=>O.map(q=>({...q,vote_count:M.get(q.id)||q.vote_count}))),console.log("Updated vote counts from direct user_votes count")}}}catch(k){console.error("Final vote count fallback failed:",k)}}catch(P){console.error("Error loading voting data:",P),d("Failed to load all designs. Limited functionality may be available.")}},je=(h,x)=>{const A={},b=async k=>{const j=`design-${k}`;return A[j]||(A[j]=new Promise(async E=>{try{await mt(k),E(`design-${k}`)}catch(M){console.error(`Failed to load design ${k}:`,M),E(null)}})),A[j]},P=k=>{if(k>=h.length)return;const j=Math.min(k+x,h.length),E=h.slice(k,j).map(M=>M.id);Promise.allSettled(E.map(M=>b(M))).then(()=>{setTimeout(()=>P(j),500)})};P(0)},we=async h=>{if(_){d("Voting period has ended");return}if(r.includes(h))try{const x=r.filter(A=>A!==h);if(a(x),sessionStorage.setItem("user_votes",JSON.stringify(x)),s(A=>A.map(b=>b.id===h?{...b,vote_count:Math.max(0,b.vote_count-1)}:b)),d(`Vote removed from Design ${h}`),e){const{data:A,error:b}=await I.rpc("remove_vote",{p_user_id:e.id,p_design_id:h});if(b){console.error("Error removing vote in database:",b);try{const{error:P}=await I.from("user_votes").delete().eq("user_id",e.id).eq("design_id",h);if(P)console.error("Error deleting vote:",P);else{const{data:k}=await I.from("voting_designs").select("vote_count").eq("id",h).single(),j=k?.vote_count||0,E=Math.max(0,j-1),{error:M}=await I.from("voting_designs").update({vote_count:E}).eq("id",h);M&&console.error("Error updating vote count:",M)}}catch(P){console.error("Fallback vote removal failed:",P)}}else console.log("Vote removed in database"),await tr("vote_removed",{design_id:h,success:!0})}}catch(x){console.error("Error removing vote:",x),d("Error removing your vote. Please try again.")}else{if(r.length>=ne){d(`You can only vote for up to ${ne} designs. Please remove a vote first.`);return}try{const x=[...r,h];if(a(x),sessionStorage.setItem("user_votes",JSON.stringify(x)),s(A=>A.map(b=>b.id===h?{...b,vote_count:b.vote_count+1}:b)),d(`Vote added for Design ${h}`),e){const{data:A,error:b}=await I.rpc("vote_for_design",{p_user_id:e.id,p_design_id:h});if(b)if(b.message.includes("Maximum number of votes")){console.log("Server rejected due to MAX_VOTES limit, using client-side fallback");try{const{data:P,error:k}=await I.from("user_votes").select("design_id").eq("user_id",e.id);if(!k&&P&&P.length<ne){const{error:j}=await I.from("user_votes").insert({user_id:e.id,design_id:h,vote_order:P.length+1});if(j)console.error("Error inserting vote in fallback:",j),d(`Error adding vote: ${j.message}`);else{const{data:E}=await I.from("voting_designs").select("vote_count").eq("id",h).single(),M=E?.vote_count||0,{error:O}=await I.from("voting_designs").update({vote_count:M+1}).eq("id",h);O&&console.error("Error updating design vote count:",O),console.log("Vote added through fallback method")}}else d(`You can only vote for up to ${ne} designs`),a(r),sessionStorage.setItem("user_votes",JSON.stringify(r)),s(j=>j.map(E=>E.id===h?{...E,vote_count:E.vote_count-1}:E))}catch(P){console.error("Vote fallback failed:",P)}}else if(b.message.includes("Already voted")){d("You have already voted for this design");return}else{console.error("Error adding vote in database:",b);try{const{error:P}=await I.from("user_votes").insert({user_id:e.id,design_id:h,vote_order:r.length+1});if(P)console.error("Error inserting vote:",P);else{const{data:k}=await I.from("voting_designs").select("vote_count").eq("id",h).single(),E=(k?.vote_count||0)+1,{error:M}=await I.from("voting_designs").update({vote_count:E}).eq("id",h);M&&console.error("Error updating vote count:",M)}}catch(P){console.error("Fallback vote addition failed:",P)}}else console.log("Vote added in database"),await tr("vote_added",{design_id:h,success:!0})}}catch(x){console.error("Error adding vote:",x),d("Error adding your vote. Please try again.")}}},qe=h=>{if(h.images.length>0){const x=h.images.filter(b=>!T[b]),A={...h,images:x};m(A),p(0)}else m(h),p(0)},Me=()=>{m(null),p(0)},F=()=>{u&&f<u.images.length-1&&p(f+1)},U=()=>{u&&f>0&&p(f-1)},xe=h=>{re(null),J(h.targetTouches[0].clientX)},ie=h=>{re(h.targetTouches[0].clientX)},Te=()=>{if(!W||!le)return;const h=W-le;Math.abs(h)>Ae&&u&&u.images.length>1&&(h>0?F():U()),J(null),re(null)},ke=h=>{const x=Math.floor(h.hours/24),A=h.hours%24;return x>0?`${x} day${x>
1261?"s":""} ${A}:${String(h.minutes).padStart(2,"0")}:${String(h.seconds).padStart(2,"0")}`:`${String(h.hours).padStart(2,"0")}:${String(h.minutes).padStart(2,"0")}:${String(h.seconds).padStart(2,"0")}`},Le=h=>{if(T[h])return;B(b=>({...b,[h]:!0}));const x=h.match(/design%20(\d+)\//);if(!x)return;const A=parseInt(x[1],10);s(b=>{const P=[...b],k=P.find(j=>j.id===A);return k&&(k.images=k.images.filter(j=>j!==h)),P}),u&&u.id===A&&m(b=>b&&{...b,images:b.images.filter(P=>P!==h)})},ft=({src:h,alt:x,onClick:A,className:b=""})=>{const P=T[h];return!h||P?i.jsx("div",{className:`aspect-[600/789] bg-[#e5e1da] flex items-center justify-center ${b}`,onClick:A,children:i.jsxs("div",{className:"flex flex-col items-center justify-center",children:[i.jsx(Gr,{className:"w-8 h-8 text-[#4a3f35]/40 mb-2"}),i.jsx("span",{className:"text-[#4a3f35] text-sm font-medium",children:x})]})}):i.jsx("div",{className:`aspect-[600/789] overflow-hidden ${b}`,onClick:A,children:i.jsx("img",{src:h,alt:x,className:"w-full h-full object-contain",onError:()=>Le(h),loading:"lazy",decoding:"async"})})},mt=async h=>{let x=!1;const A=[".JPG",".jpg",".webp",".WEBP",".png",".PNG",".jpeg",".JPEG","JPG","jpg","webp","WEBP","png","PNG","jpeg","JPEG"];for(const b of A){if(x)break;const P=b.startsWith("."),k=`https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/voting-designs/design%20${h}/${h}.1${P?b:"."+b}`;try{const j=new window.Image;j.onload=()=>{x=!0,s(E=>{const M=[...E],O=M.findIndex(q=>q.id===h);return O!==-1&&(M[O]={...M[O],images:[k]}),M}),K(E=>{const M=[...E],O=M.find(q=>q.design_id===h);return O&&(O.images=[k]),M}),setTimeout(()=>{let E=!1;for(const M of A){if(E)break;const O=M.startsWith("."),q=`https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/voting-designs/design%20${h}/${h}.2${O?M:"."+M}`,G=new window.Image;G.onload=()=>{E=!0,s(Je=>{const Fe=[...Je],pt=Fe.find(yn=>yn.id===h);return pt&&(pt.images=[k,q]),Fe}),K(Je=>{const Fe=[...Je],pt=Fe.find(yn=>yn.design_id===h);return pt&&(pt.images=[k,q]),Fe})},G.onerror=()=>{},G.src=q}},200)},j.onerror=()=>{},j.src=k}catch{}}},$=()=>Y.length===0?i.jsx("div",{className:"p-4 text-center text-[#4a3f35]/70",children:"No voting data available yet."}):i.jsxs("div",{className:"bg-white rounded-lg shadow-sm p-4",children:[i.jsxs("h3",{className:"text-[#4a3f35] font-medium mb-4 flex items-center",children:[i.jsx(_t,{className:"w-5 h-5 mr-2"}),"Top Designs"]}),i.jsx("div",{className:"space-y-4",children:Y.map(h=>i.jsxs("div",{className:"flex items-center",children:[i.jsx("div",{className:"w-8 font-bold text-[#4a3f35] text-center mr-2",children:h.rank}),i.jsx("div",{className:"w-16 h-21 bg-[#f9f7f4] rounded-md overflow-hidden mr-3",style:{aspectRatio:"600/789"},children:i.jsx(ft,{src:h.images.length>0?h.images[0]:"",alt:`Design ${h.design_id}`,className:"w-full h-full object-cover"})}),i.jsxs("div",{className:"flex-1",children:[i.jsx("div",{className:"text-sm font-medium text-[#4a3f35]",children:h.title}),i.jsxs("div",{className:"text-xs text-[#4a3f35]/70",children:[h.vote_count," votes"]})]})]},h.design_id))})]}),C=()=>Y.length===0?i.jsx("div",{className:"flex justify-center items-center h-64",children:i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-[#4a3f35] mx-auto mb-4"}),i.jsx("p",{className:"text-[#4a3f35]/70",children:"Loading final results..."})]})}):i.jsxs("div",{className:"max-w-4xl mx-auto",children:[i.jsxs("div",{className:"text-center mb-8",children:[i.jsxs("div",{className:"mb-4",children:[i.jsx(_t,{className:"w-16 h-16 text-yellow-500 mx-auto mb-4"}),i.jsx("h1",{className:"text-3xl font-bold text-[#4a3f35] mb-2",children:"Voting Results"})]}),i.jsxs("div",{className:"bg-white rounded-lg shadow-sm p-6 mb-6",children:[i.jsx("h2",{className:"text-xl font-semibold text-[#4a3f35] mb-3",children:"The Community Has Spoken! ð"}),i.jsxs("p",{className:"text-[#4a3f35]/80 leading-relaxed",children:["Thank you to everyone who participated in our design voting! We received ",i.jsx("strong",{children:"255 amazing community suggestions"})," and the voting has now concluded. Below are the ",i.jsx("strong",{children:"top 3 winning designs"})," that captured the most votes from our community."]}),i.jsx("div",{className:"mt-4 pt-4 border-t border-gray-200",children:i.jsx("p",{className:"text-sm text-[#4a3f35]/70",children:"These top 3 winning designs will be featured in our upcoming collection. Stay tuned for more details!"})})]})]}),i.jsx("div",{className:"space-y-6",children:Y.map((h,x)=>i.jsx("div",{className:`bg-white rounded-xl shadow-lg overflow-hidden transition-all duration-300 hover:shadow-xl ${x===0?"ring-4 ring-yellow-400 ring-opacity-50":""}`,children:i.jsxs("div",{className:"flex flex-col md:flex-row",children:[i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:`absolute top-4 left-4 z-10 w-12 h-12 rounded-full flex items-center justify-center font-bold text-white shadow-lg ${x===0?"bg-gradient-to-br from-yellow-400 to-yellow-600":x===1?"bg-gradient-to-br from-gray-400 to-gray-600":x===2?"bg-gradient-to-br from-orange-400 to-orange-600":"bg-gradient-to-br from-pink-400 to-pink-600"}`,children:h.rank}),x===0&&i.jsx("div",{className:"absolute -top-2 left-6 z-20",children:i.jsx("svg",{className:"w-8 h-8 text-yellow-500",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{d:"M5 4a1 1 0 00-.894 1.447l2 4A1 1 0 007 10h6a1 1 0 00.894-.553l2-4A1 1 0 0015 4H5zM3 12v4a1 1 0 001 1h12a1 1 0 001-1v-4H3z"})})}),i.jsx("div",{className:"w-full md:w-64 h-64 bg-[#f9f7f4] flex items-center justify-center",children:i.jsx(ft,{src:h.images.length>0?h.images[0]:"",alt:`${h.title} - Rank ${h.rank}`,className:"w-full h-full object-cover cursor-pointer hover:scale-105 transition-transform duration-300",onClick:()=>
126qe({id:h.design_id,title:h.title,description:`Rank ${h.rank} winner`,vote_count:h.vote_count,images:h.images})})})]}),i.jsxs("div",{className:"flex-1 p-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-2xl font-bold text-[#4a3f35] mb-2",children:h.title}),i.jsxs("div",{className:"flex items-center text-lg text-[#4a3f35]/80",children:[i.jsx("svg",{className:"w-5 h-5 mr-2",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{d:"M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"})}),i.jsxs("span",{className:"font-semibold",children:[h.vote_count," votes"]})]})]}),i.jsx("div",{className:`px-4 py-2 rounded-full text-sm font-medium ${x===0?"bg-yellow-100 text-yellow-800 border border-yellow-300":x===1?"bg-gray-100 text-gray-800 border border-gray-300":x===2?"bg-orange-100 text-orange-800 border border-orange-300":"bg-pink-100 text-pink-800 border border-pink-300"}`,children:x===0?"ð¥ Winner":x===1?"ð¥ Runner-up":"ð¥ Third Place"})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("p",{className:"text-[#4a3f35]/70 leading-relaxed",children:x===0?"ð Congratulations! This design captured the hearts of our community and will be the featured design in our upcoming collection.":x===1?"ð An outstanding design that came incredibly close to first place. The community loved this creative approach.":"⨠A fantastic design that earned its place among the top contenders with strong community support."}),i.jsxs("button",{onClick:()=>qe({id:h.design_id,title:h.title,description:`Rank ${h.rank} winner`,vote_count:h.vote_count,images:h.images}),className:"inline-flex items-center px-4 py-2 bg-[#4a3f35] text-white rounded-lg hover:bg-[#3a332b] transition-colors duration-200 text-sm font-medium",children:[i.jsxs("svg",{className:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),i.jsx("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"})]}),"View Full Design"]})]})]})]})},h.design_id))}),i.jsx("div",{className:"mt-12 text-center",children:i.jsxs("div",{className:"bg-gradient-to-r from-pink-50 to-purple-50 rounded-lg p-8",children:[i.jsx("h3",{className:"text-2xl font-bold text-[#4a3f35] mb-4",children:"Thank You for Participating! ð"}),i.jsx("p",{className:"text-[#4a3f35]/80 leading-relaxed max-w-2xl mx-auto",children:"Your votes and engagement made this community voting event a huge success. We're excited to bring these winning designs to life and can't wait to share the final collection with you. Keep an eye out for future voting opportunities!"})]})})]});return g?i.jsxs("div",{className:"fixed inset-0 bg-[#f5f1eb] z-50 overflow-y-auto",children:[i.jsx(ph,{}),i.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-4 sm:pt-6 pb-16",children:[i.jsxs("div",{className:"flex items-center mb-6",children:[i.jsxs("button",{onClick:n,className:"flex items-center text-[#4a3f35] mr-4",children:[i.jsx(vn,{className:"w-5 h-5"}),i.jsx("span",{className:"ml-1",children:"Back"})]}),i.jsx("h1",{className:"text-lg font-semibold text-[#4a3f35] flex-1 text-center",children:_?"Voting Results":"Select Designs"}),!_&&i.jsxs("button",{onClick:()=>ee(!Q),className:"flex items-center text-white bg-pink-500 px-4 py-2 rounded-full border border-pink-600 text-sm font-medium shadow-md hover:bg-pink-600 transition-colors",children:[i.jsx(_t,{className:"w-4 h-4 mr-2"}),Q?"Hide Top 3":"Show Top 3"]})]}),_?i.jsx(C,{}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"bg-white rounded-lg shadow-sm mb-4 p-4 border-l-4 border-[#4a3f35]",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("h2",{className:"text-lg font-bold text-[#4a3f35]",children:["You have ",ne," votes"]}),i.jsxs("p",{className:"text-xs text-[#4a3f35]/60 mt-1",children:["Choose your favorite designs from ",t.length," submissions"]})]}),i.jsxs("div",{className:"text-right ml-4",children:[i.jsxs("div",{className:"text-3xl font-bold text-[#4a3f35]",children:[r.length,"/",ne]}),i.jsx("p",{className:"text-xs text-[#4a3f35]/60",children:"votes used"})]})]}),i.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2.5 mb-3",children:i.jsx("div",{className:"bg-[#4a3f35] h-2.5 rounded-full transition-all duration-500",style:{width:`${r.length/ne*100}%`}})}),i.jsxs("div",{className:"border-t border-gray-200 pt-3 space-y-1 text-xs text-[#4a3f35]/70",children:[i.jsx("p",{children:"⢠Click any design to view details and vote"}),i.jsx("p",{children:"⢠Top 3 designs will be featured in our collection"})]})]}),i.jsxs("div",{className:"bg-white rounded-lg shadow-sm mb-4 p-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center text-[#4a3f35]",children:[i.jsx(tl,{className:"w-5 h-5 mr-2"}),i.jsx("span",{className:"text-sm font-medium",children:"Voting ends in"})]}),i.jsx("div",{className:"text-[#4a3f35] font-mono font-semibold",children:ke(y)})]}),i.jsx("p",{className:"text-xs text-[#4a3f35]/70 mt-2",children:"Cast your votes before time expires. The top 3 winning designs will be featured in next month's collection."})]}),Q&&i.jsx("div",{className:"mb-4",children:i.jsx($,{})}),c&&i.jsx(S.div,{initial:{opacity:0,y:-10}
126,animate:{opacity:1,y:0},exit:{opacity:0},className:"mb-6 p-4 bg-white rounded-lg shadow-md text-sm font-medium text-[#4a3f35] border-l-4 border-[#4a3f35]",children:c}),o?i.jsx("div",{className:"flex justify-center items-center h-64",children:i.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-[#4a3f35]"})}):i.jsx(i.Fragment,{children:i.jsx("div",{className:"grid grid-cols-2 gap-4 mb-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5",children:t.map(h=>i.jsxs("div",{id:`design-container-${h.id}`,className:"bg-white rounded-xl overflow-hidden shadow-sm relative",children:[r.includes(h.id)&&i.jsx("div",{className:"voted-overlay"}),i.jsxs("div",{className:"relative",children:[i.jsx(ft,{src:h.images.length>0?h.images[0]:"",alt:`Design ${h.id}`,onClick:()=>qe(h),className:"cursor-pointer bg-[#f9f7f4]"}),h.images.length>1&&i.jsxs("div",{className:"absolute bottom-2 right-2 bg-black/50 text-white text-xs px-1.5 py-0.5 rounded flex items-center",children:[i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"w-3 h-3 mr-0.5",children:[i.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),i.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),i.jsx("polyline",{points:"21 15 16 10 5 21"})]}),i.jsx("span",{children:h.images.filter(x=>!T[x]).length})]})]}),i.jsxs("div",{className:"p-3",children:[i.jsxs("h3",{className:"text-[#4a3f35] text-sm mb-2",children:["Design ",h.id]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"text-[#4a3f35]/70 text-xs",children:[h.vote_count," votes"]}),i.jsxs(S.button,{onClick:()=>{const x=document.createElement("div");x.className="absolute inset-0 bg-pink-400/30 rounded-xl z-10",x.style.animation="pulse 0.8s ease-out";const A=document.getElementById(`design-container-${h.id}`);if(A&&(A.appendChild(x),setTimeout(()=>A.removeChild(x),800),!r.includes(h.id)))for(let b=0;b<10;b++){const P=document.createElement("div");P.className="confetti",P.style.left=`${Math.random()*100}%`,P.style.top=`${Math.random()*100}%`,P.style.transform=`rotate(${Math.random()*360}deg)`,P.style.animation=`confetti-fall ${Math.random()*2+1}s forwards`,P.style.backgroundColor=["#ff69b4","#ff8da1","#ffb3ba","#ffaaa5"][Math.floor(Math.random()*4)],A.appendChild(P),setTimeout(()=>A.removeChild(P),2e3)}we(h.id)},disabled:_,whileTap:{scale:.9},whileHover:{scale:1.1,y:-2},className:`group relative flex items-center justify-center px-3 py-1.5 rounded-full text-xs font-medium transition-all duration-200 ease-in-out shadow-md ${r.includes(h.id)?"bg-pink-500 text-white animate-[heartbeat_1s_ease-in-out]":"bg-white text-pink-500 border-2 border-pink-500 hover:bg-pink-50"}`,style:r.includes(h.id)?{animation:"voted-flash 2s infinite, glowing 2s infinite"}:{},children:[i.jsx(Wn,{className:`w-3.5 h-3.5 mr-1.5 ${r.includes(h.id)?"animate-bounce":"group-hover:scale-110 transition-transform"}`}),i.jsx("span",{children:r.includes(h.id)?"Voted! â":"Vote"})]})]})]})]},h.id))})})]}),i.jsx(Ce,{children:u&&i.jsxs(S.div,{initial:{opacity:0}
126,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[60] bg-black/80 flex flex-col",children:[i.jsx("div",{className:"px-4 py-3 flex items-center justify-center bg-black/30 backdrop-blur-sm",children:i.jsxs("h3",{className:"text-white font-semibold text-center",children:["Design ",u.id]})}),i.jsx("button",{onClick:Me,className:"fixed bottom-24 right-6 z-[70] bg-black/70 text-white p-4 rounded-full shadow-lg","aria-label":"Close detail view",children:i.jsx(Ve,{className:"w-7 h-7"})}),i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-4 relative",onClick:h=>{h.target===h.currentTarget&&Me()},children:[i.jsxs("div",{className:"w-full max-w-md aspect-[600/789] bg-[#f9f7f4] rounded-lg flex items-center justify-center relative overflow-hidden",onTouchStart:xe,onTouchMove:ie,onTouchEnd:Te,children:[u.images.length>0&&f<u.images.length?i.jsx("img",{src:u.images[f],alt:`Design ${u.id} image ${f+1}`,className:"w-full h-full object-contain",onError:()=>Le(u.images[f])}):i.jsxs("div",{className:"flex flex-col items-center justify-center",children:[i.jsx(Gr,{className:"w-12 h-12 text-[#4a3f35]/40 mb-2"}),i.jsxs("span",{className:"text-[#4a3f35] text-xl font-medium",children:["Design ",u.id]})]}),u.images.length>1&&i.jsx("div",{className:"absolute inset-x-0 bottom-4 flex justify-center space-x-1",children:u.images.map((h,x)=>i.jsx("div",{className:`w-2 h-2 rounded-full ${x===f?"bg-white":"bg-white/40"}`,onClick:()=>p(x),style:{cursor:"pointer"}},x))}),u.images.length>1&&i.jsx("div",{className:"absolute inset-y-0 left-2 flex items-center pointer-events-none",children:i.jsx("div",{className:"text-white/30 transition-opacity",children:i.jsx(vn,{className:"w-6 h-6"})})}),u.images.length>1&&i.jsx("div",{className:"absolute inset-y-0 right-2 flex items-center pointer-events-none",children:i.jsx("div",{className:"text-white/30 transition-opacity",children:i.jsx(Yr,{className:"w-6 h-6"})})})]}),u.images.length>1&&i.jsxs("div",{className:"absolute inset-x-0 top-1/2 -translate-y-1/2 flex justify-between px-4",children:[i.jsx("button",{onClick:U,className:"bg-black/30 text-white rounded-full p-2",children:i.jsx(vn,{className:"w-5 h-5"})}),i.jsx("button",{onClick:F,className:"bg-black/30 text-white rounded-full p-2",children:i.jsx(Yr,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"bg-white rounded-t-2xl p-4 pt-2",children:[i.jsx("div",{className:"w-12 h-1 bg-gray-300 mx-auto mb-4 rounded-full"}),i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-[#4a3f35]",children:["Design option ",u.id]}),i.jsxs("span",{className:"text-[#4a3f35]/70 text-sm flex items-center",children:[i.jsx(_t,{className:"w-4 h-4 mr-1"}),u.vote_count," votes"]})]}),i.jsx(S.button,{onClick:()=>we(u.id),disabled:_,whileTap:{scale:.95},whileHover:{scale:1.03},className:`w-full py-3 rounded-full flex items-center justify-center transition-all duration-200 font-medium shadow-md ${_?"bg-gray-400 text-white cursor-not-allowed":r.includes(u.id)?"bg-pink-500 text-white animate-[heartbeat_1s_ease-in-out]":"bg-white text-pink-500 border-2 border-pink-500 hover:bg-pink-50"}`,style:!_&&r.includes(u.id)?{animation:"voted-flash 2s infinite, glowing 2s infinite"}:{},children:_?i.jsxs(i.Fragment,{children:[i.jsx(Ve,{className:"w-5 h-5 mr-2"}),i.jsx("span",{children:"Voting Closed"})]}):r.includes(u.id)?i.jsxs(i.Fragment,{children:[i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"w-5 h-5 mr-2",children:[i.jsx("path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"}),i.jsx("polyline",{points:"7.5 4.21 12 6.81 16.5 4.21"}),i.jsx("polyline",{points:"7.5 19.79 7.5 14.6 3 12"}),i.jsx("polyline",{points:"21 12 16.5 14.6 16.5 19.79"}),i.jsx("polyline",{points:"3.27 6.96 12 12.01 20.73 6.96"}),i.jsx("line",{x1:"12",y1:"22.08",x2:"12",y2:"12"})]}),i.jsx("span",{children:"Voted! Click to Remove â"})]}):i.jsxs(i.Fragment,{children:[i.jsx(Wn,{className:"w-5 h-5 mr-2"}),i.jsx("span",{children:"Vote for This Design"})]})})]})]})]})})]})]}):i.jsx(mh,{onAuthenticate:()=>w(!0)})},wh=()=>{const[n,e]=v.useState(0);return v.useEffect(()=>{const t=()=>
126{if(!window.visualViewport)return;const s=Math.max(0,window.innerHeight-window.visualViewport.height);e(s),document.documentElement.style.setProperty("--keyboard-height",`${s}px`)};return window.visualViewport?.addEventListener("resize",t),window.visualViewport?.addEventListener("scroll",t),()=>{window.visualViewport?.removeEventListener("resize",t),window.visualViewport?.removeEventListener("scroll",t)}},[]),n},xh=({onOpenSizeAssistant:n,onOpenWinners:e})=>{const{magazine:t,user:s,addComment:r,toggleLike:a,fetchComments:o,fetchAllComments:l,trackPageView:c,trackDownload:d,updateSessionActivity:u,trackInteraction:m,logout:f}=ut(),[p,g]=v.useState(null),[w,y]=v.useState(!1),[N,_]=v.useState(null),[L,T]=v.useState(!1),[B,Y]=v.useState(10),[K,Q]=v.useState(!1),[ee,W]=v.useState(!1),[J,le]=v.useState(!1),[re,Ae]=v.useState(!1),ne=v.useRef(null),$e=v.useRef(null),ge=wh(),Oe=v.useRef(Date.now());v.useEffect(()=>{const $=setInterval(()=>{const C=Date.now();C-Oe.current>6e4&&(u(),Oe.current=C)},6e4);return()=>clearInterval($)},[u]),v.useEffect(()=>{N!==null&&c(N)},[N,c]),v.useEffect(()=>{console.log("Magazine state changed:",{commentsCount:t.comments.length,likesCount:t.likes.length,comments:t.comments})},[t.comments,t.likes]),v.useEffect(()=>{console.log("Magazine component mounted, fetching ALL comments from database"),l()},[l]),v.useEffect(()=>{p!==null&&console.log(`Active comments changed to page ${p}`)},[p]);const De=async($,C)=>{let h={};$==="pattern"?h={download_type:"pattern",month:"January-February",year:"2026",file_type:"pdf",pattern_type:C||"unknown",source:"google_drive",pattern_name:"Aylani Coat & Tereza Set"}:$==="project"&&(h={download_type:"project",month:"January-February",year:"2026",destination:"google_drive",source:"download_button",project_name:"Jan & Feb's DIY Project"}),await d($),await m(`${$}_download`,h)},je=({className:$="",isProjectOnly:C=!1,isPatternOnly:h=!1})=>i.jsxs("div",{className:`absolute inset-0 flex flex-col items-center ${$}`,children:[!C&&i.jsx("div",{className:"absolute top-[30%] left-1/2 -translate-x-1/2 w-full max-w-sm px-4",children:i.jsxs("a",{href:"https://drive.google.com/drive/folders/1OEI8A8qxJhhdA21mIy-ou2HJmwd8dpEP?usp=sharing",target:"_blank",rel:"noopener noreferrer",onClick:x=>{x.stopPropagation(),De("pattern","aylani_coat_tereza_set")},className:"flex items-center justify-center space-x-2 bg-pink-500 text-white px-6 py-3 rounded-full font-medium transition-all transform hover:scale-105 hover:bg-pink-600 w-full",children:[i.jsx(zt,{className:"w-5 h-5"}),i.jsx("span",{children:"Download Pattern Files"})]})}),!h&&i.jsx("div",{className:"absolute top-[80%] left-1/2 -translate-x-1/2 w-full max-w-sm px-4",children:i.jsxs("a",{href:"https://drive.google.com/drive/folders/17qYxV8Co-gxn7TwLP2QXisvjSXMxPSHO?usp=drive_link",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center space-x-2 bg-white/90 hover:bg-white text-[#4a3f35] px-6 py-3 rounded-full font-medium transition-all transform hover:scale-105 w-full",onClick:x=>{x.stopPropagation(),De("project")},children:[i.jsx(zt,{className:"w-5 h-5"}),i.jsx("span",{children:"Jan & Feb's DIY Project Download Here"})]})})]}),we=({pageIndex:$,magazine:C,user:h,onLike:x,onComment:A,isFullPage:b=!1})=>{const P=C.likes.filter(G=>G.page_index===$),k=C.comments.filter(G=>G.page_index===$),j=C.likes.some(G=>G.page_index===$&&G.user_id===h?.id),M=[11,12].includes($),O="text-gray-900";return i.jsxs("div",{className:"flex items-center space-x-4",children:[i.jsxs("div",{className:"flex flex-col items-center",children:[i.jsx("button",{onClick:x,className:`${b?`${O} hover:bg-white/10`:`${O} hover:scale-110`} transition-all bg-white/90 backdrop-blur-sm rounded-full p-1.5 shadow-md`,children:i.jsx(pr,{className:`w-6 h-6 ${j?"fill-gray-900":""}`})}),i.jsx("span",{className:`${O} text-sm mt-1 font-bold bg-white/90 backdrop-blur-sm px-2.5 py-0.5 rounded-full shadow-md`,children:P.length})]}),i.jsxs("div",{className:"flex flex-col items-center",children:[i.jsx("button",{onClick:A,className:`${b?`${O} hover:bg-white/10`:`${O} hover:scale-110`} transition-all bg-white/90 backdrop-blur-sm rounded-full p-1.5
126shadow-md comment-toggle-btn`,children:i.jsx(Ks,{className:"w-6 h-6"})}),i.jsx("span",{className:`${O} text-sm mt-1 font-bold bg-white/90 backdrop-blur-sm px-2.5 py-0.5 rounded-full shadow-md`,children:k.length})]})]})},qe=({isVisible:$,onClose:C})=>i.jsx(Ce,{children:$&&i.jsx(S.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/40",onClick:C,children:i.jsxs(S.div,{initial:{scale:.95,y:20},animate:{scale:1,y:0},exit:{scale:.95,y:20},className:"relative w-full max-w-[600px] bg-white rounded-xl overflow-hidden shadow-2xl",onClick:h=>h.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-100",children:[i.jsxs("div",{className:"flex items-center space-x-3",children:[i.jsx(sl,{className:"w-6 h-6 text-pink-500"}),i.jsx("h3",{className:"font-semibold",children:"From Hormonal Chaos to Healing"})]}),i.jsx("button",{onClick:C,className:"p-2 hover:bg-gray-100 rounded-full transition-colors",children:i.jsx(Ve,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6",children:[i.jsx("h4",{className:"text-lg font-semibold mb-3",children:"Bec's Low-Tox Story"}),i.jsx("p",{className:"text-gray-600 mb-4",children:`"Why am I so unwell when this is the healthiest I've ever been in my life?" Follow Bec's journey from struggling with debilitating symptoms to discovering how everyday toxins were affecting her hormonal health.`}),i.jsx("p",{className:"text-gray-600 mb-6",children:"As a cardiac nurse and mother, Bec shares her personal transformation and practical insights on creating a low-tox lifestyle that supports hormonal balance."}),i.jsxs("div",{className:"flex flex-col space-y-4",children:[i.jsxs("a",{href:"https://drive.google.com/file/d/1kLMr8OVuNaC5nyRBJDkX-ez4NabFf9kC/view?usp=drivesdk",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center space-x-2 bg-pink-500 text-white px-6 py-3 rounded-full hover:bg-pink-600 transition-colors",children:[i.jsx("span",{children:"Read Bec's Wellness Lifestyle Booklet"}),i.jsx(ms,{className:"w-4 h-4"})]}),i.jsxs("a",{href:"https://www.youngliving.com/vo/#/signup/new-start?sponsorid=24208475&enrollerid=24208475&isocountrycode=AU&culture=en-AU&type=member",target:"_blank",rel:"noopener noreferrer",onClick:h=>{h.stopPropagation(),m("affiliate_link_click",{page_index:13,link_type:"young_living",source:"wellness_booklet",destination:"young_living_signup"})},className:"flex items-center justify-center space-x-2 bg-[#a4c639] text-white px-6 py-3 rounded-full hover:bg-[#93b233] transition-colors",children:[i.jsx("span",{children:"Start Your Wellness Journey with Young Living"}),i.jsx(ms,{className:"w-4 h-4"})]}),i.jsx("button",{onClick:C,className:"text-gray-500 hover:text-gray-700 transition-colors text-sm",children:"Close"})]})]})]})})}),Me=({isMobile:$=!1})=>{const[C,h]=v.useState(!1),[x,A]=v.useState(!1),b=v.useRef(null);v.useEffect(()=>{const j=E=>{b.current&&!b.current.contains(E.target)&&A(!1)};return document.addEventListener("mousedown",j),()=>{document.removeEventListener("mousedown",j)}},[]);const P=[{href:"https://rosyspatterns.com/collections/frontpage",label:"Rosys Patterns",icon:i.jsx(ol,{className:"w-5 h-5"}),external:!0},{href:"https://www.beginner-sewingpatterns.com/",label:"Pattern Directory",icon:i.jsx(gr,{className:"w-5 h-5"}),external:!0},{href:"#",label:"Voting",icon:i.jsx(Wn,{className:"w-5 h-5"}),external:!1,onClick:j=>{j.preventDefault(),Ae(!0),m("voting_page_open",{source:"navbar"}),h(!1)}}],k=[{href:"#",label:"Size Assistant",icon:i.jsx(qn,{className:"w-5 h-5"}),external:!1,onClick:j=>{if(j.preventDefault(),n){try{m("size_assistant_opened",{source:"navbar"}).catch(E=>{console.log("Error tracking Size Assistant opened:",E)})}catch(E){console.log("Error tracking Size Assistant opened:",E)}n()}h(!1)}},{href:"https://portal.rosyspatterns.com/",label:"Testing",icon:i.jsx(ll,{className:"w-5 h-5"}),external:!0,onClick:j=>{j.preventDefault(),m("testing_page_open",{source:"navbar",destination:"external_testing_site"}),window.open("https://portal.rosyspatterns.com/","_blank"),h(!1)}}];return $?i.jsxs("div",{className:"relative sm:hidden",children:[i.jsx("button",{onClick:()=>h(!C),className:"p-2 text-[#4a3f35] hover:bg-[#4a3f35]/10 rounded-full transition-colors",children:i.jsx(nl,{className:"w-5 h-5"})}),C&&i.jsx("div",{className:"absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-2 z-50",children:[...P,...k].map((j,E)=>i.jsxs("a",{href:j.href,target:j.external?"_blank":"_self",rel:j.external?"noopener noreferrer":void 0,className:"flex items-center space-x-3 px-4 py-2 text-[#4a3f35] hover:bg-[#4a3f35]/5 transition-colors",onClick:j.onClick||(()=>h(!1)),children:[j.icon,i.jsx("span",{className:"text-sm font-medium",children:j.label})]},E))})]}):i.jsxs("nav",{className:"hidden sm:flex items-center space-x-2",children:[P.map((j,E)=>i.jsxs("a",{href:j.href,target:j.external?"_blank":"_self",rel:j.external?"noopener noreferrer":void 0,className:"flex items-center space-x-1 px-2 text-[#4a3f35]/80 hover:text-[#4a3f35] text-sm font-medium transition-colors",onClick:j.onClick,children:[j.icon,i.jsx("span",{children:j.label})]},E)),i.jsxs("div",{className:"relative",ref:b,children:[i.jsxs("button",{onClick:()=>A(!x),className:"flex items-center space-x-1 px-2 text-[#4a3f35]/80 hover:text-[#4a3f35] text-sm font-medium transition-colors",children:[i.jsx(rl,{className:"w-5 h-5"}),i.jsx("span",{children:"More"})]}),x&&i.jsx("div",{className:"absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-2 z-50",children:k.map((j,E)=>i.jsxs("a",{href:j.href,target:j.external?"_blank":"_self",rel:j.external?"noopener noreferrer":void 0,className:"flex items-center space-x-3 px-4 py-2 text-[#4a3f35] hover:bg-[#4a3f35]/5 transition-colors",onClick:j.onClick,children:[j.icon,i.jsx("span",{className:"text-sm font-medium",children:j.label})]},E))})]})]})},F=($,C)=>{C?.stopPropagation(),C?.preventDefault(),console.log(`Toggling comments for page ${$}, current activeComments: ${p}`),p!==$?(console.log(`Opening comments modal for page ${$}`),console.log(`Calling fetchComments(${$})`),o($).then(()=>{g($)})):(console.log(`Closing comments modal for page ${$}`),g(null))},U=($,C)=>{C?.stopPropagation(),a($)},xe=async($,C)=>{$&&($.stopPropagation(),$.preventDefault());const h=yt.get(C);let x="instagram_click";
126h?.username==="heatherrosypatterns"?x="instagram_heather_click":h?.username==="rebeccarosypatterns"&&(x="instagram_rebecca_click"),await m(x,{page_index:C,username:h?.username,profile_type:h?.username==="heatherrosypatterns"?"founder":"wellness_expert",post_preview:h?.caption?.substring(0,100)}),Y(C),T(!0)},ie=async $=>{$.stopPropagation(),await m("book_recommendation_click",{page_index:7,book_title:"Amusing Ourselves to Death",author:"Neil Postman",genre:"Media Criticism/Cultural Commentary",destination:"amazon",source:"spotlight_bubble"}),W(!0)},Te=async $=>{$.stopPropagation(),await f()};v.useEffect(()=>{const $=C=>{if(!ne.current)return;const h=C.target,x=ne.current.contains(h),A=h.closest(".comment-toggle-btn"),b=h.closest(".comment-input");!x&&!A&&!b&&p!==null&&g(null)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[p]);const ke=()=>{$e.current&&($e.current.scrollTop=0),_(null),setTimeout(()=>{y($=>!$)},50)},Le=($,C)=>{C?.stopPropagation(),_($)},ft=()=>{_(null)},mt=({pageIndex:$})=>{const[C,h]=v.useState(""),x=Gi.useMemo(()=>{const b=t.comments.filter(P=>P.page_index===$);return console.log(`Comments filtered for page ${$}:`,b),b},[t.comments,$]),A=b=>{b.preventDefault(),C.trim()&&(console.log(`Adding new comment to page ${$}: ${C.trim()}`),r(C.trim(),$),h(""))};return i.jsxs(S.div,{ref:ne,initial:{y:"100%"},animate:{y:ge>0?ge:0},exit:{y:"100%"},transition:{type:"spring",damping:30,stiffness:300},className:`comments-modal touch-manipulation ${N!==null?"bg-black/90":"bg-[#f5f1eb]"}`,style:{bottom:ge>0?`${ge}px`:0,height:ge>0?`calc(100vh - ${ge}px)`:"80vh",position:"fixed",zIndex:N!==null?60:50},children:[i.jsx("div",{className:`p-4 border-b ${N!==null?"border-white/10":"border-[#4a3f35]/10"}`,children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h3",{className:`text-lg font-semibold ${N!==null?"text-white":"text-[#4a3f35]"}`,children:"Comments"}),i.jsx("button",{onClick:()=>F($),className:`p-2 rounded-full transition-colors ${N!==null?"hover:bg-white/10 text-white":"hover:bg-[#4a3f35]/10 text-[#4a3f35]"}`,children:i.jsx(Ve,{className:"w-5 h-5"})})]})}),i.jsx("div",{className:"comments-content p-4 space-y-4 touch-manipulation",children:x.length===0?i.jsx("div",{className:"text-center py-8",children:i.jsx("p",{className:`text-sm ${N!==null?"text-white/70":"text-[#4a3f35]/70"}`,children:"No comments yet. Be the first to comment!"})}):x.map((b,P)=>i.jsx("div",{className:"flex items-start space-x-3",children:i.jsxs("div",{className:`flex-1 rounded-lg p-3 ${N!==null?"bg-white/10":"bg-white/80"} border ${N!==null?"border-white/20":"border-[#4a3f35]/20"} shadow-sm`,children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:`font-medium ${N!==null?"text-white":"text-[#4a3f35]"}`,children:b.profile?.username||b.username||"Anonymous"}),i.jsx("span",{className:`text-sm ${N!==null?"text-white/60":"text-[#4a3f35]/60"}`,children:dh(new Date(b.created_at),{addSuffix:!0})})]}),i.jsx("p",{className:`mt-1 ${N!==null?"text-white":"text-[#4a3f35]"}`,children:b.content})]})},P))}),i.jsx("form",{onSubmit:A,className:`sticky bottom-0 p-4 border-t ${N!==null?"bg-black/90 border-white/10":"bg-[#f5f1eb] border-[#4a3f35]/10"}`,style:{marginBottom:ge>0?`${ge}px`:0},children:i.jsxs("div",{className:"flex items-center space-x-2",children:[i.jsx("button",{type:"button",className:`p-2 rounded-full transition-colors ${N!==null?"text-white hover:bg-white/10":"text-[#4a3f35] hover:bg-[#4a3f35]/10"}`,children:i.jsx(il,{className:"w-6 h-6"})}),i.jsx("input",{type:"text",value:C,onChange:b=>h(b.target.value),placeholder:"Add a comment...",className:`flex-1 rounded-full px-4 py-2 focus:outline-none focus:ring-2 comment-input ${N!==null?"bg-white/10 text-white placeholder-white/60 focus:ring-white/20":"bg-white/50 text-[#4a3f35] placeholder-[#4a3f35]/60 focus:ring-[#4a3f35]/20"}`,inputMode:"text",autoComplete:"off",onTouchStart:b=>b.stopPropagation()}),i.jsx("button",{type:"submit",disabled:!C.trim(),className:`p-2 rounded-full transition-colors ${N!==null?"text-white hover:bg-white/10":"text-[#4a3f35] hover:bg-[#4a3f35]/10"} ${C.trim()?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(al,{className:"w-6 h-6"})})]})})]})};return w?i.jsxs("div",{className:"bg-[#f5f1eb] h-full overflow-auto",children:[i.jsx("div",{className:"sticky top-0 z-10 bg-[#f5f1eb]/95 backdrop-blur-md border-b border-[#4a3f35]/10 safe-top",children:i.jsx("div",{className:"max-w-4xl mx-auto px-4 py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center space-x-6",children:[i.jsxs("div",{className:"flex items-center space-x-3",children:[i.jsx("img",{src:"/logowhite.png",alt:"Rosys Patterns Logo",className:"w-8 h-8 object-contain"}),i.jsx("h1",{className:"font-serif italic text-[#4a3f35] tracking-widest",children:"Jan & Feb 26' Edition"})]}),i.jsx(Me,{})]}),i.jsxs("div",{className:"flex items-center space-x-4",children:[s&&i.jsxs("div",{className:"flex items-center space-x-2",children:[i.jsx("div",{className:"w-8 h-8 rounded-full bg-pink-100 flex items-center justify-center",children:i.jsx("span",{className:"text-pink-600 font-medium text-sm",children:s.username.charAt(0).toUpperCase()})}),i.jsx("span",{className:"text-[#4a3f35] text-sm font-medium hidden sm:inline-block",children:s.username}),i.jsx("button",{onClick:Te,className:"p-2 text-[#4a3f35] hover:bg-[#4a3f35]/10 rounded-full transition-colors",title:"Logout",children:i.jsx(Qr,{className:"w-5 h-5"})})]}),i.jsx(Me,{isMobile:!0}),i.jsx("button",{onClick:ke,className:"p-2 text-[#4a3f35] hover:bg-[#4a3f35]/10 rounded-full transition-colors",children:i.jsx(Zr,{className:"w-5 h-5"})})]})]})})}),i.jsx("div",{className:"flex-1 bg-[#f5f1eb]",children:i.jsx("div",{children:i.jsx("div",{className:"max-w-lg mx-auto p-4",children:i.jsx("div",{className:"grid grid-cols-2 gap-4 pb-safe-bottom",children:t.pages.map(($,C)=>i.jsxs("div",{className:"relative aspect-[3/4] rounded-lg overflow-hidden group touch-manipulation cursor-pointer",onClick:()=>{y(!1),setTimeout(()=>{_(C)},50)},children:[i.jsx("img",{src:$,alt:`Page ${C+1}`,className:"w-full h-full object-cover",loading:"lazy"}),i.jsx(S.div,{initial:{opacity:0}
126,whileHover:{opacity:1},className:"absolute inset-0 flex items-center justify-center bg-black/20",children:i.jsx(S.div,{initial:{scale:.8},whileHover:{scale:1},className:"bg-white/90 backdrop-blur-sm p-2 rounded-full",children:i.jsx(ei,{className:"w-6 h-6 text-gray-900"})})}),i.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/15 to-transparent opacity-0 group-hover:opacity-90 transition-opacity",children:i.jsx("div",{className:"absolute inset-x-0 bottom-0 p-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(we,{pageIndex:C,magazine:t,user:s,onLike:h=>{h&&h.stopPropagation(),U(C,h)},onComment:h=>{h&&h.stopPropagation(),F(C,h)}}),yt.has(C)&&i.jsxs("button",{type:"button",onClick:x=>{xe(x,C)},className:"relative p-2 text-white hover:scale-110 transition-all z-[9999] pointer-events-auto",children:[i.jsx(ls,{className:"w-6 h-6"}),i.jsx("span",{className:"absolute top-full right-0 mt-1 px-2 py-1 text-xs bg-white text-black rounded opacity-0 hover:opacity-100 transition-opacity whitespace-nowrap",children:yt.get(C)?.username})]})]})})})]},C))})})})})]}):i.jsxs("div",{className:"bg-[#f5f1eb] h-full overflow-auto",children:[i.jsx("div",{className:"sticky top-0 z-10 bg-[#f5f1eb]/95 backdrop-blur-md border-b border-[#4a3f35]/10 safe-top",children:i.jsx("div",{className:"max-w-4xl mx-auto px-4 py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center space-x-6",children:[i.jsxs("div",{className:"flex items-center space-x-3",children:[i.jsx("img",{src:"/logowhite.png",alt:"Rosys Patterns Logo",className:"w-8 h-8 object-contain"}),i.jsx("h1",{className:"font-serif italic text-[#4a3f35] tracking-widest",children:"Jan & Feb 26' Edition"})]}),i.jsx(Me,{})]}),i.jsxs("div",{className:"flex items-center space-x-4",children:[s&&i.jsxs("div",{className:"flex items-center space-x-2",children:[i.jsx("div",{className:"w-8 h-8 rounded-full bg-pink-100 flex items-center justify-center",children:i.jsx("span",{className:"text-pink-600 font-medium text-sm",children:s.username.charAt(0).toUpperCase()})}),i.jsx("span",{className:"text-[#4a3f35] text-sm font-medium hidden sm:inline-block",children:s.username}),i.jsx("button",{onClick:Te,className:"p-2 text-[#4a3f35] hover:bg-[#4a3f35]/10 rounded-full transition-colors",title:"Logout",children:i.jsx(Qr,{className:"w-5 h-5"})})]}),i.jsx(Me,{isMobile:!0}),i.jsx("button",{onClick:ke,className:"p-2 text-[#4a3f35] hover:bg-[#4a3f35]/10 rounded-full transition-colors",children:i.jsx(Zr,{className:"w-5 h-5"})})]})]})})}),i.jsx("div",{className:"flex-1 bg-[#f5f1eb]",children:i.jsx("div",{ref:$e,className:"touch-manipulation",children:i.jsx("div",{className:"max-w-[430px] mx-auto space-y-4 py-4 pb-16",children:t.pages.map(($,C)=>(console.log("Rendering page:",C),console.log("Is this page 13?",C===13),i.jsxs("div",{className:"relative cursor-pointer group",onClick:h=>Le(C,h),children:[i.jsx("img",{src:$,alt:`Page ${C+1}`,className:"w-full h-auto rounded-lg shadow-sm",loading:"lazy"}),i.jsx(S.div,{initial:{opacity:0}
126,whileHover:{opacity:1},className:"absolute inset-0 flex items-center justify-center bg-black/20 rounded-lg",children:i.jsx(S.div,{initial:{scale:.8},whileHover:{scale:1},className:"bg-white/90 backdrop-blur-sm p-2 rounded-full",children:i.jsx(ei,{className:"w-6 h-6 text-gray-900"})})}),C===12&&i.jsx("div",{className:"absolute inset-0",children:i.jsx(je,{})}),i.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/15 to-transparent opacity-60",children:i.jsx("div",{className:"absolute inset-x-0 bottom-0 p-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(we,{pageIndex:C,magazine:t,user:s,onLike:h=>{h&&h.stopPropagation(),U(C,h)},onComment:h=>{h&&h.stopPropagation(),F(C,h)}}),yt.has(C)&&i.jsxs("button",{type:"button",onClick:x=>{x.stopPropagation(),xe(x,C)},className:"relative p-2 text-white hover:scale-110 transition-all z-[9999] pointer-events-auto",children:[i.jsx(ls,{className:"w-6 h-6"}),i.jsx("span",{className:"absolute top-full right-0 mt-1 px-2 py-1 text-xs bg-white text-black rounded opacity-0 hover:opacity-100 transition-opacity whitespace-nowrap",children:yt.get(C)?.username})]})]})})}),C===7&&i.jsx(Si,{onClick:ie,position:{bottom:"5%",right:"5%"}})]},C)))})})}),i.jsx(Ce,{children:p!==null&&i.jsx(mt,{pageIndex:p})}),i.jsx(Ce,{children:N!==null&&i.jsxs(S.div,{initial:{opacity:0}
126,animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/40 z-50 flex flex-col overflow-auto",children:[i.jsx("div",{className:"sticky top-0 z-10 bg-black/15 backdrop-blur-sm safe-top",children:i.jsxs("div",{className:"max-w-lg mx-auto px-4 py-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center",children:[i.jsx("button",{onClick:ft,className:"p-2 text-white hover:bg-white/10 rounded-full transition-colors",children:i.jsx(lt,{className:"w-5 h-5"})}),i.jsxs("h1",{className:"text-white font-semibold ml-2",children:["Page ",N+1]})]}),i.jsx("div",{className:"flex items-center space-x-4",children:yt.has(N)&&i.jsx("button",{type:"button",onClick:C=>xe(C,N),className:"p-2 text-white hover:bg-white/10 rounded-full transition-colors",children:i.jsx(ls,{className:"w-5 h-5"})})})]})}),i.jsx("div",{className:"flex-1 overflow-y-auto safe-bottom pb-safe-bottom",children:i.jsx("div",{className:"max-w-[430px] mx-auto p-4 flex items-center justify-center min-h-full",children:i.jsxs("div",{className:"relative w-full",children:[i.jsx("img",{src:t.pages[N],alt:`Page ${N+1}`,className:"w-full h-auto rounded-lg"}),N===12&&i.jsx("div",{className:"absolute inset-0",children:i.jsx(je,{})}),N===7&&i.jsx(Si,{onClick:ie,position:{bottom:"5%",right:"5%"}}),i.jsx("div",{className:"absolute bottom-4 right-4 z-10",children:i.jsx(we,{pageIndex:N,magazine:t,user:s,onLike:$=>U(N,$),onComment:$=>{$&&$.stopPropagation(),F(N,$)},isFullPage:!0})})]})})})]})}),i.jsx(Ce,{children:L&&i.jsx(uh,{isVisible:!0,onClose:()=>T(!1),pageIndex:B})}),i.jsx(Ce,{children:K&&i.jsx(qe,{isVisible:!0,onClose:()=>Q(!1)})}),i.jsx(Ce,{children:ee&&i.jsx(hh,{isVisible:!0,onClose:()=>W(!1)})}),i.jsx(Ce,{children:J&&i.jsx(fh,{isVisible:!0,onClose:()=>le(!1)})}),i.jsx(Ce,{children:re&&i.jsx(gh,{onBack:()=>Ae(!1)})})]})},sr="RFC3986",nr={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:n=>String(n)},yh="RFC1738",bh=Array.isArray,He=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),An=1024,vh=(n,e,t,s,r)=>{if(n.length===0)return n;let a=n;if(typeof n=="symbol"?a=Symbol.prototype.toString.call(n):typeof n!="string"&&(a=String(n)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let o="";for(let l=0;l<a.length;l+=An){const c=a.length>=An?a.slice(l,l+An):a,d=[];for(let u=0;u<c.length;++u){let m=c.charCodeAt(u);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||r===yh&&(m===40||m===41)){d[d.length]=c.charAt(u);continue}if(m<128){d[d.length]=He[m];continue}if(m<2048){d[d.length]=He[192|m>>6]+He[128|m&63];continue}if(m<55296||m>=57344){d[d.length]=He[224|m>>12]+He[128|m>>6&63]+He[128|m&63];continue}u+=1,m=65536+((m&1023)<<10|c.charCodeAt(u)&1023),d[d.length]=He[240|m>>18]+He[128|m>>12&63]+He[128|m>>6&63]+He[128|m&63]}o+=d.join("")}return o};function _h(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function Pi(n,e){if(bh(n)){const t=[];for(let s=0;s<n.length;s+=1)t.push(e(n[s]));return t}return e(n)}const jh=Object.prototype.hasOwnProperty,$a={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},Xe=Array.isArray,kh=Array.prototype.push,Ta=function(n,e){kh.apply(n,Xe(e)?e:[e])},Nh=Date.prototype.toISOString,oe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:vh,encodeValuesOnly:!1,format:sr,formatter:nr[sr],indices:!1,serializeDate(n){return Nh.call(n)},skipNulls:!1,strictNullHandling:!1};function Sh(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const $n={};function Ra(n,e,t,s,r,a,o,l,c,d,u,m,f,p,g,w,y,N){let _=n,L=N,T=0,B=!1;for(;(L=L.get($n))!==void 0&&!B;){const W=L.get(n);if(T+=1,typeof W<"u"){if(W===T)throw new RangeError("Cyclic object value");B=!0}typeof L.get($n)>"u"&&(T=0)}if(typeof d=="function"?_=d(e,_):_ instanceof Date?_=f?.(_):t==="comma"&&Xe(_)&&(_=Pi(_,function(W){return W instanceof Date?f?.(W):W})),_===null){if(a)return c&&!w?c(e,oe.encoder,y,"key",p):e;_=""}if(Sh(_)||_h(_)){if(c){const W=w?e:c(e,oe.encoder,y,"key",p);return[g?.(W)+"="+g?.(c(_,oe.encoder,y,"value",p))]}return[g?.(e)+"="+g?.(String(_))]}const Y=[];if(typeof _>"u")return Y;let K;if(t==="comma"&&Xe(_))w&&c&&(_=Pi(_,c)),K=[{value:_.length>0?_.join(",")||null:void 0}];else if(Xe(d))K=d;else{const W=Object.keys(_);K=u?W.sort(u):W}const Q=l?String(e).replace(/\./g,"%2E"):String(e),ee=s&&Xe(_)&&_.length===1?Q+"[]":Q;if(r&&Xe(_)&&_.length===0)return ee+"[]";for(let W=0;W<K.length;++W){const J=K[W],le=typeof J=="object"&&typeof J.value<"u"?J.value:_[J];if(o&&le===null)continue;const re=m&&l?J.replace(/\./g,"%2E"):J,Ae=Xe(_)?typeof t=="function"?t(ee,re):ee:ee+(m?"."+re:"["+re+"]");N.set(n,T);const ne=new WeakMap;ne.set($n,N),Ta(Y,Ra(le,Ae,t,s,r,a,o,l,t==="comma"&&w&&Xe(_)?null:c,d,u,m,f,p,g,w,y,ne))}return Y}function Ph(n=oe){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
126if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||oe.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=sr;if(typeof n.format<"u"){if(!jh.call(nr,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const s=nr[t];let r=oe.filter;(typeof n.filter=="function"||Xe(n.filter))&&(r=n.filter);let a;if(n.arrayFormat&&n.arrayFormat in $a?a=n.arrayFormat:"indices"in n?a=n.indices?"indices":"repeat":a=oe.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const o=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:oe.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:oe.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:oe.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:oe.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?oe.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:oe.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:oe.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:oe.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:oe.encodeValuesOnly,filter:r,format:t,formatter:s,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:oe.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:oe.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:oe.strictNullHandling}}function Eh(n,e={}){let t=n;const s=Ph(e);let r,a;typeof s.filter=="function"?(a=s.filter,t=a("",t)):Xe(s.filter)&&(a=s.filter,r=a);const o=[];if(typeof t!="object"||t===null)return"";const l=$a[s.arrayFormat],c=l==="comma"&&s.commaRoundTrip;r||(r=Object.keys(t)),s.sort&&r.sort(s.sort);const d=new WeakMap;for(let f=0;f<r.length;++f){const p=r[f];s.skipNulls&&t[p]===null||Ta(o,Ra(t[p],p,l,c,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,d))}const u=o.join(s.delimiter);let m=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),u.length>0?m+u:""}const Ot="4.91.1";let Ei=!1,hs,Ia,Oa,rr,Da,Ma,La,Fa,Ua;function Ch(n,e={auto:!1}){if(Ei)throw new Error(`you must \`import 'openai/shims/${n.kind}'\` before importing anything else from openai`);if(hs)throw new Error(`can't \`import 'openai/shims/${n.kind}'\` after \`import 'openai/shims/${hs}'\``);Ei=e.auto,hs=n.kind,Ia=n.fetch,Oa=n.FormData,rr=n.File,Da=n.ReadableStream,Ma=n.getMultipartRequestOptions,La=n.getDefaultAgent,Fa=n.fileFromPath,Ua=n.isFsReadStream}class Ah{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function $h({manuallyImported:n}={}){const e=n?"You may need to use polyfills":"Add one of these imports before your first `import ⦠from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let t,s,r,a;try{t=fetch,s=Request,r=Response,a=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${e}`)}return{kind:"web",fetch:t,Request:s,Response:r,Headers:a,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(o,l)=>({...l,body:new Ah(o)}),getDefaultAgent:o=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:o=>!1}}const za=()=>{hs||Ch($h(),{auto:!0})};za();
126class D extends Error{}class me extends D{constructor(e,t,s,r){super(`${me.makeMessage(e,t,s)}`),this.status=e,this.headers=r,this.request_id=r?.["x-request-id"],this.error=t;const a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,s){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e||!r)return new cn({message:s,cause:ar(t)});const a=t?.error;return e===400?new Ba(e,a,s,r):e===401?new Va(e,a,s,r):e===403?new Wa(e,a,s,r):e===404?new qa(e,a,s,r):e===409?new Ja(e,a,s,r):e===422?new Ha(e,a,s,r):e===429?new Ka(e,a,s,r):e>=500?new Xa(e,a,s,r):new me(e,a,s,r)}}class Re extends me{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class cn extends me{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class _r extends cn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ba extends me{}class Va extends me{}class Wa extends me{}class qa extends me{}class Ja extends me{}class Ha extends me{}class Ka extends me{}class Xa extends me{}class Ga extends D{constructor(){super("Could not parse response content as the length limit was reached")}}class Ya extends D{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var As=function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},wt=function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},Se;class dn{constructor(){Se.set(this,void 0),this.buffer=new Uint8Array,As(this,Se,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e;let s=new Uint8Array(this.buffer.length+t.length);s.set(this.buffer),s.set(t,this.buffer.length),this.buffer=s;const r=[];let a;for(;(a=Th(this.buffer,wt(this,Se,"f")))!=null;){if(a.carriage&&wt(this,Se,"f")==null){As(this,Se,a.index,"f");continue}if(wt(this,Se,"f")!=null&&(a.index!==wt(this,Se,"f")+1||a.carriage)){r.push(this.decodeText(this.buffer.slice(0,wt(this,Se,"f")-1))),this.buffer=this.buffer.slice(wt(this,Se,"f")),As(this,Se,null,"f");continue}const o=wt(this,Se,"f")!==null?a.preceding-1:a.preceding,l=this.decodeText(this.buffer.slice(0,o));r.push(l),this.buffer=this.buffer.slice(a.index),As(this,Se,null,"f")}return r}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new D(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new D(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new D("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(` 127`):[]}}Se=new WeakMap;dn.NEWLINE_CHARS=new Set([` 128`,"\r"]);dn.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Th(n,e){for(let r=e??0;r<n.length;r++){if(n[r]===10)return{preceding:r,index:r+1,carriage:!1};if(n[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function Rh(n){for(let s=0;s<n.length-1;s++){if(n[s]===10&&n[s+1]===10||n[s]===13&&n[s+1]===13)return s+2;if(n[s]===13&&n[s+1]===10&&s+3<n.length&&n[s+2]===13&&n[s+3]===10)return s+4}return-1}function Qa(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class Ye{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let s=!1;async function*r(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(const o of Ih(e,t))if(!a){if(o.data.startsWith("[DONE]")){a=!0;continue}if(o.event===null||o.event.startsWith("response.")||o.event.startsWith("transcript.")){let l;try{l=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(l&&l.error)throw new me(void 0,l.error,void 0,ao(e.headers));yield l}else{let l;try{l=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(o.event=="error")throw new me(void 0,l.error,l.message,void 0);yield{event:o.event,data:l}}}a=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{a||t.abort()}}return new Ye(r,t)}static fromReadableStream(e,t){let s=!1;async function*r(){const o=new dn,l=Qa(e);for await(const c of l)for(const d of o.decode(c))yield d;for(const c of o.flush())yield c}async function*a(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const l of r())o||l&&(yield JSON.parse(l));o=!0}catch(l){if(l instanceof Error&&l.name==="AbortError")return;throw l}finally{o||t.abort()}}return new Ye(a,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),r=a=>({next:()=>{if(a.length===0){const o=s.next();e.push(o),t.push(o)}return a.shift()}});return[new Ye(()=>r(e),this.controller),new Ye(()=>r(t),this.controller)]}toReadableStream(){const e=this;let t;const s=new TextEncoder;return new Da({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:a,done:o}=await t.next();if(o)return r.close();const l=s.encode(JSON.stringify(a)+` 129`);r.enqueue(l)}catch(a){r.error(a)}},async cancel(){await t.return?.()}})}}async function*Ih(n,e){if(!n.body)throw e.abort(),new D("Attempted to iterate over a response with no body");const t=new Dh,s=new dn,r=Qa(n.body);for await(const a of Oh(r))for(const o of s.decode(a)){const l=t.decode(o);l&&(yield l)}for(const a of s.flush()){const o=t.decode(a);o&&(yield o)}}async function*Oh(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let a;for(;(a=Rh(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Dh{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(` 130`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,r]=Mh(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function Mh(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}const Za=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function",eo=n=>
130n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&un(n),un=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Lh=n=>eo(n)||Za(n)||Ua(n);async function to(n,e,t){if(n=await n,eo(n))return n;if(Za(n)){const r=await n.blob();e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()??"unknown_file");const a=un(r)?[await r.arrayBuffer()]:[r];return new rr(a,e,t)}const s=await Fh(n);if(e||(e=zh(n)??"unknown_file"),!t?.type){const r=s[0]?.type;typeof r=="string"&&(t={...t,type:r})}return new rr(s,e,t)}async function Fh(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(un(n))e.push(await n.arrayBuffer());else if(Bh(n))for await(const t of n)e.push(t);else throw new Error(`Unexpected data type: ${typeof n}; constructor: ${n?.constructor?.name}; props: ${Uh(n)}`);return e}function Uh(n){return`[${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}function zh(n){return Tn(n.name)||Tn(n.filename)||Tn(n.path)?.split(/[\\/]/).pop()}const Tn=n=>{if(typeof n=="string")return n;if(typeof Buffer<"u"&&n instanceof Buffer)return String(n)},Bh=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Ci=n=>n&&typeof n=="object"&&n.body&&n[Symbol.toStringTag]==="MultipartBody",qt=async n=>{const e=await Vh(n.body);return Ma(e,n)},Vh=async n=>{const e=new Oa;return await Promise.all(Object.entries(n||{}).map(([t,s])=>ir(e,t,s))),e},ir=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(Lh(t)){const s=await to(t);n.append(e,s)}else if(Array.isArray(t))await Promise.all(t.map(s=>ir(n,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,r])=>ir(n,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var so={},Wh=function(n,e,t,s,r){if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t},qh=function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},$s;za();async function no(n){const{response:e}=n;if(n.options.stream)return ct("response",e.status,e.url,e.headers,e.body),n.options.__streamClass?n.options.__streamClass.fromSSEResponse(e,n.controller):Ye.fromSSEResponse(e,n.controller);if(e.status===204)return null;if(n.options.__binaryResponse)return e;const s=e.headers.get("content-type")?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){const o=await e.json();return ct("response",e.status,e.url,e.headers,o),ro(o,e)}const a=await e.text();return ct("response",e.status,e.url,e.headers,a),a}function ro(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}class hn extends Promise{constructor(e,t=no){super(s=>{s(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new hn(this.responsePromise,async t=>ro(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class Jh{constructor({baseURL:e,maxRetries:t=2,timeout:s=6e5,httpAgent:r,fetch:a}){this.baseURL=e,this.maxRetries=Rn("maxRetries",t),this.timeout=Rn("timeout",s),this.httpAgent=r,this.fetch=a??Ia}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Yh(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${tf()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(async r=>{const a=r&&un(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:a}}))}
130getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};const{method:s,path:r,query:a,headers:o={}}=e,l=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Ci(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,c=this.calculateContentLength(l),d=this.buildURL(r,a);"timeout"in e&&Rn("timeout",e.timeout),e.timeout=e.timeout??this.timeout;const u=e.httpAgent??this.httpAgent??La(d),m=e.timeout+1e3;typeof u?.options?.timeout=="number"&&m>(u.options.timeout??0)&&(u.options.timeout=m),this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);const f=this.buildHeaders({options:e,headers:o,contentLength:c,retryCount:t});return{req:{method:s,...l&&{body:l},headers:f,...u&&{agent:u},signal:e.signal??null},url:d,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:s,retryCount:r}){const a={};s&&(a["content-length"]=s);const o=this.defaultHeaders(e);return Ri(a,o),Ri(a,t),Ci(e.body)&&hs!=="node"&&delete a["content-type"],Rs(o,"x-stainless-retry-count")===void 0&&Rs(t,"x-stainless-retry-count")===void 0&&(a["x-stainless-retry-count"]=String(r)),Rs(o,"x-stainless-timeout")===void 0&&Rs(t,"x-stainless-timeout")===void 0&&e.timeout&&(a["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(a,t),a}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,s,r){return me.generate(e,t,s,r)}request(e,t=null){return new hn(this.makeRequest(e,t))}async makeRequest(e,t){const s=await e,r=s.maxRetries??this.maxRetries;t==null&&(t=r),await this.prepareOptions(s);const{req:a,url:o,timeout:l}=this.buildRequest(s,{retryCount:r-t});if(await this.prepareRequest(a,{url:o,options:s}),ct("request",o,s,a.headers),s.signal?.aborted)throw new Re;const c=new AbortController,d=await this.fetchWithTimeout(o,a,l,c).catch(ar);if(d instanceof Error){if(s.signal?.aborted)throw new Re;if(t)return this.retryRequest(s,t);throw d.name==="AbortError"?new _r:new cn({cause:d})}const u=ao(d.headers);if(!d.ok){if(t&&this.shouldRetry(d)){const y=`retrying, ${t} attempts remaining`;return ct(`response (error; ${y})`,d.status,o,u),this.retryRequest(s,t,u)}const m=await d.text().catch(y=>ar(y).message),f=Qh(m),p=f?void 0:m;throw ct(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,d.status,o,u,p),this.makeStatusError(d.status,f,p,u)}return{response:d,options:s,controller:c}}requestAPIList(e,t){const s=this.makeRequest(t,null);return new Hh(this,s,e)}buildURL(e,t){const s=ef(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery();return oo(r)||(t={...r,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,s])=>typeof s<"u").map(([t,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(t)}=`;throw new D(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,s,r){const{signal:a,...o}=t||{};a&&a.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),s),c={signal:r.signal,...o};return c.method&&(c.method=c.method.toUpperCase()),this.fetch.call(void 0,e,c).finally(()=>{clearTimeout(l)})}shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s){let r;const a=s?.["retry-after-ms"];
130if(a){const l=parseFloat(a);Number.isNaN(l)||(r=l)}const o=s?.["retry-after"];if(o&&!r){const l=parseFloat(o);Number.isNaN(l)?r=Date.parse(o)-Date.now():r=l*1e3}if(!(r&&0<=r&&r<60*1e3)){const l=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,l)}return await bs(r),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,o=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return o*l*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Ot}`}}class io{constructor(e,t,s,r){$s.set(this,void 0),Wh(this,$s,e),this.options=r,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new D("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){const s=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[r,a]of s)e.url.searchParams.set(r,a);t.query=void 0,t.path=e.url.toString()}return await qh(this,$s,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[($s=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Hh extends hn{constructor(e,t,s){super(t,async r=>new s(e,r.response,await no(r),r.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const ao=n=>new Proxy(Object.fromEntries(n.entries()),{get(e,t){const s=t.toString();return e[s.toLowerCase()]||e[s]}}),Kh={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},ue=n=>typeof n=="object"&&n!==null&&!oo(n)&&Object.keys(n).every(e=>lo(Kh,e)),Xh=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":$i(Deno.build.os),"X-Stainless-Arch":Ai(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":$i(process.platform),"X-Stainless-Arch":Ai(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const n=Gh();return n?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${n.browser}`,"X-Stainless-Runtime-Version":n.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Gh(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,a=s[2]||0,o=s[3]||0;return{browser:e,version:`${r}.${a}.${o}`}}}return null}const Ai=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",$i=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let Ti;const Yh=()=>Ti??(Ti=Xh()),Qh=n=>{try{return JSON.parse(n)}catch{return}},Zh=/^[a-z][a-z0-9+.-]*:/i,ef=n=>Zh.test(n),bs=n=>new Promise(e=>setTimeout(e,n)),Rn=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new D(`${n} must be an integer`);if(e<0)throw new D(`${n} must be a positive integer`);return e},ar=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null)try{return new Error(JSON.stringify(n))}catch{}return new Error(n)},Ts=n=>{if(typeof process<"u")return so?.[n]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(n)?.trim()};function oo(n){if(!n)return!0;for(const e in n)return!1;return!0}function lo(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Ri(n,e){for(const t in e){if(!lo(e,t))continue;const s=t.toLowerCase();if(!s)continue;const r=e[t];r===null?delete n[s]:r!==void 0&&(n[s]=r)}}const Ii=new Set(["authorization","api-key"]);function ct(n,...e){if(typeof process<"u"&&so?.DEBUG==="true"){const t=e.map(s=>{if(!s)return s;if(s.headers){const a={...s,headers:{...s.headers}};for(const o in s.headers)Ii.has(o.toLowerCase())&&(a.headers[o]="REDACTED");return a}let r=null;for(const a in s)Ii.has(a.toLowerCase())&&(r??(r={...s}),r[a]="REDACTED");return r??s});console.log(`OpenAI:DEBUG:${n}`,...t)}}const tf=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)}),sf=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",nf=n=>typeof n?.get=="function",Rs=(n,e)=>{const t=e.toLowerCase();if(nf(n)){const s=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(r,a,o)=>a+o.toUpperCase());for(const r of[e,t,e.toUpperCase(),s]){const a=n.get(r);if(a)return a}}for(const[s,r]of Object.entries(n))if(s.toLowerCase()===t)return Array.isArray(r)?(r.length<=1||console.warn(`Received ${r.length} entries for the ${e} header, using the first entry.`),r[0]):r},rf=n=>{if(typeof Buffer<"u")return Array.from(new Float32Array(Buffer.from(n,"base64").buffer));{const e=atob(n),t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}};function In(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}class jr extends io{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class _e extends io{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class X{constructor(e){this._client=e}}let co=class extends X{list(e,t={},s){return ue(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,af,{query:t,...s})}},fn=class extends X{constructor(){super(...arguments),this.messages=new co(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}
130update(e,t,s){return this._client.post(`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return ue(e)?this.list({},e):this._client.getAPIList("/chat/completions",mn,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class mn extends _e{}class af extends _e{}fn.ChatCompletionsPage=mn;fn.Messages=co;let pn=class extends X{constructor(){super(...arguments),this.completions=new fn(this._client)}};pn.Completions=fn;pn.ChatCompletionsPage=mn;class uo extends X{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class ho extends X{create(e,t){return this._client.post("/audio/transcriptions",qt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class fo extends X{create(e,t){return this._client.post("/audio/translations",qt({body:e,...t,__metadata:{model:e.model}}))}}class vs extends X{constructor(){super(...arguments),this.transcriptions=new ho(this._client),this.translations=new fo(this._client),this.speech=new uo(this._client)}}vs.Transcriptions=ho;vs.Translations=fo;vs.Speech=uo;class kr extends X{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return ue(e)?this.list({},e):this._client.getAPIList("/batches",Nr,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class Nr extends _e{}kr.BatchesPage=Nr;class Sr extends X{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,s){return this._client.post(`/assistants/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e={},t){return ue(e)?this.list({},e):this._client.getAPIList("/assistants",Pr,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Pr extends _e{}Sr.AssistantsPage=Pr;function Oi(n){return typeof n.parse=="function"}const Ft=n=>n?.role==="assistant",mo=n=>n?.role==="function",po=n=>n?.role==="tool";var Ue=function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},se=function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},or,Bs,Vs,ss,ns,Ws,rs,Ze,is,Gs,Ys,Dt,go;class Er{constructor(){or.add(this),this.controller=new AbortController,Bs.set(this,void 0),Vs.set(this,()=>{}),ss.set(this,()=>{}),ns.set(this,void 0),Ws.set(this,()=>{}),rs.set(this,()=>{}),Ze.set(this,{}),is.set(this,!1),Gs.set(this,!1),Ys.set(this,!1),Dt.set(this,!1),Ue(this,Bs,new Promise((e,t)=>{Ue(this,Vs,e,"f"),Ue(this,ss,t,"f")}),"f"),Ue(this,ns,new Promise((e,t)=>{Ue(this,Ws,e,"f"),Ue(this,rs,t,"f")}),"f"),se(this,Bs,"f").catch(()=>{}),se(this,ns,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},se(this,or,"m",go).bind(this))},0)}_connected(){this.ended||(se(this,Vs,"f").call(this),this._emit("connect"))}get ended(){return se(this,is,"f")}get errored(){return se(this,Gs,"f")}get aborted(){return se(this,Ys,"f")}abort(){this.controller.abort()}on(e,t){return(se(this,Ze,"f")[e]||(se(this,Ze,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=se(this,Ze,"f")[e];if(!s)return this;const r=s.findIndex(a=>a.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(se(this,Ze,"f")[e]||(se(this,Ze,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{Ue(this,Dt,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){Ue(this,Dt,!0,"f"),await se(this,ns,"f")}_emit(e,...t){if(se(this,is,"f"))return;e==="end"&&(Ue(this,is,!0,"f"),se(this,Ws,"f").call(this));const s=se(this,Ze,"f")[e];if(s&&(se(this,Ze,"f")[e]=s.filter(r=>
130!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!se(this,Dt,"f")&&!s?.length&&Promise.reject(r),se(this,ss,"f").call(this,r),se(this,rs,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!se(this,Dt,"f")&&!s?.length&&Promise.reject(r),se(this,ss,"f").call(this,r),se(this,rs,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Bs=new WeakMap,Vs=new WeakMap,ss=new WeakMap,ns=new WeakMap,Ws=new WeakMap,rs=new WeakMap,Ze=new WeakMap,is=new WeakMap,Gs=new WeakMap,Ys=new WeakMap,Dt=new WeakMap,or=new WeakSet,go=function(e){if(Ue(this,Gs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Re),e instanceof Re)return Ue(this,Ys,!0,"f"),this._emit("abort",e);if(e instanceof D)return this._emit("error",e);if(e instanceof Error){const t=new D(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new D(String(e)))};function Cr(n){return n?.$brand==="auto-parseable-response-format"}function _s(n){return n?.$brand==="auto-parseable-tool"}function of(n,e){return!e||!wo(e)?{...n,choices:n.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ar(n,e)}function Ar(n,e){const t=n.choices.map(s=>{if(s.finish_reason==="length")throw new Ga;if(s.finish_reason==="content_filter")throw new Ya;return{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>cf(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?lf(e,s.message.content):null}}});return{...n,choices:t}}function lf(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function cf(n,e){const t=n.tools?.find(s=>s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:_s(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function df(n,e){if(!n)return!1;const t=n.tools?.find(s=>s.function?.name===e.function.name);return _s(t)||t?.function.strict||!1}function wo(n){return Cr(n.response_format)?!0:n.tools?.some(e=>_s(e)||e.type==="function"&&e.function.strict===!0)??!1}function uf(n){for(const e of n??[]){if(e.type!=="function")throw new D(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new D(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var be=function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},pe,lr,Qs,cr,dr,ur,xo,hr;const Di=10;class yo extends Er{constructor(){super(...arguments),pe.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(mo(e)||po(e))&&e.content)this._emit("functionCallResult",e.content);else if(Ft(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Ft(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new D("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),be(this,pe,"m",lr).call(this)}async finalMessage(){return await this.done(),be(this,pe,"m",Qs).call(this)}async finalFunctionCall(){return await this.done(),be(this,pe,"m",cr).call(this)}async finalFunctionCallResult(){return await this.done(),be(this,pe,"m",dr).call(this)}async totalUsage(){return await this.done(),be(this,pe,"m",ur).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=be(this,pe,"m",Qs).call(this);
130t&&this._emit("finalMessage",t);const s=be(this,pe,"m",lr).call(this);s&&this._emit("finalContent",s);const r=be(this,pe,"m",cr).call(this);r&&this._emit("finalFunctionCall",r);const a=be(this,pe,"m",dr).call(this);a!=null&&this._emit("finalFunctionCallResult",a),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",be(this,pe,"m",ur).call(this))}async _createChatCompletion(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),be(this,pe,"m",xo).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ar(a,t))}async _runChatCompletion(e,t,s){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,s)}async _runFunctions(e,t,s){const r="function",{function_call:a="auto",stream:o,...l}=t,c=typeof a!="string"&&a?.name,{maxChatCompletions:d=Di}=s||{},u={};for(const f of t.functions)u[f.name||f.function.name]=f;const m=t.functions.map(f=>({name:f.name||f.function.name,parameters:f.parameters,description:f.description}));for(const f of t.messages)this._addMessage(f,!1);for(let f=0;f<d;++f){const g=(await this._createChatCompletion(e,{...l,function_call:a,functions:m,messages:[...this.messages]},s)).choices[0]?.message;if(!g)throw new D("missing message in ChatCompletion response");if(!g.function_call)return;const{name:w,arguments:y}=g.function_call,N=u[w];if(N){if(c&&c!==w){const B=`Invalid function_call: ${JSON.stringify(w)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:r,name:w,content:B});continue}}else{const B=`Invalid function_call: ${JSON.stringify(w)}. Available options are: ${m.map(Y=>JSON.stringify(Y.name)).join(", ")}. Please try again`;this._addMessage({role:r,name:w,content:B});continue}let _;try{_=Oi(N)?await N.parse(y):y}catch(B){this._addMessage({role:r,name:w,content:B instanceof Error?B.message:String(B)});continue}const L=await N.function(_,this),T=be(this,pe,"m",hr).call(this,L);if(this._addMessage({role:r,name:w,content:T}),c)return}}async _runTools(e,t,s){const r="tool",{tool_choice:a="auto",stream:o,...l}=t,c=typeof a!="string"&&a?.function?.name,{maxChatCompletions:d=Di}=s||{},u=t.tools.map(p=>{if(_s(p)){if(!p.$callback)throw new D("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:p.$callback,name:p.function.name,description:p.function.description||"",parameters:p.function.parameters,parse:p.$parseRaw,strict:!0}}}return p}),m={};for(const p of u)p.type==="function"&&(m[p.function.name||p.function.function.name]=p.function);const f="tools"in t?u.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description,strict:p.function.strict}}:p):void 0;for(const p of t.messages)this._addMessage(p,!1);for(let p=0;p<d;++p){const w=(await this._createChatCompletion(e,{...l,tool_choice:a,tools:f,messages:[...this.messages]},s)).choices[0]?.message;if(!w)throw new D("missing message in ChatCompletion response");if(!w.tool_calls?.length)return;for(const y of w.tool_calls){if(y.type!=="function")continue;const N=y.id,{name:_,arguments:L}=y.function,T=m[_];if(T){if(c&&c!==_){const Q=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:r,tool_call_id:N,content:Q});continue}}else{const Q=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(m).map(ee=>JSON.stringify(ee)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:N,content:Q});continue}let B;try{B=Oi(T)?await T.parse(L):L}catch(Q){const ee=Q instanceof Error?Q.message:String(Q);this._addMessage({role:r,tool_call_id:N,content:ee});continue}const Y=await T.function(B,this),K=be(this,pe,"m",hr).call(this,Y);if(this._addMessage({role:r,tool_call_id:N,content:K}),c)return}}}}pe=new WeakSet,lr=function(){return be(this,pe,"m",Qs).call(this).content??null},Qs=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Ft(t)){const{function_call:s,...r}=t,a={...r,content:t.content??null,refusal:t.refusal??null};return s&&(a.function_call=s),a}}throw new D("stream ended without producing a ChatCompletionMessage with role=assistant")},cr=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ft(t)&&t?.function_call)return t.function_call;if(Ft(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},dr=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(mo(t)&&t.content!=null||po(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===t.tool_call_id)))return t.content}},ur=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},xo=function(e){if(e.n!=null&&e.n>1)throw new D("ChatCompletion convenience helpers only support n=1 at this time. To use n>
1301, please use chat.completions.create() directly.")},hr=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class gs extends yo{static runFunctions(e,t,s){const r=new gs,a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return r._run(()=>r._runFunctions(e,t,a)),r}static runTools(e,t,s){const r=new gs,a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,a)),r}_addMessage(e,t=!0){super._addMessage(e,t),Ft(e)&&e.content&&this._emit("content",e.content)}}const bo=1,vo=2,_o=4,jo=8,ko=16,No=32,So=64,Po=128,Eo=256,Co=Po|Eo,Ao=ko|No|Co|So,$o=bo|vo|Ao,To=_o|jo,hf=$o|To,ce={STR:bo,NUM:vo,ARR:_o,OBJ:jo,NULL:ko,BOOL:No,NAN:So,INFINITY:Po,MINUS_INFINITY:Eo,INF:Co,SPECIAL:Ao,ATOM:$o,COLLECTION:To,ALL:hf};class ff extends Error{}class mf extends Error{}function pf(n,e=ce.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return gf(n.trim(),e)}const gf=(n,e)=>{const t=n.length;let s=0;const r=f=>{throw new ff(`${f} at position ${s}`)},a=f=>{throw new mf(`${f} at position ${s}`)},o=()=>(m(),s>
130=t&&r("Unexpected end of input"),n[s]==='"'?l():n[s]==="{"?c():n[s]==="["?d():n.substring(s,s+4)==="null"||ce.NULL&e&&t-s<4&&"null".startsWith(n.substring(s))?(s+=4,null):n.substring(s,s+4)==="true"||ce.BOOL&e&&t-s<4&&"true".startsWith(n.substring(s))?(s+=4,!0):n.substring(s,s+5)==="false"||ce.BOOL&e&&t-s<5&&"false".startsWith(n.substring(s))?(s+=5,!1):n.substring(s,s+8)==="Infinity"||ce.INFINITY&e&&t-s<8&&"Infinity".startsWith(n.substring(s))?(s+=8,1/0):n.substring(s,s+9)==="-Infinity"||ce.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(n.substring(s))?(s+=9,-1/0):n.substring(s,s+3)==="NaN"||ce.NAN&e&&t-s<3&&"NaN".startsWith(n.substring(s))?(s+=3,NaN):u()),l=()=>{const f=s;let p=!1;for(s++;s<t&&(n[s]!=='"'||p&&n[s-1]==="\\");)p=n[s]==="\\"?!p:!1,s++;if(n.charAt(s)=='"')try{return JSON.parse(n.substring(f,++s-Number(p)))}catch(g){a(String(g))}else if(ce.STR&e)try{return JSON.parse(n.substring(f,s-Number(p))+'"')}catch{return JSON.parse(n.substring(f,n.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{s++,m();const f={};try{for(;n[s]!=="}";){if(m(),s>=t&&ce.OBJ&e)return f;const p=l();m(),s++;try{const g=o();Object.defineProperty(f,p,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(ce.OBJ&e)return f;throw g}m(),n[s]===","&&s++}}catch{if(ce.OBJ&e)return f;r("Expected '}' at end of object")}return s++,f},d=()=>{s++;const f=[];try{for(;n[s]!=="]";)f.push(o()),m(),n[s]===","&&s++}catch{if(ce.ARR&e)return f;r("Expected ']' at end of array")}return s++,f},u=()=>{if(s===0){n==="-"&&ce.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n)}catch(p){if(ce.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}a(String(p))}}const f=s;for(n[s]==="-"&&s++;n[s]&&!",]}".includes(n[s]);)s++;s==t&&!(ce.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(n.substring(f,s))}catch{n.substring(f,s)==="-"&&ce.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n.substring(f,n.lastIndexOf("e")))}catch(g){a(String(g))}}},m=()=>{for(;s<t&&` 131\r `.includes(n[s]);)s++};return o()},Mi=n=>pf(n,ce.ALL^ce.NUM);var Et=function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},Z=function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},ae,Qe,Ct,tt,On,Is,Dn,Mn,Ln,Os,Fn,Li;class ws extends yo{constructor(e){super(),ae.add(this),Qe.set(this,void 0),Ct.set(this,void 0),tt.set(this,void 0),Et(this,Qe,e,"f"),Et(this,Ct,[],"f")}get currentChatCompletionSnapshot(){return Z(this,tt,"f")}static fromReadableStream(e){const t=new ws(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const r=new ws(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),Z(this,ae,"m",On).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const o of a)Z(this,ae,"m",Dn).call(this,o);if(a.controller.signal?.aborted)throw new Re;return this._addChatCompletion(Z(this,ae,"m",Os).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Z(this,ae,"m",On).call(this),this._connected();const r=Ye.fromReadableStream(e,this.controller);let a;for await(const o of r)a&&a!==o.id&&this._addChatCompletion(Z(this,ae,"m",Os).call(this)),Z(this,ae,"m",Dn).call(this,o),a=o.id;if(r.controller.signal?.aborted)throw new Re;return this._addChatCompletion(Z(this,ae,"m",Os).call(this))}[(Qe=new WeakMap,Ct=new WeakMap,tt=new WeakMap,ae=new WeakSet,On=function(){this.ended||Et(this,tt,void 0,"f")},Is=function(t){let s=Z(this,Ct,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Z(this,Ct,"f")[t.index]=s,s)},Dn=function(t){if(this.ended)return;const s=Z(this,ae,"m",Li).call(this,t);this._emit("chunk",t,s);for(const r of t.choices){const a=s.choices[r.index];r.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",r.delta.content,a.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),r.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:a.message.refusal}),r.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:a.logprobs?.content??[]}),r.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});const o=Z(this,ae,"m",Is).call(this,a);a.finish_reason&&(Z(this,ae,"m",Ln).call(this,a),o.current_tool_call_index!=null&&Z(this,ae,"m",Mn).call(this,a,o.current_tool_call_index));for(const l of r.delta.tool_calls??[])o.current_tool_call_index!==l.index&&(Z(this,ae,"m",Ln).call(this,a),o.current_tool_call_index!=null&&Z(this,ae,"m",Mn).call(this,a,o.current_tool_call_index)),o.current_tool_call_index=l.index;for(const l of r.delta.tool_calls??[]){const c=a.message.tool_calls?.[l.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:l.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(c?.type,void 0))}}},Mn=function(t,s){if(Z(this,ae,"m",Is).call(this,t).done_tool_calls.has(s))return;const a=t.message.tool_calls?.[s];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const o=Z(this,Qe,"f")?.tools?.find(l=>l.type==="function"&&l.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:s,arguments:a.function.arguments,parsed_arguments:_s(o)?o.$parseRaw(a.function.arguments):o?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Ln=function(t){const s=Z(this,ae,"m",Is).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;const r=Z(this,ae,"m",Fn).call(this);this._emit("content.done",{content:t.message.content,parsed:r?r.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Os=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");const t=Z(this,tt,"f");if(!t)throw new D("request ended without sending any chunks");return Et(this,tt,void 0,"f"),Et(this,Ct,[],"f"),wf(t,Z(this,Qe,"f"))},Fn=function(){const t=Z(this,Qe,"f")?.response_format;return Cr(t)?t:null},Li=function(t){var s,r,a,o;let l=Z(this,tt,"f");const{choices:c,...d}=t;l?Object.assign(l,d):l=Et(this,tt,{...d,choices:[]},"f");for(const{delta:u,finish_reason:m,index:f,logprobs:p=null,...g}of t.choices){let w=l.choices[f];if(w||(w=l.choices[f]={finish_reason:m,index:f,message:{},logprobs:p,...g}),p)if(!w.logprobs)w.logprobs=Object.assign({},p);else{const{content:Y,refusal:K,...Q}=p;Object.assign(w.logprobs,Q),Y&&((s=w.logprobs).content??(s.content=[]),w.logprobs.content.push(...Y)),K&&((r=w.logprobs).refusal??(r.refusal=[]),w.logprobs.refusal.push(...K))}if(m&&(w.finish_reason=m,Z(this,Qe,"f")&&wo(Z(this,Qe,"f")))){if(m==="length")throw new Ga;if(m==="content_filter")throw new Ya}if(Object.assign(w,g),!u)continue;const{content:y,refusal:N,function_call:_,role:L,tool_calls:T,...B}=u;if(Object.assign(w.message,B),N&&(w.message.refusal=(w.message.refusal||"")+N),L&&(w.message.role=L),_&&(w.message.function_call?(_.name&&(w.message.function_call.name=_.n
131ame),_.arguments&&((a=w.message.function_call).arguments??(a.arguments=""),w.message.function_call.arguments+=_.arguments)):w.message.function_call=_),y&&(w.message.content=(w.message.content||"")+y,!w.message.refusal&&Z(this,ae,"m",Fn).call(this)&&(w.message.parsed=Mi(w.message.content))),T){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:Y,id:K,type:Q,function:ee,...W}of T){const J=(o=w.message.tool_calls)[Y]??(o[Y]={});Object.assign(J,W),K&&(J.id=K),Q&&(J.type=Q),ee&&(J.function??(J.function={name:ee.name??"",arguments:""})),ee?.name&&(J.function.name=ee.name),ee?.arguments&&(J.function.arguments+=ee.arguments,df(Z(this,Qe,"f"),J)&&(J.function.parsed_arguments=Mi(J.function.arguments)))}}}return l},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,o)=>t.push({resolve:a,reject:o})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ye(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function wf(n,e){const{id:t,choices:s,created:r,model:a,system_fingerprint:o,...l}=n,c={...l,id:t,choices:s.map(({message:d,finish_reason:u,index:m,logprobs:f,...p})=>{if(!u)throw new D(`missing finish_reason for choice ${m}`);const{content:g=null,function_call:w,tool_calls:y,...N}=d,_=d.role;if(!_)throw new D(`missing role for choice ${m}`);if(w){const{arguments:L,name:T}=w;if(L==null)throw new D(`missing function_call.arguments for choice ${m}`);if(!T)throw new D(`missing function_call.name for choice ${m}`);return{...p,message:{content:g,function_call:{arguments:L,name:T},role:_,refusal:d.refusal??null},finish_reason:u,index:m,logprobs:f}}return y?{...p,index:m,finish_reason:u,logprobs:f,message:{...N,role:_,content:g,refusal:d.refusal??null,tool_calls:y.map((L,T)=>{const{function:B,type:Y,id:K,...Q}=L,{arguments:ee,name:W,...J}=B||{};if(K==null)throw new D(`missing choices[${m}].tool_calls[${T}].id 132${Ds(n)}`);if(Y==null)throw new D(`missing choices[${m}].tool_calls[${T}].type 133${Ds(n)}`);if(W==null)throw new D(`missing choices[${m}].tool_calls[${T}].function.name 134${Ds(n)}`);if(ee==null)throw new D(`missing choices[${m}].tool_calls[${T}].function.arguments 135${Ds(n)}`);return{...Q,id:K,type:Y,function:{...J,name:W,arguments:ee}}})}}:{...p,message:{...N,content:g,role:_,refusal:d.refusal??null},finish_reason:u,index:m,logprobs:f}}),created:r,model:a,object:"chat.completion",...o?{system_fingerprint:o}:{}};return of(c,e)}function Ds(n){return JSON.stringify(n)}class Ut extends ws{static fromReadableStream(e){const t=new Ut(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,s){const r=new Ut(null),a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return r._run(()=>r._runFunctions(e,t,a)),r}static runTools(e,t,s){const r=new Ut(t),a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,a)),r}}let Ro=class extends X{parse(e,t){return uf(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(s=>Ar(s,e))}runFunctions(e,t){return e.stream?Ut.runFunctions(this._client,e,t):gs.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?Ut.runTools(this._client,e,t):gs.runTools(this._client,e,t)}stream(e,t){return ws.createChatCompletion(this._client,e,t)}};class fr extends X{constructor(){super(...arguments),this.completions=new Ro(this._client)}}(function(n){n.Completions=Ro})(fr||(fr={}));class Io extends X{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Oo extends X{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class gn extends X{constructor(){super(...arguments),this.sessions=new Io(this._client),this.transcriptionSessions=new Oo(this._client)}}gn.Sessions=Io;gn.TranscriptionSessions=Oo;var R=function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},Ne=function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},he,mr,Ge,qs,ze,jt,Mt,vt,Zs,Ee,Js,Hs,fs,as,os,Fi,Ui,zi,Bi,Vi,Wi,qi;
135class We extends Er{constructor(){super(...arguments),he.add(this),mr.set(this,[]),Ge.set(this,{}),qs.set(this,{}),ze.set(this,void 0),jt.set(this,void 0),Mt.set(this,void 0),vt.set(this,void 0),Zs.set(this,void 0),Ee.set(this,void 0),Js.set(this,void 0),Hs.set(this,void 0),fs.set(this,void 0)}[(mr=new WeakMap,Ge=new WeakMap,qs=new WeakMap,ze=new WeakMap,jt=new WeakMap,Mt=new WeakMap,vt=new WeakMap,Zs=new WeakMap,Ee=new WeakMap,Js=new WeakMap,Hs=new WeakMap,fs=new WeakMap,he=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,o)=>t.push({resolve:a,reject:o})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new We;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=Ye.fromReadableStream(e,this.controller);for await(const a of r)R(this,he,"m",as).call(this,a);if(r.controller.signal?.aborted)throw new Re;return this._addRun(R(this,he,"m",os).call(this))}toReadableStream(){return new Ye(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,r,a){const o=new We;return o._run(()=>o._runToolAssistantStream(e,t,s,r,{...a,headers:{...a?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,s,r,a){const o=a?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const l={...r,stream:!0},c=await e.submitToolOutputs(t,s,l,{...a,signal:this.controller.signal});this._connected();for await(const d of c)R(this,he,"m",as).call(this,d);if(c.controller.signal?.aborted)throw new Re;return this._addRun(R(this,he,"m",os).call(this))}static createThreadAssistantStream(e,t,s){const r=new We;return r._run(()=>r._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,s,r){const a=new We;return a._run(()=>a._runAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return R(this,Js,"f")}currentRun(){return R(this,Hs,"f")}currentMessageSnapshot(){return R(this,ze,"f")}currentRunStepSnapshot(){return R(this,fs,"f")}async finalRunSteps(){return await this.done(),Object.values(R(this,Ge,"f"))}async finalMessages(){return await this.done(),Object.values(R(this,qs,"f"))}async finalRun(){if(await this.done(),!R(this,jt,"f"))throw Error("Final run was not received.");return R(this,jt,"f")}async _createThreadAssistantStream(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},o=await e.createAndRun(a,{...s,signal:this.controller.signal});this._connected();for await(const l of o)R(this,he,"m",as).call(this,l);if(o.controller.signal?.aborted)throw new Re;return this._addRun(R(this,he,"m",os).call(this))}async _createAssistantStream(e,t,s,r){const a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const o={...s,stream:!0},l=await e.create(t,o,{...r,signal:this.controller.signal});this._connected();for await(const c of l)R(this,he,"m",as).call(this,c);if(l.controller.signal?.aborted)throw new Re;return this._addRun(R(this,he,"m",os).call(this))}static accumulateDelta(e,t){for(const[s,r]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let a=e[s];if(a==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(In(a)&&In(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(o=>
135typeof o=="string"||typeof o=="number")){a.push(...r);continue}for(const o of r){if(!In(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);const l=o.index;if(l==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const c=a[l];c==null?a.push(o):a[l]=this.accumulateDelta(c,o)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${a}`);e[s]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,r){return await this._createAssistantStream(t,e,s,r)}async _runToolAssistantStream(e,t,s,r,a){return await this._createToolAssistantStream(s,e,t,r,a)}}as=function(e){if(!this.ended)switch(Ne(this,Js,e,"f"),R(this,he,"m",zi).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":R(this,he,"m",qi).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":R(this,he,"m",Ui).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":R(this,he,"m",Fi).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},os=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");if(!R(this,jt,"f"))throw Error("Final run has not been received");return R(this,jt,"f")},Fi=function(e){const[t,s]=R(this,he,"m",Vi).call(this,e,R(this,ze,"f"));Ne(this,ze,t,"f"),R(this,qs,"f")[t.id]=t;for(const r of s){const a=t.content[r.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,o=t.content[r.index];if(o&&o.type=="text")this._emit("textDelta",a,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=R(this,Mt,"f")){if(R(this,vt,"f"))switch(R(this,vt,"f").type){case"text":this._emit("textDone",R(this,vt,"f").text,R(this,ze,"f"));break;case"image_file":this._emit("imageFileDone",R(this,vt,"f").image_file,R(this,ze,"f"));break}Ne(this,Mt,r.index,"f")}Ne(this,vt,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(R(this,Mt,"f")!==void 0){const r=e.data.content[R(this,Mt,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,R(this,ze,"f"));break;case"text":this._emit("textDone",r.text,R(this,ze,"f"));break}}R(this,ze,"f")&&this._emit("messageDone",e.data),Ne(this,ze,void 0,"f")}},Ui=function(e){const t=R(this,he,"m",Bi).call(this,e);switch(Ne(this,fs,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of s.step_details.tool_calls)a.index==R(this,Zs,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(R(this,Ee,"f")&&this._emit("toolCallDone",R(this,Ee,"f")),Ne(this,Zs,a.index,"f"),Ne(this,Ee,t.step_details.tool_calls[a.index],"f"),R(this,Ee,"f")&&this._emit("toolCallCreated",R(this,Ee,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Ne(this,fs,void 0,"f"),e.data.step_details.type=="tool_calls"&&R(this,Ee,"f")&&(this._emit("toolCallDone",R(this,Ee,"f")),Ne(this,Ee,void 0,"f")),this._emit("runStepDone",e.data,t);break}},zi=function(e){R(this,mr,"f").push(e),this._emit("event",e)},Bi=function(e){switch(e.event){case"thread.run.step.created":return R(this,Ge,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=R(this,Ge,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=We.accumulateDelta(t,s.delta);R(this,Ge,"f")[e.data.id]=r}return R(this,Ge,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":R(this,Ge,"f")[e.data.id]=e.data;break}if(R(this,Ge,"f")[e.data.id])return R(this,Ge,"f")[e.data.id];throw new Error("No snapshot available")},Vi=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with
135no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const a of r.delta.content)if(a.index in t.content){let o=t.content[a.index];t.content[a.index]=R(this,he,"m",Wi).call(this,a,o)}else t.content[a.index]=a,s.push(a);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Wi=function(e,t){return We.accumulateDelta(t,e)},qi=function(e){switch(Ne(this,Hs,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":Ne(this,jt,e.data,"f"),R(this,Ee,"f")&&(this._emit("toolCallDone",R(this,Ee,"f")),Ne(this,Ee,void 0,"f"));break}};class $r extends X{create(e,t,s){return this._client.post(`/threads/${e}/messages`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/threads/${e}/messages/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}update(e,t,s,r){return this._client.post(`/threads/${e}/messages/${t}`,{body:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t={},s){return ue(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Tr,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t,s){return this._client.delete(`/threads/${e}/messages/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Tr extends _e{}$r.MessagesPage=Tr;class Rr extends X{retrieve(e,t,s,r={},a){return ue(r)?this.retrieve(e,t,s,{},r):this._client.get(`/threads/${e}/runs/${t}/steps/${s}`,{query:r,...a,headers:{"OpenAI-Beta":"assistants=v2",...a?.headers}})}list(e,t,s={},r){return ue(s)?this.list(e,t,{},s):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Ir,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class Ir extends _e{}Rr.RunStepsPage=Ir;class js extends X{constructor(){super(...arguments),this.steps=new Rr(this._client)}
135create(e,t,s){const{include:r,...a}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:r},body:a,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:t.stream??!1})}retrieve(e,t,s){return this._client.get(`/threads/${e}/runs/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}update(e,t,s,r){return this._client.post(`/threads/${e}/runs/${t}`,{body:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t={},s){return ue(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Or,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}cancel(e,t,s){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(e,r.id,s)}createAndStream(e,t,s){return We.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const r={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const{data:a,response:o}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...r}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const c=o.headers.get("openai-poll-after-ms");if(c){const d=parseInt(c);isNaN(d)||(l=d)}}await bs(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,s){return We.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s,r){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:s.stream??!1})}async submitToolOutputsAndPoll(e,t,s,r){const a=await this.submitToolOutputs(e,t,s,r);return await this.poll(e,a.id,r)}submitToolOutputsStream(e,t,s,r){return We.createToolAssistantStream(e,t,this._client.beta.threads.runs,s,r)}}class Or extends _e{}js.RunsPage=Or;js.Steps=Rr;js.RunStepsPage=Ir;class Kt extends X{constructor(){super(...arguments),this.runs=new js(this._client),this.messages=new $r(this._client)}create(e={},t){return ue(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,s){return this._client.post(`/threads/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.thread_id,s.id,t)}createAndRunStream(e,t){return We.createThreadAssistantStream(e,this._client.beta.threads,t)}}Kt.Runs=js;Kt.RunsPage=Or;Kt.Messages=$r;Kt.MessagesPage=Tr;class Xt extends X{constructor(){super(...arguments),this.realtime=new gn(this._client),this.chat=new fr(this._client),this.assistants=new Sr(this._client),this.threads=new Kt(this._client)}}Xt.Realtime=gn;Xt.Assistants=Sr;Xt.AssistantsPage=Pr;Xt.Threads=Kt;class Do extends X{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Mo extends X{create(e,t){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&ct("Request","User defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return s?a:(ct("response","Decoding base64 embeddings to float32 array"),a._thenUnwrap(o=>(o&&o.data&&o.data.forEach(l=>{const c=l.embedding;l.embedding=rf(c)}),o)))}}let Dr=class extends X{create(e,t){return this._client.post("/files",qt({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return ue(e)?this.list({},e):this._client.getAPIList("/files",Mr,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}
135retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=30*60*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let o=await this.retrieve(e);for(;!o.status||!r.has(o.status);)if(await bs(t),o=await this.retrieve(e),Date.now()-a>s)throw new _r({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return o}};class Mr extends _e{}Dr.FileObjectsPage=Mr;class Lr extends X{list(e,t={},s){return ue(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Fr,{query:t,...s})}}class Fr extends _e{}Lr.FineTuningJobCheckpointsPage=Fr;class Gt extends X{constructor(){super(...arguments),this.checkpoints=new Lr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return ue(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Ur,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return ue(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,zr,{query:t,...s})}}class Ur extends _e{}class zr extends _e{}Gt.FineTuningJobsPage=Ur;Gt.FineTuningJobEventsPage=zr;Gt.Checkpoints=Lr;Gt.FineTuningJobCheckpointsPage=Fr;class ks extends X{constructor(){super(...arguments),this.jobs=new Gt(this._client)}}ks.Jobs=Gt;ks.FineTuningJobsPage=Ur;ks.FineTuningJobEventsPage=zr;class Lo extends X{createVariation(e,t){return this._client.post("/images/variations",qt({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",qt({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Br extends X{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Vr,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Vr extends jr{}Br.ModelsPage=Vr;class Fo extends X{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function xf(n,e){return!e||!bf(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(s=>({...s,parsed:null}))}:t)}:Uo(n,e)}function Uo(n,e){const t=n.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:jf(e,r)};if(r.type==="message"){const a=r.content.map(o=>o.type==="output_text"?{...o,parsed:yf(e,o.text)}:o);return{...r,content:a}}return r}),s=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||zo(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),s}function yf(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function bf(n){return!!Cr(n.text?.format)}function vf(n){return n?.$brand==="auto-parseable-tool"}function _f(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function jf(n,e){const t=_f(n.tools??[],e.name);return{...e,...e,parsed_arguments:vf(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function zo(n){const e=[];for(const t of n.output)if(t.type==="message")for(const s of t.content)s.type==="output_text"&&e.push(s.text);n.output_text=e.join("")}class Bo extends X{list(e,t={},s){return ue(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Nf,{query:t,...s})}}var At=function(n,e,t,s,r){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},st=function(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)},$t,Ms,nt,Ls,Ji,Hi,Ki,Xi;
135class Wr extends Er{constructor(e){super(),$t.add(this),Ms.set(this,void 0),nt.set(this,void 0),Ls.set(this,void 0),At(this,Ms,e,"f")}static createResponse(e,t,s){const r=new Wr(t);return r._run(()=>r._createResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createResponse(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),st(this,$t,"m",Ji).call(this);const a=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const o of a)st(this,$t,"m",Hi).call(this,o);if(a.controller.signal?.aborted)throw new Re;return st(this,$t,"m",Ki).call(this)}[(Ms=new WeakMap,nt=new WeakMap,Ls=new WeakMap,$t=new WeakSet,Ji=function(){this.ended||At(this,nt,void 0,"f")},Hi=function(t){if(this.ended)return;const s=st(this,$t,"m",Xi).call(this,t);switch(this._emit("event",t),t.type){case"response.output_text.delta":{const r=s.output[t.output_index];if(!r)throw new D(`missing output at index ${t.output_index}`);if(r.type==="message"){const a=r.content[t.content_index];if(!a)throw new D(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new D(`expected content to be 'output_text', got ${a.type}`);this._emit("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{const r=s.output[t.output_index];if(!r)throw new D(`missing output at index ${t.output_index}`);r.type==="function_call"&&this._emit("response.function_call_arguments.delta",{...t,snapshot:r.arguments});break}default:this._emit(t.type,t);break}},Ki=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");const t=st(this,nt,"f");if(!t)throw new D("request ended without sending any events");At(this,nt,void 0,"f");const s=kf(t,st(this,Ms,"f"));return At(this,Ls,s,"f"),s},Xi=function(t){let s=st(this,nt,"f");if(!s){if(t.type!=="response.created")throw new D(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return s=At(this,nt,t.response,"f"),s}switch(t.type){case"response.output_item.added":{s.output.push(t.item);break}case"response.content_part.added":{const r=s.output[t.output_index];if(!r)throw new D(`missing output at index ${t.output_index}`);r.type==="message"&&r.content.push(t.part);break}case"response.output_text.delta":{const r=s.output[t.output_index];if(!r)throw new D(`missing output at index ${t.output_index}`);if(r.type==="message"){const a=r.content[t.content_index];if(!a)throw new D(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new D(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const r=s.output[t.output_index];if(!r)throw new D(`missing output at index ${t.output_index}`);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.completed":{At(this,nt,t.response,"f");break}}return s},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,o)=>t.push({resolve:a,reject:o})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=st(this,Ls,"f");if(!e)throw new D("stream ended without producing a ChatCompletion");return e}}function kf(n,e){return xf(n,e)}class qr extends X{constructor(){super(...arguments),this.inputItems=new Bo(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&zo(s),s))}retrieve(e,t={},s){return ue(t)?this.retrieve(e,{},t):this._client.get(`/responses/${e}`,{query:t,...s})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>Uo(s,e))}stream(e,t){return Wr.createResponse(this._client,e,t)}}class Nf extends _e{}qr.InputItems=Bo;
135class Vo extends X{create(e,t,s){return this._client.post(`/uploads/${e}/parts`,qt({body:t,...s}))}}class Jr extends X{constructor(){super(...arguments),this.parts=new Vo(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(`/uploads/${e}/complete`,{body:t,...s})}}Jr.Parts=Vo;const Sf=async n=>{const e=await Promise.allSettled(n),t=e.filter(r=>r.status==="rejected");if(t.length){for(const r of t)console.error(r.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const s=[];for(const r of e)r.status==="fulfilled"&&s.push(r.value);return s};class wn extends X{create(e,t,s){return this._client.post(`/vector_stores/${e}/files`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/vector_stores/${e}/files/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}update(e,t,s,r){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t={},s){return ue(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,xn,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t,s){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(e,r.id,s)}async poll(e,t,s){const r={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const a=await this.retrieve(e,t,{...s,headers:r}).withResponse(),o=a.data;switch(o.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const c=a.response.headers.get("openai-poll-after-ms");if(c){const d=parseInt(c);isNaN(d)||(l=d)}}await bs(l);break;case"failed":case"completed":return o}}}async upload(e,t,s){const r=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,t,s){const r=await this.upload(e,t,s);return await this.poll(e,r.id,s)}content(e,t,s){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Hr,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class xn extends _e{}class Hr extends jr{}wn.VectorStoreFilesPage=xn;wn.FileContentResponsesPage=Hr;class Wo extends X{create(e,t,s){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}cancel(e,t,s){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async createAndPoll(e,t,s){const r=await this.create(e,t);return await this.poll(e,r.id,s)}listFiles(e,t,s={},r){return ue(s)?this.listFiles(e,t,{},s):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,xn,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async poll(e,t,s){const r={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const{data:a,response:o}=await this.retrieve(e,t,{...s,headers:r}).withResponse();switch(a.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const c=o.headers.get("openai-poll-after-ms");if(c){const d=parseInt(c);isNaN(d)||(l=d)}}await bs(l);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},r){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=r?.maxConcurrency??5,o=Math.min(a,t.length),l=this._client,c=t.values(),d=[...s];async function u(f){for(let p of f){const g=await l.files.create({file:p,purpose:"assistants"},r);d.push(g.id)}}const m=Array(o).fill(c).map(u);return await Sf(m),await this.createAndPoll(e,{file_ids:d})}}class ht extends X{constructor(){super(...arguments),this.files=new wn(this._client),this.fileBatches=new Wo(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}
135update(e,t,s){return this._client.post(`/vector_stores/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e={},t){return ue(e)?this.list({},e):this._client.getAPIList("/vector_stores",Kr,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,s){return this._client.getAPIList(`/vector_stores/${e}/search`,Xr,{body:t,method:"post",...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Kr extends _e{}class Xr extends jr{}ht.VectorStoresPage=Kr;ht.VectorStoreSearchResponsesPage=Xr;ht.Files=wn;ht.VectorStoreFilesPage=xn;ht.FileContentResponsesPage=Hr;ht.FileBatches=Wo;var qo;class V extends Jh{constructor({baseURL:e=Ts("OPENAI_BASE_URL"),apiKey:t=Ts("OPENAI_API_KEY"),organization:s=Ts("OPENAI_ORG_ID")??null,project:r=Ts("OPENAI_PROJECT_ID")??null,...a}={}){if(t===void 0)throw new D("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:t,organization:s,project:r,...a,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&sf())throw new D(`It looks like you're running in a browser-like environment. 136 137This is disabled by default, as it risks exposing your secret API credentials to attackers. 138If you understand the risks and have appropriate mitigations in place, 139you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g., 140 141new OpenAI({ apiKey, dangerouslyAllowBrowser: true }); 142 143https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety 144`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new Do(this),this.chat=new pn(this),this.embeddings=new Mo(this),this.files=new Dr(this),this.images=new Lo(this),this.audio=new vs(this),this.moderations=new Fo(this),this.models=new Br(this),this.fineTuning=new ks(this),this.vectorStores=new ht(this),this.beta=new Xt(this),this.batches=new kr(this),this.uploads=new Jr(this),this.responses=new qr(this),this._options=o,this.apiKey=t,this.organization=s,this.project=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Eh(e,{arrayFormat:"brackets"})}}qo=V;V.OpenAI=qo;V.DEFAULT_TIMEOUT=6e5;V.OpenAIError=D;V.APIError=me;V.APIConnectionError=cn;V.APIConnectionTimeoutError=_r;V.APIUserAbortError=Re;V.NotFoundError=qa;V.ConflictError=Ja;V.RateLimitError=Ka;V.BadRequestError=Ba;V.AuthenticationError=Va;V.InternalServerError=Xa;V.PermissionDeniedError=Wa;V.UnprocessableEntityError=Ha;V.toFile=to;V.fileFromPath=Fa;V.Completions=Do;V.Chat=pn;V.ChatCompletionsPage=mn;V.Embeddings=Mo;V.Files=Dr;V.FileObjectsPage=Mr;V.Images=Lo;V.Audio=vs;V.Moderations=Fo;V.Models=Br;V.ModelsPage=Vr;V.FineTuning=ks;V.VectorStores=ht;V.VectorStoresPage=Kr;V.VectorStoreSearchResponsesPage=Xr;V.Beta=Xt;V.Batches=kr;V.BatchesPage=Nr;V.Uploads=Jr;V.Responses=qr;let Un=null;const Jo=()=>{const n="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";return Un||(Un=new V({apiKey:n,dangerouslyAllowBrowser:!0})),Un},Pf=n=>n.map(e=>{if(typeof e.content=="string")return{role:e.role,content:e.content};const t=e.content.map(s=>{if(s.type==="text")return s;if(s.type==="image_url"){const r=s;let a=r.image_url.url;return a.startsWith("/")?(console.log(`AI Assistant: Converting relative URL ${a} to an absolute URL`),a=window.location.origin+a,console.log(`- Using host origin: ${a}`),console.log(`- Final URL being sent: ${a}`)):console.log(`AI Assistant: Using provided absolute URL: ${a}`),{type:"image_url",image_url:{url:a,detail:r.image_url.detail||"high"}}}return s}
144).filter(Boolean);return{role:e.role,content:t}}),Ef=async n=>{const e=Jo();if(!e)throw new Error("OpenAI API is not initialized. Please check your API key.");const t={role:"system",content:`You are the sizing assistant for Rosys Patterns, helping customers find the right size for their purchased patterns. 145 146Focus only on recommending the most appropriate size based on the customer's measurements for Rosys Patterns products. Do not mention other brands or general pattern advice. 147 148Return your response as a JSON object in this exact format: 149{ 150 "recommendedSize": "The exact size recommendation (XS, S, M, L, XL, etc.)", 151 "additionalNote": "A single brief sentence with a specific fit tip related to their measurements (optional)" 152} 153 154Be concise and direct. The customer has already purchased the pattern and only needs to know which size to use.`},s=Pf(n.slice(1)),r=[t,...s];console.log("AI Assistant: Full request payload:"),console.log(`System message: ${t.content}`),console.log(`User messages count: ${s.length}`),s.forEach((l,c)=>{console.log(`Message ${c+1} role: ${l.role}`),typeof l.content=="string"?console.log(`Message ${c+1} content: ${l.content.substring(0,100)}...`):Array.isArray(l.content)&&(console.log(`Message ${c+1} content elements: ${l.content.length}`),l.content.forEach((d,u)=>{typeof d=="string"?console.log(` Content part ${u+1}: text string`):typeof d=="object"&&"type"in d&&(console.log(` Content part ${u+1}: ${d.type}`),d.type==="image_url"&&"image_url"in d&&(console.log(` Image URL: ${d.image_url.url}`),console.log(` Detail level: ${d.image_url.detail||"auto"}`)))}))});const a=await e.chat.completions.create({model:"gpt-4o",messages:r,temperature:.7,max_tokens:200,response_format:{type:"json_object"}});console.log("AI Assistant: Received response:",JSON.stringify(a.choices[0]?.message,null,2));const o=a.choices[0]?.message?.content||'{"recommendedSize": "M", "additionalNote": "Consider taking in the waist for a better fit."}';try{const l=JSON.parse(o);let c=`Based on your measurements, we recommend size **${l.recommendedSize}** for your Rosys Patterns Bell Sleeve Dress.`;return l.additionalNote&&(c+=` 155 156${l.additionalNote}`),c}catch(l){return console.error("Error parsing response as JSON:",l),o}},es=async(n,e)=>{try{const t=ut.getState().trackInteraction;typeof t=="function"&&await t(n,e)}catch(t){console.log("Error in safe interaction tracking:",t)}},Cf=({size:n="medium",variant:e="dark",withText:t=!0})=>{const s={small:"h-8 w-8",medium:"h-10 w-10",large:"h-14 w-14"},r={small:"text-lg",medium:"text-xl",large:"text-2xl"};return i.jsxs(S.div,{className:"flex items-center",initial:{opacity:0}
156,animate:{opacity:1},transition:{duration:.3},children:[i.jsx("div",{className:`relative ${s[n]}`,children:i.jsx("img",{src:"/logowhite.png",alt:"Rosy's Patterns",className:`${s[n]} object-contain`})}),t&&i.jsx(S.div,{className:"ml-2.5",initial:{opacity:0,x:-5},animate:{opacity:1,x:0},transition:{duration:.3,delay:.1},children:i.jsx("span",{className:`font-semibold ${r[n]} ${e==="light"?"text-white":"text-gray-900"}`,children:"Rosy's Patterns"})})]})};function Af(){const[n,e]=v.useState({width:typeof window<"u"?window.innerWidth:0,height:typeof window<"u"?window.innerHeight:0}),[t,s]=v.useState("mobile");return v.useEffect(()=>{function r(){e({width:window.innerWidth,height:window.innerHeight}),window.innerWidth<768?s("mobile"):window.innerWidth<1024?s("tablet"):s("desktop")}return window.addEventListener("resize",r),r(),()=>window.removeEventListener("resize",r)},[]),{windowSize:n,deviceType:t,isMobile:t==="mobile",isTablet:t==="tablet",isDesktop:t==="desktop"}}function $f(){const[n,e]=v.useState(!1);return v.useEffect(()=>{const t=navigator.userAgent||navigator.vendor||window.opera,s=/Mac|iPhone|iPod|iPad/.test(t);e(s)},[]),n}const Tf=[{id:"bell_sleeve",name:"Bell Sleeve Dress",image:"https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/sizing/bellsleevedress/bellsleevedressimage.jpeg",patternSni
156ppetUrl:"https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/sizing/bellsleevedress/bellsleevepatternsnippet.png",finishedMeasurementsImage:"https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/sizing/bellsleevedress/finisheddressmeasurements.jpeg",bodyMeasurementsImage:"https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/sizing/bellsleevedress/ProviderBodyMeasurementsofModel.jpeg",patternSheets:["https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/sizing/bellsleevedress/patternbellsleeveA0-1.png","https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/sizing/bellsleevedress/patternbellsleeveA0-2.png","https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/sizing/bellsleevedress/patternbellsleeveA0-3.png"]}],Fs={hidden:{opacity:0},visible:{opacity:1,transition:{duration:.2}},exit:{opacity:0,transition:{duration:.1}}},Tt={hidden:{opacity:0},visible:{opacity:1,transition:{duration:.2}},rest:{opacity:1},hover:{opacity:1,transition:{duration:.1}},tap:{opacity:1,transition:{duration:.05}}},Rf=()=>{const{trackInteraction:n}=ut(),{isDesktop:e,isMobile:t}=Af(),s=$f(),[r,a]=v.useState(!1),[o,l]=v.useState(""),[c,d]=v.useState(!1),[u,m]=v.useState(""),[f,p]=v.useState(1),[g,w]=v.useState(null),[y,N]=v.useState({bust:"",waist:"",hips:"",height:""}),[_,L]=v.useState("cm"),[T,B]=v.useState(""),[Y,K]=v.useState(!1),[Q,ee]=v.useState("Initializing..."),[W,J]=v.useState(""),[le,re]=v.useState(!1),[Ae,ne]=v.useState([]),$e=v.useRef(null),[ge,Oe]=v.useState([{role:"system",content:"You are the sizing assistant for Rosys Patterns. Help customers find the correct size for their purchased Rosys Patterns sewing patterns based on their measurements. Be concise and focus only on size recommendation."}]);v.useEffect(()=>{sessionStorage.getItem("size_assistant_authenticated")==="true"&&a(!0);const x=Jo();ee(x?"GPT-4o":"Simulation Mode (No API Key)")},[]),v.useEffect(()=>{const h=console.log,x=console.error;console.log=(...b)=>{h(...b),b[0]?.toString().includes("AI Assistant:")&&ne(P=>[...P,b.join(" ")])},console.error=(...b)=>{x(...b),ne(P=>[...P,`ERROR: ${b.join(" ")}`])};const A=b=>{b.ctrlKey&&b.shiftKey&&b.key==="D"&&(b.preventDefault(),re(P=>!P))};return window.addEventListener("keydown",A),()=>{console.log=h,console.error=x,window.removeEventListener("keydown",A)}},[]);const De=(h,x)=>{N(A=>({...A,[h]:x}))},je=h=>{if(!h||h==="")return"";const x=parseFloat(h);return isNaN(x)?"":(x/2.54).toFixed(1)},we=h=>{if(!h||h==="")return"";const x=parseFloat(h);return isNaN(x)?"":(x*2.54).toFixed(1)},qe=()=>{const h=_==="cm"?"inches":"cm";N(h==="inches"?{bust:je(y.bust),waist:je(y.waist),hips:je(y.hips),height:je(y.height)}:{bust:we(y.bust),waist:we(y.waist),hips:we(y.hips),height:we(y.height)}),L(h)},Me=h=>{w(h),es("pattern_selected",{pattern_id:h.id,pattern_name:h.name})},F=()=>{f===1&&!g||f===2&&(!y.bust||!y.waist||!y.hips||!y.height)||f===3&&!T||(p(h=>h+1),f===3&&ie())},U=()=>{p(h=>Math.max(1,h-1))},xe=()=>{p(1),w(null),N({bust:"",waist:"",hips:"",height:""}),B(""),J("")},ie=async()=>{if(!g){J("Please select a pattern first.");return}if(!y.bust||!y.waist||!y.hips||!y.height){J("Please provide all your measurements.");return}K(!0),J("");try{es("size_recommendation_requested",{pattern:g.id});const h=`I need help determining my size for the ${g.name} pattern. 157 158My measurements are: 159- Bust: ${y.bust} ${_} 160- Waist: ${y.waist} ${_} 161- Hip: ${y.hips} ${_} 162- Height: ${y.height} ${_} 163 164${T?`I usually wear a size ${T}.`:""} 165 166Please examine all the pattern images carefully. The pattern sheets and finished measurements image contain the actual size chart and measurements of the pattern pieces. Look at how the measurements in these images compare to my measurements above. 167 168I need the most accurate size recommendation - this could be XXS, XS, S, M, L, XL, or XXL depending on the actual pattern measurements shown in the images, not just general sizing guidelines. 169 170Important: My usual clothing size (${T||""}) can be a helpful reference, but sewing pattern sizes often differ from retail sizing. 171 172Based on these measurements and the pattern information in the images, what size of the ${g.n
172ame} would fit me best? 173 174Return your response in this format: "Based on your measurements, we recommend size **SIZE** for your Rosys Patterns ${g.name}. [Include any fit advice here if relevant]."`;console.log("Sending prompt:",h),console.log("Adding pattern images to request");const x=[{type:"text",text:h}];g&&(console.log("Adding all pattern images for:",g.name),g.image&&(console.log("Adding main pattern image:",g.image),x.push({type:"image_url",image_url:{url:g.image,detail:"high"}})),g.patternSnippetUrl&&(console.log("Adding pattern snippet:",g.patternSnippetUrl),x.push({type:"image_url",image_url:{url:g.patternSnippetUrl,detail:"high"}})),g.finishedMeasurementsImage&&(console.log("Adding finished measurements image:",g.finishedMeasurementsImage),x.push({type:"image_url",image_url:{url:g.finishedMeasurementsImage,detail:"high"}})),g.bodyMeasurementsImage&&(console.log("Adding body measurements image:",g.bodyMeasurementsImage),x.push({type:"image_url",image_url:{url:g.bodyMeasurementsImage,detail:"high"}})),g.patternSheets&&g.patternSheets.length>0?(console.log(`Adding ${g.patternSheets.length} pattern sheets:`),g.patternSheets.forEach((k,j)=>{console.log(`- Pattern sheet ${j+1}:`,k);const E=new Image;E.onload=()=>console.log(`Pattern sheet ${j+1} loaded successfully, dimensions: ${E.width}x${E.height}`),E.onerror=()=>console.error(`Error loading pattern sheet ${j+1}: ${k}`),E.src=k,x.push({type:"image_url",image_url:{url:k,detail:"high"}})})):console.log("No pattern sheets found to add"),console.log(`Total images being sent: ${x.length-1}`));const P=[{role:"system",content:`You are the sizing assistant for Rosys Patterns, helping customers find the right size for their purchased patterns. 175 176Recommend the most appropriate size based on the customer's measurements for Rosys Patterns sewing patterns. 177 178Prioritize the pattern's actual measurements shown in the pattern sheets and finished garment measurements images. Compare these closely with the customer's measurements. Someone who typically wears a certain size in retail brands might need a different size in sewing patterns. 179 180Be direct and specific with your size recommendation, including any relevant fit advice that might help the customer.`},{role:"user",content:x}];Oe(P);try{let k=await Ef(P);J(k),es("size_recommendation_received",{pattern:g.id,success:!0}),$e.current&&$e.current.scrollIntoView({behavior:"smooth"})}catch(k){console.error("Error generating AI response:",k);let j="Could not generate a size recommendation. ";k.message.includes("downloading")?(j+="There was an issue with one or more image files. ",k.message.includes("localhost")?j+="A local image URL cannot be accessed by the AI. All images must be publicly accessible.":j+="Please ensure all images are publicly accessible."):k.message.includes("API key")?j+="The OpenAI API key is missing or invalid. Please contact support.":k.message.includes("response_format")||k.message.includes("JSON")?j+="There was an issue with the response format. Please try again.":j+=k.message||"Unknown error occurred.",J(j),es("size_recommendation_error",{pattern:g?.id,error:k instanceof Error?k.message:String(k)})}}catch(h){console.error("Error generating size recommendation:",h),J("Sorry, I encountered an error while generating your size recommendation. Please try again."),es("size_recommendation_error",{pattern:g?.id,error:h instanceof Error?h.message:String(h)})}finally{K(!1)}},Te=h=>{h.preventDefault(),o==="Admin123!"?(a(!0),m(""),sessionStorage.setItem("size_assistant_authenticated","true"),n("size_assistant_password_success",{timestamp:new Date().toISOString()})):(m("Incorrect password. Please try again."),n("size_assistant_password_failed",{timestamp:new Date().toISOString()}))},ke=()=>{const h=v.useRef(null),x=A=>{l(A.target.value),setTimeout(()=>{h.current?.focus()},0)};return i.jsxs("div",{className:"h-full flex flex-col items-center justify-center px-4 py-8",children:[i.jsxs("div",{className:"w-full max-w-md bg-white rounded-xl shadow-lg p-6 relative overflow-hidden",children:[i.jsxs("div",{className:"text-center mb-6",children:[i.jsx("div",{className:"bg-rose-500 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4",children:i.jsx(Us,{className:"w-8 h-8 text-white"})}),i.jsx("h2",{className:"text-xl font-bold text-gray-800",children:"Size Assistant"}),i.jsx("p",{className:"text-gray-600 mt-2",children:"This section contains pattern measurements. Please enter the password to continue."})]}),i.jsxs("form",{onSubmit:Te,className:"space-y-4",children:[i.jsxs("div",{className:"relative",children:[i.jsx("input",{ref:h,type:c?"text":"password",value:o,onChange:x,placeholder:"Enter password",className:"w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-rose-400 pr-10",autoComplete:"off",autoFocus:!0}),i.jsx("button",{type:"button",onClick:()=>d(!c),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-500",children:c?i.jsx(zn,{size:18}):i.jsx(Bn,{size:18})})]}),u&&i.jsx("p",{className:"text-red-500 text-sm",children:u}),i.jsx("button",{type:"submit",className:"w-full bg-rose-500 text-white py-3 rounded-lg font-medium hover:bg-rose-600 transition-colors",children:"Access Size Assistant"})]})]}),i.jsx("div",{className:"absolute inset-0 -z-10 overflow-hidden blur-md opacity-30",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4",children:[i.jsx("div",{className:"bg-white rounded-xl overflow-hidden shadow-md",children:i.jsx("div",{className:"bg-rose-100 h-40"})}),i.jsx("div",{className:"bg-white rounded-xl overflow-hidden shadow-md",children:i.jsx("div",{className:"bg-rose-200 h-40"})}),i.jsx("div",{className:"bg-white rounded-xl overflow-hidden shadow-md",children:i.jsx("div",{className:"bg-rose-300 h-40"})}),i.jsx("div",{className:"bg-white rounded-xl overflow-hidden shadow-md",children:i.jsx("div",{className:"bg-rose-400 h-40"})})]})})]})},Le=()=>i.jsxs(S.div,{className:"w-full space-y-8",variants:Fs,initial:"hidden",animate:"visible",exit:"exit",children:[i.jsxs("div",{className:"text-center mb-8",children:[i.jsx(S.h2,{className:"text-2xl font-semibold mb-3 text-gray-800",initial:{opacity:0,y:-10}
180,animate:{opacity:1,y:0},transition:{delay:.1},children:"Select Your Pattern"}),i.jsx(S.p,{className:"text-gray-600 mb-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},children:"Choose the pattern you'd like to get sizing for"}),i.jsx(S.div,{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-gray-700",initial:{opacity:0},animate:{opacity:1},transition:{delay:.3},children:"We have collected feedback from many customers so we can give you more accurate size information with our tool than the standard size chart."})]}),i.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:Tf.map((h,x)=>i.jsxs(S.div,{className:`relative rounded-xl overflow-hidden shadow-sm ${g?.id===h.id?"ring-3 ring-blue-400 ring-offset-2":"border border-gray-100 hover:border-blue-200"} transition-all duration-200 cursor-pointer`,variants:Tt,initial:"rest",whileHover:"hover",whileTap:"tap",custom:x,animate:g?.id===h.id?"hover":"rest",onClick:()=>Me(h),children:[i.jsxs("div",{className:"aspect-square relative bg-gray-100",children:[i.jsx("img",{src:h.image,alt:h.name,className:"w-full h-full object-cover",loading:"lazy",decoding:"async",style:{objectPosition:"center center",maxWidth:"100%",height:"auto"},onError:A=>{A.currentTarget.src="https://lahzrlyhojyfadjasdrc.supabase.co/storage/v1/object/public/sizing/bellsleevedress/bellsleevedressimage.jpeg"}}),g?.id===h.id&&i.jsx(S.div,{className:"absolute top-2 right-2 bg-blue-500 text-white rounded-full p-1.5 shadow-lg z-10",initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:400,damping:15},children:i.jsx(ti,{size:16})}),i.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 hover:opacity-100 transition-opacity duration-300"})]}),i.jsxs("div",{className:"p-3 bg-white",children:[i.jsx("h3",{className:"font-medium text-sm text-gray-900 leading-tight",children:h.name}),i.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Tap to select"})]})]},h.id))})]}),ft=()=>i.jsxs(S.div,{className:"w-full space-y-6",variants:Fs,initial:"hidden",animate:"visible",exit:"exit",children:[i.jsxs("div",{className:"text-center mb-6",children:[i.jsx(S.h2,{className:"text-2xl font-semibold mb-3 text-gray-800",initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:.1},children:"Your Measurements"}),i.jsx(S.p,{className:"text-gray-600 mb-3",initial:{opacity:0}
180,animate:{opacity:1},transition:{delay:.2},children:"Enter your body measurements"}),i.jsxs(S.a,{href:"https://www.youtube.com/watch?v=3ZSfY87v6pM",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-blue-600 text-sm font-medium hover:text-blue-700 transition-colors bg-blue-50 hover:bg-blue-100 px-3 py-2 rounded-lg border border-blue-200",initial:{opacity:0},animate:{opacity:1},transition:{delay:.3},children:[i.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{d:"M21 3H3c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h5v2h8v-2h5c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 12H3V5h18v10zm-5-6l-7 4V9l7 4z"})}),"ð¹ Watch: How to take measurements correctly"]})]}),i.jsx("div",{className:"flex justify-end mb-4",children:i.jsxs(S.button,{onClick:qe,className:"inline-flex items-center gap-1.5 bg-white shadow-sm hover:shadow px-4 py-2 rounded-full text-sm font-medium text-blue-600 transition-all border border-blue-100",children:[i.jsx(qn,{size:16}),_==="cm"?"Switch to inches":"Switch to cm"]})}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs(S.div,{className:"space-y-2",variants:Tt,initial:"hidden",animate:"visible",transition:{delay:.1},children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 ml-1",children:"Bust"}),i.jsxs("div",{className:"relative shadow-sm",children:[i.jsx("input",{type:t?"number":"text",inputMode:"decimal",value:y.bust||"",onChange:h=>De("bust",h.target.value),className:"block w-full px-3 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all outline-none text-center text-base shadow-sm",placeholder:`Bust (${_})`,step:"0.1",min:"0"}),i.jsx("div",{className:"absolute inset-y-0 right-3 flex items-center pointer-events-none",children:i.jsx("span",{className:"text-gray-500 text-sm",children:_})})]})]}),i.jsxs(S.div,{className:"space-y-2",variants:Tt,initial:"hidden",animate:"visible",transition:{delay:.2},children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 ml-1",children:"Waist"}),i.jsxs("div",{className:"relative shadow-sm",children:[i.jsx("input",{type:t?"number":"text",inputMode:"decimal",value:y.waist||"",onChange:h=>De("waist",h.target.value),className:"block w-full px-3 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all outline-none text-center text-base shadow-sm",placeholder:`Waist (${_})`,step:"0.1",min:"0"}),i.jsx("div",{className:"absolute inset-y-0 right-3 flex items-center pointer-events-none",children:i.jsx("span",{className:"text-gray-500 text-sm",children:_})})]})]}),i.jsxs(S.div,{className:"space-y-2",variants:Tt,initial:"hidden",animate:"visible",transition:{delay:.3},children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 ml-1",children:"Hip"}),i.jsxs("div",{className:"relative shadow-sm",children:[i.jsx("input",{type:t?"number":"text",inputMode:"decimal",value:y.hips||"",onChange:h=>De("hips",h.target.value),className:"block w-full px-3 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all outline-none text-center text-base shadow-sm",placeholder:`Hip (${_})`,step:"0.1",min:"0"}),i.jsx("div",{className:"absolute inset-y-0 right-3 flex items-center pointer-events-none",children:i.jsx("span",{className:"text-gray-500 text-sm",children:_})})]})]}),i.jsxs(S.div,{className:"space-y-2",variants:Tt,initial:"hidden",animate:"visible",transition:{delay:.4},children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 ml-1",children:"Height"}),i.jsxs("div",{className:"relative shadow-sm",children:[i.jsx("input",{type:t?"number":"text",inputMode:"decimal",value:y.height||"",onChange:h=>De("height",h.target.value),className:"block w-full px-3 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all outline-none text-center text-base shadow-sm",placeholder:`Height (${_})`,step:"0.1",min:"0"}),i.jsx("div",{className:"absolute inset-y-0 right-3 flex items-center pointer-events-none",children:i.jsx("span",{className:"text-gray-500 text-sm",children:_})})]})]})]}),i.jsx(S.div,{className:"flex items-center justify-center pt-4",initial:{opacity:0}
180,animate:{opacity:1},transition:{delay:.5},children:i.jsxs("div",{className:"text-sm text-gray-600 flex items-center gap-2 bg-blue-50 py-2 px-4 rounded-lg",children:[i.jsx(si,{size:16,className:"text-blue-500"}),i.jsx("span",{children:"Measurements are used only for sizing recommendations"})]})})]}),mt=()=>i.jsxs(S.div,{className:"w-full space-y-8",variants:Fs,initial:"hidden",animate:"visible",exit:"exit",children:[i.jsxs("div",{className:"text-center mb-8",children:[i.jsx(S.h2,{className:"text-2xl font-semibold mb-3 text-gray-800",initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:.1},children:"Your Usual Size"}),i.jsx(S.p,{className:"text-gray-600",initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},children:"What size do you usually wear?"})]}),i.jsx(S.div,{className:"space-y-6",variants:Tt,initial:"hidden",animate:"visible",transition:{delay:.3},children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 ml-1",children:"Size"}),i.jsxs("div",{className:"relative shadow-sm",children:[i.jsxs("select",{value:T,onChange:h=>B(h.target.value),className:"block w-full px-4 py-3.5 border border-blue-200 rounded-xl focus:ring-2 focus:ring-blue-400 focus:border-blue-300 transition-all outline-none text-lg shadow-sm appearance-none bg-blue-50 text-gray-700",children:[i.jsx("option",{value:"",children:"Select your usual size"}),i.jsx("option",{value:"XXS",children:"XXS"}),i.jsx("option",{value:"XS",children:"XS"}),i.jsx("option",{value:"S",children:"S"}),i.jsx("option",{value:"M",children:"M"}),i.jsx("option",{value:"L",children:"L"}),i.jsx("option",{value:"XL",children:"XL"}),i.jsx("option",{value:"XXL",children:"XXL"})]}),i.jsx("div",{className:"absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none",children:i.jsx(dl,{className:"h-5 w-5 text-blue-400"})})]})]})}),i.jsx(S.div,{className:"flex items-center justify-center pt-6",initial:{opacity:0}
180,animate:{opacity:1},transition:{delay:.5},children:i.jsxs("div",{className:"text-sm text-gray-600 flex items-center gap-2 bg-blue-50 py-2 px-4 rounded-lg",children:[i.jsx(si,{size:16,className:"text-blue-500"}),i.jsx("span",{children:"This helps us calibrate your recommendation"})]})})]}),$=()=>{const x=(W.match(/\*\*([^*]+)\*\*/)?.[1]||W.match(/size ([A-Z]+)/i)?.[1]||"M").trim();let A="";const b=new RegExp(`\\*\\*${x}\\*\\*.*?\\.(.*?)$`,"s"),P=W.match(b);if(P&&P[1]&&(A=P[1].trim()),!A){const k=W.split(".");k.length>1&&(A=k.slice(1).join(".").trim())}return console.log("Size recommendation:",x),console.log("Fit advice extracted:",A),i.jsxs(S.div,{className:"w-full",variants:Fs,initial:"hidden",animate:"visible",exit:"exit",ref:$e,children:[i.jsxs("div",{className:"mb-8 text-center",children:[i.jsx(S.div,{className:"inline-flex justify-center items-center rounded-full bg-gradient-to-r from-blue-500 to-blue-600 p-4 mb-5 shadow-lg",initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",stiffness:260,damping:20,delay:.1},children:i.jsx(zt,{size:32,className:"text-white"})}),i.jsx(S.h2,{className:"text-2xl font-semibold mb-3 text-gray-800",initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{delay:.2},children:"Your Recommended Size"}),g&&i.jsx(S.p,{className:"text-rose-600 font-medium",initial:{opacity:0}
180,animate:{opacity:1},transition:{delay:.3},children:g.name})]}),Y?i.jsxs(S.div,{className:"flex flex-col items-center justify-center py-16",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[i.jsxs("div",{className:"relative w-16 h-16 mb-6",children:[i.jsx(ul,{className:"w-16 h-16 text-rose-400 animate-spin absolute"}),i.jsx(S.div,{className:"w-16 h-16 rounded-full border-4 border-rose-200",initial:{opacity:0},animate:{opacity:1},transition:{delay:.3}})]}),i.jsx("p",{className:"text-gray-600 text-lg",children:"Analyzing your measurements..."}),i.jsx(S.p,{className:"text-gray-500 mt-2 text-sm",initial:{opacity:0},animate:{opacity:1},transition:{delay:.6},children:"This may take a moment"})]}):i.jsxs(S.div,{className:"bg-white rounded-2xl border border-gray-200 shadow-lg overflow-hidden",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.4},children:[g&&i.jsx(S.div,{className:"w-full p-6 bg-gradient-to-r from-blue-50 to-blue-100 relative overflow-hidden border-b border-blue-200",initial:{opacity:0}
180,animate:{opacity:1},transition:{delay:.3},children:i.jsxs("div",{className:"flex items-center justify-between flex-wrap",children:[i.jsxs("div",{className:"w-full md:w-1/2 mb-4 md:mb-0 md:pr-6",children:[i.jsx("h3",{className:"text-lg font-medium text-gray-800 mb-2",children:"Pattern Preview"}),i.jsxs("p",{className:"text-sm text-gray-600",children:[g.name," - Your recommended size for this pattern"]})]}),i.jsx("div",{className:"w-full md:w-1/2 flex justify-center rounded-lg overflow-hidden bg-white shadow-sm border border-gray-100",children:i.jsx("img",{src:g.image,alt:`${g.name} Pattern`,className:"h-48 w-auto object-cover"})})]})}),i.jsxs("div",{className:"p-8",children:[i.jsxs(S.div,{className:"text-center",initial:{opacity:0},animate:{opacity:1},transition:{delay:.4},children:[i.jsx("h3",{className:"text-5xl font-bold text-blue-600 mb-6",children:x}),i.jsx("div",{className:"inline-flex gap-4 justify-center flex-wrap mb-6",children:["XXS","XS","S","M","L","XL","XXL"].map(k=>i.jsx("div",{className:`h-12 w-12 rounded-full flex items-center justify-center border-2 transition-all duration-300 ${k===x?"border-blue-500 bg-blue-50 text-blue-600 font-bold scale-110 shadow-md":"border-gray-200 text-gray-400"}`,children:k},k))})]}),A&&i.jsx(S.div,{className:"bg-green-50 rounded-xl p-5 border border-green-100 mb-8",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.5},children:i.jsxs("p",{className:"text-gray-700 text-center",children:[i.jsx("span",{className:"font-medium",children:"Fit advice: "}),A.charAt(0).toUpperCase()+A.slice(1)]})}),i.jsxs(S.div,{className:"space-y-4",initial:{opacity:0}
180,animate:{opacity:1},transition:{delay:.6},children:[i.jsx("h3",{className:"text-lg font-medium text-gray-800 mb-4",children:"Your Measurements"}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{className:"bg-gray-50 p-4 rounded-xl border border-gray-100 transition-all hover:border-blue-200 hover:bg-gray-100",children:[i.jsx("div",{className:"text-sm text-gray-500 mb-1",children:"Bust"}),i.jsxs("div",{className:"font-medium",children:[y.bust," ",_]})]}),i.jsxs("div",{className:"bg-gray-50 p-4 rounded-xl border border-gray-100 transition-all hover:border-blue-200 hover:bg-gray-100",children:[i.jsx("div",{className:"text-sm text-gray-500 mb-1",children:"Waist"}),i.jsxs("div",{className:"font-medium",children:[y.waist," ",_]})]}),i.jsxs("div",{className:"bg-gray-50 p-4 rounded-xl border border-gray-100 transition-all hover:border-blue-200 hover:bg-gray-100",children:[i.jsx("div",{className:"text-sm text-gray-500 mb-1",children:"Hip"}),i.jsxs("div",{className:"font-medium",children:[y.hips," ",_]})]}),i.jsxs("div",{className:"bg-gray-50 p-4 rounded-xl border border-gray-100 transition-all hover:border-blue-200 hover:bg-gray-100",children:[i.jsx("div",{className:"text-sm text-gray-500 mb-1",children:"Height"}),i.jsxs("div",{className:"font-medium",children:[y.height," ",_]})]})]})]}),T&&i.jsx(S.div,{className:"mt-8 bg-blue-50 p-4 rounded-xl border border-blue-100",initial:{opacity:0}
180,animate:{opacity:1},transition:{delay:.7},children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-sm text-gray-500 mb-1",children:"Usual Size"}),i.jsx("div",{className:"font-medium",children:T})]}),i.jsx("div",{className:"h-12 w-12 rounded-full flex items-center justify-center bg-white border border-blue-200 text-blue-600 font-semibold shadow-sm",children:T})]})}),i.jsx(S.div,{className:"mt-8 text-center",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:i.jsx("div",{className:"text-sm text-gray-500",children:"This recommendation is based on your measurements and the pattern specifications."})})]})]})]})},C=()=>{const h=f===1&&!g||f===2&&(!y.bust||!y.waist||!y.hips||!y.height)||f===3&&!T;return i.jsxs(S.div,{className:"flex justify-between items-center",initial:{opacity:0},animate:{opacity:1},transition:{delay:.5},children:[f>1?i.jsxs(S.button,{onClick:U,className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl border border-gray-200 hover:border-gray-300 backdrop-blur-sm bg-white/30 text-gray-700 font-medium transition-all shadow-md",whileHover:{x:-3,backgroundColor:"rgb(249, 250, 251, 0.8)",scale:1.01},whileTap:{scale:.98},children:[i.jsx(lt,{size:18}),i.jsx("span",{children:"Back"})]}):i.jsx("div",{}),f<4&&i.jsxs(S.button,{onClick:F,disabled:h,className:`inline-flex items-center gap-2 px-7 py-4 rounded-xl text-white font-medium transition-all ${h?"bg-gray-300 cursor-not-allowed shadow-sm":"bg-gradient-to-r from-blue-500 to-blue-600 hover:shadow-xl shadow-lg shadow-blue-500/20"}`,whileHover:h?{}:{x:3,scale:1.03},whileTap:h?{}:{scale:.98},children:[i.jsx("span",{className:"text-base",children:f===3?"Get Size":"Next"}),f===3?i.jsx(ti,{size:18}):i.jsx(Vn,{size:18})]})]})};return i.jsxs("div",{className:`bg-white min-h-screen relative ${s?"font-sf-pro":""}`,children:[r?i.jsxs(i.Fragment,{children:[i.jsx("header",{className:"px-6 pt-6 pb-4 flex justify-between items-center bg-gradient-to-r from-blue-50 to-white",children:i.jsx(Cf,{withText:!0,size:"medium"})}),i.jsx("div",{className:"px-6 py-4",children:i.jsxs("div",{className:"flex justify-between mb-4 max-w-md mx-auto",children:[i.jsxs("div",{className:"flex-1 flex items-center",children:[i.jsx("div",{className:`rounded-full w-8 h-8 flex items-center justify-center shadow-sm transition-all duration-300 ${f>=1?"bg-blue-500 text-white scale-110":"bg-gray-100 text-gray-400"}`,children:i.jsx(cl,{size:14})}),i.jsx("div",{className:`h-1 flex-grow mx-1 transition-all duration-500 ${f>1?"bg-blue-500":"bg-gray-200"}`})]}),i.jsxs("div",{className:"flex-1 flex items-center",children:[i.jsx("div",{className:`rounded-full w-8 h-8 flex items-center justify-center shadow-sm transition-all duration-300 ${f>=2?"bg-blue-500 text-white scale-110":"bg-gray-100 text-gray-400"}`,children:i.jsx(qn,{size:14})}),i.jsx("div",{className:`h-1 flex-grow mx-1 transition-all duration-500 ${f>2?"bg-blue-500":"bg-gray-200"}`})]}),i.jsxs("div",{className:"flex-1 flex items-center",children:[i.jsx("div",{className:`rounded-full w-8 h-8 flex items-center justify-center shadow-sm transition-all duration-300 ${f>=3?"bg-blue-500 text-white scale-110":"bg-gray-100 text-gray-400"}`,children:i.jsx(Yi,{size:14})}),i.jsx("div",{className:`h-1 flex-grow mx-1 transition-all duration-500 ${f>3?"bg-blue-500":"bg-gray-200"}`})]}),i.jsx("div",{className:"flex items-center",children:i.jsx("div",{className:`rounded-full w-8 h-8 flex items-center justify-center shadow-sm transition-all duration-300 ${f>=4?"bg-blue-500 text-white scale-110":"bg-gray-100 text-gray-400"}`,children:i.jsx(zt,{size:14})})})]})}),i.jsx("div",{className:`px-6 py-4 ${e?"max-w-xl":"max-w-md"} mx-auto ${f<4,"pb-32"}`,children:i.jsxs(Ce,{mode:"wait",children:[f===1&&Le(),f===2&&ft(),f===3&&mt(),f===4&&$()]})}),f<4&&i.jsx(S.div,{className:"fixed bottom-0 left-0 right-0 backdrop-blur-lg bg-gradient-to-t from-white/60 to-transparent shadow-lg px-6 py-4 z-10 pb-safe",style:{paddingBottom:"calc(env(safe-area-inset-bottom, 0px) + 1rem)"},initial:{opacity:0,y:20}
180,animate:{opacity:1,y:0},transition:{delay:.5},children:i.jsx("div",{className:`mx-auto ${e?"max-w-xl":"max-w-md"}`,children:C()})}),f===4&&i.jsx(S.div,{className:"fixed bottom-0 left-0 right-0 backdrop-blur-lg bg-gradient-to-t from-white/60 to-transparent shadow-lg px-6 py-4 z-10 pb-safe",style:{paddingBottom:"calc(env(safe-area-inset-bottom, 0px) + 1rem)"},initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5},children:i.jsx("div",{className:`mx-auto ${e?"max-w-xl":"max-w-md"}`,children:i.jsx(S.div,{className:"flex justify-center",children:i.jsxs(S.button,{onClick:xe,className:"py-3.5 px-7 rounded-xl bg-gradient-to-r from-blue-50 to-blue-100 hover:from-blue-100 hover:to-blue-200 text-blue-700 font-medium transition-all shadow-md w-full md:w-auto flex items-center justify-center gap-2",whileHover:{scale:1.02},whileTap:{scale:.98},children:[i.jsx(lt,{size:18}),i.jsx("span",{children:"Start Over"})]})})})})]}):i.jsx(ke,{}),le&&i.jsx(S.div,{className:"fixed inset-0 bg-black bg-opacity-80 z-50 overflow-auto p-4",initial:{opacity:0}
180,animate:{opacity:1},exit:{opacity:0},children:i.jsxs(S.div,{className:"bg-white rounded-2xl max-w-2xl mx-auto p-4 h-[90vh] overflow-auto",initial:{opacity:0,y:50},animate:{opacity:1,y:0},transition:{delay:.2},children:[i.jsxs("div",{className:"flex justify-between items-center mb-4 border-b pb-3",children:[i.jsx("h3",{className:"font-semibold text-lg",children:"Debug Mode"}),i.jsx("button",{onClick:()=>re(!1),className:"text-gray-500 hover:text-gray-700 bg-gray-100 rounded-full p-1.5",children:i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor",children:i.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]}),i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"space-y-2",children:[i.jsxs("h4",{className:"font-medium mb-1 flex items-center gap-2",children:[i.jsx("span",{className:"inline-block w-3 h-3 rounded-full bg-green-500"}),"Selected Model"]}),i.jsx("div",{className:"bg-gray-100 p-2.5 rounded-xl text-sm",children:Q})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("h4",{className:"font-medium mb-1 flex items-center gap-2",children:[i.jsx("span",{className:"inline-block w-3 h-3 rounded-full bg-blue-500"}),"Current State"]}),i.jsxs("div",{className:"bg-gray-100 p-2.5 rounded-xl space-y-2 text-sm",children:[i.jsxs("p",{children:["Authentication: ",r?"Yes":"No"]}),i.jsxs("p",{children:["Step: ",f]}),i.jsxs("p",{children:["Selected Pattern: ",g?.name||"None"]}),i.jsxs("p",{children:["Measurements:",y.bust?` Bust: ${y.bust}${_}`:" Not set",y.waist?` Waist: ${y.waist}${_}`:"",y.hips?` Hip: ${y.hips}${_}`:"",y.height?` Height: ${y.height}${_}`:""]}),i.jsxs("p",{children:["Usual Size: ",T||"Not set"]})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("h4",{className:"font-medium mb-1 flex items-center gap-2",children:[i.jsx("span",{className:"inline-block w-3 h-3 rounded-full bg-purple-500"}),"Debug Logs"]}),i.jsx("pre",{className:"bg-gray-900 text-green-400 p-3 rounded-xl text-xs overflow-auto max-h-[40vh] font-mono",children:Ae.length===0?i.jsx("span",{className:"text-gray-500",children:"No logs yet..."}):Ae.map((h,x)=>i.jsx("div",{className:"mb-1",children:h.includes("ERROR:")?i.jsx("span",{className:"text-red-400",children:h}):h},x))})]}),i.jsx("div",{className:"pt-2 border-t",children:i.jsx("button",{onClick:()=>re(!1),className:"w-full py-3 rounded-xl bg-gray-900 text-white font-medium",children:"Close Debug Panel"})})]})]})})]})},If=({onBack:n})=>{const e=[{month:"May",monthColor:"from-pink-500 to-pink-600",bgColor:"bg-pink-50",borderColor:"border-pink-200",textColor:"text-[#4a3f35]",winners:[{position:1,name:"sgolden",crown:!0},{position:2,name:"hannadealba",crown:!1},{position:3,name:"shanyholo",crown:!1}]},{month:"June",monthColor:"from-pink-500 to-pink-600",bgColor:"bg-pink-50",borderColor:"border-pink-200",textColor:"text-[#4a3f35]",winners:[{position:1,name:"klossiah",crown:!0},{position:2,name:"gilly",crown:!1},{position:3,name:"lonestrarry",crown:!1}]}];return i.jsxs("div",{className:"min-h-screen bg-[#f5f1eb] overflow-auto",children:[i.jsx("div",{className:"sticky top-0 z-10 bg-[#f5f1eb]/95 backdrop-blur-md border-b border-[#4a3f35]/10 safe-top",children:i.jsx("div",{className:"max-w-4xl mx-auto px-4 py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center space-x-4",children:[i.jsx("button",{onClick:n,className:"p-2 text-[#4a3f35] hover:bg-[#4a3f35]/10 rounded-full transition-colors",children:i.jsx(lt,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex items-center space-x-3",children:[i.jsx("img",{src:"/logowhite.png",alt:"Rosys Patterns Logo",className:"w-8 h-8 object-contain"}),i.jsx("h1",{className:"font-serif italic text-[#4a3f35] tracking-widest",children:"Contest Winners"})]})]}),i.jsx("div",{className:"flex items-center",children:i.jsx(_t,{className:"w-6 h-6 text-amber-500"})})]})})}),i.jsx("div",{className:"flex-1 overflow-auto bg-[#f5f1eb]",children:i.jsxs("div",{className:"max-w-4xl mx-auto p-6 space-y-8",children:[i.jsxs(S.div,{initial:{opacity:0,y:20}
180,animate:{opacity:1,y:0},transition:{duration:.6},className:"text-center",children:[i.jsxs("div",{className:"inline-flex items-center space-x-2 bg-gradient-to-r from-pink-500 to-pink-600 text-white px-6 py-3 rounded-full shadow-lg mb-4",children:[i.jsx(_t,{className:"w-5 h-5"}),i.jsx("span",{className:"font-bold",children:"Contest Winners"}),i.jsx(_t,{className:"w-5 h-5"})]}),i.jsx("h2",{className:"text-2xl font-serif italic text-[#4a3f35] mb-2",children:"Celebrating Our Community"}),i.jsx("p",{className:"text-[#4a3f35]/70 max-w-2xl mx-auto",children:"Congratulations to all our amazing winners! Each month, we celebrate creativity and community spirit with fabric prizes and special accessories."})]}),i.jsxs(S.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.6,delay:.3},className:"bg-white/80 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-[#4a3f35]/10",children:[i.jsxs("div",{className:"flex items-center justify-center space-x-2 mb-4",children:[i.jsx(hl,{className:"w-6 h-6 text-pink-500"}),i.jsx("h3",{className:"text-xl font-bold text-[#4a3f35]",children:"Fair & Transparent Selection"})]}),i.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-6",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"w-12 h-12 bg-pink-100 rounded-full flex items-center justify-center mx-auto mb-3",children:i.jsx(fl,{className:"w-6 h-6 text-pink-500"})}),i.jsx("h4",{className:"font-semibold text-[#4a3f35] mb-2",children:"Eligible Entries"}),i.jsx("p",{className:"text-[#4a3f35]/70 text-sm",children:"One entry per user, based on latest vote. All participants have equal chance."})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"w-12 h-12 bg-pink-100 rounded-full flex items-center justify-center mx-auto mb-3",children:i.jsx(ml,{className:"w-6 h-6 text-pink-500"})}),i.jsx("h4",{className:"font-semibold text-[#4a3f35] mb-2",children:"Secure Random Draw"}),i.jsx("p",{className:"text-[#4a3f35]/70 text-sm",children:"Cryptographically secure random selection with SHA-256 integrity verification."})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"w-12 h-12 bg-pink-100 rounded-full flex items-center justify-center mx-auto mb-3",children:i.jsx(Qi,{className:"w-6 h-6 text-pink-500"})}),i.jsx("h4",{className:"font-semibold text-[#4a3f35] mb-2",children:"Timestamped Results"}),i.jsx("p",{className:"text-[#4a3f35]/70 text-sm",children:"All draws are timestamped and documented for complete transparency."})]})]}),i.jsxs("div",{className:"bg-[#f5f1eb] rounded-xl p-4 border border-pink-200/50",children:[i.jsx("h4",{className:"font-semibold text-[#4a3f35] mb-2 text-sm",children:"ð Latest Draw Example (June):"}),i.jsxs("div",{className:"text-xs text-[#4a3f35]/80 space-y-1",children:[i.jsxs("p",{children:[i.jsx("span",{className:"font-medium",children:"Draw Date:"})," 03 Aug 2025 13:44 WEST"]}),i.jsxs("p",{children:[i.jsx("span",{className:"font-medium",children:"Eligible Entries:"})," 136 unique voters"]}),i.jsxs("p",{children:[i.jsx("span",{className:"font-medium",children:"Winners Selected:"})," klossiah, gilly, lonestarry"]}),i.jsxs("p",{children:[i.jsx("span",{className:"font-medium",children:"Integrity Hash:"})," fb47518a9..."]})]})]})]}),i.jsx("div",{className:"grid md:grid-cols-2 gap-8",children:e.map((t,s)=>i.jsxs(S.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.6,delay:s*.2},className:`${t.bgColor} ${t.borderColor} border-2 rounded-2xl p-6 shadow-lg hover:shadow-xl transition-shadow`,children:[i.jsxs("div",{className:"text-center mb-6",children:[i.jsx("div",{className:`inline-block bg-gradient-to-r ${t.monthColor} text-white px-6 py-2 rounded-full shadow-md mb-3`,children:i.jsxs("h3",{className:"font-bold text-lg",children:[t.month," 2025"]})}),i.jsx("p",{className:`text-sm ${t.textColor}/70`,children:"Fabric Voting Contest Winners"})]}),i.jsx("div",{className:"space-y-4",children:t.winners.map((r,a)=>i.jsxs(S.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{duration:.4,delay:s*.2+a*.1},className:`flex items-center justify-between bg-white/80 backdrop-blur-sm rounded-xl p-4 shadow-sm border ${t.borderColor}/30`,children:[i.jsxs("div",{className:"flex items-center space-x-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full bg-gradient-to-r ${t.monthColor} flex items-center justify-center text-white font-bold shadow-md`,children:r.position===1?i.jsx(pl,{className:"w-5 h-5"}):r.position}),i.jsxs("div",{children:[i.jsxs("p",{className:`font-semibold ${t.textColor}`,children:["@",r.name]}),i.jsx("p",{className:`text-xs ${t.textColor}
180/60`,children:r.position===1?"First Place":r.position===2?"Second Place":"Third Place"})]})]}),i.jsx("div",{className:"flex items-center",children:i.jsx(gl,{className:`w-5 h-5 ${t.textColor}/60`})})]},a))}),i.jsx("div",{className:"mt-4 text-center p-3 bg-white/60 rounded-xl border border-pink-200/30",children:i.jsx("p",{className:"text-xs text-[#4a3f35]/70 font-medium",children:"ð Winners received premium fabrics + matching accessories"})})]},t.month))}),i.jsxs(S.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},className:"bg-gradient-to-r from-pink-50 to-pink-100 rounded-2xl p-6 shadow-lg border border-pink-200",children:[i.jsxs("div",{className:"flex items-center justify-center space-x-2 mb-4",children:[i.jsx(Ks,{className:"w-6 h-6 text-pink-500"}),i.jsx("h3",{className:"text-xl font-bold text-[#4a3f35]",children:"ð Are You a Winner?"})]}),i.jsx("div",{className:"text-center mb-4",children:i.jsx("p",{className:"text-[#4a3f35]/80 mb-3",children:"If you see your username above, congratulations! We need to gather your shipping information to send you your fabrics and accessories."})}),i.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[i.jsxs("div",{className:"flex items-center space-x-3 bg-white/80 rounded-xl p-4 shadow-sm border border-pink-200/50",children:[i.jsx("div",{className:"w-10 h-10 bg-green-100 rounded-full flex items-center justify-center",children:i.jsx(Ks,{className:"w-5 h-5 text-green-600"})}),i.jsxs("div",{className:"text-left",children:[i.jsx("h4",{className:"font-semibold text-[#4a3f35] text-sm",children:"Drop me a WhatsApp message"}),i.jsx("p",{className:"text-[#4a3f35]/70 text-xs",children:"I'll guide you through the shipping details"})]})]}),i.jsxs("div",{className:"flex items-center space-x-3 bg-white/80 rounded-xl p-4 shadow-sm border border-pink-200/50",children:[i.jsx("div",{className:"w-10 h-10 bg-pink-100 rounded-full flex items-center justify-center",children:i.jsx(wl,{className:"w-5 h-5 text-pink-600"})}),i.jsxs("div",{className:"text-left",children:[i.jsx("h4",{className:"font-semibold text-[#4a3f35] text-sm",children:"What we'll need from you:"}),i.jsx("p",{className:"text-[#4a3f35]/70 text-xs",children:"Full name, shipping address, contact number"})]})]})]}),i.jsx("div",{className:"mt-4 text-center",children:i.jsx("p",{className:"text-[#4a3f35]/60 text-xs",children:"ð± Winners will be contacted via the email address used for voting registration"})})]}),i.jsxs(S.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.6,delay:.9},className:"text-center bg-white/80 backdrop-blur-sm rounded-2xl p-8 border border-pink-200 shadow-lg",children:[i.jsxs("div",{className:"inline-flex items-center space-x-2 mb-4",children:[i.jsx(zt,{className:"w-6 h-6 text-pink-500"}),i.jsx("h3",{className:"text-xl font-bold text-[#4a3f35]",children:"Want to be next?"}),i.jsx(zt,{className:"w-6 h-6 text-pink-500"})]}),i.jsx("p",{className:"text-[#4a3f35]/70 mb-4 max-w-md mx-auto",children:"Join our monthly fabric voting contests! Every vote counts, and you could be our next winner."}),i.jsxs("button",{onClick:n,className:"inline-flex items-center space-x-2 bg-gradient-to-r from-pink-500 to-pink-600 text-white px-6 py-3 rounded-full font-medium shadow-lg hover:shadow-xl hover:from-pink-600 hover:to-pink-700 transition-all transform hover:scale-105",children:[i.jsx("span",{children:"Vote Now"}),i.jsx(lt,{className:"w-4 h-4 rotate-180"})]})]})]})})]})},Of=()=>{const{isAuthenticated:n,initializeSession:e}=ut(),t=()=>{const d=window.location.hash;return!!(d&&(d.includes("type=recovery")||d.includes("access_token=")))},[s,r]=v.useState(()=>t()),[a,o]=v.useState(!1),[l,c]=v.useState(!1);return v.useEffect(()=>{const u=new URLSearchParams(window.location.search).get("size-assistant")==="true";o(u)},[]),v.useEffect(()=>{const d=sessionStorage.getItem("has_reset_token")==="true";t()||d?(console.log("Password reset URL detected, staying on login page"),sessionStorage.setItem("has_reset_token","true"),r(!0)):(console.log("Normal initialization, not a reset URL"),sessionStorage.removeItem("has_reset_token"),e(),r(!1));const f=()=>{const p=sessionStorage.getItem("has_reset_token")==="true",w=t()||p;console.log("Hash changed, inResetFlow:",w),r(w)};return window.addEventListener("hashchange",f),()=>{window.removeEventListener("hashchange",f)}},[e]),v.useEffect(()=>{n&&s&&(console.log("User authenticated â leaving password-reset mode"),sessionStorage.removeItem("has_reset_token"),r(!1))},[n,s]),v.useEffect(()=>{const u=`march25_${Date.now()}`,m=navigator.userAgent.toLowerCase(),f=m.includes("whatsapp")||m.includes("facebook")||m.includes("facebookexternalhit")||m.
180includes("facebot")||m.includes("twitter")||m.includes("bot"),p={'meta[property="og:title"]':"Rosys Patterns Magazine - Jan & Feb 26' Edition",'meta[property="og:description"]':"Explore the latest edition of Rosys Patterns Magazine. Discover sewing patterns, DIY projects, and creative inspiration for your next crafting adventure.",'meta[property="og:image"]':`https://rosyspatterns.vercel.app/January/1.webp?v=${u}`,'meta[property="og:updated_time"]':new Date().toISOString(),'meta[property="twitter:title"]':"Rosys Patterns Magazine - Jan & Feb 26' Edition",'meta[property="twitter:image"]':`https://rosyspatterns.vercel.app/January/1.webp?v=${u}`};Object.entries(p).forEach(([g,w])=>{const y=document.querySelector(g);y&&y.setAttribute("content",w)}),f&&console.log("Social media bot detected:",{userAgent:m,url:window.location.href,time:new Date().toISOString(),uniqueId:u})},[]),s&&!n?(console.log("Rendering login component due to password reset mode"),i.jsx(ji,{isPasswordResetMode:!0})):n?a?i.jsx("div",{className:"min-h-screen bg-gray-50",children:i.jsxs("div",{className:"max-w-4xl mx-auto py-8 px-4",children:[i.jsx("div",{className:"mb-4",children:i.jsx("button",{onClick:()=>o(!1),className:"text-purple-600 hover:text-purple-800 mb-4",children:"â Back to Magazine"})}),i.jsx(Rf,{})]})}):l?i.jsx(If,{onBack:()=>c(!1)}):(console.log("User authenticated, rendering Magazine component"),i.jsx(xh,{onOpenSizeAssistant:()=>o(!0),onOpenWinners:()=>c(!0)})):(console.log("Rendering login component due to not being authenticated"),i.jsx(ji,{isPasswordResetMode:!1}))};Zi(document.getElementById("root")).render(i.jsxs(v.StrictMode,{children:[i.jsx(Of,{}),i.jsx(Pl,{})]}));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.