const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BonusPolicy-Cz5KGpzR.js","assets/rolldown-runtime-DAXXjFlN.js","assets/jsx-runtime-BTND-Rlb.js","assets/grade-DjYqckKI.js","assets/kpiActual-uNLVLqEw.js","assets/KpiExecutive-4GCMbT09.js","assets/createLucideIcon-BEN84EUK.js","assets/KpiMatrix-Ckzdx3sq.js","assets/aggregate-B1iSXQit.js","assets/KpiForecast-CDZXHaIv.js","assets/MonthlyReport-C03txRu7.js","assets/leaf-UYb_vhq4.js","assets/OperationsDashboard-DBaD9u9P.js","assets/chartTheme-Cd2GOU7n.js","assets/Legend-CaWfdOxn.js","assets/Bar-lKPJYnI6.js","assets/PieChart-M670fka4.js","assets/BarChart-zeUmO_uE.js","assets/displayFormat-CIcx-MRX.js","assets/PeopleDashboard-C_ai0pyt.js","assets/Line-CLDyQRHN.js","assets/ReferenceLine-C04EA47m.js","assets/LineChart-BDLT7dAl.js","assets/PredictiveYield-K00-wFq_.js","assets/EChartsReact-BXbWpxVQ.js","assets/ProductionDashboard-D6jG0xT5.js","assets/SalesDashboard-D5LcZsyz.js","assets/StrategicHub-dP4RueBQ.js","assets/SupplierScorecard-7MZ0IRpT.js","assets/refresh-cw-BO9JGcqB.js","assets/ComposedChart-CcfN7JKi.js","assets/AdvancedAnalytics-C9_jz8C1.js","assets/hourlyIssues-DdbkmVxc.js","assets/echartOptions-B_s_BS4S.js","assets/AndonBoard-B_iUMrLc.js","assets/AuditCoverage-BXlx4p9X.js","assets/CostDashboard-j--3RCqD.js","assets/ESGDashboard-CqxGKHrP.js","assets/QaDashboard-D-QXxaPB.js","assets/qaGridConfig-Dc_ZOblQ.js","assets/MonthPicker-M-dd8QPg.js","assets/DailySnapshot-BrM8y3Hm.js","assets/FinancialDashboard-Cn3lCZjJ.js","assets/FlowMapsHub-BuoBmsI7.js","assets/GovernanceHub-JcClstyB.js","assets/InventoryDashboard-Ded1AeOP.js","assets/KpiDeepDive-DhU1tLlD.js","assets/PlantCompare-X72GHZvd.js","assets/WeighTurnaround--Zwhh127.js","assets/download-KAgrCwaI.js","assets/Dashboard-BujJ3s7W.js","assets/trending-down-A_-0LGmf.js","assets/Skeleton-bw8n3Mak.js","assets/Reports-DG7EoJZH.js","assets/chevron-up-CwdPc_G4.js","assets/printer-iPZVOAJ3.js","assets/TicketSearch-CsBxvBUP.js","assets/DataEntry-BY9Jyb5N.js","assets/pencil-CeYO4ppK.js","assets/QaGridEntry-BmvPpQ1W.js","assets/save-Du4QVJed.js","assets/DateCommitInput-2lzJIKvJ.js","assets/logo-form-B0cwdJlv.js","assets/QaExport-BtOvF2Uv.js","assets/QaImport-BJK2Uc2U.js","assets/ProductionEnergyEntry-BZOQGFeq.js","assets/CutYieldHub-RKNfTNy2.js","assets/QaDailyReportHub-lmFiQnJN.js","assets/UserManagement--3YDrBcx.js","assets/WeighingTargets-IzkB-FK8.js","assets/KpiTargets-DPvhyaFX.js","assets/ImportHistory-ccPvJr3r.js","assets/AuditLog-Be-lAO5O.js","assets/ApiUsage-Bijkviyg.js","assets/SyncStatus-B97z9pqx.js","assets/ReferenceConfig-BeBWV5oU.js","assets/NotifyCenter-CtKzikvz.js","assets/ImportWeighing-k7HB83kB.js","assets/ImportPowerGeneration-CAS19Zn1.js","assets/pbeDateDetect-CVHgs6rX.js","assets/ImportPbeExtras-Dapuf_yL.js","assets/SellerOnlyPage-D174mJBH.js"])))=>i.map(i=>d[i]); import{n as e,o as t,r as n,t as r}from"./rolldown-runtime-DAXXjFlN.js";import{n as i,t as a}from"./jsx-runtime-BTND-Rlb.js";import{t as o}from"./createLucideIcon-BEN84EUK.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var s=r((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,ee||(ee=!0,ae());else{var t=n(l);t!==null&&ce(x,t.startTime-e)}}var ee=!1,S=-1,te=5,ne=-1;function re(){return g?!0:!(e.unstable_now()-net&&re());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&ce(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ae():ee=!1}}}var ae;if(typeof y==`function`)ae=function(){y(ie)};else if(typeof MessageChannel<`u`){var oe=new MessageChannel,se=oe.port2;oe.port1.onmessage=ie,ae=function(){se.postMessage(null)}}else ae=function(){_(ie,0)};function ce(t,n){S=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(S),S=-1):h=!0,ce(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,ee||(ee=!0,ae()))),r},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),c=r(((e,t)=>{t.exports=s()})),l=r((e=>{var t=i();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=l()})),d=r((e=>{var t=c(),n=i(),r=u();function a(e){var t=`https://react.dev/errors/`+e;if(1he||(e.current=me[he],me[he]=null,he--)}function T(e,t){he++,me[he]=e.current,e.current=t}var ve=ge(null),ye=ge(null),be=ge(null),xe=ge(null);function Se(e,t){switch(T(be,t),T(ye,e),T(ve,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Vd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Vd(t),e=Hd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}_e(ve),T(ve,e)}function Ce(){_e(ve),_e(ye),_e(be)}function we(e){e.memoizedState!==null&&T(xe,e);var t=ve.current,n=Hd(t,e.type);t!==n&&(T(ye,e),T(ve,n))}function Te(e){ye.current===e&&(_e(ve),_e(ye)),xe.current===e&&(_e(xe),Qf._currentValue=pe)}var Ee,De;function Oe(e){if(Ee===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Ee=t&&t[1]||``,De=-1)`:-1i||c[r]!==l[i]){var u=` `+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{ke=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Oe(n):``}function je(e,t){switch(e.tag){case 26:case 27:case 5:return Oe(e.type);case 16:return Oe(`Lazy`);case 13:return e.child!==t&&t!==null?Oe(`Suspense Fallback`):Oe(`Suspense`);case 19:return Oe(`SuspenseList`);case 0:case 15:return Ae(e.type,!1);case 11:return Ae(e.type.render,!1);case 1:return Ae(e.type,!0);case 31:return Oe(`Activity`);default:return``}}function Me(e){try{var t=``,n=null;do t+=je(e,n),n=e,e=e.return;while(e);return t}catch(e){return` Error generating stack: `+e.message+` `+e.stack}}var Ne=Object.prototype.hasOwnProperty,Pe=t.unstable_scheduleCallback,Fe=t.unstable_cancelCallback,Ie=t.unstable_shouldYield,Le=t.unstable_requestPaint,Re=t.unstable_now,ze=t.unstable_getCurrentPriorityLevel,Be=t.unstable_ImmediatePriority,Ve=t.unstable_UserBlockingPriority,He=t.unstable_NormalPriority,Ue=t.unstable_LowPriority,We=t.unstable_IdlePriority,Ge=t.log,Ke=t.unstable_setDisableYieldValue,qe=null,Je=null;function Ye(e){if(typeof Ge==`function`&&Ke(e),Je&&typeof Je.setStrictMode==`function`)try{Je.setStrictMode(qe,e)}catch{}}var Xe=Math.clz32?Math.clz32:$e,Ze=Math.log,Qe=Math.LN2;function $e(e){return e>>>=0,e===0?32:31-(Ze(e)/Qe|0)|0}var et=256,tt=262144,nt=4194304;function rt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function it(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=rt(n))):i=rt(o):i=rt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=rt(n))):i=rt(o)):i=rt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function at(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function ot(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function st(){var e=nt;return nt<<=1,!(nt&62914560)&&(nt=4194304),e}function ct(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function lt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function E(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),Sn=!1;if(xn)try{var Cn={};Object.defineProperty(Cn,"passive",{get:function(){Sn=!0}}),window.addEventListener(`test`,Cn,Cn),window.removeEventListener(`test`,Cn,Cn)}catch{Sn=!1}var wn=null,Tn=null,En=null;function Dn(){if(En)return En;var e,t=Tn,n=t.length,r,i=`value`in wn?wn.value:wn.textContent,a=i.length;for(e=0;e=ir),sr=` `,cr=!1;function lr(e,t){switch(e){case`keyup`:return nr.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function ur(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var dr=!1;function fr(e,t){switch(e){case`compositionend`:return ur(t);case`keypress`:return t.which===32?(cr=!0,sr):null;case`textInput`:return e=t.data,e===sr&&cr?null:e;default:return null}}function pr(e,t){if(dr)return e===`compositionend`||!rr&&lr(e,t)?(e=Dn(),En=Tn=wn=null,dr=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Pr(n)}}function Ir(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ir(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Lr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Jt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Jt(e.document)}return t}function Rr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var zr=xn&&`documentMode`in document&&11>=document.documentMode,Br=null,Vr=null,Hr=null,Ur=!1;function Wr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ur||Br==null||Br!==Jt(r)||(r=Br,`selectionStart`in r&&Rr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Hr&&Nr(Hr,r)||(Hr=r,r=Ed(Vr,`onSelect`),0>=o,i-=o,Fi=1<<32-Xe(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),M&&Li(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),M&&Li(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return M&&Li(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),M&&Li(i,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=i(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===ae&&Pa(l)===r.type){n(e,r.sibling),c=i(r,o.props),Ba(c,o),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}o.type===y?(c=Ci(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=Si(o.type,o.key,o.props,null,e.mode,c),Ba(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=i(r,o.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=Ei(o,e.mode,c),c.return=e,e=c}return s(e);case ae:return o=Pa(o),b(e,r,o,c)}if(fe(o))return h(e,r,o,c);if(le(o)){if(l=le(o),typeof l!=`function`)throw Error(a(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,za(o),c);if(o.$$typeof===S)return b(e,r,ca(e,o),c);Va(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=i(r,o),c.return=e,e=c):(n(e,r),c=wi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Ra=0;var i=b(e,t,n,r);return La=null,i}catch(t){if(t===Oa||t===Aa)throw t;var a=vi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Ua=Ha(!0),Wa=Ha(!1),Ga=!1;function Ka(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function qa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ja(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ya(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,G&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=hi(e),mi(e,null,n),t}return di(e,r,t,n),hi(e)}function Xa(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,dt(e,n)}}function Za(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Qa=!1;function $a(){if(Qa){var e=ya;if(e!==null)throw e}}function eo(e,t,n,r){Qa=!1;var i=e.updateQueue;Ga=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(J&f)===f:(r&f)===f){f!==0&&f===va&&(Qa=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:Ga=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Gl|=o,e.lanes=o,e.memoizedState=d}}function to(e,t){if(typeof e!=`function`)throw Error(a(191,e));e.call(t)}function no(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=C.T,s={};C.T=s,zs(e,!1,t,n);try{var c=i(),l=C.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Rs(e,t,Sa(c,r),pu(e)):Rs(e,t,r,pu(e))}catch(n){Rs(e,t,{then:function(){},status:`rejected`,reason:n},pu())}finally{w.p=a,o!==null&&s.types!==null&&(o.types=s.types),C.T=o}}function Os(){}function ks(e,t,n,r){if(e.tag!==5)throw Error(a(476));var i=As(e).queue;Ds(e,i,t,pe,n===null?Os:function(){return js(e),n(r)})}function As(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:pe,baseState:pe,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Bo,lastRenderedState:pe},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Bo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function js(e){var t=As(e);t.next===null&&(t=e.alternate.memoizedState),Rs(e,t.next.queue,{},pu())}function Ms(){return sa(Qf)}function Ns(){return Fo().memoizedState}function Ps(){return Fo().memoizedState}function Fs(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=pu();e=Ja(n);var r=Ya(t,e,n);r!==null&&(hu(r,t,n),Xa(r,t,n)),t={cache:ma()},e.payload=t;return}t=t.return}}function Is(e,t,n){var r=pu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Bs(e)?Vs(t,n):(n=fi(e,t,n,r),n!==null&&(hu(n,e,r),Hs(n,t,r)))}function Ls(e,t,n){Rs(e,t,n,pu())}function Rs(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Bs(e))Vs(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Mr(s,o))return di(e,t,i,0),K===null&&ui(),!1}catch{}if(n=fi(e,t,i,r),n!==null)return hu(n,e,r),Hs(n,t,r),!0}return!1}function zs(e,t,n,r){if(r={lane:2,revertLane:dd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Bs(e)){if(t)throw Error(a(479))}else t=fi(e,n,r,2),t!==null&&hu(t,e,2)}function Bs(e){var t=e.alternate;return e===I||t!==null&&t===I}function Vs(e,t){bo=yo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Hs(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,dt(e,n)}}var Us={readContext:sa,use:Ro,useCallback:R,useContext:R,useEffect:R,useImperativeHandle:R,useLayoutEffect:R,useInsertionEffect:R,useMemo:R,useReducer:R,useRef:R,useState:R,useDebugValue:R,useDeferredValue:R,useTransition:R,useSyncExternalStore:R,useId:R,useHostTransitionStatus:R,useFormState:R,useActionState:R,useOptimistic:R,useMemoCache:R,useCacheRefresh:R};Us.useEffectEvent=R;var Ws={readContext:sa,use:Ro,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:sa,useEffect:ms,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),fs(4194308,4,bs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return fs(4194308,4,e,t)},useInsertionEffect:function(e,t){fs(4,2,e,t)},useMemo:function(e,t){var n=Po();t=t===void 0?null:t;var r=e();if(xo){Ye(!0);try{e()}finally{Ye(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Po();if(n!==void 0){var i=n(t);if(xo){Ye(!0);try{n(t)}finally{Ye(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Is.bind(null,I,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:function(e){e=Xo(e);var t=e.queue,n=Ls.bind(null,I,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:Ss,useDeferredValue:function(e,t){return Ts(Po(),e,t)},useTransition:function(){var e=Xo(!1);return e=Ds.bind(null,I,e.queue,!0,!1),Po().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=I,i=Po();if(M){if(n===void 0)throw Error(a(407));n=n()}else{if(n=t(),K===null)throw Error(a(349));J&127||Go(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,ms(qo.bind(null,r,o,e),[e]),r.flags|=2048,us(9,{destroy:void 0},Ko.bind(null,r,o,n,t),null),n},useId:function(){var e=Po(),t=K.identifierPrefix;if(M){var n=Ii,r=Fi;n=(r&~(1<<32-Xe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=So++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(i,{is:r.is}):s.createElement(i)}}o[vt]=t,o[yt]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Pd(o,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Fc(t)}}return H(t),Ic(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Fc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(a(166));if(e=be.current,N(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=A,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[vt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Md(e.nodeValue,n)),e||Gi(t,!0)}else e=Bd(e).createTextNode(r),e[vt]=t,t.stateNode=e}return H(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=N(t),n!==null){if(e===null){if(!r)throw Error(a(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(a(557));e[vt]=t}else Ji(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;H(t),e=!1}else n=Yi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(mo(t),t):(mo(t),null);if(t.flags&128)throw Error(a(558))}return H(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=N(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(a(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(a(317));i[vt]=t}else Ji(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;H(t),i=!1}else i=Yi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(mo(t),t):(mo(t),null)}return mo(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Rc(t,t.updateQueue),H(t),null);case 4:return Ce(),e===null&&Sd(t.stateNode.containerInfo),H(t),null;case 10:return ta(t.type),H(t),null;case 19:if(_e(ho),r=t.memoizedState,r===null)return H(t),null;if(i=(t.flags&128)!=0,o=r.rendering,o===null)if(i)zc(r,!1);else{if(X!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=go(e),o!==null){for(t.flags|=128,zc(r,!1),e=o.updateQueue,t.updateQueue=e,Rc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)xi(n,e),n=n.sibling;return T(ho,ho.current&1|2),M&&Li(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Re()>tu&&(t.flags|=128,i=!0,zc(r,!1),t.lanes=4194304)}else{if(!i)if(e=go(o),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,Rc(t,e),zc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!M)return H(t),null}else 2*Re()-r.renderingStartTime>tu&&n!==536870912&&(t.flags|=128,i=!0,zc(r,!1),t.lanes=4194304);r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(H(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Re(),e.sibling=null,n=ho.current,T(ho,i?n&1|2:n&1),M&&Li(t,r.treeForkCount),e);case 22:case 23:return mo(t),F(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(H(t),t.subtreeFlags&6&&(t.flags|=8192)):H(t),n=t.updateQueue,n!==null&&Rc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&_e(wa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),ta(pa),H(t),null;case 25:return null;case 30:return null}throw Error(a(156,t.tag))}function Vc(e,t){switch(Bi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ta(pa),Ce(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Te(t),null;case 31:if(t.memoizedState!==null){if(mo(t),t.alternate===null)throw Error(a(340));Ji()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(mo(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(a(340));Ji()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return _e(ho),null;case 4:return Ce(),null;case 10:return ta(t.type),null;case 22:case 23:return mo(t),F(),e!==null&&_e(wa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return ta(pa),null;case 25:return null;default:return null}}function Hc(e,t){switch(Bi(t),t.tag){case 3:ta(pa),Ce();break;case 26:case 27:case 5:Te(t);break;case 4:Ce();break;case 31:t.memoizedState!==null&&mo(t);break;case 13:mo(t);break;case 19:_e(ho);break;case 10:ta(t.type);break;case 22:case 23:mo(t),F(),e!==null&&_e(wa);break;case 24:ta(pa)}}function Uc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Z(t,t.return,e)}}function Wc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Z(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Z(t,t.return,e)}}function Gc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{no(t,n)}catch(t){Z(e,e.return,t)}}}function Kc(e,t,n){n.props=Zs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Z(e,t,n)}}function qc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Z(e,t,n)}}function Jc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){Z(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Z(e,t,n)}else n.current=null}function Yc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Z(e,e.return,t)}}function Xc(e,t,n){try{var r=e.stateNode;Fd(r,e.type,n,t),r[yt]=t}catch(t){Z(e,e.return,t)}}function Zc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Zd(e.type)||e.tag===4}function Qc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Zc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Zd(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function $c(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fn));else if(r!==4&&(r===27&&Zd(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for($c(e,t,n),e=e.sibling;e!==null;)$c(e,t,n),e=e.sibling}function el(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&Zd(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(el(e,t,n),e=e.sibling;e!==null;)el(e,t,n),e=e.sibling}function tl(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Pd(t,r,n),t[vt]=e,t[yt]=n}catch(t){Z(e,e.return,t)}}var nl=!1,rl=!1,il=!1,al=typeof WeakSet==`function`?WeakSet:Set,ol=null;function sl(e,t){if(e=e.containerInfo,Rd=sp,e=Lr(e),Rr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||i!==0&&f.nodeType!==3||(c=s+i),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===i&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(zd={focusedElem:e,selectionRange:n},sp=!1,ol=t;ol!==null;)if(t=ol,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,ol=e;else for(;ol!==null;){switch(t=ol,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Pd(o,r,n),o[vt]=e,jt(o),r=o;break a;case`link`:var s=Vf(`link`,`href`,i).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Fr(s,h),v=Fr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,C.T=null,n=lu,lu=null;var o=au,s=su;if(iu=0,ou=au=null,su=0,G&6)throw Error(a(331));var c=G;if(G|=4,Fl(o.current),Dl(o,o.current,s,n),G=c,id(0,!1),Je&&typeof Je.onPostCommitFiberRoot==`function`)try{Je.onPostCommitFiberRoot(qe,o)}catch{}return!0}finally{w.p=i,C.T=r,Vu(e,t)}}function Wu(e,t,n){t=Oi(n,t),t=rc(e.stateNode,t,2),e=Ya(e,t,2),e!==null&&(lt(e,2),rd(e))}function Z(e,t,n){if(e.tag===3)Wu(e,e,n);else for(;t!==null;){if(t.tag===3){Wu(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(ru===null||!ru.has(r))){e=Oi(n,e),n=ic(2),r=Ya(t,n,2),r!==null&&(ac(n,r,t,e),lt(r,2),rd(r));break}}t=t.return}}function Gu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new zl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Ul=!0,i.add(n),e=Ku.bind(null,e,t,n),t.then(e,e))}function Ku(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,K===e&&(J&n)===n&&(X===4||X===3&&(J&62914560)===J&&300>Re()-$l?!(G&2)&&Su(e,0):ql|=n,Yl===J&&(Yl=0)),rd(e)}function qu(e,t){t===0&&(t=st()),e=pi(e,t),e!==null&&(lt(e,t),rd(e))}function Ju(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),qu(e,n)}function Yu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(a(314))}r!==null&&r.delete(t),qu(e,n)}function Xu(e,t){return Pe(e,t)}var Zu=null,Qu=null,$u=!1,ed=!1,td=!1,nd=0;function rd(e){e!==Qu&&e.next===null&&(Qu===null?Zu=Qu=e:Qu=Qu.next=e),ed=!0,$u||($u=!0,ud())}function id(e,t){if(!td&&ed){td=!0;do for(var n=!1,r=Zu;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Xe(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,ld(r,a))}else a=J,a=it(r,r===K?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||at(r,a)||(n=!0,ld(r,a));r=r.next}while(n);td=!1}}function ad(){od()}function od(){ed=$u=!1;var e=0;nd!==0&&Gd()&&(e=nd);for(var t=Re(),n=null,r=Zu;r!==null;){var i=r.next,a=sd(r,t);a===0?(r.next=null,n===null?Zu=i:n.next=i,i===null&&(Qu=n)):(n=r,(e!==0||a&3)&&(ed=!0)),r=i}iu!==0&&iu!==5||id(e,!1),nd!==0&&(nd=0)}function sd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Id(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function xf(e,t,n){var r=bf;if(r&&typeof t==`string`&&t){var i=Xt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),hf.has(i)||(hf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Pd(t,`link`,e),jt(t),r.head.appendChild(t)))}}function Sf(e){_f.D(e),xf(`dns-prefetch`,e,null)}function Cf(e,t){_f.C(e,t),xf(`preconnect`,e,t)}function wf(e,t,n){_f.L(e,t,n);var r=bf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Xt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Xt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Xt(n.imageSizes)+`"]`)):i+=`[href="`+Xt(e)+`"]`;var a=i;switch(t){case`style`:a=Af(e);break;case`script`:a=Pf(e)}mf.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),mf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(jf(a))||t===`script`&&r.querySelector(Ff(a))||(t=r.createElement(`link`),Pd(t,`link`,e),jt(t),r.head.appendChild(t)))}}function Tf(e,t){_f.m(e,t);var n=bf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Xt(r)+`"][href="`+Xt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Pf(e)}if(!mf.has(a)&&(e=h({rel:`modulepreload`,href:e},t),mf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Ff(a)))return}r=n.createElement(`link`),Pd(r,`link`,e),jt(r),n.head.appendChild(r)}}}function Ef(e,t,n){_f.S(e,t,n);var r=bf;if(r&&e){var i=At(r).hoistableStyles,a=Af(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(jf(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=mf.get(a))&&Rf(e,n);var c=o=r.createElement(`link`);jt(c),Pd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Lf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Df(e,t){_f.X(e,t);var n=bf;if(n&&e){var r=At(n).hoistableScripts,i=Pf(e),a=r.get(i);a||(a=n.querySelector(Ff(i)),a||(e=h({src:e,async:!0},t),(t=mf.get(i))&&zf(e,t),a=n.createElement(`script`),jt(a),Pd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Of(e,t){_f.M(e,t);var n=bf;if(n&&e){var r=At(n).hoistableScripts,i=Pf(e),a=r.get(i);a||(a=n.querySelector(Ff(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=mf.get(i))&&zf(e,t),a=n.createElement(`script`),jt(a),Pd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function kf(e,t,n,r){var i=(i=be.current)?gf(i):null;if(!i)throw Error(a(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Af(n.href),n=At(i).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Af(n.href);var o=At(i).hoistableStyles,s=o.get(e);if(s||(i=i.ownerDocument||i,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=i.querySelector(jf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),mf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},mf.set(e,n),o||Nf(i,e,n,s.state))),t&&r===null)throw Error(a(528,``));return s}if(t&&r!==null)throw Error(a(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Pf(n),n=At(i).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(a(444,e))}}function Af(e){return`href="`+Xt(e)+`"`}function jf(e){return`link[rel="stylesheet"][`+e+`]`}function Mf(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function Nf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Pd(t,`link`,n),jt(t),e.head.appendChild(t))}function Pf(e){return`[src="`+Xt(e)+`"]`}function Ff(e){return`script[async]`+e}function If(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Xt(n.href)+`"]`);if(r)return t.instance=r,jt(r),r;var i=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),jt(r),Pd(r,`style`,i),Lf(r,n.precedence,e),t.instance=r;case`stylesheet`:i=Af(n.href);var o=e.querySelector(jf(i));if(o)return t.state.loading|=4,t.instance=o,jt(o),o;r=Mf(n),(i=mf.get(i))&&Rf(r,i),o=(e.ownerDocument||e).createElement(`link`),jt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Pd(o,`link`,r),t.state.loading|=4,Lf(o,n.precedence,e),t.instance=o;case`script`:return o=Pf(n.src),(i=e.querySelector(Ff(o)))?(t.instance=i,jt(i),i):(r=n,(i=mf.get(o))&&(r=h({},n),zf(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),jt(i),Pd(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(a(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Lf(r,n.precedence,e));return t.instance}function Lf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Uf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Wf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Gf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Af(r.href),a=t.querySelector(jf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Jf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,jt(a);return}a=t.ownerDocument||t,r=Mf(r),(i=mf.get(i))&&Rf(r,i),a=a.createElement(`link`),jt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Pd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Jf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Kf=0;function qf(e,t){return e.stylesheets&&e.count===0&&Xf(e,e.stylesheets),0Kf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Jf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Xf(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Yf=null;function Xf(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Yf=new Map,t.forEach(Zf,e),Yf=null,Jf.call(e))}function Zf(e,t){if(!(t.state.loading&4)){var n=Yf.get(e);if(n)var r=n.get(null);else{n=new Map,Yf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=d()})),p=t(i(),1),m=f(),h=n({__addDisposableResource:()=>T,__assign:()=>xe,__asyncDelegator:()=>fe,__asyncGenerator:()=>de,__asyncValues:()=>C,__await:()=>ue,__awaiter:()=>ne,__classPrivateFieldGet:()=>he,__classPrivateFieldIn:()=>_e,__classPrivateFieldSet:()=>ge,__createBinding:()=>Se,__decorate:()=>v,__disposeResources:()=>ve,__esDecorate:()=>b,__exportStar:()=>ie,__extends:()=>g,__generator:()=>re,__importDefault:()=>me,__importStar:()=>pe,__makeTemplateObject:()=>w,__metadata:()=>te,__param:()=>y,__propKey:()=>ee,__read:()=>oe,__rest:()=>_,__rewriteRelativeImportExtension:()=>ye,__runInitializers:()=>x,__setFunctionName:()=>S,__spread:()=>se,__spreadArray:()=>le,__spreadArrays:()=>ce,__values:()=>ae,default:()=>Ee});function g(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);be(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function _(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function y(e,t){return function(n,r){t(n,r,e)}}function b(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function x(e,t,n){for(var r=arguments.length>2,i=0;i0&&a[a.length-1]))&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function oe(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function se(){for(var e=[],t=0;t1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof ue?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function fe(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:ue(e[r](t)),done:!1}:i?i(t):t}:i}}function C(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof ae==`function`?ae(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function w(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function pe(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=we(e),r=0;r{be=function(e,t){return be=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},be(e,t)},xe=function(){return xe=Object.assign||function(e){for(var t,n=1,r=arguments.length;ne?(...t)=>e(...t):(...e)=>fetch(...e),ke=class extends Error{constructor(e,t=`FunctionsError`,n){super(e),this.name=t,this.context=n}toJSON(){return{name:this.name,message:this.message,context:this.context}}},Ae=class extends ke{constructor(e){super(`Failed to send a request to the Edge Function`,`FunctionsFetchError`,e)}},je=class extends ke{constructor(e){super(`Relay Error invoking the Edge Function`,`FunctionsRelayError`,e)}},Me=class extends ke{constructor(e){super(`Edge Function returned a non-2xx status code`,`FunctionsHttpError`,e)}},Ne;(function(e){e.Any=`any`,e.ApNortheast1=`ap-northeast-1`,e.ApNortheast2=`ap-northeast-2`,e.ApSouth1=`ap-south-1`,e.ApSoutheast1=`ap-southeast-1`,e.ApSoutheast2=`ap-southeast-2`,e.CaCentral1=`ca-central-1`,e.EuCentral1=`eu-central-1`,e.EuWest1=`eu-west-1`,e.EuWest2=`eu-west-2`,e.EuWest3=`eu-west-3`,e.SaEast1=`sa-east-1`,e.UsEast1=`us-east-1`,e.UsWest1=`us-west-1`,e.UsWest2=`us-west-2`})(Ne||={}),De();var Pe=class{constructor(e,{headers:t={},customFetch:n,region:r=Ne.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Oe(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return ne(this,arguments,void 0,function*(e,t={}){var n;let r,i,a;try{let{headers:n,method:o,body:s,signal:c,timeout:l}=t,u={},{region:d}=t;d||=this.region;let f=new URL(`${this.url}/${e}`);d&&d!==`any`&&(u[`x-region`]=d,f.searchParams.set(`forceFunctionRegion`,d));let p,m=!!n&&Object.keys(n).some(e=>e.toLowerCase()===`content-type`);s&&!m?typeof Blob<`u`&&s instanceof Blob||s instanceof ArrayBuffer?(u[`Content-Type`]=`application/octet-stream`,p=s):typeof s==`string`?(u[`Content-Type`]=`text/plain`,p=s):typeof FormData<`u`&&s instanceof FormData?p=s:(u[`Content-Type`]=`application/json`,p=JSON.stringify(s)):p=s&&typeof s!=`string`&&!(typeof Blob<`u`&&s instanceof Blob)&&!(s instanceof ArrayBuffer)&&!(typeof FormData<`u`&&s instanceof FormData)?JSON.stringify(s):s;let h=c;l&&(i=new AbortController,r=setTimeout(()=>i.abort(),l),c?(h=i.signal,a=()=>i.abort(),c.addEventListener(`abort`,a)):h=i.signal);let g=yield this.fetch(f.toString(),{method:o||`POST`,headers:Object.assign(Object.assign(Object.assign({},u),this.headers),n),body:p,signal:h}).catch(e=>{throw new Ae(e)}),_=g.headers.get(`x-relay-error`);if(_&&_===`true`)throw new je(g);if(!g.ok)throw new Me(g);let v=(g.headers.get(`Content-Type`)??`text/plain`).split(`;`)[0].trim().toLowerCase(),y;return y=v===`application/json`?yield g.json():v===`application/octet-stream`||v===`application/pdf`?yield g.blob():v===`text/event-stream`?g:v===`multipart/form-data`?yield g.formData():yield g.text(),{data:y,error:null,response:g}}catch(e){return{data:null,error:e,response:e instanceof Me||e instanceof je?e.context:void 0}}finally{r&&clearTimeout(r),a&&((n=t.signal)==null||n.removeEventListener(`abort`,a))}})}},Fe=3,Ie=e=>Math.min(1e3*2**e,3e4),Le=[520,503],Re=[`GET`,`HEAD`,`OPTIONS`],ze=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Be(e,t){return new Promise(n=>{if(t?.aborted){n();return}let r=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);function i(){clearTimeout(r),n()}t?.addEventListener(`abort`,i)})}function Ve(e,t,n,r){return!(!r||n>=Fe||!Re.includes(e)||!Le.includes(t))}var He=class{constructor(e){this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.shouldStripNulls=e.shouldStripNulls??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,this.retryEnabled=e.retry??!0,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get(`Accept`)===`text/csv`)throw Error(`stripNulls() cannot be used with csv()`);return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var n=this;if(this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`),this.shouldStripNulls){let e=this.headers.get(`Accept`);e===`application/vnd.pgrst.object+json`?this.headers.set(`Accept`,`application/vnd.pgrst.object+json;nulls=stripped`):(!e||e===`application/json`)&&this.headers.set(`Accept`,`application/vnd.pgrst.array+json;nulls=stripped`)}let r=this.fetch,i=(async()=>{let e=0;for(;;){let t={};n.headers.forEach((e,n)=>{t[n]=e}),e>0&&(t[`X-Retry-Count`]=String(e));let i;try{i=await r(n.url.toString(),{method:n.method,headers:t,body:JSON.stringify(n.body,(e,t)=>typeof t==`bigint`?t.toString():t),signal:n.signal})}catch(t){if(t?.name===`AbortError`||t?.code===`ABORT_ERR`||!Re.includes(n.method))throw t;if(n.retryEnabled&&e{let t=``,n=``,r=``,i=e?.cause;if(i){let n=i?.message??``,r=i?.code??``;t=`${e?.name??`FetchError`}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??`Error`}: ${n}`,r&&(t+=` (${r})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??``;let a=this.url.toString().length;return e?.name===`AbortError`||e?.code===`ABORT_ERR`?(r=``,n=`Request was aborted (timeout or manual cancellation)`,a>this.urlLengthLimit&&(n+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(i?.name===`HeadersOverflowError`||i?.code===`UND_ERR_HEADERS_OVERFLOW`)&&(r=``,n=`HTTP headers exceeded server limits (typically 16KB)`,a>this.urlLengthLimit&&(n+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:t,hint:n,code:r},data:null,count:null,status:0,statusText:``}})),i.then(e,t)}async processResponse(e){var t=this;let n=null,r=null,i=null,a=e.status,o=e.statusText;if(e.ok){if(t.method!==`HEAD`){let i=await e.text();if(i!==``)if(t.headers.get(`Accept`)===`text/csv`)r=i;else if(t.headers.get(`Accept`)&&t.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`))r=i;else try{r=JSON.parse(i)}catch{if(n={message:i},r=null,t.shouldThrowOnError)throw new ze({message:i,details:``,hint:``,code:``})}}let s=t.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),c=e.headers.get(`content-range`)?.split(`/`);s&&c&&c.length>1&&(i=parseInt(c[1])),t.isMaybeSingle&&Array.isArray(r)&&(r.length>1?(n={code:`PGRST116`,details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:`JSON object requested, multiple (or no) rows returned`},r=null,i=null,a=406,o=`Not Acceptable`):r=r.length===1?r[0]:null)}else{let i=await e.text();try{n=JSON.parse(i),Array.isArray(n)&&e.status===404&&(r=[],n=null,a=200,o=`OK`)}catch{e.status===404&&i===``?(a=204,o=`No Content`):n={message:i}}if(n&&t.shouldThrowOnError)throw new ze(n)}return{success:n===null,error:n,data:r,count:i,status:a,statusText:o}}returns(){return this}overrideTypes(){return this}},Ue=class extends He{throwOnError(){return super.throwOnError()}select(e){let t=!1,n=(e??`*`).split(``).map(e=>/\s/.test(e)&&!t?``:(e===`"`&&(t=!t),e)).join(``);return this.url.searchParams.set(`select`,n),this.headers.append(`Prefer`,`return=representation`),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){let a=i?`${i}.order`:`order`,o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:``}${e}.${t?`asc`:`desc`}${n===void 0?``:n?`.nullsfirst`:`.nullslast`}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let r=n===void 0?`limit`:`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){let i=r===void 0?`offset`:`${r}.offset`,a=r===void 0?`limit`:`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set(`Accept`,`text/csv`),this}geojson(){return this.headers.set(`Accept`,`application/geo+json`),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:a=`text`}={}){let o=[e?`analyze`:null,t?`verbose`:null,n?`settings`:null,r?`buffers`:null,i?`wal`:null].filter(Boolean).join(`|`),s=this.headers.get(`Accept`)??`application/json`;return this.headers.set(`Accept`,`application/vnd.pgrst.plan+${a}; for="${s}"; options=${o};`),this}rollback(){return this.headers.append(`Prefer`,`tx=rollback`),this}returns(){return this}maxAffected(e){return this.headers.append(`Prefer`,`handling=strict`),this.headers.append(`Prefer`,`max-affected=${e}`),this}},We=RegExp(`[,()]`),Ge=class extends Ue{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(`,`)}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(`,`)}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(`,`)}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(`,`)}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&We.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&We.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`not.in.(${n})`),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:n,type:r}={}){let i=``;r===`plain`?i=`pl`:r===`phrase`?i=`ph`:r===`websearch`&&(i=`w`);let a=n===void 0?``:`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>t!==void 0).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let r=n?`${n}.or`:`or`;return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},Ke=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:i=8e3,retry:a}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=i,this.retry=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:n=!1,count:r}=t??{},i=n?`HEAD`:`GET`,a=!1,o=(e??`*`).split(``).map(e=>/\s/.test(e)&&!a?``:(e===`"`&&(a=!a),e)).join(``),{url:s,headers:c}=this.cloneRequestState();return s.searchParams.set(`select`,o),r&&c.append(`Prefer`,`count=${r}`),new Ge({method:i,url:s,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:n=!0}={}){let{url:r,headers:i}=this.cloneRequestState();if(t&&i.append(`Prefer`,`count=${t}`),n||i.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);r.searchParams.set(`columns`,e.join(`,`))}}return new Ge({method:`POST`,url:r,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:i=!0}={}){let{url:a,headers:o}=this.cloneRequestState();if(o.append(`Prefer`,`resolution=${n?`ignore`:`merge`}-duplicates`),t!==void 0&&a.searchParams.set(`on_conflict`,t),r&&o.append(`Prefer`,`count=${r}`),i||o.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set(`columns`,e.join(`,`))}}return new Ge({method:`POST`,url:a,headers:o,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){let{url:n,headers:r}=this.cloneRequestState();return t&&r.append(`Prefer`,`count=${t}`),new Ge({method:`PATCH`,url:n,headers:r,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){let{url:t,headers:n}=this.cloneRequestState();return e&&n.append(`Prefer`,`count=${e}`),new Ge({method:`DELETE`,url:t,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function qe(e){"@babel/helpers - typeof";return qe=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},qe(e)}function Je(e,t){if(qe(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(qe(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Ye(e){var t=Je(e,`string`);return qe(t)==`symbol`?t:t+``}function Xe(e,t,n){return(t=Ye(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ze(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Qe(e){for(var t=1;t0?this.fetch=(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(r),s(e,t);let i=()=>{clearTimeout(r),n.abort()};return a.addEventListener(`abort`,i,{once:!0}),s(e,Qe(Qe({},t),{},{signal:n.signal})).finally(()=>{clearTimeout(r),a.removeEventListener(`abort`,i)})}return s(e,Qe(Qe({},t),{},{signal:n.signal})).finally(()=>clearTimeout(r))}:this.fetch=s,this.retry=o}from(e){if(!e||typeof e!=`string`||e.trim()===``)throw Error(`Invalid relation name: relation must be a non-empty string.`);return new Ke(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,t={},{head:n=!1,get:r=!1,count:i}={}){let a,o=new URL(`${this.url}/rpc/${e}`),s,c=e=>typeof e==`object`&&!!e&&(!Array.isArray(e)||e.some(c)),l=n&&Object.values(t).some(c);l?(a=`POST`,s=t):n||r?(a=n?`HEAD`:`GET`,Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(`,`)}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a=`POST`,s=t);let u=new Headers(this.headers);return l?u.set(`Prefer`,i?`count=${i},return=minimal`:`return=minimal`):i&&u.set(`Prefer`,`count=${i}`),new Ge({method:a,url:o,headers:u,schema:this.schemaName,body:s,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},et=class{constructor(){}static detectEnvironment(){if(typeof WebSocket<`u`)return{type:`native`,wsConstructor:WebSocket};let e=globalThis;if(typeof globalThis<`u`&&e.WebSocket!==void 0)return{type:`native`,wsConstructor:e.WebSocket};let t=typeof global<`u`?global:void 0;if(t&&t.WebSocket!==void 0)return{type:`native`,wsConstructor:t.WebSocket};if(typeof globalThis<`u`&&e.WebSocketPair!==void 0&&globalThis.WebSocket===void 0)return{type:`cloudflare`,error:`Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.`,workaround:`Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.`};if(typeof globalThis<`u`&&e.EdgeRuntime||typeof navigator<`u`&&navigator.userAgent?.includes(`Vercel-Edge`))return{type:`unsupported`,error:`Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.`,workaround:`Use serverless functions or a different deployment target for WebSocket functionality.`};let n=globalThis.process;if(n){let e=n.versions;if(e&&e.node)return{type:`unsupported`,error:`Node.js detected but native WebSocket not found.`,workaround:`Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option.`}}return{type:`unsupported`,error:`Unknown JavaScript runtime without WebSocket support.`,workaround:`Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.`}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let t=e.error||`WebSocket not supported in this environment.`;throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),Error(t)}static isWebSocketSupported(){try{return this.detectEnvironment().type===`native`}catch{return!1}}},tt=`realtime-js/2.111.0`,nt=`1.0.0`,rt=`2.0.0`,it=rt,at=1e4,ot={closed:`closed`,errored:`errored`,joined:`joined`,joining:`joining`,leaving:`leaving`},st={close:`phx_close`,error:`phx_error`,join:`phx_join`,reply:`phx_reply`,leave:`phx_leave`,access_token:`access_token`},ct={connecting:`connecting`,open:`open`,closing:`closing`,closed:`closed`},lt=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT=`broadcast`,this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event==`string`)return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){return this._isArrayBuffer(e.payload?.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){let t=e.payload?.payload??new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,t)}_encodeJsonUserBroadcastPush(e){let t=e.payload?.payload??{},n=new TextEncoder().encode(JSON.stringify(t)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,n){let r=new TextEncoder,i=r.encode(e.topic),a=r.encode(e.ref??``),o=r.encode(e.join_ref??``),s=r.encode(e.payload.event),c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=r.encode(Object.keys(c).length===0?``:JSON.stringify(c));if(o.length>255)throw Error(`joinRef length ${o.length} exceeds maximum of 255`);if(a.length>255)throw Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw Error(`topic length ${i.length} exceeds maximum of 255`);if(s.length>255)throw Error(`userEvent length ${s.length} exceeds maximum of 255`);if(l.length>255)throw Error(`metadata length ${l.length} exceeds maximum of 255`);let u=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+a.length+i.length+s.length+l.length,d=new ArrayBuffer(this.HEADER_LENGTH+u),f=new DataView(d),p=new Uint8Array(d),m=0;f.setUint8(m++,this.KINDS.userBroadcastPush),f.setUint8(m++,o.length),f.setUint8(m++,a.length),f.setUint8(m++,i.length),f.setUint8(m++,s.length),f.setUint8(m++,l.length),f.setUint8(m++,t),p.set(o,m),m+=o.length,p.set(a,m),m+=a.length,p.set(i,m),m+=i.length,p.set(s,m),m+=s.length,p.set(l,m),m+=l.length;var h=new Uint8Array(d.byteLength+n.byteLength);return h.set(new Uint8Array(d),0),h.set(new Uint8Array(n),d.byteLength),h.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if(typeof e==`string`){let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}return t({})}_binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,r)}}_decodeUserBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+4,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=e.slice(s,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(n.decode(d)):d,p={type:this.BROADCAST_EVENT,event:l,payload:f};return a>0&&(p.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){return e instanceof ArrayBuffer||e?.constructor?.name===`ArrayBuffer`}_pick(e,t){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}},E;(function(e){e.abstime=`abstime`,e.bool=`bool`,e.date=`date`,e.daterange=`daterange`,e.float4=`float4`,e.float8=`float8`,e.int2=`int2`,e.int4=`int4`,e.int4range=`int4range`,e.int8=`int8`,e.int8range=`int8range`,e.json=`json`,e.jsonb=`jsonb`,e.money=`money`,e.numeric=`numeric`,e.oid=`oid`,e.reltime=`reltime`,e.text=`text`,e.time=`time`,e.timestamp=`timestamp`,e.timestamptz=`timestamptz`,e.timetz=`timetz`,e.tsrange=`tsrange`,e.tstzrange=`tstzrange`})(E||={});var ut=(e,t,n={})=>{let r=n.skipTypes??[];return t?Object.keys(t).reduce((n,i)=>(n[i]=dt(i,e,t,r),n),{}):{}},dt=(e,t,n,r)=>{let i=t.find(t=>t.name===e)?.type,a=n[e];return i&&!r.includes(i)?ft(i,a):pt(a)},ft=(e,t)=>{if(e.charAt(0)===`_`)return _t(t,e.slice(1,e.length));switch(e){case E.bool:return mt(t);case E.float4:case E.float8:case E.int2:case E.int4:case E.int8:case E.numeric:case E.oid:return ht(t);case E.json:case E.jsonb:return gt(t);case E.timestamp:return vt(t);case E.abstime:case E.date:case E.daterange:case E.int4range:case E.int8range:case E.money:case E.reltime:case E.text:case E.time:case E.timestamptz:case E.timetz:case E.tsrange:case E.tstzrange:return pt(t);default:return pt(t)}},pt=e=>e,mt=e=>{switch(e){case`t`:return!0;case`f`:return!1;default:return e}},ht=e=>{if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},gt=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e},_t=(e,t)=>{if(typeof e!=`string`)return e;let n=e.length-1,r=e[n];if(e[0]===`{`&&r===`}`){let r,i=e.slice(1,n);try{r=JSON.parse(`[`+i+`]`)}catch{r=i?i.split(`,`):[]}return r.map(e=>ft(t,e))}return e},vt=e=>typeof e==`string`?e.replace(` `,`T`):e,yt=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,`http`),t.pathname=t.pathname.replace(/\/+$/,``).replace(/\/socket\/websocket$/i,``).replace(/\/socket$/i,``).replace(/\/websocket$/i,``),t.pathname===``||t.pathname===`/`?t.pathname=`/api/broadcast`:t.pathname+=`/api/broadcast`,t.href},bt=e=>typeof e==`function`?e:function(){return e},xt=typeof self<`u`?self:null,St=typeof window<`u`?window:null,Ct=xt||St||globalThis,wt=`2.0.0`,Tt=1e4,Et=1e3,Dt=100,Ot={connecting:0,open:1,closing:2,closed:3},kt={closed:`closed`,errored:`errored`,joined:`joined`,joining:`joining`,leaving:`leaving`},At={close:`phx_close`,error:`phx_error`,join:`phx_join`,reply:`phx_reply`,leave:`phx_leave`},jt={longpoll:`longpoll`,websocket:`websocket`},Mt={complete:4},Nt=`base64url.bearer.phx.`,Pt=class{constructor(e,t,n,r){this.channel=e,this.event=t,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),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()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:n}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger(`timeout`,{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},Ft=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries+=1,this.callback()},this.timerCalc(this.tries+1))}},It=class{constructor(e,t,n){this.state=kt.closed,this.topic=e,this.params=bt(t||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Pt(this,At.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Ft(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive(`ok`,()=>{this.state=kt.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this.joinPush.receive(`error`,e=>{this.state=kt.errored,this.socket.hasLogger()&&this.socket.log(`channel`,`error ${this.topic}`,e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log(`channel`,`close ${this.topic}`),this.state=kt.closed,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log(`channel`,`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=kt.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive(`timeout`,()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`timeout ${this.topic}`,this.joinPush.timeout),new Pt(this,At.leave,bt({}),this.timeout).send(),this.state=kt.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(At.reply,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(this.joinedOnce)throw Error(`tried to join multiple times. 'join' can only be called a single time per channel instance`);return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=kt.closed,this.bindings=[]}onClose(e){this.on(At.close,e)}onError(e){return this.on(At.error,t=>e(t))}on(e,t){let n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}off(e,t){this.bindings=this.bindings.filter(n=>!(n.event===e&&(t===void 0||t===n.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,n=this.timeout){if(t||={},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new Pt(this,e,function(){return t},n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=kt.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`leave ${this.topic}`),this.trigger(At.close,`leave`)},n=new Pt(this,At.leave,bt({}),e);return n.receive(`ok`,()=>t()).receive(`timeout`,()=>t()),n.send(),this.canPush()||n.trigger(`ok`,{}),n}onMessage(e,t,n){return t}filterBindings(e,t,n){return!0}isMember(e,t,n,r){return this.topic===e?r&&r!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log(`channel`,`dropping outdated message`,{topic:e,event:t,payload:n,joinRef:r}),!1):!0:!1}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=kt.joining,this.joinPush.resend(e))}trigger(e,t,n,r){let i=this.onMessage(e,t,n,r);if(t&&!i)throw Error(`channel onMessage callbacks must return the payload, modified or unmodified`);let a=this.bindings.filter(r=>r.event===e&&this.filterBindings(r,t,n));for(let e=0;ec.abort(),i),s.signal=c.signal),Ct.fetch(t,s).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>o&&o(e)).catch(e=>{e.name===`AbortError`&&a?a():o&&o(null)}),c}static xdomainRequest(e,t,n,r,i,a,o){return e.timeout=i,e.open(t,n),e.onload=()=>{let t=this.parseJSON(e.responseText);o&&o(t)},a&&(e.ontimeout=a),e.onprogress=()=>{},e.send(r),e}static xhrRequest(e,t,n,r,i,a,o,s){e.open(t,n,!0),e.timeout=a;for(let[t,n]of Object.entries(r))e.setRequestHeader(t,n);return e.onerror=()=>s&&s(null),e.onreadystatechange=()=>{e.readyState===Mt.complete&&s&&s(this.parseJSON(e.responseText))},o&&(e.ontimeout=o),e.send(i),e}static parseJSON(e){if(!e||e===``)return null;try{return JSON.parse(e)}catch{return console&&console.log(`failed to parse JSON response`,e),null}}static serialize(e,t){let n=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=t?`${t}[${r}]`:r,a=e[r];typeof a==`object`?n.push(this.serialize(a,i)):n.push(encodeURIComponent(i)+`=`+encodeURIComponent(a))}return n.join(`&`)}static appendParams(e,t){return Object.keys(t).length===0?e:`${e}${e.match(/\?/)?`&`:`?`}${this.serialize(t)}`}},Rt=e=>{let t=``,n=new Uint8Array(e),r=n.byteLength;for(let e=0;ethis.poll(),0)}normalizeEndpoint(e){return e.replace(`ws://`,`http://`).replace(`wss://`,`https://`).replace(RegExp(`(.*)/`+jt.websocket),`$1/`+jt.longpoll)}endpointURL(){return Lt.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,n){this.close(e,t,n),this.readyState=Ot.connecting}ontimeout(){this.onerror(`timeout`),this.closeAndRetry(1005,`timeout`,!1)}isActive(){return this.readyState===Ot.open||this.readyState===Ot.connecting}poll(){let e={Accept:`application/json`};this.authToken&&(e[`X-Phoenix-AuthToken`]=this.authToken),this.ajax(`GET`,e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:n,messages:r}=e;if(t===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,`session_gone`,!1);return}this.token=n}else t=0;switch(t){case 200:r.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Ot.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,`forbidden`,!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,`internal server error`,500);break;default:throw Error(`unhandled poll status ${t}`)}})}send(e){typeof e!=`string`&&(e=Rt(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e,t=0){this.awaitingBatchAck=!0;let n=t+Dt,r=e.slice(t,n);this.ajax(`POST`,{"Content-Type":`application/x-ndjson`},r.join(` `),()=>this.onerror(`timeout`),t=>{!t||t.status!==200?(this.awaitingBatchAck=!1,this.onerror(t&&t.status),this.closeAndRetry(1011,`internal server error`,!1)):n0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(e,t,n){for(let e of this.reqs)e.abort();this.readyState=Ot.closed;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<`u`?this.onclose(new CloseEvent(`close`,r)):this.onclose(r)}ajax(e,t,n,r,i){let a;a=Lt.request(e,this.endpointURL(),t,n,this.timeout,()=>{this.reqs.delete(a),r()},e=>{this.reqs.delete(a),this.isActive()&&i(e)}),this.reqs.add(a)}},Bt=class e{constructor(t,n={}){let r=n.events||{state:`presence_state`,diff:`presence_diff`};this.state=Object.create(null),this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(r.state,t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.joinRef=this.channel.joinRef(),this.state=e.syncState(this.state,t,n,r),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,n,r)}),this.pendingDiffs=[],i()}),this.channel.on(r.diff,t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,n,r),i())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,n,r){let i=this.toNullProtoObj(this.clone(e));t=this.toNullProtoObj(t);let a=Object.create(null),o=Object.create(null);return this.map(i,(e,n)=>{t[e]||(o[e]=n)}),this.map(t,(e,t)=>{let n=i[e];if(n){let r=t.metas.map(e=>e.phx_ref),i=n.metas.map(e=>e.phx_ref),s=t.metas.filter(e=>i.indexOf(e.phx_ref)<0),c=n.metas.filter(e=>r.indexOf(e.phx_ref)<0);s.length>0&&(a[e]=t,a[e].metas=s),c.length>0&&(o[e]=this.clone(n),o[e].metas=c)}else a[e]=t}),this.syncDiff(i,{joins:a,leaves:o},n,r)}static syncDiff(e,t,n,r){e=this.toNullProtoObj(e);let{joins:i,leaves:a}=this.clone(t);return n||=function(){},r||=function(){},this.map(i,(t,r)=>{let i=e[t];if(e[t]=this.clone(r),i){let n=e[t].metas.map(e=>e.phx_ref),r=i.metas.filter(e=>n.indexOf(e.phx_ref)<0);e[t].metas.unshift(...r)}n(t,i,r)}),this.map(a,(t,n)=>{let i=e[t];if(!i)return;let a=n.metas.map(e=>e.phx_ref);i.metas=i.metas.filter(e=>a.indexOf(e.phx_ref)<0),r(t,i,n),i.metas.length===0&&delete e[t]}),e}static list(e,t){return t||=function(e,t){return t},this.map(e,(e,n)=>t(e,n))}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(n=>{t[n]=e[n]}),t}static clone(e){return JSON.parse(JSON.stringify(e))}},Vt={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}},binaryEncode(e){let{join_ref:t,ref:n,event:r,topic:i,payload:a}=e,o=new TextEncoder,s=o.encode(t),c=o.encode(n),l=o.encode(i),u=o.encode(r);this.assertFieldSize(s.byteLength,`join_ref`),this.assertFieldSize(c.byteLength,`ref`),this.assertFieldSize(l.byteLength,`topic`),this.assertFieldSize(u.byteLength,`event`);let d=this.META_LENGTH+s.byteLength+c.byteLength+l.byteLength+u.byteLength,f=new ArrayBuffer(this.HEADER_LENGTH+d),p=new Uint8Array(f),m=new DataView(f),h=0;m.setUint8(h++,this.KINDS.push),m.setUint8(h++,s.byteLength),m.setUint8(h++,c.byteLength),m.setUint8(h++,l.byteLength),m.setUint8(h++,u.byteLength),p.set(s,h),h+=s.byteLength,p.set(c,h),h+=c.byteLength,p.set(l,h),h+=l.byteLength,p.set(u,h),h+=u.byteLength;var g=new Uint8Array(f.byteLength+a.byteLength);return g.set(p,0),g.set(new Uint8Array(a),f.byteLength),g.buffer},assertFieldSize(e,t){if(e>255)throw Error(`unable to convert ${t} to binary: must be less than or equal to 255 bytes, but is ${e} bytes`)},binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,s=n.decode(e.slice(o,o+r));o+=r;let c=n.decode(e.slice(o,o+i));o+=i;let l=n.decode(e.slice(o,o+a));return o+=a,{join_ref:s,ref:null,topic:c,event:l,payload:e.slice(o,e.byteLength)}},decodeReply(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+this.META_LENGTH,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=n.decode(e.slice(s,s+o));s+=o;let f={status:d,response:e.slice(s,e.byteLength)};return{join_ref:c,ref:l,topic:u,event:At.reply,payload:f}},decodeBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,o=n.decode(e.slice(a,a+r));a+=r;let s=n.decode(e.slice(a,a+i));return a+=i,{join_ref:null,ref:null,topic:o,event:s,payload:e.slice(a,e.byteLength)}}},Ht=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||Tt,this.transport=t.transport||Ct.WebSocket||zt,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let n=null;try{n=Ct&&Ct.sessionStorage}catch{}this.sessionStore=t.sessionStorage||n,this.establishedConnections=0,this.defaultEncoder=Vt.encode.bind(Vt),this.defaultDecoder=Vt.decode.bind(Vt),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||`arraybuffer`,this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport===zt?(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder):(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder);let r=null;St&&St.addEventListener&&(St.addEventListener(`pagehide`,e=>{this.conn&&(this.disconnect(),r=this.connectClock)}),St.addEventListener(`pageshow`,e=>{r===this.connectClock&&(r=null,this.connect())}),St.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,n)=>{console.log(`${e}: ${t}`,n)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=bt(t.params||{}),this.endPoint=`${e}/${jt.websocket}`,this.vsn=t.vsn||wt,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Ft(()=>{if(this.pageHidden){this.log(`Not reconnecting as page is hidden!`),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken&&bt(t.authToken)}getLongPollTransport(){return zt}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&=(this.conn.close(),null),this.transport=e}protocol(){return location.protocol.match(/^https/)?`wss`:`ws`}endPointURL(){let e=Lt.appendParams(Lt.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)===`/`?e.charAt(1)===`/`?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`:e}disconnect(e,t,n){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,n)}connect(e){e&&(console&&console.log(`passing params to connect is deprecated. Instead pass :params to the Socket constructor`),this.params=bt(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==zt?this.connectWithFallback(zt,this.longPollFallbackMs):this.transportConnect())}log(e,t,n){this.logger&&this.logger(e,t,n)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),n=Date.now();this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:t});let r=this.onMessage(i=>{i.ref===t&&(this.off([r]),e(Date.now()-n))});return!0}transportName(e){switch(e){case zt:return`LongPoll`;default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=[`phoenix`,`${Nt}${btoa(this.authToken()).replace(/=/g,``)}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let n=!1,r=!0,i,a=this.transportName(e),o=t=>{this.log(`transport`,`falling back to ${a}...`,t),this.off([void 0,i]),r=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o(`memorized`);this.fallbackTimer=setTimeout(o,t),i=this.onError(e=>{this.log(`transport`,`error`,e),r&&!n&&(clearTimeout(this.fallbackTimer),o(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!r){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,`true`),this.log(`transport`,`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,t),this.ping(e=>{this.log(`transport`,`connected to primary after`,e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log(`transport`,`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks(`open`)}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log(`transport`,`heartbeat timeout. Attempting to re-establish connection`);try{this.heartbeatCallback(`timeout`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.triggerChanError(Error(`heartbeat timeout`)),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Et,`heartbeat timeout`)}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,n){if(!this.conn)return e&&e();let r=this.conn;this.waitForBufferDone(r,()=>{t?r.close(t,n||``):r.close(),this.waitForSocketClosed(r,()=>{this.conn===r&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,n=1){if(n===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,n+1)},150*n)}waitForSocketClosed(e,t,n=1){if(n===5||e.readyState===Ot.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,n+1)},150*n)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log(`transport`,`close`,e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks(`close`,e)}onConnError(e){this.hasLogger()&&this.log(`transport`,`error`,e);let t=this.transport,n=this.establishedConnections;this.triggerStateCallbacks(`error`,e,t,n),(t===this.transport||n>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(At.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case Ot.connecting:return`connecting`;case Ot.open:return`open`;case Ot.closing:return`closing`;default:return`closed`}}isConnected(){return this.connectionState()===`open`}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>e.indexOf(t)===-1)}channel(e,t={}){let n=new It(e,t,this);return this.channels.push(n),n}push(e){if(this.hasLogger()){let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;this.log(`push`,`${t} ${n} (${a}, ${i})`,r)}this.isConnected()?this.encode(e,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(e,e=>this.conn.send(e)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback(`disconnected`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback(`sent`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){let e=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(r.status===`ok`?`ok`:`error`,e)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log(`receive`,`${r.status||``} ${t} ${n} ${i&&`(`+i+`)`||``}`.trim(),r);for(let e=0;e{try{r(...t)}catch(t){this.log(`error`,`error in ${e} callback`,t)}})}catch(t){this.log(`error`,`error triggering ${e} callbacks`,t)}}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log(`transport`,`leaving duplicate topic "${e}"`),t.leave())}},Ut=class e{constructor(t,n){let r=Kt(n);this.presence=new Bt(t.getChannel(),r),this.presence.onJoin((n,r,i)=>{let a=e.onJoinPayload(n,r,i);t.getChannel().trigger(`presence`,a)}),this.presence.onLeave((n,r,i)=>{let a=e.onLeavePayload(n,r,i);t.getChannel().trigger(`presence`,a)}),this.presence.onSync(()=>{t.getChannel().trigger(`presence`,{event:`sync`})})}get state(){return e.transformState(this.presence.state)}static transformState(e){return e=Gt(e),Object.getOwnPropertyNames(e).reduce((t,n)=>{let r=e[n];return t[n]=Wt(r),t},{})}static onJoinPayload(e,t,n){return{event:`join`,key:e,currentPresences:qt(t),newPresences:Wt(n)}}static onLeavePayload(e,t,n){return{event:`leave`,key:e,currentPresences:qt(t),leftPresences:Wt(n)}}};function Wt(e){return e.metas.map(e=>{let t=Object.getOwnPropertyDescriptors(e),n=Object.defineProperties({},t);return n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n})}function Gt(e){return JSON.parse(JSON.stringify(e))}function Kt(e){return e?.events&&{events:e.events}}function qt(e){return e?.metas?Wt(e):[]}var Jt;(function(e){e.SYNC=`sync`,e.JOIN=`join`,e.LEAVE=`leave`})(Jt||={});var Yt=class{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new Ut(this.channel.channelAdapter,t)}};function Xt(e){if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);if(e&&typeof e==`object`){let t=e;if(typeof t.code==`number`){let n=typeof t.reason==`string`&&t.reason?` (${t.reason})`:``;return Error(`socket closed: ${t.code}${n}`,{cause:e})}return Error(`channel error: transport failure`,{cause:e})}return Error(`channel error: connection lost`)}var Zt=class{constructor(e,t,n){let r=Qt(n);this.channel=e.getSocket().channel(t,r),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,t,n){let r;try{r=this.channel.push(e,t,n)}catch{throw Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>100){let e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log(`channel`,`discarded push due to buffer overflow: ${e.event}`,e.payload())}return r}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===ot.joined}isJoined(){return this.state===ot.joined}isJoining(){return this.state===ot.joining}isClosed(){return this.state===ot.closed}isLeaving(){return this.state===ot.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function Qt(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:``,enabled:!1},private:!1},e.config)}}var $t=/[,()"\\]/,en=e=>$t.test(e)||e!==e.trim(),tn=e=>`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`,nn=e=>{let t=e===null?`null`:String(e);return en(t)?tn(t):t},rn=e=>e===null?`null`:String(e),an=(e,t)=>{if(e===`in`){let e=Array.isArray(t)?t:[t];if(e.length===0)throw Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(e)).map(e=>nn(e)).join(`,`)})`}return e===`is`?`is.${rn(t)}`:`${e}.${nn(t)}`},on=class{constructor(){this.filters=[]}add(e,t,n,r=!1){let i=r?`not.`:``;return this.filters.push(`${e}=${i}${an(t,n)}`),this}eq(e,t){return this.add(e,`eq`,t)}neq(e,t){return this.add(e,`neq`,t)}gt(e,t){return this.add(e,`gt`,t)}gte(e,t){return this.add(e,`gte`,t)}lt(e,t){return this.add(e,`lt`,t)}lte(e,t){return this.add(e,`lte`,t)}in(e,t){return this.add(e,`in`,t)}like(e,t){return this.add(e,`like`,t)}ilike(e,t){return this.add(e,`ilike`,t)}match(e,t){return this.add(e,`match`,t)}imatch(e,t){return this.add(e,`imatch`,t)}is(e,t){return this.add(e,`is`,t)}isDistinct(e,t){return this.add(e,`isdistinct`,t)}not(e,t,n){return this.add(e,t,n,!0)}build(){return this.filters.join(`,`)}toString(){return this.build()}},sn;(function(e){e.ALL=`*`,e.INSERT=`INSERT`,e.UPDATE=`UPDATE`,e.DELETE=`DELETE`})(sn||={});var cn;(function(e){e.BROADCAST=`broadcast`,e.PRESENCE=`presence`,e.POSTGRES_CHANGES=`postgres_changes`,e.SYSTEM=`system`})(cn||={});var ln;(function(e){e.SUBSCRIBED=`SUBSCRIBED`,e.TIMED_OUT=`TIMED_OUT`,e.CLOSED=`CLOSED`,e.CHANNEL_ERROR=`CHANNEL_ERROR`})(ln||={});var un=class e{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,t={config:{}},n){if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,``),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:``,enabled:!1},private:!1},t.config),this.channelAdapter=new Zt(this.socket.socketAdapter,e,this.params),this.presence=new Yt(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=yt(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&this.params.config?.broadcast?.replay)throw Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,t=this.timeout){if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:n,presence:r,private:i}}=this.params,a=this.bindings.postgres_changes?.map(e=>e.filter)??[],o=!!this.bindings[cn.PRESENCE]&&this.bindings[cn.PRESENCE].length>0||this.params.config.presence?.enabled===!0,s={},c={broadcast:n,presence:Object.assign(Object.assign({},r),{enabled:o}),postgres_changes:a,private:i};this.socket.accessTokenValue&&(s.access_token=this.socket.accessTokenValue),this._onError(t=>{e?.(ln.CHANNEL_ERROR,Xt(t))}),this._onClose(()=>e?.(ln.CLOSED)),this.updateJoinPayload(Object.assign({config:c},s)),this._updateFilterMessage(),this.channelAdapter.subscribe(t).receive(`ok`,async({postgres_changes:t})=>{if(this.socket._isManualToken()||this.socket.setAuth(),t===void 0){e?.(ln.SUBSCRIBED);return}this._updatePostgresBindings(t,e)}).receive(`error`,t=>{this.state=ot.errored;let n=Object.values(t).join(`, `)||`error`;e?.(ln.CHANNEL_ERROR,Error(n,{cause:t}))}).receive(`timeout`,()=>{e?.(ln.TIMED_OUT)})}return this}_updatePostgresBindings(t,n){let r=this.bindings.postgres_changes,i=r?.length??0,a=[];for(let o=0;o{let r=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);e.type===`broadcast`&&!this.params?.config?.broadcast?.ack&&n(`ok`),r.receive(`ok`,()=>n(`ok`)),r.receive(`error`,()=>n(`error`)),r.receive(`timeout`,()=>n(`timed out`))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(t=>{this.channelAdapter.unsubscribe(e).receive(`ok`,()=>t(`ok`)).receive(`timeout`,()=>t(`timed out`)).receive(`error`,()=>t(`error`))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),a}_on(e,t,n){let r=e.toLocaleLowerCase(),i=t?.filter;(i instanceof on||typeof i==`object`&&i&&typeof i.build==`function`)&&(t=Object.assign(Object.assign({},t),{filter:i.build()}));let a=this.channelAdapter.on(e,n),o={type:r,filter:t,callback:n,ref:a};return this.bindings[r]?this.bindings[r].push(o):this.bindings[r]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,n)=>{let r=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(r,n))return!1;let i=this.bindings[r]?.find(t=>t.ref===e.ref);if(!i)return!0;if([`broadcast`,`presence`,`postgres_changes`].includes(r))if(`id`in i){let e=i.id,n=i.filter?.event;return e&&t.ids?.includes(e)&&(n===`*`||n?.toLocaleLowerCase()===t.data?.type.toLocaleLowerCase())}else{let e=(i?.filter?.event)?.toLocaleLowerCase();return e===`*`||e===(t?.event)?.toLocaleLowerCase()}else return i.type.toLocaleLowerCase()===r})}_notThisChannelEvent(e,t){let{close:n,error:r,leave:i,join:a}=st;return t&&[n,r,i,a].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,n)=>{if(typeof t==`object`&&`ids`in t){let e=t.data,{schema:n,table:r,commit_timestamp:i,type:a,errors:o}=e;return Object.assign(Object.assign({},{schema:n,table:r,commit_timestamp:i,eventType:a,new:{},old:{},errors:o}),this._getPayloadRecords(e))}return t})}copyBindings(e){if(this.joinedOnce)throw Error(`cannot copy bindings into joined channel`);for(let t in e.bindings)for(let n of e.bindings[t])this._on(n.type,n.filter,n.callback)}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type===`INSERT`||e.type===`UPDATE`)&&(t.new=ut(e.columns,e.record)),(e.type===`UPDATE`||e.type===`DELETE`)&&(t.old=ut(e.columns,e.old_record)),t}},dn=class{constructor(e,t){this.socket=new Ht(e,t)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,n,r=1e4){return new Promise(i=>{setTimeout(()=>i(`timeout`),r),this.socket.disconnect(()=>{e(),i(`ok`)},t,n)})}push(e){this.socket.push(e)}log(e,t,n){this.socket.log(e,t,n)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==ct.connecting}isDisconnecting(){return this.socket.connectionState()==ct.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}},fn={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},pn=[1e3,2e3,5e3,1e4],mn=1e4;function hn(){let e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem(t){return e.has(t)?e.get(t):null},key(t){return Array.from(e.keys())[t]??null},removeItem(t){e.delete(t)},setItem(t,n){e.set(t,String(n))}}}function gn(){try{if(typeof globalThis<`u`&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return hn()}var _n=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`,vn=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,t){if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint=``,this.headers={},this.params={},this.ref=0,this.serializer=new lt,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!t?.params?.apikey)throw Error(`API key is required to connect to Realtime`);this.apiKey=t.params.apikey;let n=this._initializeOptions(t);this.socketAdapter=new dn(e,n),this.httpEndpoint=yt(e),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely(`connect`),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let t=e.message;throw Error(`WebSocket not available: ${t}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return this._cancelPendingDisconnect(),this.isDisconnecting()?`ok`:await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return t===`ok`&&e.teardown(),t}async removeAllChannels(){let e=this.channels.map(async e=>{let t=await e.unsubscribe();return e.teardown(),t}),t=await Promise.all(e);return await this.disconnect(),t}log(e,t,n){this.socketAdapter.log(e,t,n)}connectionState(){return this.socketAdapter.connectionState()||ct.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let n=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===n);if(r)return r;{let n=new un(`realtime:${e}`,t,this);return this._cancelPendingDisconnect(),this.channels.push(n),n}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic),this.channels.length===0&&(this.log(`transport`,`no channels remaining, scheduling disconnect`),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log(`transport`,`disconnecting immediately - no channels`),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log(`transport`,`deferred disconnect fired - no channels, disconnecting`),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log(`transport`,`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log(`transport`,`pending disconnect cancelled - channel activity detected`),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let t,n=!1;if(e)t=e,n=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log(`error`,`Error fetching access token from callback`,e),t=this.accessTokenValue}else t=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{let n={access_token:t,version:tt};t&&e.updateJoinPayload(n),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(st.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e=`general`){this._isManualToken()||this.setAuth().catch(t=>{this.log(`error`,`Error setting auth in ${e}`,t)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(e=>{this.log(`error`,`error waiting for auth on connect`,e)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,n)=>{t!==`disconnected`&&(t==`sent`&&this._setAuthSafely(),e&&e(t,n))}}_startWorkerHeartbeat(){this.workerUrl?this.log(`worker`,`starting worker for from ${this.workerUrl}`):this.log(`worker`,`starting default worker`);let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log(`worker`,`worker error`,e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{e.data.event===`keepAlive`&&this.sendHeartbeat()},this.workerRef.postMessage({event:`start`,interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&=(this.log(`worker`,`terminating worker`),this.workerRef.terminate(),void 0)}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([_n],{type:`application/javascript`});t=URL.createObjectURL(e)}return t}_initializeOptions(e){this.worker=e?.worker??!1,this.accessToken=e?.accessToken??null;let t={};t.timeout=e?.timeout??at,t.heartbeatIntervalMs=e?.heartbeatIntervalMs??fn.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=e?.disconnectOnEmptyChannelsAfterMs??2*(e?.heartbeatIntervalMs??fn.HEARTBEAT_INTERVAL),t.transport=e?.transport??et.getWebSocketConstructor(),t.params=e?.params,t.logger=e?.logger,t.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),t.sessionStorage=e?.sessionStorage??gn(),t.reconnectAfterMs=e?.reconnectAfterMs??(e=>pn[e-1]||mn);let n,r,i=e?.vsn??it;switch(i){case nt:n=(e,t)=>t(JSON.stringify(e)),r=(e,t)=>t(JSON.parse(e));break;case rt:n=this.serializer.encode.bind(this.serializer),r=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${t.vsn}`)}if(t.vsn=i,t.encode=e?.encode??n,t.decode=e?.decode??r,t.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,t.params=Object.assign(Object.assign({},t.params),{log_level:this.logLevel})),this.worker){if(typeof window<`u`&&!window.Worker)throw Error(`Web Worker is not supported`);this.workerUrl=e?.workerUrl,t.autoSendHeartbeat=!this.worker}return t}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}},yn=class extends Error{constructor(e,t){super(e),this.name=`IcebergError`,this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType===`CommitStateUnknownException`||[500,502,504].includes(t.status)&&t.icebergType?.includes(`CommitState`)===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function bn(e,t,n){let r=new URL(t,e);if(n)for(let[e,t]of Object.entries(n))t!==void 0&&r.searchParams.set(e,t);return r.toString()}async function xn(e){return!e||e.type===`none`?{}:e.type===`bearer`?{Authorization:`Bearer ${e.token}`}:e.type===`header`?{[e.name]:e.value}:e.type===`custom`?await e.getHeaders():{}}function Sn(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:i,body:a,headers:o}){let s=bn(e.baseUrl,r,i),c=await xn(e.auth),l=await t(s,{method:n,headers:{...a?{"Content-Type":`application/json`}:{},...c,...o},body:a?JSON.stringify(a):void 0}),u=await l.text(),d=(l.headers.get(`content-type`)||``).includes(`application/json`),f=d&&u?JSON.parse(u):u;if(!l.ok){let e=d?f:void 0,t=e?.error;throw new yn(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:f}}}}function Cn(e){return e.join(``)}var wn=class{constructor(e,t=``){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:Cn(e.namespace)}:void 0;return(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let n={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:`POST`,path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:`DELETE`,path:`${this.prefix}/namespaces/${Cn(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Cn(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${Cn(e.namespace)}`}),!0}catch(e){if(e instanceof yn&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof yn&&e.status===409)return;throw e}}};function Tn(e){return e.join(``)}var En=class{constructor(e,t=``,n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Tn(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let n={};return this.accessDelegation&&(n[`X-Iceberg-Access-Delegation`]=this.accessDelegation),(await this.client.request({method:`POST`,path:`${this.prefix}/namespaces/${Tn(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){let n=await this.client.request({method:`POST`,path:`${this.prefix}/namespaces/${Tn(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data[`metadata-location`],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:`DELETE`,path:`${this.prefix}/namespaces/${Tn(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t[`X-Iceberg-Access-Delegation`]=this.accessDelegation),(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Tn(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t[`X-Iceberg-Access-Delegation`]=this.accessDelegation);try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${Tn(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof yn&&e.status===404)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof yn&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},Dn=class{constructor(e){let t=`v1`;e.catalogName&&(t+=`/${e.catalogName}`);let n=e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`;this.client=Sn({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(`,`),this.namespaceOps=new wn(this.client,t),this.tableOps=new En(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};function On(e){"@babel/helpers - typeof";return On=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},On(e)}function kn(e,t){if(On(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(On(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function An(e){var t=kn(e,`string`);return On(t)==`symbol`?t:t+``}function jn(e,t,n){return(t=An(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Mn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function D(e){for(var t=1;te?(...t)=>e(...t):(...e)=>fetch(...e),Bn=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Vn=e=>{if(Array.isArray(e))return e.map(e=>Vn(e));if(typeof e==`function`||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,``));t[r]=Vn(n)}),t},Hn=e=>!e||typeof e!=`string`||e.length===0||e.length>100||e.trim()!==e||e.includes(`/`)||e.includes(`\\`)?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e),Un=e=>e.split(`/`).map(encodeURIComponent).join(`/`),Wn=e=>{if(typeof e==`object`&&e){let t=e;if(typeof t.msg==`string`)return t.msg;if(typeof t.message==`string`)return t.message;if(typeof t.error_description==`string`)return t.error_description;if(typeof t.error==`string`)return t.error;if(typeof t.error==`object`&&t.error!==null){let e=t.error;if(typeof e.message==`string`)return e.message}}return JSON.stringify(e)},Gn=async(e,t,n,r)=>{if(typeof e==`object`&&e&&`json`in e&&typeof e.json==`function`){let n=e,i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(e=>{let n=e?.statusCode||e?.code||i+``;t(new Fn(Wn(e),i,n,r))}).catch(()=>{let e=i+``;t(new Fn(n.statusText||`HTTP ${i} error`,i,e,r))})}else t(new In(Wn(e),e,r))},Kn=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};if(e===`GET`||e===`HEAD`||!r)return D(D({},i),n);if(Bn(r)){let e=t?.headers||{},n;for(let[t,r]of Object.entries(e))t.toLowerCase()===`content-type`&&(n=r);i.headers=Ln(e,`Content-Type`,n??`application/json`),i.body=JSON.stringify(r)}else i.body=r;return t?.duplex&&(i.duplex=t.duplex),D(D({},i),n)};async function qn(e,t,n,r,i,a,o){return new Promise((s,c)=>{e(n,Kn(t,r,i,a)).then(e=>{if(!e.ok)throw e;if(r?.noResolveJson)return e;if(o===`vectors`){let t=e.headers.get(`content-type`);if(e.headers.get(`content-length`)===`0`||e.status===204||!t||!t.includes(`application/json`))return{}}return e.json()}).then(e=>s(e)).catch(e=>Gn(e,c,r,o))})}function Jn(e=`storage`){return{get:async(t,n,r,i)=>qn(t,`GET`,n,r,i,void 0,e),post:async(t,n,r,i,a)=>qn(t,`POST`,n,i,a,r,e),put:async(t,n,r,i,a)=>qn(t,`PUT`,n,i,a,r,e),head:async(t,n,r,i)=>qn(t,`HEAD`,n,D(D({},r),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,n,r,i,a)=>qn(t,`DELETE`,n,i,a,r,e)}}var{get:Yn,post:Xn,put:Zn,head:Qn,remove:$n}=Jn(`storage`),er=Jn(`vectors`),tr=class{constructor(e,t={},n,r=`storage`){this.shouldThrowOnError=!1,this.url=e,this.headers=Rn(t),this.fetch=zn(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Ln(this.headers,e,t),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pn(e))return{data:null,error:e};throw e}}},nr=Symbol.toStringTag,rr=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[nr]=`StreamDownloadBuilder`,this.promise=null}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||=this.execute(),this.promise}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Pn(t))return{data:null,error:t};throw t}}},ir=Symbol.toStringTag,ar=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[ir]=`BlobDownloadBuilder`,this.promise=null}asStream(){return new rr(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||=this.execute(),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Pn(t))return{data:null,error:t};throw t}}},or={limit:100,offset:0,sortBy:{column:`name`,order:`asc`}},sr={cacheControl:`3600`,contentType:`text/plain;charset=UTF-8`,upsert:!1},cr=class extends tr{constructor(e,t={},n,r){super(e,t,r,`storage`),this.bucketId=n}async uploadOrUpdate(e,t,n,r){var i=this;return i.handleOperation(async()=>{let a,o=D(D({},sr),r),s=D(D({},i.headers),e===`POST`&&{"x-upsert":String(o.upsert)}),c=o.metadata;if(typeof Blob<`u`&&n instanceof Blob?(a=new FormData,a.append(`cacheControl`,o.cacheControl),c&&a.append(`metadata`,i.encodeMetadata(c)),a.append(``,n)):typeof FormData<`u`&&n instanceof FormData?(a=n,a.has(`cacheControl`)||a.append(`cacheControl`,o.cacheControl),c&&!a.has(`metadata`)&&a.append(`metadata`,i.encodeMetadata(c))):(a=n,s[`cache-control`]=`max-age=${o.cacheControl}`,s[`content-type`]=o.contentType,c&&(s[`x-metadata`]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<`u`&&a instanceof ReadableStream||a&&typeof a==`object`&&`pipe`in a&&typeof a.pipe==`function`)&&!o.duplex&&(o.duplex=`half`)),r?.headers)for(let[e,t]of Object.entries(r.headers))s=Ln(s,e,t);let l=i._removeEmptyFolders(t),u=i._getFinalPath(l),d=await(e==`PUT`?Zn:Xn)(i.fetch,`${i.url}/object/${u}`,a,D({headers:s},o?.duplex?{duplex:o.duplex}:{}));return{path:l,id:d.Id,fullPath:d.Key}})}async upload(e,t,n){return this.uploadOrUpdate(`POST`,e,t,n)}async uploadToSignedUrl(e,t,n,r){var i=this;let a=i._removeEmptyFolders(e),o=i._getFinalPath(a),s=new URL(i.url+`/object/upload/sign/${o}`);return s.searchParams.set(`token`,t),i.handleOperation(async()=>{let e,t=D(D({},sr),r),o=D(D({},i.headers),{"x-upsert":String(t.upsert)}),c=t.metadata;if(typeof Blob<`u`&&n instanceof Blob?(e=new FormData,e.append(`cacheControl`,t.cacheControl),c&&e.append(`metadata`,i.encodeMetadata(c)),e.append(``,n)):typeof FormData<`u`&&n instanceof FormData?(e=n,e.has(`cacheControl`)||e.append(`cacheControl`,t.cacheControl),c&&!e.has(`metadata`)&&e.append(`metadata`,i.encodeMetadata(c))):(e=n,o[`cache-control`]=`max-age=${t.cacheControl}`,o[`content-type`]=t.contentType,c&&(o[`x-metadata`]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<`u`&&e instanceof ReadableStream||e&&typeof e==`object`&&`pipe`in e&&typeof e.pipe==`function`)&&!t.duplex&&(t.duplex=`half`)),r?.headers)for(let[e,t]of Object.entries(r.headers))o=Ln(o,e,t);return{path:a,fullPath:(await Zn(i.fetch,s.toString(),e,D({headers:o},t?.duplex?{duplex:t.duplex}:{}))).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(e),i=D({},n.headers);t?.upsert&&(i[`x-upsert`]=`true`);let a=await Xn(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(n.url+a.url),s=o.searchParams.get(`token`);if(!s)throw new Nn(`No token returned by API`);return{signedUrl:o.toString(),path:e,token:s}})}async update(e,t,n){return this.uploadOrUpdate(`PUT`,e,t,n)}async move(e,t,n){var r=this;return r.handleOperation(async()=>await Xn(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket},{headers:r.headers}))}async copy(e,t,n){var r=this;return r.handleOperation(async()=>({path:(await Xn(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(e,t,n){var r=this;return r.handleOperation(async()=>{let i=r._getFinalPath(e),a=typeof n?.transform==`object`&&n.transform!==null&&Object.keys(n.transform).length>0,o=await Xn(r.fetch,`${r.url}/object/sign/${i}`,D({expiresIn:t},a?{transform:n.transform}:{}),{headers:r.headers}),s=new URLSearchParams;n?.download&&s.set(`download`,n.download===!0?``:n.download),n?.cacheNonce!=null&&s.set(`cacheNonce`,String(n.cacheNonce));let c=s.toString();return{signedUrl:encodeURI(`${r.url}${o.signedURL}${c?`&${c}`:``}`)}})}async createSignedUrls(e,t,n){var r=this;return r.handleOperation(async()=>{let i=await Xn(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),a=new URLSearchParams;n?.download&&a.set(`download`,n.download===!0?``:n.download),n?.cacheNonce!=null&&a.set(`cacheNonce`,String(n.cacheNonce));let o=a.toString();return i.map(e=>D(D({},e),{},{signedUrl:e.signedURL?encodeURI(`${r.url}${e.signedURL}${o?`&${o}`:``}`):null}))})}download(e,t,n){let r=typeof t?.transform==`object`&&t.transform!==null&&Object.keys(t.transform).length>0?`render/image/authenticated`:`object`,i=new URLSearchParams;t?.transform&&this.applyTransformOptsToQuery(i,t.transform),t?.cacheNonce!=null&&i.set(`cacheNonce`,String(t.cacheNonce));let a=i.toString(),o=this._getFinalPath(e);return new ar(()=>Yn(this.fetch,`${this.url}/${r}/${o}${a?`?${a}`:``}`,{headers:this.headers,noResolveJson:!0},n),this.shouldThrowOnError)}async info(e){var t=this;let n=t._getFinalPath(e);return t.handleOperation(async()=>Vn(await Yn(t.fetch,`${t.url}/object/info/${n}`,{headers:t.headers})))}async exists(e){var t=this;let n=t._getFinalPath(e);try{return await Qn(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pn(e)){let t=e instanceof Fn?e.status:e instanceof In?e.originalError?.status:void 0;if(t!==void 0&&[400,404].includes(t))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let n=this._getFinalPath(e),r=new URLSearchParams;t?.download&&r.set(`download`,t.download===!0?``:t.download),t?.transform&&this.applyTransformOptsToQuery(r,t.transform),t?.cacheNonce!=null&&r.set(`cacheNonce`,String(t.cacheNonce));let i=r.toString(),a=typeof t?.transform==`object`&&t.transform!==null&&Object.keys(t.transform).length>0?`render/image`:`object`;return{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${n}`)+(i?`?${i}`:``)}}}async remove(e){var t=this;return t.handleOperation(async()=>await $n(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async purgeCache(e,t,n){var r=this;return r.handleOperation(async()=>{let i=Un(r._getFinalPath(e)),a=new URLSearchParams;t?.transformations&&a.set(`transformations`,`true`);let o=a.toString();return await $n(r.fetch,`${r.url}/cdn/${i}${o?`?${o}`:``}`,{},{headers:r.headers},n)})}async list(e,t,n){var r=this;return r.handleOperation(async()=>{let i=t?.sortBy?D(D({},or.sortBy),t.sortBy):or.sortBy,a=D(D(D({},or),t),{},{sortBy:i,prefix:e||``});return await Xn(r.fetch,`${r.url}/object/list/${r.bucketId}`,a,{headers:r.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{let r=D({},e);return await Xn(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},t)})}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.replace(/^\/+/,``)}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,``).replace(/\/+/g,`/`)}applyTransformOptsToQuery(e,t){return t.width&&e.set(`width`,t.width.toString()),t.height&&e.set(`height`,t.height.toString()),t.resize&&e.set(`resize`,t.resize),t.format&&e.set(`format`,t.format),t.quality&&e.set(`quality`,t.quality.toString()),e}},lr={"X-Client-Info":`storage-js/2.111.0`},ur=class extends tr{constructor(e,t={},n,r){let i=new URL(e);r?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes(`storage.supabase.`)&&(i.hostname=i.hostname.replace(`supabase.`,`storage.supabase.`));let a=i.href.replace(/\/$/,``),o=D(D({},lr),t);super(a,o,n,`storage`)}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=t.listBucketOptionsToQueryString(e);return await Yn(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Yn(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await Xn(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await Zn(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await Xn(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await $n(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}async purgeBucketCache(e,t,n){var r=this;return r.handleOperation(async()=>{let i=new URLSearchParams;t?.transformations&&i.set(`transformations`,`true`);let a=i.toString();return await $n(r.fetch,`${r.url}/cdn/${Un(e)}${a?`?${a}`:``}`,{},{headers:r.headers},n)})}listBucketOptionsToQueryString(e){let t={};return e&&(`limit`in e&&(t.limit=String(e.limit)),`offset`in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?`?`+new URLSearchParams(t).toString():``}},dr=class extends tr{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=D(D({},lr),t);super(r,i,n,`storage`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await Xn(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=new URLSearchParams;e?.limit!==void 0&&n.set(`limit`,e.limit.toString()),e?.offset!==void 0&&n.set(`offset`,e.offset.toString()),e?.sortColumn&&n.set(`sortColumn`,e.sortColumn),e?.sortOrder&&n.set(`sortOrder`,e.sortOrder),e?.search&&n.set(`search`,e.search);let r=n.toString(),i=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await Yn(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await $n(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!Hn(e))throw new Nn(`Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.`);let n=new Dn({baseUrl:this.url,catalogName:e,auth:{type:`custom`,getHeaders:async()=>t.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(e,t){let n=e[t];return typeof n==`function`?async(...t)=>{try{return{data:await n.apply(e,t),error:null}}catch(e){if(r)throw e;return{data:null,error:e}}}:n}})}},fr=class extends tr{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=D(D({},lr),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createIndex(e){var t=this;return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await er.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await er.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},pr=class extends tr{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=D(D({},lr),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error(`Vector batch size must be between 1 and 500 items`);return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw Error(`segmentCount must be between 1 and 16`);if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error(`Keys batch size must be between 1 and 500 items`);return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},mr=class extends tr{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=D(D({},lr),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await er.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},hr=class extends mr{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new gr(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},gr=class extends fr{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new _r(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},_r=class extends pr{constructor(e,t,n,r,i){super(e,t,i),this.vectorBucketName=n,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},vr=class extends ur{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new cr(this.url,this.headers,e,this.fetch)}get vectors(){return new hr(this.url+`/vector`,{headers:this.headers,fetch:this.fetch})}get analytics(){return new dr(this.url+`/iceberg`,this.headers,this.fetch)}},yr=`2.111.0`,br=30*1e3,xr=3*br,Sr=2*br,Cr=`http://localhost:9999`,wr=`supabase.auth.token`,Tr={"X-Client-Info":`gotrue-js/${yr}`},Er=`X-Supabase-Api-Version`,Dr={"2024-01-01":{timestamp:Date.parse(`2024-01-01T00:00:00.0Z`),name:`2024-01-01`}},Or=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,kr=`sb_flow_id`,Ar=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name=`AuthError`,this.status=t,this.code=n}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};function O(e){return typeof e==`object`&&!!e&&`__isAuthError`in e}var jr=class extends Ar{constructor(e,t,n){super(e,t,n),this.name=`AuthApiError`,this.status=t,this.code=n}};function Mr(e){return O(e)&&e.name===`AuthApiError`}var Nr=class extends Ar{constructor(e,t){super(e),this.name=`AuthUnknownError`,this.originalError=t}},Pr=class extends Ar{constructor(e,t,n,r){super(e,n,r),this.name=t,this.status=n}},Fr=class extends Pr{constructor(){super(`Auth session missing!`,`AuthSessionMissingError`,400,void 0)}};function Ir(e){return O(e)&&e.name===`AuthSessionMissingError`}var Lr=class extends Pr{constructor(){super(`Auth session or user missing`,`AuthInvalidTokenResponseError`,500,void 0)}},Rr=class extends Pr{constructor(e){super(e,`AuthInvalidCredentialsError`,400,void 0)}},zr=class extends Pr{constructor(e,t=null){super(e,`AuthImplicitGrantRedirectError`,500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function Br(e){return O(e)&&e.name===`AuthImplicitGrantRedirectError`}var Vr=class extends Pr{constructor(e,t=null){super(e,`AuthPKCEGrantCodeExchangeError`,500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Hr=class extends Pr{constructor(){super(`PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.`,`AuthPKCECodeVerifierMissingError`,400,`pkce_code_verifier_not_found`)}},Ur=class extends Pr{constructor(e,t){super(e,`AuthRetryableFetchError`,t,void 0)}};function Wr(e){return O(e)&&e.name===`AuthRetryableFetchError`}var Gr=class extends Pr{constructor(e=`Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)`){super(e,`AuthRefreshDiscardedError`,409,void 0)}};function Kr(e){return O(e)&&e.name===`AuthRefreshDiscardedError`}var qr=class extends Pr{constructor(e,t,n){super(e,`AuthWeakPasswordError`,t,`weak_password`),this.reasons=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}},Jr=class extends Pr{constructor(e){super(e,`AuthInvalidJwtError`,400,`invalid_jwt`)}},Yr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`.split(``),Xr=` \r=`.split(``),Zr=(()=>{let e=Array(128);for(let t=0;t=6;)n(Yr[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue<<=6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)n(Yr[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function $r(e,t,n){let r=Zr[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(r===-2)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function ei(e){let t=[],n=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=e=>{ri(e,r,n)};for(let t=0;t>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function ni(e,t){for(let n=0;n55295&&r<=56319){let t=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|t)+65536,n+=1}ti(r,t)}}function ri(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let n=1;n<6;n+=1)if(!(e>>7-n&1)){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw Error(`Invalid UTF-8 sequence`);--t.utf8seq}else if(t.utf8seq>0){if(e<=127)throw Error(`Invalid UTF-8 sequence`);t.codepoint=t.codepoint<<6|e&63,--t.utf8seq,t.utf8seq===0&&n(t.codepoint)}}function ii(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;tt.push(e)),new Uint8Array(t)}function oi(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>Qr(e,n,r)),Qr(null,n,r),t.join(``)}function si(e){return Math.round(Date.now()/1e3)+e}function ci(){return Symbol(`auth-callback`)}var li=()=>typeof window<`u`&&typeof document<`u`,ui={tested:!1,writable:!1},di=()=>{if(!li())return!1;try{if(typeof globalThis.localStorage!=`object`)return!1}catch{return!1}if(ui.tested)return ui.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),ui.tested=!0,ui.writable=!0}catch{ui.tested=!0,ui.writable=!1}return ui.writable};function fi(e){let t={},n=new URL(e);if(n.hash&&n.hash[0]===`#`)try{new URLSearchParams(n.hash.substring(1)).forEach((e,n)=>{t[n]=e})}catch{}return n.searchParams.forEach((e,n)=>{t[n]=e}),t}var pi=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),mi=e=>typeof e==`object`&&!!e&&`status`in e&&`ok`in e&&`json`in e&&typeof e.json==`function`,hi=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},gi=async(e,t)=>{let n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return null}},_i=async(e,t)=>{await e.removeItem(t)},vi=class e{constructor(){this.promise=new e.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};vi.promiseConstructor=Promise;function yi(e){let t=e.split(`.`);if(t.length!==3)throw new Jr(`Invalid JWT structure`);for(let e=0;e{setTimeout(()=>t(null),e)})}function xi(e,t){return new Promise((n,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{let r=await e(i);if(!t(i,null,r)){n(r);return}}catch(e){if(!t(i,e)){r(e);return}}})()})}function Si(e){return(`0`+e.toString(16)).substr(-2)}function Ci(){let e=new Uint32Array(56);if(typeof crypto>`u`){let e=``;for(let t=0;t<56;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~`.charAt(Math.floor(Math.random()*66));return e}return crypto.getRandomValues(e),Array.from(e,Si).join(``)}async function wi(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n);return Array.from(r).map(e=>String.fromCharCode(e)).join(``)}async function Ti(e){if(!(typeof crypto<`u`&&crypto.subtle!==void 0&&typeof TextEncoder<`u`))return console.warn(`WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.`),e;let t=await wi(e);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Ei=/^[a-zA-Z0-9_-]{8,64}$/;function Di(e){return typeof e==`string`&&Ei.test(e)?e:null}function Oi(){if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,Si).join(``)}let e=``;for(let t=0;t<32;t++)e+=Math.floor(Math.random()*16).toString(16);return e}var ki=(e,t)=>`${e}-flow-${t}-code-verifier`,Ai=e=>`${e}-flows-code-verifier`;async function ji(e,t){let n=await gi(e,Ai(t));return Array.isArray(n)?n.filter(e=>Di(e)!==null):[]}async function Mi(e,t,n,r,i){await hi(e,ki(t,n),r);let a=(await ji(e,t)).filter(e=>e!==n);for(a.push(n);a.length>5;){let n=a.shift();await _i(e,ki(t,n)),i?.(n)}await hi(e,Ai(t),a),await hi(e,`${t}-code-verifier`,r)}async function Ni(e,t,n){if(n){let r=await gi(e,ki(t,n));return{verifier:typeof r==`string`?r:null,flowId:n}}let r=await gi(e,`${t}-code-verifier`);return{verifier:typeof r==`string`?r:null,flowId:null}}async function k(e,t,n){let r=`${t}-code-verifier`;if(!n){await _i(e,r);return}let i=ki(t,n),a=await gi(e,i);await _i(e,i);let o=await ji(e,t),s=o.filter(e=>e!==n);s.length!==o.length&&(s.length>0?await hi(e,Ai(t),s):await _i(e,Ai(t))),a!=null&&a===await gi(e,r)&&await _i(e,r)}async function Pi(e,t){let n=await ji(e,t);for(let r of n)await _i(e,ki(t,r));await _i(e,Ai(t)),await _i(e,`${t}-code-verifier`)}function Fi(e,t){let n=e.indexOf(`#`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n),a=r.indexOf(`?`);if(a!==-1){let e=r.slice(0,a),t=r.slice(a+1).split(`&`).filter(e=>e!==``&&e!==`sb_flow_id`&&!e.startsWith(`sb_flow_id=`));r=t.length>0?`${e}?${t.join(`&`)}`:e}let o=r.includes(`?`)?`&`:`?`;return`${r}${o}${kr}=${encodeURIComponent(t)}${i}`}async function Ii(e,t,n=!1,r){let i=Ci(),a=i;n&&(a+=`/recovery`);let o=Oi();await Mi(e,t,o,a,r);let s=await Ti(i);return[s,i===s?`plain`:`s256`,o]}var Li=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ri(e){let t=e.headers.get(Er);if(!t||!t.match(Li))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function zi(e){if(!e)throw Error(`Missing exp claim`);if(e<=Math.floor(Date.now()/1e3))throw Error(`JWT has expired`)}function Bi(e){switch(e){case`RS256`:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case`ES256`:return{name:`ECDSA`,namedCurve:`P-256`,hash:{name:`SHA-256`}};default:throw Error(`Invalid alg claim`)}}var Vi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function A(e){if(!Vi.test(e))throw Error(`@supabase/auth-js: Expected parameter to be UUID but is not`)}function j(e){if(!e.passkey)throw Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function M(){return new Proxy({},{get:(e,t)=>{if(t===`__isUserNotAvailableProxy`)return!0;if(typeof t==`symbol`){let e=t.toString();if(e===`Symbol(Symbol.toPrimitive)`||e===`Symbol(Symbol.toStringTag)`||e===`Symbol(util.inspect.custom)`)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Hi(e,t){return new Proxy(e,{get:(e,n,r)=>{if(n===`__isInsecureUserWarningProxy`)return!0;if(typeof n==`symbol`){let t=n.toString();if(t===`Symbol(Symbol.toPrimitive)`||t===`Symbol(Symbol.toStringTag)`||t===`Symbol(util.inspect.custom)`||t===`Symbol(nodejs.util.inspect.custom)`)return Reflect.get(e,n,r)}return!t.value&&typeof n==`string`&&(console.warn(`Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.`),t.value=!0),Reflect.get(e,n,r)}})}function Ui(e){return JSON.parse(JSON.stringify(e))}De();var Wi=e=>{if(typeof e==`object`&&e){let t=e;if(typeof t.msg==`string`)return t.msg;if(typeof t.message==`string`)return t.message;if(typeof t.error_description==`string`)return t.error_description;if(typeof t.error==`string`)return t.error}return JSON.stringify(e)},Gi=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function Ki(e){if(!mi(e))throw new Ur(Wi(e),0);if(Gi.includes(e.status))throw new Ur(Wi(e),e.status);let t;try{t=await e.json()}catch(e){throw new Nr(Wi(e),e)}let n,r=Ri(e);if(r&&r.getTime()>=Dr[`2024-01-01`].timestamp&&typeof t==`object`&&t&&typeof t.code==`string`?n=t.code:typeof t==`object`&&t&&typeof t.error_code==`string`&&(n=t.error_code),!n){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((e,t)=>e&&typeof t==`string`,!0))throw new qr(Wi(t),e.status,t.weak_password.reasons)}else if(n===`weak_password`)throw new qr(Wi(t),e.status,t.weak_password?.reasons||[]);else if(n===`session_not_found`)throw new Fr;throw new jr(Wi(t),e.status||500,n)}var qi=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};return e===`GET`?i:(i.headers=Object.assign({"Content-Type":`application/json;charset=UTF-8`},t?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function N(e,t,n,r){let i=Object.assign({},r?.headers);i[`X-Supabase-Api-Version`]||(i[Er]=Dr[`2024-01-01`].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let a=r?.query??{};r?.redirectTo&&(a.redirect_to=r.redirectTo);let o=await Ji(e,t,n+(Object.keys(a).length?`?`+new URLSearchParams(a).toString():``),{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(o):{data:Object.assign({},o),error:null}}async function Ji(e,t,n,r,i,a){let o=qi(t,r,i,a),s;try{s=await e(n,Object.assign({},o))}catch(e){throw new Ur(Wi(e),0)}if(s.ok||await Ki(s),r?.noResolveJson)return s;try{return await s.json()}catch(e){await Ki(e)}}function Yi(e){let t=null;ta(e)&&(t=Object.assign({},e),e.expires_at||(t.expires_at=si(e.expires_in)));let n=e.user??(typeof e?.id==`string`?e:null);return{data:{session:t,user:n},error:null}}function Xi(e){let t=Yi(e);return!t.error&&e.weak_password&&typeof e.weak_password==`object`&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message==`string`&&e.weak_password.reasons.reduce((e,t)=>e&&typeof t==`string`,!0)&&(t.data.weak_password=e.weak_password),t}function Zi(e){return{data:{user:e.user??e},error:null}}function Qi(e){return{data:e,error:null}}function $i(e){let{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:a}=e,o=_(e,[`action_link`,`email_otp`,`hashed_token`,`redirect_to`,`verification_type`]);return{data:{properties:{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:a},user:Object.assign({},o)},error:null}}function ea(e){return e}function ta(e){return!!e.access_token&&!!e.refresh_token&&!!e.expires_in}var na=[`global`,`local`,`others`];De();var ra=class{constructor({url:e=``,headers:t={},fetch:n,experimental:r}){this.url=e,this.headers=t,this.fetch=pi(n),this.experimental=r??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=na[0]){if(na.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${na.join(`, `)}`);try{return await N(this.fetch,`POST`,`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(O(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await N(this.fetch,`POST`,`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Zi})}catch(e){if(O(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,n=_(e,[`options`]),r=Object.assign(Object.assign({},n),t);return`newEmail`in n&&(r.new_email=n?.newEmail,delete r.newEmail),await N(this.fetch,`POST`,`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:$i,redirectTo:t?.redirectTo})}catch(e){if(O(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await N(this.fetch,`POST`,`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Zi})}catch(e){if(O(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},n=await N(this.fetch,`GET`,`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:ea});if(n.error)throw n.error;let r=await n.json(),i=n.headers.get(`x-total-count`)??0,a=n.headers.get(`link`)?.split(`,`)??[];return a.length>0&&(a.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(i)),{data:Object.assign(Object.assign({},r),t),error:null}}catch(e){if(O(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){A(e);try{return await N(this.fetch,`GET`,`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Zi})}catch(e){if(O(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){A(e);try{return await N(this.fetch,`PUT`,`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Zi})}catch(e){if(O(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){A(e);try{return await N(this.fetch,`DELETE`,`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Zi})}catch(e){if(O(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){A(e.userId);try{let{data:t,error:n}=await N(this.fetch,`GET`,`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:n}}catch(e){if(O(e))return{data:null,error:e};throw e}}async _deleteFactor(e){A(e.userId),A(e.id);try{return{data:await N(this.fetch,`DELETE`,`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(O(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){try{let t={nextPage:null,lastPage:0,total:0},n=await N(this.fetch,`GET`,`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:ea});if(n.error)throw n.error;let r=await n.json(),i=n.headers.get(`x-total-count`)??0,a=n.headers.get(`link`)?.split(`,`)??[];return a.length>0&&(a.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(i)),{data:Object.assign(Object.assign({},r),t),error:null}}catch(e){if(O(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await N(this.fetch,`POST`,`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(O(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await N(this.fetch,`GET`,`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(O(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await N(this.fetch,`PUT`,`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(O(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await N(this.fetch,`DELETE`,`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(O(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await N(this.fetch,`POST`,`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(O(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await N(this.fetch,`GET`,`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>({data:{providers:e?.providers??[]},error:null})})}catch(e){if(O(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await N(this.fetch,`POST`,`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(O(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await N(this.fetch,`GET`,`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(O(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await N(this.fetch,`PUT`,`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(O(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await N(this.fetch,`DELETE`,`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(O(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){j(this.experimental),A(e.userId);try{return await N(this.fetch,`GET`,`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(O(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){j(this.experimental),A(e.userId),A(e.passkeyId);try{return await N(this.fetch,`DELETE`,`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(O(e))return{data:null,error:e};throw e}}};function ia(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}globalThis&&di()&&globalThis.localStorage&&globalThis.localStorage.getItem(`supabase.gotrue-js.locks.debug`);var aa=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function oa(){if(typeof globalThis!=`object`)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<`u`&&(self.globalThis=self)}}function sa(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function ca(e){return parseInt(e,16)}function la(e){let t=new TextEncoder().encode(e);return`0x`+Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function ua(e){let{chainId:t,domain:n,expirationTime:r,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:s,resources:c,scheme:l,uri:u,version:d}=e;if(!Number.isInteger(t))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!n)throw Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`);if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);if(d!==`1`)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(e.statement?.includes(` `))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let f=sa(e.address),p=`${l?`${l}://${n}`:n} wants you to sign in with your Ethereum account:\n${f}\n\n${e.statement?`${e.statement}\n`:``}`,m=`URI: ${u}\nVersion: ${d}\nChain ID: ${t}${a?`\nNonce: ${a}`:``}\nIssued At: ${i.toISOString()}`;if(r&&(m+=`\nExpiration Time: ${r.toISOString()}`),o&&(m+=`\nNot Before: ${o.toISOString()}`),s&&(m+=`\nRequest ID: ${s}`),c){let e=` Resources:`;for(let t of c){if(!t||typeof t!=`string`)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}m+=e}return`${p}\n${m}`}var da=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=r??(n instanceof Error?n.name:void 0)??`Unknown Error`,this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},fa=class extends da{constructor(e,t){super({code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:t,message:e}),this.name=`WebAuthnUnknownError`,this.originalError=t}};function pa({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new da({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new da({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new da({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new da({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new da({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new da({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new da({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new da({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=window.location.hostname;if(!ba(t))return new da({message:`${window.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new da({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new da({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new da({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return new da({message:`a Non-Webauthn related error has occurred`,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e})}function ma({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new da({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new da({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=window.location.hostname;if(!ba(t))return new da({message:`${window.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new da({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new da({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return new da({message:`a Non-Webauthn related error has occurred`,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e})}De();var ha=new class{createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}};function ga(e){if(!e)throw Error(`Credential creation options are required`);if(typeof PublicKeyCredential<`u`&&`parseCreationOptionsFromJSON`in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON==`function`)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:n,excludeCredentials:r}=e,i=_(e,[`challenge`,`user`,`excludeCredentials`]),a=ii(t).buffer,o=Object.assign(Object.assign({},n),{id:ii(n.id).buffer}),s=Object.assign(Object.assign({},i),{challenge:a,user:o});if(r&&r.length>0){s.excludeCredentials=Array(r.length);for(let e=0;e0){a.allowCredentials=Array(n.length);for(let e=0;etypeof e==`object`&&!!e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),r={};for(let i of e)if(i)for(let e in i){let a=i[e];if(a!==void 0)if(Array.isArray(a))r[e]=a;else if(n(a))r[e]=a;else if(t(a)){let n=r[e];t(n)?r[e]=Ea(n,a):r[e]=Ea(a)}else r[e]=a}return r}function Da(e,t){return Ea(wa,e,t||{})}function Oa(e,t){return Ea(Ta,e,t||{})}var ka=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:`webauthn`}))}async _challenge({factorId:e,webauthn:t,friendlyName:n,signal:r},i){try{let{data:a,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!a)return{data:null,error:o};let s=r??ha.createNewAbortSignal();if(a.webauthn.type===`create`){let{user:e}=a.webauthn.credential_options.publicKey;if(!e.name){let t=n;if(t)e.name=`${e.id}:${t}`;else{let t=(await this.client.getUser()).data.user,n=t?.user_metadata?.name||t?.email||t?.id||`User`;e.name=`${e.id}:${n}`}}e.displayName||=e.name}switch(a.webauthn.type){case`create`:{let{data:t,error:n}=await Sa({publicKey:Da(a.webauthn.credential_options.publicKey,i?.create),signal:s});return t?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:t}},error:null}:{data:null,error:n}}case`request`:{let t=Oa(a.webauthn.credential_options.publicKey,i?.request),{data:n,error:r}=await Ca(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:t,signal:s}));return n?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}}}catch(e){return O(e)?{data:null,error:e}:{data:null,error:new Nr(`Unexpected error in challenge`,e)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<`u`?window.location.hostname:void 0,rpOrigins:n=typeof window<`u`?[window.location.origin]:void 0,signal:r}={}},i){if(!t)return{data:null,error:new Ar(`rpId is required for WebAuthn authentication`)};try{if(!xa())return{data:null,error:new Nr(`Browser does not support WebAuthn`,null)};let{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:r},{request:i});if(!a)return{data:null,error:o};let{webauthn:s}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:s.type,rpId:t,rpOrigins:n,credential_response:s.credential_response}})}catch(e){return O(e)?{data:null,error:e}:{data:null,error:new Nr(`Unexpected error in authenticate`,e)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<`u`?window.location.hostname:void 0,rpOrigins:n=typeof window<`u`?[window.location.origin]:void 0,signal:r}={}},i){if(!t)return{data:null,error:new Ar(`rpId is required for WebAuthn registration`)};try{if(!xa())return{data:null,error:new Nr(`Browser does not support WebAuthn`,null)};let{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(t=>t.data?.all.find(t=>t.factor_type===`webauthn`&&t.friendly_name===e&&t.status!==`unverified`)).then(e=>e?this.client.mfa.unenroll({factorId:e?.id}):void 0),{data:null,error:o};let{data:s,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:r},{create:i});return s?this._verify({factorId:a.id,challengeId:s.challengeId,webauthn:{rpId:t,rpOrigins:n,type:s.webauthn.type,credential_response:s.webauthn.credential_response}}):{data:null,error:c}}catch(e){return O(e)?{data:null,error:e}:{data:null,error:new Nr(`Unexpected error in register`,e)}}}};oa();var Aa={url:Cr,storageKey:wr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Tr,flowType:`implicit`,debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},ja={},Ma=class e{get jwks(){return ja[this.storageKey]?.jwks??{keys:[]}}set jwks(e){ja[this.storageKey]=Object.assign(Object.assign({},ja[this.storageKey]),{jwks:e})}get jwks_cached_at(){return ja[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){ja[this.storageKey]=Object.assign(Object.assign({},ja[this.storageKey]),{cachedAt:e})}constructor(t){var n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let r=Object.assign(Object.assign({},Aa),t);if(this.storageKey=r.storageKey,this.instanceID=e.nextInstanceID[this.storageKey]??0,e.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!r.debug,typeof r.debug==`function`&&(this.logger=r.debug),this.instanceID>0&&li()){let e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=r.persistSession,this.autoRefreshToken=r.autoRefreshToken,this.experimental=r.experimental??{},this.admin=new ra({url:r.url,headers:r.headers,fetch:r.fetch,experimental:this.experimental}),this.url=r.url,this.headers=r.headers,this.fetch=pi(r.fetch),this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,this.throwOnError=r.throwOnError,this.lockAcquireTimeout=r.lockAcquireTimeout,r.lock!=null&&(this.lock=r.lock),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=-(2**53-1)),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new ka(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(r.storage?this.storage=r.storage:di()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ia(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=ia(this.memoryStorage)),li()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error(`Failed to create a new BroadcastChannel, multi-tab state changes will not be available`,e)}(n=this.broadcastChannel)==null||n.addEventListener(`message`,async e=>{this._debug(`received broadcast notification from other tab or client`,e),(e.data.event===`TOKEN_REFRESHED`||e.data.event===`SIGNED_IN`)&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug(`#broadcastChannel`,`error`,e)}})}r.skipAutoInitialize||this.initialize().catch(e=>{this._debug(`#initialize()`,`error`,e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${yr}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock==null?await this._initialize():await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))();let e=await this.initializePromise,t=this._pendingInitNotifications??[];this._pendingInitNotifications=null;for(let e of t)await this._notifyAllSubscribers(e.event,e.session,e.broadcast);return e}async _initialize(){try{let e={},t=`none`;if(li()&&(e=fi(window.location.href),this._isImplicitGrantCallback(e)?t=`implicit`:await this._isPKCECallback(e)&&(t=`pkce`)),li()&&this.detectSessionInUrl&&t!==`none`){let{data:n,error:r}=await this._getSessionFromURL(e,t);if(r){if(this._debug(`#_initialize()`,`error detecting session from URL`,r),Br(r)){let e=r.details?.code;if(e===`identity_already_exists`||e===`identity_not_found`||e===`single_identity_not_deletable`)return{error:r}}return{error:r}}let{session:i,redirectType:a}=n;return this._debug(`#_initialize()`,`detected session in URL`,i,`redirect type`,a),await this._saveSession(i),setTimeout(async()=>{a===`recovery`?await this._notifyAllSubscribers(`PASSWORD_RECOVERY`,i):await this._notifyAllSubscribers(`SIGNED_IN`,i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return O(e)?this._returnResult({error:e}):this._returnResult({error:new Nr(`Unexpected error during initialization`,e)})}finally{await this._handleVisibilityChange(),this._debug(`#_initialize()`,`end`)}}async signInAnonymously(e){try{let{data:t,error:n}=await N(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:Yi});if(n||!t)return this._returnResult({data:{user:null,session:null},error:n});let r=t.session,i=t.user;return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(`SIGNED_IN`,r)),this._returnResult({data:{user:i,session:r},error:null})}catch(e){if(O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){let t=null;try{let n;if(`email`in e){let{email:r,password:i,options:a}=e,o=null,s=null;this.flowType===`pkce`&&([o,s,t]=await this._getCodeChallengeAndMethod()),n=await N(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(a?.emailRedirectTo,t),body:{email:r,password:i,data:a?.data??{},gotrue_meta_security:{captcha_token:a?.captchaToken},code_challenge:o,code_challenge_method:s},xform:Yi})}else if(`phone`in e){let{phone:t,password:r,options:i}=e;n=await N(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:r,data:i?.data??{},channel:i?.channel??`sms`,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Yi})}else throw new Rr(`You must provide either an email or phone number and a password`);let{data:r,error:i}=n;if(i||!r)return await k(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:i});let a=r.session,o=r.user;return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(await k(this.storage,this.storageKey,t),O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if(`email`in e){let{email:n,password:r,options:i}=e;t=await N(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Xi})}else if(`phone`in e){let{phone:n,password:r,options:i}=e;t=await N(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Xi})}else throw new Rr(`You must provide either an email or phone number and a password`);let{data:n,error:r}=t;if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!n||!n.session||!n.user){let e=new Lr;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers(`SIGNED_IN`,n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:r})}catch(e){if(O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){return await this._handleProviderSignIn(e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:e.options?.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock==null?this._exchangeCodeForSession(e,t):this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case`ethereum`:return await this.signInWithEthereum(e);case`solana`:return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:a,options:o}=e,s;if(!li()){if(typeof i!=`object`||!o?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);s=i}else if(typeof i==`object`)s=i;else{let e=window;if(`ethereum`in e&&typeof e.ethereum==`object`&&`request`in e.ethereum&&typeof e.ethereum.request==`function`)s=e.ethereum;else throw Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`)}let c=new URL(o?.url??window.location.href),l=await s.request({method:`eth_requestAccounts`}).then(e=>e).catch(()=>{throw Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`)});if(!l||l.length===0)throw Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`);let u=sa(l[0]),d=o?.signInWithEthereum?.chainId;d||=ca(await s.request({method:`eth_chainId`})),t=ua({domain:c.host,address:u,statement:a,uri:c.href,version:`1`,chainId:d,nonce:o?.signInWithEthereum?.nonce,issuedAt:o?.signInWithEthereum?.issuedAt??new Date,expirationTime:o?.signInWithEthereum?.expirationTime,notBefore:o?.signInWithEthereum?.notBefore,requestId:o?.signInWithEthereum?.requestId,resources:o?.signInWithEthereum?.resources}),n=await s.request({method:`personal_sign`,params:[la(t),u]})}try{let{data:r,error:i}=await N(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`ethereum`,message:t,signature:n},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Yi});if(i)throw i;if(!r||!r.session||!r.user){let e=new Lr;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),this._returnResult({data:Object.assign({},r),error:i})}catch(e){if(O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:a,options:o}=e,s;if(!li()){if(typeof i!=`object`||!o?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);s=i}else if(typeof i==`object`)s=i;else{let e=window;if(`solana`in e&&typeof e.solana==`object`&&(`signIn`in e.solana&&typeof e.solana.signIn==`function`||`signMessage`in e.solana&&typeof e.solana.signMessage==`function`))s=e.solana;else throw Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`)}let c=new URL(o?.url??window.location.href);if(`signIn`in s&&s.signIn){let e=await s.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},o?.signInWithSolana),{version:`1`,domain:c.host,uri:c.href}),a?{statement:a}:null)),r;if(Array.isArray(e)&&e[0]&&typeof e[0]==`object`)r=e[0];else if(e&&typeof e==`object`&&`signedMessage`in e&&`signature`in e)r=e;else throw Error(`@supabase/auth-js: Wallet method signIn() returned unrecognized value`);if(`signedMessage`in r&&`signature`in r&&(typeof r.signedMessage==`string`||r.signedMessage instanceof Uint8Array)&&r.signature instanceof Uint8Array)t=typeof r.signedMessage==`string`?r.signedMessage:new TextDecoder().decode(r.signedMessage),n=r.signature;else throw Error(`@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields`)}else{if(!(`signMessage`in s)||typeof s.signMessage!=`function`||!(`publicKey`in s)||typeof s!=`object`||!s.publicKey||!(`toBase58`in s.publicKey)||typeof s.publicKey.toBase58!=`function`)throw Error(`@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API`);t=[`${c.host} wants you to sign in with your Solana account:`,s.publicKey.toBase58(),...a?[``,a,``]:[``],`Version: 1`,`URI: ${c.href}`,`Issued At: ${o?.signInWithSolana?.issuedAt??new Date().toISOString()}`,...o?.signInWithSolana?.notBefore?[`Not Before: ${o.signInWithSolana.notBefore}`]:[],...o?.signInWithSolana?.expirationTime?[`Expiration Time: ${o.signInWithSolana.expirationTime}`]:[],...o?.signInWithSolana?.chainId?[`Chain ID: ${o.signInWithSolana.chainId}`]:[],...o?.signInWithSolana?.nonce?[`Nonce: ${o.signInWithSolana.nonce}`]:[],...o?.signInWithSolana?.requestId?[`Request ID: ${o.signInWithSolana.requestId}`]:[],...o?.signInWithSolana?.resources?.length?[`Resources`,...o.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join(` `);let e=await s.signMessage(new TextEncoder().encode(t),`utf8`);if(!e||!(e instanceof Uint8Array))throw Error(`@supabase/auth-js: Wallet signMessage() API returned an recognized value`);n=e}}try{let{data:r,error:i}=await N(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`solana`,message:t,signature:oi(n)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Yi});if(i)throw i;if(!r||!r.session||!r.user){let e=new Lr;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),this._returnResult({data:Object.assign({},r),error:i})}catch(e){if(O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e,t){let n=t?.flowId!=null,r=n?Di(t?.flowId):li()?Di(fi(window.location.href)[kr]):null;n&&!r&&this._debug(`#_exchangeCodeForSession()`,`provided flowId is not a valid flow id`,t?.flowId);let{verifier:i,flowId:a}=n&&!r?{verifier:null,flowId:null}:await Ni(this.storage,this.storageKey,r),[o,s]=(i??``).split(`/`);try{if(!o&&this.flowType===`pkce`)throw new Hr;let{data:t,error:n}=await N(this.fetch,`POST`,`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:Yi});if(await k(this.storage,this.storageKey,a),n)throw n;if(!t||!t.session||!t.user){let e=new Lr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(s===`recovery`?`PASSWORD_RECOVERY`:`SIGNED_IN`,t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:s??null}),error:n})}catch(e){if(await k(this.storage,this.storageKey,a),O(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:n,token:r,access_token:i,nonce:a}=e,{data:o,error:s}=await N(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:r,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:Yi});if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!o||!o.session||!o.user){let e=new Lr;return this._returnResult({data:{user:null,session:null},error:e})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers(`SIGNED_IN`,o.session)),this._returnResult({data:o,error:s})}catch(e){if(O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){let t=null;try{if(`email`in e){let{email:n,options:r}=e,i=null,a=null;this.flowType===`pkce`&&([i,a,t]=await this._getCodeChallengeAndMethod());let{error:o}=await N(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{email:n,data:r?.data??{},create_user:r?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:r?.captchaToken},code_challenge:i,code_challenge_method:a},redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,t)});return this._returnResult({data:{user:null,session:null},error:o})}if(`phone`in e){let{phone:t,options:n}=e,{data:r,error:i}=await N(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:n?.data??{},create_user:n?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:n?.captchaToken},channel:n?.channel??`sms`}});return this._returnResult({data:{user:null,session:null,messageId:r?.message_id},error:i})}throw new Rr(`You must provide either an email or phone number.`)}catch(e){if(await k(this.storage,this.storageKey,t),O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){try{let t,n;`options`in e&&(t=e.options?.redirectTo,n=e.options?.captchaToken);let{data:r,error:i}=await N(this.fetch,`POST`,`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:t,xform:Yi});if(i)throw i;if(!r)throw Error(`An error occurred on token verification.`);let a=r.session,o=r.user;return a?.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers(e.type==`recovery`?`PASSWORD_RECOVERY`:`SIGNED_IN`,a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){let t=null;try{let n=null,r=null;this.flowType===`pkce`&&([n,r,t]=await this._getCodeChallengeAndMethod());let i=await N(this.fetch,`POST`,`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},`providerId`in e?{provider_id:e.providerId}:null),`domain`in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect(e.options?.redirectTo,t)}),e?.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:r}),headers:this.headers,xform:Qi});return i.data?.url&&li()&&!e.options?.skipBrowserRedirect&&window.location.assign(i.data.url),this._returnResult(i)}catch(e){if(await k(this.storage,this.storageKey,t),O(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,this.lock==null?await this._reauthenticate():await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new Fr;let{error:r}=await N(this.fetch,`GET`,`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:r})})}catch(e){if(O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let n=`${this.url}/resend`;if(`email`in e){let{email:r,type:i,options:a}=e,o=null,s=null;this.flowType===`pkce`&&([o,s,t]=await this._getCodeChallengeAndMethod());let{error:c}=await N(this.fetch,`POST`,n,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:a?.captchaToken},code_challenge:o,code_challenge_method:s},redirectTo:this._maybeAppendFlowIdToRedirect(a?.emailRedirectTo,t)});return c&&await k(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:c})}else if(`phone`in e){let{phone:t,type:r,options:i}=e,{data:a,error:o}=await N(this.fetch,`POST`,n,{headers:this.headers,body:{phone:t,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:o})}throw new Rr(`You must provide either an email or phone number and a type`)}catch(e){if(await k(this.storage,this.storageKey,t),O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,this.lock==null?await this._useSession(async e=>e):await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug(`#_acquireLock`,`begin`,e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug(`#_acquireLock`,`lock acquired for storage key`,this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch{}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug(`#_acquireLock`,`lock released for storage key`,this.storageKey),this.lockAcquired=!1}})}finally{this._debug(`#_acquireLock`,`end`)}}async _useSession(e){this._debug(`#_useSession`,`begin`);try{return await e(await this.__loadSession())}finally{this._debug(`#_useSession`,`end`)}}async __loadSession(){this._debug(`#__loadSession()`,`begin`),this.lock!=null&&!this.lockAcquired&&this._debug(`#__loadSession()`,`used outside of an acquired lock!`,Error().stack);try{let e=null,t=await gi(this.storage,this.storageKey);if(this._debug(`#getSession()`,`session from storage`,t),t!==null&&(this._isValidSession(t)?e=t:(this._debug(`#getSession()`,`session from storage is not valid`),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()Date.now()){let t=await gi(this.storage,this.storageKey);if(t&&t.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:r},error:null})}finally{this._debug(`#__loadSession()`,`end`)}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return t=this.lock==null?await this._getUser():await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await N(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:e,xform:Zi}):await this._useSession(async e=>{let{data:t,error:n}=e;if(n)throw n;return!t.session?.access_token&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Fr}:await N(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:Zi})})}catch(e){if(O(e))return Ir(e)&&await this._removeSession(),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,this.lock==null?await this._updateUser(e,t):await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){let n=null;try{return await this._useSession(async r=>{let{data:i,error:a}=r;if(a)throw a;if(!i.session)throw new Fr;let o=i.session,s=null,c=null;this.flowType===`pkce`&&e.email!=null&&([s,c,n]=await this._getCodeChallengeAndMethod());let{data:l,error:u}=await N(this.fetch,`PUT`,`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,n),body:Object.assign(Object.assign({},e),{code_challenge:s,code_challenge_method:c}),jwt:o.access_token,xform:Zi});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers(`USER_UPDATED`,o),this._returnResult({data:{user:o.user},error:null})})}catch(e){if(await k(this.storage,this.storageKey,n),O(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,this.lock==null?await this._setSession(e):await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Fr;let t=Date.now()/1e3,n=t,r=!0,i=null,{payload:a}=yi(e.access_token);if(a.exp&&(n=a.exp,r=n<=t),r){let{data:t,error:n}=await this._callRefreshToken(e.refresh_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:r,error:a}=await this._getUser(e.access_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});i={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:`bearer`,expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers(`SIGNED_IN`,i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(O(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,this.lock==null?await this._refreshSession(e):await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{if(!e){let{data:n,error:r}=t;if(r)throw r;e=n.session??void 0}if(!e?.refresh_token)throw new Fr;let{data:n,error:r}=await this._callRefreshToken(e.refresh_token);return r?this._returnResult({data:{user:null,session:null},error:r}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!li())throw new zr(`No browser detected.`);if(e.error||e.error_description||e.error_code)throw new zr(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 Vr(`Not a valid PKCE flow url.`);break;case`pkce`:if(this.flowType===`implicit`)throw new zr(`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 Vr(`No code detected.`);let{data:t,error:n}=await this._exchangeCodeForSession(e.code,{flowId:e[kr]});if(n)throw n;let r=new URL(window.location.href);return r.searchParams.delete(`code`),r.searchParams.delete(kr),window.history.replaceState(window.history.state,``,r.toString()),{data:{session:t.session,redirectType:t.redirectType??null},error:null}}let{provider_token:n,provider_refresh_token:r,access_token:i,refresh_token:a,expires_in:o,expires_at:s,token_type:c}=e;if(!i||!o||!a||!c)throw new zr(`No session defined in URL`);let l=Math.round(Date.now()/1e3),u=parseInt(o),d=l+u;s&&(d=parseInt(s));let f=d-l;f*1e3<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let p=d-u;l-p>=120?console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale`,p,d,l):l-p<0&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew`,p,d,l);let{data:m,error:h}=await this._getUser(i);if(h)throw h;let g={provider_token:n,provider_refresh_token:r,access_token:i,expires_in:u,expires_at:d,refresh_token:a,token_type:c,user:m.user};return window.location.hash=``,this._debug(`#_getSessionFromURL()`,`clearing window.location.hash`),this._returnResult({data:{session:g,redirectType:e.type},error:null})}catch(e){if(O(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl==`function`?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=Di(e[kr]);return t&&await gi(this.storage,ki(this.storageKey,t))?!0:!!await gi(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:`global`}){return await this.initializePromise,this.lock==null?await this._signOut(e):await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:`global`}){return await this._useSession(async t=>{let n=async()=>{await this._removeSession()},{data:r,error:i}=t;if(i&&!Ir(i))return this._returnResult({error:i});let a=r.session?.access_token;if(a){let{error:t}=await this.admin.signOut(a,e);if(t&&!(Mr(t)&&(t.status===404||t.status===401||t.status===403)||Ir(t)))return e!==`others`&&await n(),this._returnResult({error:t})}return e!==`others`&&await n(),this._returnResult({error:null})})}onAuthStateChange(e){let t=ci(),n={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,n),(async()=>{await this.initializePromise,this.lock==null?await this._emitInitialSession(t):await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{try{let{data:{session:n},error:r}=t;if(r)throw r;await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,n),this._debug(`INITIAL_SESSION`,`callback id`,e,`session`,n)}catch(t){await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,null),this._debug(`INITIAL_SESSION`,`callback id`,e,`error`,t),Ir(t)||Wr(t)||Mr(t)&&(t.code===`refresh_token_not_found`||t.code===`refresh_token_already_used`||t.code===`session_expired`)?console.warn(t):console.error(t)}})}async resetPasswordForEmail(e,t={}){let n=null,r=null,i=null;this.flowType===`pkce`&&([n,r,i]=await this._getCodeChallengeAndMethod(!0));try{return await N(this.fetch,`POST`,`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(e){if(await k(this.storage,this.storageKey,i),O(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){try{let{data:e,error:t}=await this.getUser();if(t)throw t;return this._returnResult({data:{identities:e.user.identities??[]},error:null})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return`token`in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){let t=null;try{let{data:n,error:r}=await this._useSession(async n=>{let{data:r,error:i}=n;if(i)throw i;let{url:a,flowId:o}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:!0});return t=o,await N(this.fetch,`GET`,a,{headers:this.headers,jwt:r.session?.access_token??void 0})});if(r)throw r;return li()&&!e.options?.skipBrowserRedirect&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url,flowId:t},error:null})}catch(n){if(O(n))return this._returnResult({data:{provider:e.provider,url:null,flowId:t},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async t=>{try{let{error:n,data:{session:r}}=t;if(n)throw n;let{options:i,provider:a,token:o,access_token:s,nonce:c}=e,{data:l,error:u}=await N(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:r?.access_token??void 0,body:{provider:a,id_token:o,access_token:s,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Yi});return u?this._returnResult({data:{user:null,session:null},error:u}):!l||!l.session||!l.user?this._returnResult({data:{user:null,session:null},error:new Lr}):(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers(`USER_UPDATED`,l.session)),this._returnResult({data:l,error:u}))}catch(e){if(await k(this.storage,this.storageKey,null),O(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)throw r;return await N(this.fetch,`DELETE`,`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:n.session?.access_token??void 0})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken()`;this._debug(t,`begin`);try{let n=Date.now();return await xi(async n=>(n>0&&await bi(200*2**(n-1)),this._debug(t,`refreshing attempt`,n),await N(this.fetch,`POST`,`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Yi})),(e,t)=>{let r=200*2**e;return t&&Wr(t)&&Date.now()+r-n<3e4})}catch(e){if(this._debug(t,`error`,e),O(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,`end`)}}_isValidSession(e){return typeof e==`object`&&!!e&&`access_token`in e&&`refresh_token`in e&&`expires_at`in e}async _handleProviderSignIn(e,t){let{url:n,flowId:r}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug(`#_handleProviderSignIn()`,`provider`,e,`options`,t,`url`,n),li()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n,flowId:r},error:null}}async _recoverAndRefresh(){let e=`#_recoverAndRefresh()`;this._debug(e,`begin`);try{let t=await gi(this.storage,this.storageKey);if(t&&this.userStorage){let e=await gi(this.userStorage,this.storageKey+`-user`);!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!e&&(e={user:t.user},await hi(this.userStorage,this.storageKey+`-user`,e)),t.user=e?.user??M()}else if(t&&!t.user&&!t.user){let e=await gi(this.storage,this.storageKey+`-user`);e&&e?.user?(t.user=e.user,await _i(this.storage,this.storageKey+`-user`),await hi(this.storage,this.storageKey,t)):t.user=M()}if(this._debug(e,`session from storage`,t),!this._isValidSession(t)){this._debug(e,`session is not valid`),t!==null&&await this._removeSession();return}let n=(t.expires_at??1/0)*1e3-Date.now()Date.now()?this._debug(r,`proactive refresh failed, access token still valid — preserving session`):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:n,expiresAt:Date.now()+Sr},(t=this.refreshingDeferred)==null||t.resolve(n),n}throw(n=this.refreshingDeferred)==null||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(r,`end`)}}async _notifyAllSubscribers(e,t,n=!0){if(this._pendingInitNotifications!==null&&n){this._pendingInitNotifications.push({event:e,session:t,broadcast:n});return}let r=`#_notifyAllSubscribers(${e})`;this._debug(r,`begin`,t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let r=[],i=Array.from(this.stateChangeEmitters.values()).map(async n=>{try{await n.callback(e,t)}catch(e){r.push(e)}});if(await Promise.all(i),r.length>0){for(let e=0;ethis._autoRefreshTokenTick(),br);this.autoRefreshTicker=e,e&&typeof e==`object`&&typeof e.unref==`function`?e.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t==`object`&&typeof t.unref==`function`?t.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug(`#_stopAutoRefresh()`);let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)==null||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug(`#_autoRefreshTokenTick()`,`begin`),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug(`#_autoRefreshTokenTick()`,`no session`);return}let r=Math.floor((n.expires_at*1e3-e)/br);this._debug(`#_autoRefreshTokenTick()`,`access token expires in ${r} ticks, a tick lasts ${br}ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(n.refresh_token)})}catch(e){console.error(`Auto refresh tick failed with error. This is likely a transient error.`,e)}}finally{this._debug(`#_autoRefreshTokenTick()`,`end`)}})}catch(e){if(e instanceof aa)this._debug(`auto refresh token tick lock not available`);else throw e}return}if(this.refreshingDeferred!==null){this._debug(`#_autoRefreshTokenTick()`,`refresh already in flight, skipping`);return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug(`#_autoRefreshTokenTick()`,`no session`);return}let r=Math.floor((n.expires_at*1e3-e)/br);this._debug(`#_autoRefreshTokenTick()`,`access token expires in ${r} ticks, a tick lasts ${br}ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(n.refresh_token)})}catch(e){console.error(`Auto refresh tick failed with error. This is likely a transient error.`,e)}}finally{this._debug(`#_autoRefreshTokenTick()`,`end`)}}async _handleVisibilityChange(){if(this._debug(`#_handleVisibilityChange()`),!li()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug(`#visibilityChangedCallback`,`error`,e)}},window==null||window.addEventListener(`visibilitychange`,this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error(`_handleVisibilityChange`,e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,`visibilityState`,document.visibilityState),document.visibilityState===`visible`){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!==`visible`){this._debug(t,`acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting`);return}await this._recoverAndRefresh()});else{if(document.visibilityState!==`visible`){this._debug(t,`visibilityState is no longer visible, skipping recovery`);return}await this._recoverAndRefresh()}}else document.visibilityState===`hidden`&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let r=n?.redirectTo,i=null,a=null,o=null;this.flowType===`pkce`&&([i,a,o]=await this._getCodeChallengeAndMethod(),r=this._maybeAppendFlowIdToRedirect(r,o));let s=[`provider=${encodeURIComponent(t)}`];if(r&&s.push(`redirect_to=${encodeURIComponent(r)}`),n?.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),i!=null&&a!=null){let e=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});s.push(e.toString())}if(n?.queryParams){let e=new URLSearchParams(n.queryParams);s.push(e.toString())}return n?.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),{url:`${e}?${s.join(`&`)}`,flowId:o}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:Fi(e,t)}async _getCodeChallengeAndMethod(e=!1){return Ii(this.storage,this.storageKey,e,e=>this._debug(`#_getCodeChallengeAndMethod()`,`evicted oldest pending PKCE verifier slot`,e))}async _unenroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;return r?this._returnResult({data:null,error:r}):await N(this.fetch,`DELETE`,`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:n?.session?.access_token})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType===`phone`?{phone:e.phone}:e.factorType===`totp`?{issuer:e.issuer}:{}),{data:a,error:o}=await N(this.fetch,`POST`,`${this.url}/factors`,{body:i,headers:this.headers,jwt:n?.session?.access_token});return o?this._returnResult({data:null,error:o}):(e.factorType===`totp`&&a.type===`totp`&&a?.totp?.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){let t=async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=Object.assign({challenge_id:e.challengeId},`webauthn`in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type===`create`?va(e.webauthn.credential_response):ya(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await N(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:n?.session?.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers(`MFA_CHALLENGE_VERIFIED`,a),this._returnResult({data:a,error:o}))})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}};return this.lock==null?t():this._acquireLock(this.lockAcquireTimeout,t)}async _challenge(e){let t=async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=await N(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:n?.session?.access_token});if(i.error)return i;let{data:a}=i;if(a.type!==`webauthn`)return{data:a,error:null};switch(a.webauthn.type){case`create`:return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:ga(a.webauthn.credential_options.publicKey)})})}),error:null};case`request`:return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:_a(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}};return this.lock==null?t():this._acquireLock(this.lockAcquireTimeout,t)}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n={all:[],phone:[],totp:[],webauthn:[]};for(let t of e?.factors??[])n.all.push(t),t.status===`verified`&&n[t.factor_type].push(t);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){if(e)try{let{payload:t}=yi(e),n=null;t.aal&&(n=t.aal);let r=n,{data:{user:i},error:a}=await this.getUser(e);if(a)return this._returnResult({data:null,error:a});((i?.factors)?.filter(e=>e.status===`verified`)??[]).length>0&&(r=`aal2`);let o=t.amr||[];return{data:{currentLevel:n,nextLevel:r,currentAuthenticationMethods:o},error:null}}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:t},error:n}=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!t)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:r}=yi(t.access_token),i=null;r.aal&&(i=r.aal);let a=i;(t.user.factors?.filter(e=>e.status===`verified`)??[]).length>0&&(a=`aal2`);let o=r.amr||[];return{data:{currentLevel:i,nextLevel:a,currentAuthenticationMethods:o},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await N(this.fetch,`GET`,`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new Fr})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new Fr});let a=await N(this.fetch,`POST`,`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:`approve`},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&li()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new Fr});let a=await N(this.fetch,`POST`,`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:`deny`},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&li()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await N(this.fetch,`GET`,`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new Fr})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?(await N(this.fetch,`DELETE`,`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Fr})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(t=>t.kid===e);if(n)return n;let r=Date.now();if(n=this.jwks.keys.find(t=>t.kid===e),n&&this.jwks_cached_at+6e5>r)return n;let{data:i,error:a}=await N(this.fetch,`GET`,`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=r,n=i.keys.find(t=>t.kid===e),!n)?null:n}async getClaims(e,t={}){try{let n=e;if(!n){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}let{header:r,payload:i,signature:a,raw:{header:o,payload:s}}=yi(n);if(!t?.allowExpired)try{zi(i.exp)}catch(e){throw new Jr(e instanceof Error?e.message:`JWT validation failed`)}let c=!r.alg||r.alg.startsWith(`HS`)||!r.kid||!(`crypto`in globalThis&&`subtle`in globalThis.crypto)?null:await this.fetchJwk(r.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!c){let{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:i,header:r,signature:a},error:null}}let l=Bi(r.alg),u=await crypto.subtle.importKey(`jwk`,c,l,!0,[`verify`]);if(!await crypto.subtle.verify(l,u,a,ai(`${o}.${s}`)))throw new Jr(`Invalid JWT signature`);return{data:{claims:i,header:r,signature:a},error:null}}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){j(this.experimental);try{if(!xa())return this._returnResult({data:null,error:new Nr(`Browser does not support WebAuthn`,null)});let{data:t,error:n}=await this._startPasskeyAuthentication({options:{captchaToken:e?.options?.captchaToken}});if(n||!t)return this._returnResult({data:null,error:n});let{data:r,error:i}=await Ca({publicKey:_a(t.options),signal:e?.options?.signal??ha.createNewAbortSignal()});if(i||!r)return this._returnResult({data:null,error:i??new Nr(`WebAuthn ceremony failed`,null)});let a=ya(r);return this._verifyPasskeyAuthentication({challengeId:t.challenge_id,credential:a})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){j(this.experimental);try{if(!xa())return this._returnResult({data:null,error:new Nr(`Browser does not support WebAuthn`,null)});let{data:t,error:n}=await this._startPasskeyRegistration();if(n||!t)return this._returnResult({data:null,error:n});let{data:r,error:i}=await Sa({publicKey:ga(t.options),signal:e?.options?.signal??ha.createNewAbortSignal()});if(i||!r)return this._returnResult({data:null,error:i??new Nr(`WebAuthn ceremony failed`,null)});let a=va(r);return this._verifyPasskeyRegistration({challengeId:t.challenge_id,credential:a})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){j(this.experimental);try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!t)return this._returnResult({data:null,error:new Fr});let{data:r,error:i}=await N(this.fetch,`POST`,`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:r,error:null})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){j(this.experimental);try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new Fr});let{data:i,error:a}=await N(this.fetch,`POST`,`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){j(this.experimental);try{let{data:t,error:n}=await N(this.fetch,`POST`,`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:e?.options?.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:t,error:null})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){j(this.experimental);try{let{data:t,error:n}=await N(this.fetch,`POST`,`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Yi});return n?this._returnResult({data:null,error:n}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(`SIGNED_IN`,t.session)),this._returnResult({data:t,error:null}))}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){j(this.experimental);try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!t)return this._returnResult({data:null,error:new Fr});let{data:r,error:i}=await N(this.fetch,`GET`,`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:r,error:null})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){j(this.experimental);try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new Fr});let{data:i,error:a}=await N(this.fetch,`PATCH`,`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){j(this.experimental);try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new Fr});let{error:i}=await N(this.fetch,`DELETE`,`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(e){if(O(e))return this._returnResult({data:null,error:e});throw e}}};Ma.nextInstanceID={};var Na=Ma,Pa=`modulepreload`,Fa=function(e){return`/`+e},Ia={},P=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Fa(t,n),t=s(t),t in Ia)return;Ia[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Pa,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},La=`2.111.0`,Ra=``,za;if(typeof Deno<`u`)Ra=`deno`,za=Deno.version?.deno;else if(typeof document<`u`)Ra=`web`;else if(typeof navigator<`u`&&navigator.product===`ReactNative`)Ra=`react-native`;else{var Ba;Ra=`node`;let e=globalThis.process;za=e==null||(Ba=e.version)==null?void 0:Ba.replace(/^v/,``)}var Va=[`runtime=${Ra}`];za&&Va.push(`runtime-version=${za}`);var Ha={headers:{"X-Client-Info":`supabase-js/${La}; ${Va.join(`; `)}`}},Ua={schema:`public`},Wa={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:`implicit`},Ga={},Ka={enabled:!1,respectSamplingDecision:!0};function qa(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}var Ja=null,Ya=`@opentelemetry/api`;function Xa(){return Ja===null&&(Ja=P(()=>import(Ya),[]).catch(()=>null)),Ja}function Za(){return qa(this,void 0,void 0,function*(){try{let e=yield Xa();if(!e||!e.propagation||!e.context)return null;let t={};e.propagation.inject(e.context.active(),t);let n=t.traceparent;return n?{traceparent:n,tracestate:t.tracestate,baggage:t.baggage}:null}catch{return null}})}function Qa(e){if(!e||typeof e!=`string`)return null;let t=e.split(`-`);if(t.length!==4)return null;let[n,r,i,a]=t;if(n.length!==2||r.length!==32||i.length!==16||a.length!==2)return null;let o=/^[0-9a-f]+$/i;return!o.test(n)||!o.test(r)||!o.test(i)||!o.test(a)||r===`00000000000000000000000000000000`||i===`0000000000000000`?null:{version:n,traceId:r,parentId:i,traceFlags:a,isSampled:(parseInt(a,16)&1)==1}}function $a(e,t){if(!e||!t||t.length===0)return!1;let n;if(e instanceof URL)n=e;else try{n=new URL(e)}catch{return!1}for(let e of t)try{if(typeof e==`string`){if(eo(n.hostname,e))return!0}else if(e instanceof RegExp){if(e.test(n.hostname))return!0}else if(typeof e==`function`&&e(n))return!0}catch{continue}return!1}function eo(e,t){if(t===e)return!0;if(t.startsWith(`*.`)){let n=t.slice(2);if(e.endsWith(n)&&(e===n||e.endsWith(`.`+n)))return!0}return!1}function to(e){let t=[];try{let n=new URL(e);t.push(n.hostname)}catch{}return t.push(`*.supabase.co`,`*.supabase.in`),t.push(`localhost`,`127.0.0.1`,`[::1]`),t}function no(e){"@babel/helpers - typeof";return no=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},no(e)}function ro(e,t){if(no(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(no(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function io(e){var t=ro(e,`string`);return no(t)==`symbol`?t:t+``}function ao(e,t,n){return(t=io(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function oo(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function F(e){for(var t=1;te?(...t)=>e(...t):(...e)=>fetch(...e),co=()=>Headers,lo=e=>e.startsWith(`sb_publishable_`)||e.startsWith(`sb_secret_`),uo=`sb_temp_`,fo=new Set,po=e=>{if(!e.startsWith(`sb_`)||lo(e)||e.startsWith(uo))return;let t=e.match(/^sb_[a-zA-Z0-9]+_/)?.[0]??`unknown`;fo.has(t)||(fo.add(t),console.warn(`@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type.`))},mo=(e,t,n,r,i,a)=>{let o=so(r),s=co(),c=i?.enabled===!0,l=i?.respectSamplingDecision!==!1,u=c?to(t):null,d=!(a?.omitApiKeyAsBearer&&lo(e));return async(t,r)=>{let i=await n(),a=new s(r?.headers);if(a.has(`apikey`)||a.set(`apikey`,e),!a.has(`Authorization`)){let t=i??(d?e:null);t&&a.set(`Authorization`,`Bearer ${t}`)}if(u){let e=await ho(t,u,l);e&&(e.traceparent&&!a.has(`traceparent`)&&a.set(`traceparent`,e.traceparent),e.tracestate&&!a.has(`tracestate`)&&a.set(`tracestate`,e.tracestate),e.baggage&&!a.has(`baggage`)&&a.set(`baggage`,e.baggage))}return o(t,F(F({},r),{},{headers:a}))}};async function ho(e,t,n){if(!$a(typeof e==`string`||e instanceof URL?e:e.url,t))return null;let r=await Za();if(!r||!r.traceparent)return null;if(n){let e=Qa(r.traceparent);if(e&&!e.isSampled)return null}return r}function go(e){return typeof e==`boolean`?{enabled:e}:e}function _o(e){return e.endsWith(`/`)?e:e+`/`}function I(e,t){let{db:n,auth:r,realtime:i,global:a}=e,{db:o,auth:s,realtime:c,global:l}=t,u=go(e.tracePropagation),d=go(t.tracePropagation),f={db:F(F({},o),n),auth:F(F({},s),r),realtime:F(F({},c),i),storage:{},global:F(F(F({},l),a),{},{headers:F(F({},l?.headers??{}),a?.headers??{})}),tracePropagation:{enabled:u?.enabled??d?.enabled??!1,respectSamplingDecision:u?.respectSamplingDecision??d?.respectSamplingDecision??!0},accessToken:async()=>``};return e.accessToken?f.accessToken=e.accessToken:delete f.accessToken,f}function L(e){let t=e?.trim();if(!t)throw Error(`supabaseUrl is required.`);if(!t.match(/^https?:\/\//i))throw Error(`Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.`);try{return new URL(_o(t))}catch{throw Error(`Invalid supabaseUrl: Provided URL is malformed.`)}}var vo=class extends Na{constructor(e){super(e)}},yo=class{constructor(e,t,n){this.supabaseUrl=e,this.supabaseKey=t;let r=L(e);if(!t)throw Error(`supabaseKey is required.`);po(t),this.realtimeUrl=new URL(`realtime/v1`,r),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace(`http`,`ws`),this.authUrl=new URL(`auth/v1`,r),this.storageUrl=new URL(`storage/v1`,r),this.functionsUrl=new URL(`functions/v1`,r);let i=`sb-${r.hostname.split(`.`)[0]}-auth-token`,a={db:Ua,realtime:Ga,auth:F(F({},Wa),{},{storageKey:i}),global:Ha,tracePropagation:Ka},o=I(n??{},a);this.settings=o,this.storageKey=o.auth.storageKey??``,this.headers=o.global.headers??{},o.accessToken?(this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(o.auth??{},this.headers,o.global.fetch),this.fetch=mo(t,e,this._getSessionToken.bind(this),o.global.fetch,o.tracePropagation),this.functionsFetch=mo(t,e,this._getSessionToken.bind(this),o.global.fetch,o.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(F({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn(`Failed to set initial Realtime auth token:`,e)),this.rest=new $e(new URL(`rest/v1`,r).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch,timeout:o.db.timeout,urlLengthLimit:o.db.urlLengthLimit}),this.storage=new vr(this.storageUrl.href,this.headers,this.fetch,n?.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new Pe(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var e=this;if(e.accessToken)return await e.accessToken();let{data:t}=await e.auth.getSession();return t.session?.access_token??null}async _getAccessToken(){var e=this;return await e._getSessionToken()??e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,storageKey:a,flowType:o,lock:s,debug:c,throwOnError:l,experimental:u,lockAcquireTimeout:d,skipAutoInitialize:f},p,m){let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new vo({url:this.authUrl.href,headers:F(F({},h),p),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,flowType:o,lock:s,debug:c,throwOnError:l,experimental:u,fetch:m,lockAcquireTimeout:d,skipAutoInitialize:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>e.toLowerCase()===`authorization`)})}_initRealtimeClient(e){return new vn(this.realtimeUrl.href,F(F({},e),{},{params:F(F({},{apikey:this.supabaseKey}),e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,`CLIENT`,t?.access_token)})}_handleTokenChanged(e,t,n){(e===`TOKEN_REFRESHED`||e===`SIGNED_IN`||e===`INITIAL_SESSION`)&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e===`SIGNED_OUT`&&(this.realtime.setAuth(),t==`STORAGE`&&this.auth.signOut(),this.changedAccessToken=void 0)}},bo=(e,t,n)=>new yo(e,t,n);function xo(){if(typeof window<`u`||globalThis.Deno!==void 0)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(t==null)return!1;let n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=20:!1}xo()&&console.warn(`⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715`);var So=`pqs_ms_photo_`;function Co(e){if(!e)return null;try{return sessionStorage.getItem(So+e)}catch{return null}}async function wo(e,t){if(!e||!t)return null;try{let n=await fetch(`https://graph.microsoft.com/v1.0/me/photo/$value`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)return null;let r=await n.blob(),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(r)});try{sessionStorage.setItem(So+e,i)}catch{}return i}catch{return null}}var To=`pqs_google_photo_`;function R(e){if(!e)return null;try{return sessionStorage.getItem(To+e)}catch{return null}}async function Eo(e,t){if(!e||!t)return null;try{let n=await fetch(t);if(!n.ok)return null;let r=await n.blob(),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(r)});try{sessionStorage.setItem(To+e,i)}catch{}return i}catch{return null}}var Do=bo(`[SENSITIVE]`,`[SENSITIVE]`,{db:{schema:`sys022_prd`}});async function Oo(){let{data:{user:e}}=await Do.auth.getUser();if(!e)return null;let{data:t,error:n}=await Do.from(`users`).select(`email, role, plant, department, display_name, active`).eq(`email`,e.email.toLowerCase()).eq(`active`,!0).maybeSingle();if(n||!t)return null;let r=e.user_metadata?.avatar_url||e.user_metadata?.picture,i=R(e.email)||r||Co(e.email);return{...t,avatar_url:i}}var ko=8,Ao={cassava_weighing:`weigh_date`,biomass_weighing:`weigh_date`,qa_flour_report:`report_date`,qa_starch_milk:`report_date`,qa_viscosity:`report_date`,qa_micro:`report_date`,qa_ash:`report_date`,qa_ncr:`entry_date`,production_daily:`prod_date`,energy_daily:`energy_date`,hourly_production:`prod_date`,fuel_energy_daily:`usage_date`,power_generation_daily:`log_date`};async function jo(e,t,n){let r=1e3,i=Ao[e],a=()=>{let r=n(Do.from(e).select(t));return i&&(r=r.order(i,{ascending:!0})),r.order(`id`,{ascending:!0})},{count:o,error:s}=await n(Do.from(e).select(t,{count:`exact`,head:!0}));if(s)return{rows:[],count:0,error:s};let c=Math.max(1,Math.ceil((o||0)/r)),l=[];for(let e=0;e{let i=e+n;return a().range(i*r,i*r+r-1)})),n=t.find(e=>e.error);if(n)return{rows:[],count:0,error:n.error};l.push(...t)}return{rows:l.flatMap(e=>e.data||[]),count:o||0,error:null}}async function Mo(e,t=1e3){let n=[];for(let r=0;;r+=t){let{data:i,error:a}=await e().order(`id`,{ascending:!0}).range(r,r+t-1);if(a)return{data:null,error:a};if(n.push(...i||[]),!i||i.length(e.error&&Po.delete(n),e));return Po.set(n,{at:Date.now(),promise:i}),i}function Lo(){Po.clear()}var Ro=o(`activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),zo=o(`arrow-down-up`,[[`path`,{d:`m3 16 4 4 4-4`,key:`1co6wj`}],[`path`,{d:`M7 20V4`,key:`1yoxec`}],[`path`,{d:`m21 8-4-4-4 4`,key:`1c9v7m`}],[`path`,{d:`M17 4v16`,key:`7dpous`}]]),Bo=o(`award`,[[`path`,{d:`m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526`,key:`1yiouv`}],[`circle`,{cx:`12`,cy:`8`,r:`6`,key:`1vp47v`}]]),Vo=o(`bell`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]),Ho=o(`box`,[[`path`,{d:`M21 8a2 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`,key:`hh9hay`}],[`path`,{d:`m3.3 7 8.7 5 8.7-5`,key:`g66t2b`}],[`path`,{d:`M12 22V12`,key:`d0xqtd`}]]),Uo=o(`boxes`,[[`path`,{d:`M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z`,key:`lc1i9w`}],[`path`,{d:`m7 16.5-4.74-2.85`,key:`1o9zyk`}],[`path`,{d:`m7 16.5 5-3`,key:`va8pkn`}],[`path`,{d:`M7 16.5v5.17`,key:`jnp8gn`}],[`path`,{d:`M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z`,key:`8zsnat`}],[`path`,{d:`m17 16.5-5-3`,key:`8arw3v`}],[`path`,{d:`m17 16.5 4.74-2.85`,key:`8rfmw`}],[`path`,{d:`M17 16.5v5.17`,key:`k6z78m`}],[`path`,{d:`M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z`,key:`1xygjf`}],[`path`,{d:`M12 8 7.26 5.15`,key:`1vbdud`}],[`path`,{d:`m12 8 4.74-2.85`,key:`3rx089`}],[`path`,{d:`M12 13.5V8`,key:`1io7kd`}]]),Wo=o(`building-2`,[[`path`,{d:`M10 12h4`,key:`a56b0p`}],[`path`,{d:`M10 8h4`,key:`1sr2af`}],[`path`,{d:`M14 21v-3a2 2 0 0 0-4 0v3`,key:`1rgiei`}],[`path`,{d:`M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2`,key:`secmi2`}],[`path`,{d:`M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16`,key:`16ra0t`}]]),Go=o(`calculator`,[[`rect`,{width:`16`,height:`20`,x:`4`,y:`2`,rx:`2`,key:`1nb95v`}],[`line`,{x1:`8`,x2:`16`,y1:`6`,y2:`6`,key:`x4nwl0`}],[`line`,{x1:`16`,x2:`16`,y1:`14`,y2:`18`,key:`wjye3r`}],[`path`,{d:`M16 10h.01`,key:`1m94wz`}],[`path`,{d:`M12 10h.01`,key:`1nrarc`}],[`path`,{d:`M8 10h.01`,key:`19clt8`}],[`path`,{d:`M12 14h.01`,key:`1etili`}],[`path`,{d:`M8 14h.01`,key:`6423bh`}],[`path`,{d:`M12 18h.01`,key:`mhygvu`}],[`path`,{d:`M8 18h.01`,key:`lrp35t`}]]),Ko=o(`calendar-days`,[[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`4`,rx:`2`,key:`1hopcy`}],[`path`,{d:`M3 10h18`,key:`8toen8`}],[`path`,{d:`M8 14h.01`,key:`6423bh`}],[`path`,{d:`M12 14h.01`,key:`1etili`}],[`path`,{d:`M16 14h.01`,key:`1gbofw`}],[`path`,{d:`M8 18h.01`,key:`lrp35t`}],[`path`,{d:`M12 18h.01`,key:`mhygvu`}],[`path`,{d:`M16 18h.01`,key:`kzsmim`}]]),qo=o(`calendar-range`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`4`,rx:`2`,key:`1hopcy`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`path`,{d:`M3 10h18`,key:`8toen8`}],[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`path`,{d:`M17 14h-6`,key:`bkmgh3`}],[`path`,{d:`M13 18H7`,key:`bb0bb7`}],[`path`,{d:`M7 14h.01`,key:`1qa3f1`}],[`path`,{d:`M17 18h.01`,key:`1bdyru`}]]),Jo=o(`camera`,[[`path`,{d:`M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z`,key:`18u6gg`}],[`circle`,{cx:`12`,cy:`13`,r:`3`,key:`1vg3eu`}]]),Yo=o(`chart-column`,[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M18 17V9`,key:`2bz60n`}],[`path`,{d:`M13 17V5`,key:`1frdt8`}],[`path`,{d:`M8 17v-3`,key:`17ska0`}]]),Xo=o(`chart-line`,[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`m19 9-5 5-4-4-3 3`,key:`2osh9i`}]]),Zo=o(`chart-pie`,[[`path`,{d:`M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z`,key:`pzmjnu`}],[`path`,{d:`M21.21 15.89A10 10 0 1 1 8 2.83`,key:`k2fpak`}]]),Qo=o(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),$o=o(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),es=o(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),ts=o(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),ns=o(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),rs=o(`clipboard-list`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`M12 11h4`,key:`1jrz19`}],[`path`,{d:`M12 16h4`,key:`n85exb`}],[`path`,{d:`M8 11h.01`,key:`1dfujw`}],[`path`,{d:`M8 16h.01`,key:`18s6g9`}]]),is=o(`clock`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 6v6l4 2`,key:`mmk7yg`}]]),as=o(`cloud`,[[`path`,{d:`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`,key:`p7xjir`}]]),os=o(`cog`,[[`path`,{d:`M11 10.27 7 3.34`,key:`16pf9h`}],[`path`,{d:`m11 13.73-4 6.93`,key:`794ttg`}],[`path`,{d:`M12 22v-2`,key:`1osdcq`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M14 12h8`,key:`4f43i9`}],[`path`,{d:`m17 20.66-1-1.73`,key:`eq3orb`}],[`path`,{d:`m17 3.34-1 1.73`,key:`2wel8s`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`m20.66 17-1.73-1`,key:`sg0v6f`}],[`path`,{d:`m20.66 7-1.73 1`,key:`1ow05n`}],[`path`,{d:`m3.34 17 1.73-1`,key:`nuk764`}],[`path`,{d:`m3.34 7 1.73 1`,key:`1ulond`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}],[`circle`,{cx:`12`,cy:`12`,r:`8`,key:`46899m`}]]),ss=o(`compass`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z`,key:`9ktpf1`}]]),cs=o(`corner-down-left`,[[`path`,{d:`M20 4v7a4 4 0 0 1-4 4H4`,key:`6o5b7l`}],[`path`,{d:`m9 10-5 5 5 5`,key:`1kshq7`}]]),ls=o(`crown`,[[`path`,{d:`M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z`,key:`1vdc57`}],[`path`,{d:`M5 21h14`,key:`11awu3`}]]),us=o(`droplet`,[[`path`,{d:`M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z`,key:`c7niix`}]]),ds=o(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),fs=o(`factory`,[[`path`,{d:`M12 16h.01`,key:`1drbdi`}],[`path`,{d:`M16 16h.01`,key:`1f9h7w`}],[`path`,{d:`M3 19a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8.5a.5.5 0 0 0-.769-.422l-4.462 2.844A.5.5 0 0 1 15 10.5v-2a.5.5 0 0 0-.769-.422L9.77 10.922A.5.5 0 0 1 9 10.5V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2z`,key:`1iv0i2`}],[`path`,{d:`M8 16h.01`,key:`18s6g9`}]]),ps=o(`file-search`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`circle`,{cx:`11.5`,cy:`14.5`,r:`2.5`,key:`1bq0ko`}],[`path`,{d:`M13.3 16.3 15 18`,key:`2quom7`}]]),ms=o(`file-spreadsheet`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M8 13h2`,key:`yr2amv`}],[`path`,{d:`M14 13h2`,key:`un5t4a`}],[`path`,{d:`M8 17h2`,key:`2yhykz`}],[`path`,{d:`M14 17h2`,key:`10kma7`}]]),hs=o(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),gs=o(`flame`,[[`path`,{d:`M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4`,key:`1slcih`}]]),_s=o(`flask-conical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),vs=o(`folder-open`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),ys=o(`gauge`,[[`path`,{d:`m12 14 4-4`,key:`9kzdfg`}],[`path`,{d:`M3.34 19a10 10 0 1 1 17.32 0`,key:`19p75a`}]]),bs=o(`gift`,[[`path`,{d:`M12 7v14`,key:`1akyts`}],[`path`,{d:`M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8`,key:`1sqzm4`}],[`path`,{d:`M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5`,key:`kc0143`}],[`rect`,{x:`3`,y:`7`,width:`18`,height:`4`,rx:`1`,key:`1hberx`}]]),xs=o(`git-compare`,[[`circle`,{cx:`18`,cy:`18`,r:`3`,key:`1xkwt0`}],[`circle`,{cx:`6`,cy:`6`,r:`3`,key:`1lh9wr`}],[`path`,{d:`M13 6h3a2 2 0 0 1 2 2v7`,key:`1yeb86`}],[`path`,{d:`M11 18H8a2 2 0 0 1-2-2V9`,key:`19pyzm`}]]),Ss=o(`grid-3x3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M3 9h18`,key:`1pudct`}],[`path`,{d:`M3 15h18`,key:`5xshup`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`M15 3v18`,key:`14nvp0`}]]),Cs=o(`headphones`,[[`path`,{d:`M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3`,key:`1xhozi`}]]),ws=o(`house`,[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`r6nss1`}]]),Ts=o(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),Es=o(`key-round`,[[`path`,{d:`M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z`,key:`1s6t7t`}],[`circle`,{cx:`16.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`w0ekpg`}]]),Ds=o(`layout-dashboard`,[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]),Os=o(`layout-grid`,[[`rect`,{width:`7`,height:`7`,x:`3`,y:`3`,rx:`1`,key:`1g98yp`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`14`,rx:`1`,key:`nxv5o0`}],[`rect`,{width:`7`,height:`7`,x:`3`,y:`14`,rx:`1`,key:`1bb6yr`}]]),ks=o(`log-out`,[[`path`,{d:`m16 17 5-5-5-5`,key:`1bji2h`}],[`path`,{d:`M21 12H9`,key:`dn1m92`}],[`path`,{d:`M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4`,key:`1uf3rs`}]]),As=o(`menu`,[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]),js=o(`monitor`,[[`rect`,{width:`20`,height:`14`,x:`2`,y:`3`,rx:`2`,key:`48i651`}],[`line`,{x1:`8`,x2:`16`,y1:`21`,y2:`21`,key:`1svkeh`}],[`line`,{x1:`12`,x2:`12`,y1:`17`,y2:`21`,key:`vw1qmm`}]]),Ms=o(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),Ns=o(`panel-left-close`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`m16 15-3-3 3-3`,key:`14y99z`}]]),Ps=o(`panel-left-open`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`m14 9 3 3-3 3`,key:`8010ee`}]]),Fs=o(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Is=o(`pen-line`,[[`path`,{d:`M13 21h8`,key:`1jsn5i`}],[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}]]),Ls=o(`percent`,[[`line`,{x1:`19`,x2:`5`,y1:`5`,y2:`19`,key:`1x9vlm`}],[`circle`,{cx:`6.5`,cy:`6.5`,r:`2.5`,key:`4mh3h7`}],[`circle`,{cx:`17.5`,cy:`17.5`,r:`2.5`,key:`1mdrzq`}]]),Rs=o(`pin`,[[`path`,{d:`M12 17v5`,key:`bb1du9`}],[`path`,{d:`M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z`,key:`1nkz8b`}]]),zs=o(`presentation`,[[`path`,{d:`M2 3h20`,key:`91anmk`}],[`path`,{d:`M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3`,key:`2k9sn8`}],[`path`,{d:`m7 21 5-5 5 5`,key:`bip4we`}]]),Bs=o(`radar`,[[`path`,{d:`M19.07 4.93A10 10 0 0 0 6.99 3.34`,key:`z3du51`}],[`path`,{d:`M4 6h.01`,key:`oypzma`}],[`path`,{d:`M2.29 9.62A10 10 0 1 0 21.31 8.35`,key:`qzzz0`}],[`path`,{d:`M16.24 7.76A6 6 0 1 0 8.23 16.67`,key:`1yjesh`}],[`path`,{d:`M12 18h.01`,key:`mhygvu`}],[`path`,{d:`M17.99 11.66A6 6 0 0 1 15.77 16.67`,key:`1u2y91`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}],[`path`,{d:`m13.41 10.59 5.66-5.66`,key:`mhq4k0`}]]),Vs=o(`rotate-ccw-clock`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),Hs=o(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Us=o(`scissors`,[[`circle`,{cx:`6`,cy:`6`,r:`3`,key:`1lh9wr`}],[`path`,{d:`M8.12 8.12 12 12`,key:`1alkpv`}],[`path`,{d:`M20 4 8.12 15.88`,key:`xgtan2`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M14.8 14.8 20 20`,key:`ptml3r`}]]),Ws=o(`scroll-text`,[[`path`,{d:`M15 12h-5`,key:`r7krc0`}],[`path`,{d:`M15 8h-5`,key:`1khuty`}],[`path`,{d:`M19 17V5a2 2 0 0 0-2-2H4`,key:`zz82l3`}],[`path`,{d:`M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3`,key:`1ph1d7`}]]),Gs=o(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Ks=o(`settings`,[[`path`,{d:`M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915`,key:`1i5ecw`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),qs=o(`share-2`,[[`circle`,{cx:`18`,cy:`5`,r:`3`,key:`gq8acd`}],[`circle`,{cx:`6`,cy:`12`,r:`3`,key:`w7nqdw`}],[`circle`,{cx:`18`,cy:`19`,r:`3`,key:`1xt0gg`}],[`line`,{x1:`8.59`,x2:`15.42`,y1:`13.51`,y2:`17.49`,key:`47mynk`}],[`line`,{x1:`15.41`,x2:`8.59`,y1:`6.51`,y2:`10.49`,key:`1n3mei`}]]),Js=o(`shield-alert`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M12 16h.01`,key:`1drbdi`}]]),Ys=o(`shield-check`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Xs=o(`shopping-cart`,[[`circle`,{cx:`8`,cy:`21`,r:`1`,key:`jimo8o`}],[`circle`,{cx:`19`,cy:`21`,r:`1`,key:`13723u`}],[`path`,{d:`M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12`,key:`9zh506`}]]),Zs=o(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),Qs=o(`sprout`,[[`path`,{d:`M14 9.536V7a4 4 0 0 1 4-4h1.5a.5.5 0 0 1 .5.5V5a4 4 0 0 1-4 4 4 4 0 0 0-4 4c0 2 1 3 1 5a5 5 0 0 1-1 3`,key:`139s4v`}],[`path`,{d:`M4 9a5 5 0 0 1 8 4 5 5 0 0 1-8-4`,key:`1dlkgp`}],[`path`,{d:`M5 21h14`,key:`11awu3`}]]),$s=o(`square-check-big`,[[`path`,{d:`M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344`,key:`2acyp4`}],[`path`,{d:`m9 11 3 3L22 4`,key:`1pflzl`}]]),ec=o(`stethoscope`,[[`path`,{d:`M11 2v2`,key:`1539x4`}],[`path`,{d:`M5 2v2`,key:`1yf1q8`}],[`path`,{d:`M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1`,key:`rb5t3r`}],[`path`,{d:`M8 15a6 6 0 0 0 12 0v-3`,key:`x18d4x`}],[`circle`,{cx:`20`,cy:`10`,r:`2`,key:`ts1r5v`}]]),tc=o(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),nc=o(`swords`,[[`polyline`,{points:`14.5 17.5 3 6 3 3 6 3 17.5 14.5`,key:`1hfsw2`}],[`line`,{x1:`13`,x2:`19`,y1:`19`,y2:`13`,key:`1vrmhu`}],[`line`,{x1:`16`,x2:`20`,y1:`16`,y2:`20`,key:`1bron3`}],[`line`,{x1:`19`,x2:`21`,y1:`21`,y2:`19`,key:`13pww6`}],[`polyline`,{points:`14.5 6.5 18 3 21 3 21 6 17.5 9.5`,key:`hbey2j`}],[`line`,{x1:`5`,x2:`9`,y1:`14`,y2:`18`,key:`1hf58s`}],[`line`,{x1:`7`,x2:`4`,y1:`17`,y2:`20`,key:`pidxm4`}],[`line`,{x1:`3`,x2:`5`,y1:`19`,y2:`21`,key:`1pehsh`}]]),rc=o(`table-2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),ic=o(`target`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`6`,key:`1vlfrh`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),ac=o(`timer`,[[`line`,{x1:`10`,x2:`14`,y1:`2`,y2:`2`,key:`14vaq8`}],[`line`,{x1:`12`,x2:`15`,y1:`14`,y2:`11`,key:`17fdiu`}],[`circle`,{cx:`12`,cy:`14`,r:`8`,key:`1e1u0o`}]]),oc=o(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),sc=o(`trees`,[[`path`,{d:`M10 10v.2A3 3 0 0 1 8.9 16H5a3 3 0 0 1-1-5.8V10a3 3 0 0 1 6 0Z`,key:`1l6gj6`}],[`path`,{d:`M7 16v6`,key:`1a82de`}],[`path`,{d:`M13 19v3`,key:`13sx9i`}],[`path`,{d:`M12 19h8.3a1 1 0 0 0 .7-1.7L18 14h.3a1 1 0 0 0 .7-1.7L16 9h.2a1 1 0 0 0 .8-1.7L13 3l-1.4 1.5`,key:`1sj9kv`}]]),z=o(`trending-up`,[[`path`,{d:`M16 7h6v6`,key:`box55l`}],[`path`,{d:`m22 7-8.5 8.5-5-5L2 17`,key:`1t1m79`}]]),B=o(`triangle-alert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),cc=o(`truck`,[[`path`,{d:`M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2`,key:`wrbu53`}],[`path`,{d:`M15 18H9`,key:`1lyqi6`}],[`path`,{d:`M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14`,key:`lysw3i`}],[`circle`,{cx:`17`,cy:`18`,r:`2`,key:`332jqn`}],[`circle`,{cx:`7`,cy:`18`,r:`2`,key:`19iecd`}]]),lc=o(`upload`,[[`path`,{d:`M12 3v12`,key:`1x0j5s`}],[`path`,{d:`m17 8-5-5-5 5`,key:`7q97r8`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}]]),uc=o(`users`,[[`path`,{d:`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`,key:`1yyitq`}],[`path`,{d:`M16 3.128a4 4 0 0 1 0 7.744`,key:`16gr8j`}],[`path`,{d:`M22 21v-2a4 4 0 0 0-3-3.87`,key:`kshegd`}],[`circle`,{cx:`9`,cy:`7`,r:`4`,key:`nufk8`}]]),dc=o(`wallet`,[[`path`,{d:`M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1`,key:`18etb6`}],[`path`,{d:`M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4`,key:`xoc0q4`}]]),fc=o(`waves-horizontal`,[[`path`,{d:`M2 12q2.5 2 5 0t5 0 5 0 5 0`,key:`8ddzzs`}],[`path`,{d:`M2 19q2.5 2 5 0t5 0 5 0 5 0`,key:`1wj4st`}],[`path`,{d:`M2 5q2.5 2 5 0t5 0 5 0 5 0`,key:`69x50u`}]]),pc=o(`wheat`,[[`path`,{d:`M2 22 16 8`,key:`60hf96`}],[`path`,{d:`M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z`,key:`1rdhi6`}],[`path`,{d:`M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z`,key:`1sdzmb`}],[`path`,{d:`M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z`,key:`eoatbi`}],[`path`,{d:`M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z`,key:`19rau1`}],[`path`,{d:`M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z`,key:`tc8ph9`}],[`path`,{d:`M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z`,key:`2m8kc5`}],[`path`,{d:`M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z`,key:`vex3ng`}]]),mc=o(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]),hc=o(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),gc=o(`zap`,[[`path`,{d:`M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z`,key:`1v7up4`}]]),_c=o(`zoom-in`,[[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`line`,{x1:`21`,x2:`16.65`,y1:`21`,y2:`16.65`,key:`13gj7c`}],[`line`,{x1:`11`,x2:`11`,y1:`8`,y2:`14`,key:`1vmskp`}],[`line`,{x1:`8`,x2:`14`,y1:`11`,y2:`11`,key:`durymu`}]]),V=a(),vc={error:{Icon:ts,color:`text-red-600`,bg:`bg-red-50`,ring:`ring-red-100`},success:{Icon:es,color:`text-green-600`,bg:`bg-green-50`,ring:`ring-green-100`},info:{Icon:Ts,color:`text-brand`,bg:`bg-brand-light`,ring:`ring-blue-100`}};function yc({open:e,type:t=`info`,title:n,message:r,onClose:i,autoCloseMs:a,children:o}){let{Icon:s,color:c,bg:l,ring:u}=vc[t]||vc.info;return(0,p.useEffect)(()=>{if(!e||!a)return;let t=setTimeout(i,a);return()=>clearTimeout(t)},[e,a,i]),e?(0,V.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4`,onClick:i,children:(0,V.jsxs)(`div`,{className:`relative w-full max-w-sm rounded-2xl bg-white p-6 text-center shadow-xl`,onClick:e=>e.stopPropagation(),children:[(0,V.jsx)(`div`,{className:`mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full ${l} ring-8 ${u}`,children:(0,V.jsx)(s,{size:28,strokeWidth:2,className:c,"aria-hidden":`true`})}),n&&(0,V.jsx)(`h3`,{className:`mb-1 text-base font-semibold text-gray-800`,children:n}),r&&(0,V.jsx)(`p`,{className:`text-sm text-gray-500`,children:r}),o||(0,V.jsx)(`button`,{type:`button`,onClick:i,className:`mt-5 w-full rounded-lg bg-brand py-2.5 text-sm font-medium text-white transition-colors hover:bg-brand-dark`,children:`ตกลง`}),(0,V.jsx)(`button`,{type:`button`,onClick:i,"aria-label":`ปิด`,className:`absolute right-4 top-4 text-gray-500 hover:text-gray-600`,children:(0,V.jsx)(hc,{size:18,"aria-hidden":`true`})})]})}):null}var bc={dashboard:{th:`แดชบอร์ด`,en:`Dashboard`},reports:{th:`รายงาน`,en:`Reports`},ticket_search:{th:`ค้นหาตั๋วชั่ง`,en:`Search Weigh Tickets`},import_weighing:{th:`Import ใบชั่ง`,en:`Import Weigh Tickets`},insights:{th:`ข้อมูลเชิงลึก`,en:`Insights`},admin:{th:`ผู้ดูแลระบบ`,en:`Administration`},logout:{th:`ออกจากระบบ`,en:`Log out`},language:{th:`ภาษา`,en:`Language`},admin_users:{th:`จัดการผู้ใช้`,en:`User Management`},admin_targets:{th:`เป้าหมายรับซื้อ`,en:`Purchase Targets`},admin_kpi_targets:{th:`ค่าเป้าหมาย KPI`,en:`KPI Targets`},admin_reference:{th:`ข้อมูลอ้างอิง`,en:`Reference Data`},admin_notify:{th:`ระบบแจ้งเตือน`,en:`Notifications`},admin_imports:{th:`ประวัติ Import`,en:`Import History`},admin_log:{th:`Log กิจกรรม`,en:`Activity Log`},admin_api_usage:{th:`การใช้ API`,en:`API Usage`},admin_sync_status:{th:`สถานะตัวดึงข้อมูล`,en:`Sync Status`},group_operations:{th:`ปฏิบัติการ`,en:`Operations`},group_quality:{th:`คุณภาพ`,en:`Quality`},group_business:{th:`ธุรกิจ`,en:`Business`},login_title:{th:`PQS KPI Dashboard`,en:`PQS KPI Dashboard`},login_google:{th:`เข้าสู่ระบบด้วย Google`,en:`Sign in with Google`},login_microsoft:{th:`เข้าสู่ระบบด้วย Microsoft`,en:`Sign in with Microsoft`},login_connecting:{th:`กำลังเชื่อมต่อ...`,en:`Connecting...`},login_other_method:{th:`เข้าสู่ระบบด้วยวิธีอื่น`,en:`Sign in another way`},login_or_email:{th:`หรือด้วยอีเมล`,en:`or with email`},login_email:{th:`อีเมล`,en:`Email`},login_password:{th:`รหัสผ่าน`,en:`Password`},login_submit:{th:`เข้าสู่ระบบ`,en:`Sign in`},login_submitting:{th:`กำลังเข้าสู่ระบบ...`,en:`Signing in...`},login_failed_title:{th:`เข้าสู่ระบบไม่สำเร็จ`,en:`Sign-in failed`},insights_summary_title:{th:`สรุปจาก Insights`,en:`Insights Summary`},group_kpi_strategy:{th:`KPI และกลยุทธ์`,en:`KPI & Strategy`},group_production_analytics:{th:`การผลิตและการวิเคราะห์`,en:`Production & Analytics`},group_finance_business:{th:`การเงินและธุรกิจ`,en:`Finance & Business`},group_people_sustainability:{th:`บุคลากรและความยั่งยืน`,en:`People & Sustainability`},group_daily_tracking:{th:`ติดตามประจำวัน`,en:`Daily Tracking`},sourcing_targets_title:{th:`เป้าหมายรับซื้อหัวมัน ปีนี้ (ตัน)`,en:`This Year's Cassava Sourcing Target (tons)`},monthly_trend_title:{th:`ปริมาณรับซื้อรายเดือน — หัวมัน vs ไบโอแมส (ตัน)`,en:`Monthly Purchase Volume — Cassava vs Biomass (tons)`},top_sellers_title:{th:`ผู้ขายหัวมันสูงสุด 10 อันดับ (ปีนี้)`,en:`Top 10 Cassava Sellers (This Year)`},kpi_executive_table_title:{th:`KPI ระดับบริษัท (Executive Target)`,en:`Company-level KPI (Executive Target)`},kpi_operational_table_title:{th:`KPI ปฏิบัติการ (Operational, รายโรงงาน)`,en:`Operational KPI (by Plant)`},loading:{th:`กำลังโหลด...`,en:`Loading...`},no_data:{th:`ยังไม่มีข้อมูล`,en:`No data yet`},unsaved_confirm:{th:`ข้อมูลที่กรอกยังไม่ได้บันทึก ต้องการออกจากหน้านี้เลยไหม?`,en:`You have unsaved changes. Leave this page anyway?`},unsaved_confirm_title:{th:`ข้อมูลยังไม่ได้บันทึก`,en:`Unsaved Changes`},leave_page:{th:`ออกจากหน้านี้`,en:`Leave Page`},no_access:{th:`ไม่มีข้อมูลผู้ใช้ในระบบ กรุณาติดต่อผู้ดูแล`,en:`No user record found. Please contact an administrator.`},legal_entity_label:{th:`นิติบุคคล`,en:`Legal Entity`},plant_label:{th:`โรงงาน`,en:`Plant`},unsaved_indicator:{th:`มีข้อมูลยังไม่บันทึก`,en:`Unsaved changes`},saving:{th:`กำลังบันทึก...`,en:`Saving...`},save:{th:`บันทึก`,en:`Save`},recent_entries:{th:`รายการล่าสุด`,en:`Recent Entries`},empty_state:{th:`ยังไม่มีข้อมูล — บันทึกรายการแรกด้านบนได้เลย`,en:`No data yet — save your first entry above`},manage_col:{th:`จัดการ`,en:`Actions`},save_edit:{th:`บันทึก`,en:`Save`},cancel_edit:{th:`ยกเลิก`,en:`Cancel`},edit_row:{th:`แก้ไข`,en:`Edit`},delete_row:{th:`ลบ`,en:`Delete`},save_failed:{th:`บันทึกไม่สำเร็จ: `,en:`Save failed: `},save_success:{th:`บันทึกสำเร็จ`,en:`Saved successfully`},edit_failed:{th:`แก้ไขไม่สำเร็จ: `,en:`Edit failed: `},edit_success:{th:`แก้ไขสำเร็จ`,en:`Edited successfully`},delete_failed:{th:`ลบไม่สำเร็จ: `,en:`Delete failed: `},delete_success:{th:`ลบสำเร็จ`,en:`Deleted successfully`},error_title:{th:`เกิดข้อผิดพลาด`,en:`An error occurred`},success_title:{th:`สำเร็จ`,en:`Success`},confirm_delete_title:{th:`ยืนยันลบข้อมูล`,en:`Confirm Delete`},confirm_delete_message:{th:`ลบแล้วกู้คืนไม่ได้ ต้องการลบรายการนี้ใช่ไหม?`,en:`This cannot be undone. Delete this entry?`},close:{th:`ปิด`,en:`Close`},customize_dashboard_title:{th:`ปรับแต่งแดชบอร์ด`,en:`Customize Dashboard`},customize_kpi_cards_title:{th:`การ์ด KPI แต่ละตัว`,en:`Individual KPI Cards`},section_statstrip:{th:`สรุปตัวเลขหลัก`,en:`Key Stats`},hide_section:{th:`ซ่อน`,en:`Hide`},show_section:{th:`แสดง`,en:`Show`},move_up:{th:`เลื่อนขึ้น`,en:`Move up`},move_down:{th:`เลื่อนลง`,en:`Move down`},reset_layout:{th:`รีเซ็ตเป็นค่าเริ่มต้น`,en:`Reset to default`},select_placeholder:{th:`เลือก...`,en:`Select...`},load_more:{th:`โหลดเพิ่ม`,en:`Load more`},dark_mode_on:{th:`โหมดกลางคืน`,en:`Dark Mode`},dark_mode_off:{th:`โหมดกลางวัน`,en:`Light Mode`},cassava:{th:`หัวมัน`,en:`Cassava`},biomass:{th:`ไบโอแมส`,en:`Biomass`},filter_all:{th:`ทั้งหมด`,en:`All`},ts_type:{th:`ประเภท`,en:`Type`},ts_date_from:{th:`วันที่เริ่ม`,en:`Date From`},ts_date_to:{th:`ถึงวันที่`,en:`Date To`},ts_seller:{th:`ผู้ขาย`,en:`Seller`},ts_seller_placeholder:{th:`ชื่อผู้ขาย`,en:`Seller name`},ts_plate:{th:`ทะเบียนรถ`,en:`License Plate`},ts_ticket_no:{th:`เลขที่ตั๋ว`,en:`Ticket No.`},ts_searching:{th:`กำลังค้นหา...`,en:`Searching...`},ts_search_btn:{th:`ค้นหา`,en:`Search`},ts_hint:{th:`ไม่ใส่ตัวกรองใดๆ จะได้ผลล่าสุดของทุกโรงงาน — ใส่ช่วงวันที่ช่วยให้ค้นหาเร็วขึ้น`,en:`No filters means the latest results across all plants — a date range makes it faster`},ts_th_date:{th:`วันที่`,en:`Date`},ts_th_entity:{th:`นิติบุคคล`,en:`Legal Entity`},ts_th_net_weight:{th:`น้ำหนักสุทธิ (กก.)`,en:`Net Weight (kg)`},ts_th_starch:{th:`% แป้ง`,en:`Starch %`},ts_th_moisture:{th:`% ความชื้น`,en:`Moisture %`},ts_th_price:{th:`ราคา/กก. (บาท)`,en:`Price/kg (THB)`},ts_th_amount:{th:`ยอดเงิน (บาท)`,en:`Amount (THB)`},ts_no_results:{th:`ไม่พบข้อมูล`,en:`No results`},ts_search_failed_title:{th:`ค้นหาไม่สำเร็จ`,en:`Search failed`},yoy_compare:{th:`เทียบปีก่อน (YoY)`,en:`Compare to last year (YoY)`},export_csv:{th:`Export CSV`,en:`Export CSV`},export_excel:{th:`Export Excel`,en:`Export Excel`},export_pdf:{th:`Export PDF`,en:`Export PDF`},plant_compare_title:{th:`รายงานเปรียบเทียบ 3 โรงงาน`,en:`3-Plant Comparison Report`},drill_hint:{th:`คลิกที่แท่งกราฟเพื่อดูรายละเอียดตามโรงงาน`,en:`Click a bar to see the breakdown by plant`},chart_cassava_monthly:{th:`รับซื้อหัวมันรายเดือน (ตัน)`,en:`Monthly Cassava Purchases (tons)`},chart_biomass_monthly:{th:`รับซื้อไบโอแมสรายเดือน (ตัน)`,en:`Monthly Biomass Purchases (tons)`},chart_production_monthly:{th:`ผลผลิตรายเดือน (ตัน)`,en:`Monthly Production (tons)`},chart_fuel_monthly:{th:`ค่าเชื้อเพลิงรายเดือน (บาท)`,en:`Monthly Fuel Cost (THB)`},yoy_section_title:{th:`เปรียบเทียบปีต่อปี (รวมทุกโรงงาน)`,en:`Year-over-Year Comparison (All Plants)`},other_monthly_title:{th:`ข้อมูลอื่นๆ รายเดือน (รวมทุกโรงงาน)`,en:`Other Monthly Data (All Plants)`},chart_total_cost:{th:`ต้นทุนรวม`,en:`Total Cost`},chart_revenue_profit:{th:`รายได้ / กำไรสุทธิ`,en:`Revenue / Net Profit`},series_revenue:{th:`รายได้`,en:`Revenue`},series_profit:{th:`กำไรสุทธิ`,en:`Net Profit`},chart_ghg_total:{th:`GHG Emission รวม`,en:`Total GHG Emissions`},chart_headcount_total:{th:`จำนวนพนักงานรวม`,en:`Total Headcount`},full_year_summary_title:{th:`สรุปรวมทั้งปี`,en:`Full-Year Summary`},detail_table_title:{th:`ข้อมูลรายละเอียด (รายวัน)`,en:`Detailed Data (Daily)`},detail_type_label:{th:`ประเภทข้อมูล`,en:`Data Type`},detail_category_production_log:{th:`การผลิตรายวัน (Log)`,en:`Daily Production (Log)`},detail_category_production:{th:`การผลิต (รายกะ/ไลน์)`,en:`Production (by Shift/Line)`},detail_category_energy:{th:`พลังงานรายวัน`,en:`Daily Energy`},detail_category_power_generation:{th:`ผลิตไฟฟ้ารายวัน`,en:`Daily Power Generation`},detail_category_boiler:{th:`Boiler รายวัน`,en:`Daily Boiler`},detail_category_lab:{th:`ผลแลป`,en:`Lab Results`},detail_category_water_treatment:{th:`บำบัดน้ำ`,en:`Water Treatment`},detail_category_machine_state:{th:`สถานะเครื่องจักร`,en:`Machine State`},detail_category_flour_loss:{th:`แป้งสูญเสีย`,en:`Flour Loss`},detail_category_product_mix:{th:`สัดส่วนการผลิต`,en:`Product Mix`},detail_category_near_miss:{th:`Near Miss`,en:`Near Miss`},detail_category_audit:{th:`ตรวจสอบ (Audit)`,en:`Audit`},detail_col_date:{th:`วันที่`,en:`Date`},detail_col_plant:{th:`โรงงาน`,en:`Plant`},detail_col_shift:{th:`กะ`,en:`Shift`},detail_col_line:{th:`สายการผลิต`,en:`Line`},detail_col_production_ton:{th:`ผลผลิต (ตัน)`,en:`Production (tons)`},detail_col_notes:{th:`หมายเหตุ`,en:`Notes`},detail_col_downtime_reason:{th:`สาเหตุ Downtime`,en:`Downtime Reason`},detail_col_electricity:{th:`ไฟฟ้า (kWh)`,en:`Electricity (kWh)`},detail_col_status:{th:`สถานะ`,en:`Status`},show_data_btn:{th:`แสดงข้อมูล`,en:`Show Data`},search_failed_generic:{th:`ค้นหาไม่สำเร็จ`,en:`Search failed`},print_title:{th:`รายงานเปรียบเทียบ 3 โรงงาน — ปี`,en:`3-Plant Comparison Report — Year`},print_date:{th:`พิมพ์เมื่อ`,en:`Printed on`},year_prefix:{th:`ปี`,en:`Year`},full_year_summary_col_plant:{th:`โรงงาน`,en:`Plant`},full_year_summary_col_cassava:{th:`รับซื้อหัวมัน (ตัน)`,en:`Cassava Purchased (tons)`},full_year_summary_col_biomass:{th:`รับซื้อไบโอแมส (ตัน)`,en:`Biomass Purchased (tons)`},full_year_summary_col_production:{th:`ผลผลิต (ตัน)`,en:`Production (tons)`},full_year_summary_col_fuel:{th:`ค่าเชื้อเพลิง (บาท)`,en:`Fuel Cost (THB)`},purchases_cassava:{th:`รับซื้อหัวมัน`,en:`Cassava Purchases`},purchases_biomass:{th:`รับซื้อไบโอแมส`,en:`Biomass Purchases`},label_production:{th:`ผลผลิต`,en:`Production`},label_fuel_cost:{th:`ค่าเชื้อเพลิง`,en:`Fuel Cost`},label_total_cost:{th:`ต้นทุนรวม`,en:`Total Cost`},label_revenue_profit:{th:`รายได้ / กำไรสุทธิ`,en:`Revenue / Net Profit`},label_sales_revenue:{th:`ยอดขาย (รายได้)`,en:`Sales Revenue`},series_sales_revenue:{th:`รายได้ขาย`,en:`Sales Revenue`},series_sales_volume:{th:`ปริมาณขาย (ตัน)`,en:`Sales Volume (t)`},label_ghg_total:{th:`GHG Emission รวม`,en:`Total GHG Emissions`},label_headcount_total:{th:`จำนวนพนักงานรวม`,en:`Total Headcount`},label_inventory_stock:{th:`สต็อกคงเหลือ`,en:`Inventory Stock`},label_it_tickets:{th:`IT Helpdesk (เคส)`,en:`IT Helpdesk (Cases)`},series_open_cases:{th:`เคสเปิด`,en:`Open`},series_closed_cases:{th:`เคสปิด`,en:`Closed`},unit_ton:{th:`ตัน`,en:`t`},unit_baht:{th:`บาท`,en:`THB`},unit_million_baht:{th:`ล้านบาท`,en:`M THB`},unit_persons:{th:`คน`,en:`persons`},unit_cases:{th:`เคส`,en:`cases`},total_label:{th:`รวม`,en:`Total`},drag_reorder_hint:{th:`ลากไอคอน ⠿ เพื่อสลับลำดับ`,en:`Drag the ⠿ icon to reorder`},kpi_th_unit:{th:`หน่วย`,en:`Unit`},kpi_th_actual:{th:`ค่าจริง`,en:`Actual`},kpi_th_grade:{th:`เกรด`,en:`Grade`},kpi_th_weight:{th:`น้ำหนัก`,en:`Weight`},ts_th_rank:{th:`อันดับ`,en:`Rank`},ts_th_volume_ton:{th:`ปริมาณ (ตัน)`,en:`Volume (tons)`},ts_th_value_thb:{th:`มูลค่า (บาท)`,en:`Value (THB)`},ts_th_trips:{th:`จำนวนเที่ยว`,en:`Trips`},dashboard_load_failed_title:{th:`โหลดแดชบอร์ดไม่สำเร็จ`,en:`Failed to load dashboard`}};function xc(e,t){return bc[t]?.[e]??t}var Sc=(0,p.createContext)(null),Cc=`th`;function wc({children:e}){let t=(0,p.useCallback)(e=>xc(Cc,e),[]);return(0,V.jsx)(Sc.Provider,{value:{lang:Cc,t},children:e})}function Tc(){let e=(0,p.useContext)(Sc);if(!e)throw Error(`useLanguage must be used within LanguageProvider`);return e}var Ec=`/assets/pqs-logo-full-DHkpeAkj.webp`;function Dc(){let e=typeof window<`u`?window.location.pathname+window.location.search:``;return typeof window<`u`?window.location.origin+e:`http://localhost:5173`+e}var Oc=``,kc=[{src:`/login/pqs-tower.webp`,pos:`55% 40%`,label:`สาขามุกดาหาร (MUK)`},{src:`/login/pqs-aerial-1.webp`,pos:`62% 55%`,label:`สาขามุกดาหาร (MUK)`},{src:`/login/pqs-sak-gate.webp`,pos:`28% 65%`,label:`สาขาสกลนคร (SAK)`},{src:`/login/pqs-sign.webp`,pos:`20% 60%`,label:`สาขามุกดาหาร (MUK)`},{src:`/login/pqs-kls-queue.webp`,pos:`55% 60%`,label:`สาขากาฬสินธุ์ (KLS)`},{src:`/login/pms-sign.webp`,pos:`30% 70%`,label:`พรีเมียร์โมดิฟายด์สตาร์ช (PMS)`},{src:`/login/pqs-tower-trucks.webp`,pos:`20% 50%`,label:`สาขาสกลนคร (SAK)`},{src:`/login/pqs-kls-gate.webp`,pos:`58% 70%`,label:`สาขากาฬสินธุ์ (KLS)`}].map(e=>({...e,src:Oc+e.src})),Ac=5e3;function jc(){let e=kc.length,[t,n]=(0,p.useState)(0),[r,i]=(0,p.useState)(()=>kc.map((e,t)=>t===0)),a=(0,p.useRef)(new Set),o=t=>{for(let n=1;n<=e;n++){let r=(t+n)%e;if(!a.current.has(r))return r}return t},s=e=>i(t=>{let n=t.slice();return n[e]=!0,n});(0,p.useEffect)(()=>{let e=o(t);if(r[e]||a.current.has(e))return;let n=new Image;return n.onload=()=>s(e),n.onerror=()=>{a.current.add(e)},n.src=kc[e].src,()=>{n.onload=null,n.onerror=null}},[t,r]),(0,p.useEffect)(()=>{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;let e=setInterval(()=>n(e=>{let t=o(e);return r[t]?t:e}),Ac);return()=>clearInterval(e)},[r,t]);let c=e=>{if(e===t||a.current.has(e))return;if(r[e]){n(e);return}let i=new Image;i.onload=()=>{s(e),n(e)},i.onerror=()=>{a.current.add(e)},i.src=kc[e].src},l=kc[t].label;return(0,V.jsxs)(V.Fragment,{children:[kc.map((e,n)=>(0,V.jsx)(`div`,{"aria-hidden":`true`,className:`login-slide${n===t?` on`:``}`,style:r[n]||n===t?{backgroundImage:`url('${e.src}')`,backgroundPosition:e.pos}:void 0},e.src)),l&&(0,V.jsx)(`div`,{className:`login-place`,"aria-hidden":`true`,children:l},t),(0,V.jsx)(`div`,{className:`login-dots`,role:`tablist`,"aria-label":`เลือกรูปพื้นหลัง`,children:kc.map((e,n)=>(0,V.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":n===t,"aria-label":`รูปที่ ${n+1} · ${e.label}`,className:n===t?`on`:``,onClick:()=>c(n)},e.src))})]})}function Mc({initialError:e}){let{t,lang:n}=Tc(),[r,i]=(0,p.useState)(e||``),[a,o]=(0,p.useState)(``),[s,c]=(0,p.useState)(()=>new Date);(0,p.useEffect)(()=>{let e=setInterval(()=>c(new Date),1e3);return()=>clearInterval(e)},[]);async function l(e){i(``),o(e);let{error:t}=await Do.auth.signInWithOAuth({provider:e,options:{redirectTo:Dc(),...e===`azure`?{scopes:`openid profile email User.Read`}:{}}});t&&(o(``),i(t.message))}let u=(()=>{if(!s)return null;let e=s.getHours(),t=n===`th`;return{text:t?e<5?`สวัสดีตอนดึก`:e<12?`สวัสดีตอนเช้า`:e<17?`สวัสดีตอนบ่าย`:`สวัสดีตอนเย็น`:e<12?`Good morning`:e<17?`Good afternoon`:`Good evening`,night:e<5||e>=18,time:`${String(e).padStart(2,`0`)}:${String(s.getMinutes()).padStart(2,`0`)}:${String(s.getSeconds()).padStart(2,`0`)}${t?` น.`:``}`}})();return(0,V.jsxs)(`main`,{className:`login-wrap`,children:[(0,V.jsx)(`div`,{className:`login-side`,children:(0,V.jsx)(jc,{})}),(0,V.jsxs)(`div`,{className:`login-form`,children:[(0,V.jsxs)(`div`,{className:`login-card`,children:[(0,V.jsx)(`img`,{className:`login-logo`,src:Ec,alt:`Premier Quality Starch Group`,width:240,height:105}),(0,V.jsx)(`div`,{className:`login-title`,children:`KPI Dashboard`}),(0,V.jsx)(`div`,{className:`login-greet`,children:u&&(0,V.jsxs)(`span`,{className:`login-greet-in`,children:[u.night?(0,V.jsx)(Ms,{size:13,"aria-hidden":`true`}):(0,V.jsx)(tc,{size:13,"aria-hidden":`true`}),u.text,(0,V.jsx)(`span`,{className:`login-clock`,children:u.time})]})}),(0,V.jsxs)(`button`,{type:`button`,className:`login-btn ms`,onClick:()=>l(`azure`),disabled:!!a,children:[(0,V.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 21 21`,"aria-hidden":`true`,children:[(0,V.jsx)(`rect`,{x:`1`,y:`1`,width:`9`,height:`9`,fill:`#f25022`}),(0,V.jsx)(`rect`,{x:`11`,y:`1`,width:`9`,height:`9`,fill:`#7fba00`}),(0,V.jsx)(`rect`,{x:`1`,y:`11`,width:`9`,height:`9`,fill:`#00a4ef`}),(0,V.jsx)(`rect`,{x:`11`,y:`11`,width:`9`,height:`9`,fill:`#ffb900`})]}),t(a===`azure`?`login_connecting`:`login_microsoft`)]}),(0,V.jsxs)(`button`,{type:`button`,className:`login-btn google`,onClick:()=>l(`google`),disabled:!!a,children:[(0,V.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,V.jsx)(`path`,{d:`M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z`,fill:`#4285F4`}),(0,V.jsx)(`path`,{d:`M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z`,fill:`#34A853`}),(0,V.jsx)(`path`,{d:`M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18A11.02 11.02 0 001 12c0 1.78.43 3.46 1.18 4.93l3.66-2.84z`,fill:`#FBBC05`}),(0,V.jsx)(`path`,{d:`M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z`,fill:`#EA4335`})]}),t(a===`google`?`login_connecting`:`login_google`)]}),(0,V.jsx)(`p`,{className:`login-hint`,children:n===`th`?`ใช้บัญชี Microsoft หรือ Google ที่ผู้ดูแลระบบเพิ่มสิทธิ์ให้`:`Use the Microsoft or Google account an admin has granted access`})]}),(0,V.jsxs)(`div`,{className:`login-foot`,children:[(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,V.jsx)(Ys,{size:12,"aria-hidden":`true`}),n===`th`?`ระบบภายในของกลุ่ม PQS · การเข้าใช้งานถูกบันทึก`:`PQS internal system · access is logged`]}),(0,V.jsxs)(`div`,{className:`login-credit`,children:[`© `,new Date().getFullYear(),` Premier Quality Starch · Developed by Digital Organization Development Department`]})]})]}),(0,V.jsx)(yc,{open:!!r,type:`error`,title:t(`login_failed_title`),message:r,onClose:()=>i(``)})]})}var Nc=(()=>{let e=new Date().getFullYear(),t=[];for(let n=e+1;n>=2022;n--)t.push(n);return t})(),Pc={cassava_weighing:{grid:!0,label:{th:`กรอกข้อมูลของการชั่งหัวมัน`,en:`Data Entry: Cassava Weighing`},icon:pc,group:`operations`,fields:[{name:`weigh_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`seller_name`,label:{th:`ชื่อผู้ขาย`,en:`Seller Name`},type:`text`},{name:`license_plate`,label:{th:`ทะเบียนรถ`,en:`License Plate`},type:`text`},{name:`product_code`,label:{th:`รหัสสินค้า`,en:`Product Code`},type:`select`,options:[`RM001`,`RM-KS`]},{name:`weigh_ticket_no`,label:{th:`เลขที่ตั๋วชั่ง`,en:`Weigh Ticket No.`},type:`text`,required:!0},{name:`gross_weight_kg`,label:{th:`น้ำหนักรวม (กก.)`,en:`Gross Weight (kg)`},type:`number`},{name:`tare_weight_kg`,label:{th:`น้ำหนักรถเปล่า (กก.)`,en:`Tare Weight (kg)`},type:`number`},{name:`net_weight_kg`,label:{th:`น้ำหนักสุทธิ (กก.)`,en:`Net Weight (kg)`},type:`number`},{name:`starch_pct_avg`,label:{th:`แป้ง (%)`,en:`Starch (%)`},type:`number`},{name:`price_per_kg_thb`,label:{th:`ราคา/กก. (บาท)`,en:`Price/kg (THB)`},type:`number`},{name:`total_amount_thb`,label:{th:`ยอดรวม (บาท)`,en:`Total Amount (THB)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},biomass_weighing:{grid:!0,label:{th:`กรอกข้อมูลของการชั่งไบโอแมส`,en:`Data Entry: Biomass Weighing`},icon:gs,group:`operations`,fields:[{name:`weigh_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`seller_name`,label:{th:`ชื่อผู้ขาย`,en:`Seller Name`},type:`text`},{name:`license_plate`,label:{th:`ทะเบียนรถ`,en:`License Plate`},type:`text`},{name:`product_code`,label:{th:`รหัสสินค้า`,en:`Product Code`},type:`select`,options:[`BOM001`,`BOM-KS`]},{name:`weigh_ticket_no`,label:{th:`เลขที่ตั๋วชั่ง`,en:`Weigh Ticket No.`},type:`text`,required:!0},{name:`gross_weight_kg`,label:{th:`น้ำหนักรวม (กก.)`,en:`Gross Weight (kg)`},type:`number`},{name:`tare_weight_kg`,label:{th:`น้ำหนักรถเปล่า (กก.)`,en:`Tare Weight (kg)`},type:`number`},{name:`net_weight_kg`,label:{th:`น้ำหนักสุทธิ (กก.)`,en:`Net Weight (kg)`},type:`number`},{name:`moisture_pct`,label:{th:`ความชื้น (%)`,en:`Moisture (%)`},type:`number`},{name:`heat_value_mj_per_kg`,label:{th:`ค่าความร้อน (MJ/kg)`,en:`Heat Value (MJ/kg)`},type:`number`},{name:`price_per_kg_thb`,label:{th:`ราคา/กก. (บาท)`,en:`Price/kg (THB)`},type:`number`},{name:`total_amount_thb`,label:{th:`ยอดรวม (บาท)`,en:`Total Amount (THB)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},production_daily:{label:{th:`กรอกข้อมูลของการผลิต`,en:`Data Entry: Production`},grid:!0,icon:fs,group:`operations`,fields:[{name:`prod_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`production_ton`,label:{th:`ผลผลิต (ตัน)`,en:`Production (ton)`},type:`number`},{name:`pulp_ton`,label:{th:`กากมัน (ตัน)`,en:`Pulp Output (ton)`},type:`number`},{name:`wastewater_m3`,label:{th:`น้ำเสีย (m³)`,en:`Wastewater Output (m³)`},type:`number`},{name:`yield_pct`,label:{th:`Yield เฉลี่ย (%)`,en:`Avg Yield (%)`},type:`number`},{name:`utilization_pct`,label:{th:`Utilization เฉลี่ย (%)`,en:`Avg Utilization (%)`},type:`number`},{name:`oee_pct`,label:{th:`OEE เฉลี่ย (%)`,en:`Avg OEE (%)`},type:`number`},{name:`availability_pct`,label:{th:`Availability เฉลี่ย (%)`,en:`Avg Availability (%)`},type:`number`},{name:`performance_pct`,label:{th:`Performance เฉลี่ย (%)`,en:`Avg Performance (%)`},type:`number`},{name:`quality_pct`,label:{th:`Quality เฉลี่ย (%)`,en:`Avg Quality (%)`},type:`number`},{name:`recovery_pct`,label:{th:`Recovery เฉลี่ย (%)`,en:`Avg Recovery (%)`},type:`number`},{name:`nc_rate`,label:{th:`ปริมาณแป้ง NC (%)`,en:`NC Flour Rate (%)`},type:`number`},{name:`breakdown_pct`,label:{th:`Breakdown (%)`,en:`Breakdown (%)`},type:`number`},{name:`pm_compliance_pct`,label:{th:`PM Compliance (%)`,en:`PM Compliance (%)`},type:`number`},{name:`productivity_ton_per_manday`,label:{th:`Productivity (ตัน/man-day)`,en:`Productivity (ton/man-day)`},type:`number`},{name:`water_intensity_m3_per_ton`,label:{th:`Water Intensity (m³/ตัน)`,en:`Water Intensity (m³/ton)`},type:`number`},{name:`water_reserve_days`,label:{th:`จำนวนวันน้ำสำรองผลิตได้ (วัน)`,en:`Water Reserve (days)`},type:`number`},{name:`water_chemical_cost_thb`,label:{th:`ค่าสารเคมีน้ำประปา (บาท)`,en:`Water Chemical Cost (THB)`},type:`number`},{name:`energy_intensity_kwh_per_ton`,label:{th:`Energy Intensity (kWh/ตัน)`,en:`Energy Intensity (kWh/ton)`},type:`number`},{name:`steam_intensity_mj_per_ton`,label:{th:`Steam Intensity (MJ/ตัน)`,en:`Steam Intensity (MJ/ton)`},type:`number`},{name:`downtime_hours`,label:{th:`Downtime รวม (ชม.)`,en:`Total Downtime (hr)`},type:`number`},{name:`man_count`,label:{th:`จำนวนคนงานเฉลี่ย`,en:`Avg Headcount`},type:`number`},{name:`flour_transfer_to_pms_kg`,label:{th:`แป้งจ่ายให้ PMS รวม (กก.)`,en:`Flour Transferred to PMS Total (kg)`},type:`number`},{name:`flour_wash_kg`,label:{th:`แป้งล้างรวม (กก.)`,en:`Flour Washed Total (kg)`},type:`number`},{name:`net_remaining_kg`,label:{th:`แป้งคงเหลือสุทธิ (กก.)`,en:`Net Remaining Flour (kg)`},type:`number`},{name:`office_electricity_kwh`,label:{th:`ไฟฟ้าสำนักงานรวม (kWh)`,en:`Office Electricity Total (kWh)`},type:`number`},{name:`production_0to0_kg`,label:{th:`ผลผลิต 0-0 รวม (กก.)`,en:`Production 0-0 Total (kg)`},type:`number`},{name:`production_8to8_kg`,label:{th:`ผลผลิต 8-8 รวม (กก.)`,en:`Production 8-8 Total (kg)`},type:`number`},{name:`yield_sakon`,label:{th:`Yield สกล (%)`,en:`Yield - Sakon (%)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},production_daily_log:{grid:!0,label:{th:`กรอกข้อมูลของการผลิตรายวัน (สำหรับกราฟ)`,en:`Data Entry: Daily Production (for charts)`},icon:Ko,group:`operations`,fields:[{name:`log_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`shift`,label:{th:`กะการผลิต (Shift)`,en:`Shift`},type:`select`,options:[`A`,`B`,`C`]},{name:`line`,label:{th:`ไลน์ผลิต (L1/L2)`,en:`Production Line (L1/L2)`},type:`select`,options:[`L1`,`L2`]},{name:`supervisor_name`,label:{th:`หัวหน้ากะ (Supervisor)`,en:`Supervisor`},type:`text`},{name:`production_ton`,label:{th:`ผลผลิต (ตัน)`,en:`Production (ton)`},type:`number`,required:!0},{name:`yield_pct`,label:{th:`Yield (%)`,en:`Yield (%)`},type:`number`},{name:`utilization_pct`,label:{th:`Utilization (%)`,en:`Utilization (%)`},type:`number`},{name:`downtime_hours`,label:{th:`Downtime (ชม.)`,en:`Downtime (hr)`},type:`number`},{name:`availability_pct`,label:{th:`Availability (%)`,en:`Availability (%)`},type:`number`},{name:`performance_pct`,label:{th:`Performance (%)`,en:`Performance (%)`},type:`number`},{name:`quality_pct`,label:{th:`Quality (%)`,en:`Quality (%)`},type:`number`},{name:`oee_pct`,label:{th:`OEE (%)`,en:`OEE (%)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},fuel_monthly:{grid:!0,label:{th:`กรอกข้อมูลของค่าเชื้อเพลิง`,en:`Data Entry: Fuel Cost`},icon:gs,group:`operations`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`fuel_type`,label:{th:`ประเภทเชื้อเพลิง`,en:`Fuel Type`},type:`text`},{name:`quantity`,label:{th:`ปริมาณ`,en:`Quantity`},type:`number`},{name:`unit`,label:{th:`หน่วย`,en:`Unit`},type:`text`},{name:`cost_thb`,label:{th:`ค่าใช้จ่าย (บาท)`,en:`Cost (THB)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},fuel_daily:{grid:!0,label:{th:`กรอกข้อมูลของค่าเชื้อเพลิงรายวัน (สำหรับกราฟ)`,en:`Data Entry: Daily Fuel Cost (for charts)`},icon:gs,group:`operations`,fields:[{name:`log_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`fuel_type`,label:{th:`ประเภทเชื้อเพลิง`,en:`Fuel Type`},type:`text`},{name:`quantity`,label:{th:`ปริมาณ`,en:`Quantity`},type:`number`},{name:`unit`,label:{th:`หน่วย`,en:`Unit`},type:`text`},{name:`cost_thb`,label:{th:`ค่าใช้จ่าย (บาท)`,en:`Cost (THB)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},energy_daily:{label:{th:`กรอกข้อมูลของพลังงาน`,en:`Data Entry: Energy`},grid:!0,icon:gc,group:`operations`,fields:[{name:`energy_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`biogas_m3`,label:{th:`Biogas ผลิต (m3)`,en:`Biogas Produced (m3)`},type:`number`},{name:`biogas_used_m3`,label:{th:`Biogas ใช้ (m3)`,en:`Biogas Used (m3)`},type:`number`},{name:`electricity_kwh`,label:{th:`ไฟฟ้าใช้ (kWh)`,en:`Electricity Used (kWh)`},type:`number`},{name:`electricity_sold_kwh`,label:{th:`ไฟฟ้าขาย (kWh)`,en:`Electricity Sold (kWh)`},type:`number`},{name:`gas_to_boiler_pct`,label:{th:`แก๊สเข้า Boiler (%)`,en:`Gas to Boiler (%)`},type:`number`},{name:`working_hours`,label:{th:`ชั่วโมงทำงานรวม`,en:`Total Working Hours`},type:`number`},{name:`hourly_capacity_kw`,label:{th:`Hourly Capacity (kW)`,en:`Hourly Capacity (kW)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},energy_daily_log:{grid:!0,label:{th:`กรอกข้อมูลของพลังงานรายวัน (สำหรับกราฟ)`,en:`Data Entry: Daily Energy (for charts)`},icon:Ko,group:`operations`,fields:[{name:`log_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`biogas_m3`,label:{th:`Biogas ผลิต (m3)`,en:`Biogas Produced (m3)`},type:`number`},{name:`electricity_kwh`,label:{th:`ไฟฟ้าใช้ (kWh)`,en:`Electricity Used (kWh)`},type:`number`},{name:`electricity_sold_kwh`,label:{th:`ไฟฟ้าขาย (kWh)`,en:`Electricity Sold (kWh)`},type:`number`},{name:`solar_kwh`,label:{th:`Solar (kWh)`,en:`Solar (kWh)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},power_generation_daily:{label:{th:`กรอกข้อมูลของการผลิตไฟฟ้ารายวัน (ต่อเครื่องปั่นไฟ)`,en:`Data Entry: Daily Power Generation (per generator)`},grid:!0,icon:gc,group:`operations`,fields:[{name:`log_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`gen1_gas_meter_start`,label:{th:`Gen#1 มิเตอร์แก็ส เริ่มวัน (Nm³)`,en:`Gen#1 Gas Meter Start (Nm³)`},type:`number`},{name:`gen1_gas_meter_end`,label:{th:`Gen#1 มิเตอร์แก็ส สิ้นวัน (Nm³)`,en:`Gen#1 Gas Meter End (Nm³)`},type:`number`},{name:`gen1_power_meter_start`,label:{th:`Gen#1 มิเตอร์ไฟฟ้า เริ่มวัน`,en:`Gen#1 Power Meter Start`},type:`number`},{name:`gen1_power_meter_end`,label:{th:`Gen#1 มิเตอร์ไฟฟ้า สิ้นวัน`,en:`Gen#1 Power Meter End`},type:`number`},{name:`gen1_status_note`,label:{th:`Gen#1 สถานะเดินเครื่อง`,en:`Gen#1 Run Status`},type:`text`},{name:`gen2_gas_meter_start`,label:{th:`Gen#2 มิเตอร์แก็ส เริ่มวัน (Nm³)`,en:`Gen#2 Gas Meter Start (Nm³)`},type:`number`},{name:`gen2_gas_meter_end`,label:{th:`Gen#2 มิเตอร์แก็ส สิ้นวัน (Nm³)`,en:`Gen#2 Gas Meter End (Nm³)`},type:`number`},{name:`gen2_power_meter_start`,label:{th:`Gen#2 มิเตอร์ไฟฟ้า เริ่มวัน`,en:`Gen#2 Power Meter Start`},type:`number`},{name:`gen2_power_meter_end`,label:{th:`Gen#2 มิเตอร์ไฟฟ้า สิ้นวัน`,en:`Gen#2 Power Meter End`},type:`number`},{name:`gen2_status_note`,label:{th:`Gen#2 สถานะเดินเครื่อง`,en:`Gen#2 Run Status`},type:`text`},{name:`gen3_gas_meter_start`,label:{th:`Gen#3 มิเตอร์แก็ส เริ่มวัน (Nm³)`,en:`Gen#3 Gas Meter Start (Nm³)`},type:`number`},{name:`gen3_gas_meter_end`,label:{th:`Gen#3 มิเตอร์แก็ส สิ้นวัน (Nm³)`,en:`Gen#3 Gas Meter End (Nm³)`},type:`number`},{name:`gen3_power_meter_start`,label:{th:`Gen#3 มิเตอร์ไฟฟ้า เริ่มวัน`,en:`Gen#3 Power Meter Start`},type:`number`},{name:`gen3_power_meter_end`,label:{th:`Gen#3 มิเตอร์ไฟฟ้า สิ้นวัน`,en:`Gen#3 Power Meter End`},type:`number`},{name:`gen3_status_note`,label:{th:`Gen#3 สถานะเดินเครื่อง`,en:`Gen#3 Run Status`},type:`text`},{name:`gen4_gas_meter_start`,label:{th:`Gen#4 มิเตอร์แก็ส เริ่มวัน (Nm³)`,en:`Gen#4 Gas Meter Start (Nm³)`},type:`number`},{name:`gen4_gas_meter_end`,label:{th:`Gen#4 มิเตอร์แก็ส สิ้นวัน (Nm³)`,en:`Gen#4 Gas Meter End (Nm³)`},type:`number`},{name:`gen4_power_meter_start`,label:{th:`Gen#4 มิเตอร์ไฟฟ้า เริ่มวัน`,en:`Gen#4 Power Meter Start`},type:`number`},{name:`gen4_power_meter_end`,label:{th:`Gen#4 มิเตอร์ไฟฟ้า สิ้นวัน`,en:`Gen#4 Power Meter End`},type:`number`},{name:`gen4_status_note`,label:{th:`Gen#4 สถานะเดินเครื่อง`,en:`Gen#4 Run Status`},type:`text`},{name:`solar_mwh`,label:{th:`ผลิตไฟฟ้าจากโซล่าเซลล์ (MWh)`,en:`Solar Production (MWh)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},cost:{grid:!0,label:{th:`กรอกข้อมูลของต้นทุน`,en:`Data Entry: Cost`},icon:dc,group:`operations`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`cost_category`,label:{th:`หมวดต้นทุน`,en:`Cost Category`},type:`text`,required:!0},{name:`cost_code`,label:{th:`รหัสต้นทุน`,en:`Cost Code`},type:`text`},{name:`amount_thb`,label:{th:`จำนวนเงิน (บาท)`,en:`Amount (THB)`},type:`number`},{name:`unit`,label:{th:`หน่วย`,en:`Unit`},type:`text`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},financial:{grid:!0,label:{th:`กรอกข้อมูลของการเงิน`,en:`Data Entry: Financial`},icon:z,group:`operations`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`revenue_type`,label:{th:`ประเภทรายได้`,en:`Revenue Type`},type:`text`,required:!0},{name:`revenue_thb_m`,label:{th:`รายได้ (ล้านบาท)`,en:`Revenue (THB M)`},type:`number`},{name:`cogs_thb_m`,label:{th:`COGS (ล้านบาท)`,en:`COGS (THB M)`},type:`number`},{name:`gross_profit_thb_m`,label:{th:`กำไรขั้นต้น (ล้านบาท)`,en:`Gross Profit (THB M)`},type:`number`},{name:`sga_expense_thb_m`,label:{th:`ค่าใช้จ่าย SG&A (ล้านบาท)`,en:`SG&A Expense (THB M)`},type:`number`},{name:`net_profit_thb_m`,label:{th:`กำไรสุทธิ (ล้านบาท)`,en:`Net Profit (THB M)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},esg:{grid:!0,label:{th:`กรอกข้อมูลของ ESG`,en:`Data Entry: ESG`},icon:Qs,group:`operations`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`ghg_scope1`,label:{th:`GHG Scope 1`,en:`GHG Scope 1`},type:`number`},{name:`ghg_scope2`,label:{th:`GHG Scope 2`,en:`GHG Scope 2`},type:`number`},{name:`renewable_energy_pct`,label:{th:`พลังงานหมุนเวียน (%)`,en:`Renewable Energy (%)`},type:`number`},{name:`env_complaint_count`,label:{th:`ข้อร้องเรียนสิ่งแวดล้อม (ครั้ง)`,en:`Environmental Complaints (count)`},type:`number`},{name:`pqs_model_acres`,label:{th:`PQS Model (ไร่)`,en:`PQS Model (rai)`},type:`number`},{name:`cg_score`,label:{th:`CG Score`,en:`CG Score`},type:`number`},{name:`customer_satisfaction`,label:{th:`Customer Satisfaction`,en:`Customer Satisfaction`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},people:{grid:!0,label:{th:`กรอกข้อมูลของบุคคล`,en:`Data Entry: People`},icon:uc,group:`operations`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`total_employees`,label:{th:`จำนวนพนักงาน`,en:`Total Employees`},type:`number`},{name:`new_hires`,label:{th:`รับเข้าใหม่`,en:`New Hires`},type:`number`},{name:`recruited`,label:{th:`รับเข้า (สรรหา)`,en:`Recruited`},type:`number`},{name:`resigned`,label:{th:`ลาออก`,en:`Resigned`},type:`number`},{name:`turnover`,label:{th:`Turnover (%)`,en:`Turnover (%)`},type:`number`},{name:`training_completion`,label:{th:`Training Completion (%)`,en:`Training Completion (%)`},type:`number`},{name:`training_plan_count`,label:{th:`แผนอบรม (ครั้ง)`,en:`Training Plan (count)`},type:`number`},{name:`training_actual_count`,label:{th:`อบรมจริง (ครั้ง)`,en:`Training Actual (count)`},type:`number`},{name:`engagement_score`,label:{th:`Engagement Score`,en:`Engagement Score`},type:`number`},{name:`succession_readiness`,label:{th:`Succession Readiness (%)`,en:`Succession Readiness (%)`},type:`number`},{name:`culture_score`,label:{th:`Culture Score`,en:`Culture Score`},type:`number`},{name:`compliance_rate`,label:{th:`Compliance Rate (%)`,en:`Compliance Rate (%)`},type:`number`},{name:`safety_incidents`,label:{th:`อุบัติเหตุ (ครั้ง)`,en:`Incidents (count)`},type:`number`},{name:`occupational_disease_count`,label:{th:`โรคจากการทำงาน (ครั้ง)`,en:`Occupational Disease (count)`},type:`number`},{name:`safety_complaint_count`,label:{th:`ข้อร้องเรียนความปลอดภัย (ครั้ง)`,en:`Safety Complaints (count)`},type:`number`},{name:`ltifr`,label:{th:`LTIFR`,en:`LTIFR`},type:`number`},{name:`pvd_member_pct`,label:{th:`สมาชิกกองสำรองเลี้ยงชีพ (%)`,en:`PVD Members (%)`},type:`number`},{name:`salary_total_thb`,label:{th:`เงินเดือนรวม (บาท)`,en:`Total Salary (THB)`},type:`number`},{name:`overtime_hours`,label:{th:`OT รวม (ชม.)`,en:`Total OT (hr)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},hourly_production:{label:{th:`กรอกข้อมูลของผลผลิตรายชั่วโมง`,en:`Data Entry: Hourly Production`},grid:!0,icon:is,group:`operations`,fields:[{name:`prod_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`line`,label:{th:`ไลน์ผลิต`,en:`Production Line`},type:`select`,options:[`L1`,`L2`]},{name:`time_slot`,label:{th:`ช่วงเวลา (เช่น 08:00-09:00)`,en:`Time Slot (e.g. 08:00-09:00)`},type:`text`},{name:`time_start`,label:{th:`เวลาเริ่ม`,en:`Start Time`},type:`time`},{name:`time_end`,label:{th:`เวลาสิ้นสุด`,en:`End Time`},type:`time`},{name:`production_ton_hour`,label:{th:`ผลผลิต (ตัน)`,en:`Production (ton)`},type:`number`},{name:`issue_text`,label:{th:`เหตุการณ์`,en:`Event`},type:`text`},{name:`issue_duration_min`,label:{th:`เวลาหยุด (นาที)`,en:`Downtime (min)`},type:`number`},{name:`fix_action`,label:{th:`การแก้ไข`,en:`Corrective Action`},type:`text`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},boiler_energy:{grid:!0,label:{th:`กรอกข้อมูลของ Boiler`,en:`Data Entry: Boiler`},icon:ys,group:`operations`,fields:[{name:`energy_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`boiler_type`,label:{th:`ประเภท Boiler`,en:`Boiler Type`},type:`select`,options:[`PMS`,`PQS`]},{name:`heat_mj`,label:{th:`ความร้อน (MJ)`,en:`Heat (MJ)`},type:`number`},{name:`fuel_gas_m3`,label:{th:`Fuel Gas (m3)`,en:`Fuel Gas (m3)`},type:`number`},{name:`biogas_input_m3`,label:{th:`Biogas Input (m3)`,en:`Biogas Input (m3)`},type:`number`},{name:`elec_from_heat_mwh`,label:{th:`ไฟฟ้าจากความร้อน (MWh)`,en:`Electricity from Heat (MWh)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},qa_flour_report:{label:{th:`ใบรายงานผลวิเคราะห์คุณภาพผลิตภัณฑ์ประจำวัน`,en:`QA: Daily Product Quality`},icon:ns,group:`qaqc`,grid:!0,fields:[]},qa_starch_milk:{label:{th:`รายงานการตรวจสอบคุณภาพในกระบวนการผลิต`,en:`QA: In-Process Quality Analysis`},icon:_s,group:`qaqc`,grid:!0,fields:[]},qa_ncr:{label:{th:`NCR. Log Book`,en:`QA: NCR Log Book`},icon:Js,group:`qaqc`,grid:!0,fields:[]},qa_viscosity:{label:{th:`ใบรายงานผลการวิเคราะห์ความหนืดด้วยเครื่องบราเบนเดอร์`,en:`QA: Brabender Viscosity`},icon:ys,group:`qaqc`,grid:!0,fields:[]},qa_micro:{label:{th:`ใบบันทึกผลวิเคราะห์เชื้อ (ในแป้ง / ในน้ำประปา)`,en:`QA: Microbial Analysis`},icon:ps,group:`qaqc`,grid:!0,fields:[]},qa_ash:{label:{th:`ใบวิเคราะห์ค่า ASH`,en:`QA: ASH Analysis`},icon:gs,group:`qaqc`,grid:!0,fields:[]},production_order:{grid:!0,label:{th:`กรอกข้อมูลของคำสั่งผลิต`,en:`Data Entry: Production Order`},icon:rs,group:`operations`,fields:[{name:`order_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`sku_code`,label:{th:`รหัสสินค้า (SKU)`,en:`Product Code (SKU)`},type:`select`,dynamic:`product_sku`},{name:`pack_size`,label:{th:`ขนาดบรรจุ`,en:`Pack Size`},type:`text`},{name:`order_quantity`,label:{th:`จำนวนสั่งผลิต`,en:`Order Quantity`},type:`number`},{name:`order_type`,label:{th:`ประเภทคำสั่ง`,en:`Order Type`},type:`text`},{name:`customer_name`,label:{th:`ลูกค้า`,en:`Customer`},type:`text`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},machine_state:{grid:!0,label:{th:`กรอกข้อมูลของสถานะเครื่องจักร`,en:`Data Entry: Machine State`},icon:os,group:`operations`,fields:[{name:`state_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`line`,label:{th:`ไลน์ผลิต`,en:`Production Line`},type:`select`,options:[`L1`,`L2`]},{name:`equipment`,label:{th:`เครื่องจักร`,en:`Equipment`},type:`text`},{name:`time_slot`,label:{th:`ช่วงเวลา`,en:`Time Slot`},type:`text`},{name:`state_type`,label:{th:`สถานะ`,en:`Status`},type:`text`},{name:`duration_min`,label:{th:`ระยะเวลา (นาที)`,en:`Duration (min)`},type:`number`},{name:`reason`,label:{th:`สาเหตุ`,en:`Cause`},type:`text`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},flour_loss:{grid:!0,label:{th:`กรอกข้อมูลของแป้งเสีย`,en:`Data Entry: Flour Loss`},icon:oc,group:`operations`,fields:[{name:`loss_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`line`,label:{th:`ไลน์ผลิต`,en:`Production Line`},type:`select`,options:[`L1`,`L2`]},{name:`shift`,label:{th:`กะ (Shift)`,en:`Shift`},type:`select`,options:[`A`,`B`,`C`]},{name:`loss_type`,label:{th:`ประเภทแป้งเสีย`,en:`Loss Type`},type:`text`,required:!0},{name:`loss_kg`,label:{th:`ปริมาณ (กก.)`,en:`Quantity (kg)`},type:`number`},{name:`cassava_input_ton`,label:{th:`หัวมันเข้า (ตัน)`,en:`Cassava Input (ton)`},type:`number`},{name:`yield_pct_impact`,label:{th:`ผลกระทบต่อ Yield (%)`,en:`Yield Impact (%)`},type:`number`},{name:`root_cause`,label:{th:`สาเหตุ`,en:`Cause`},type:`text`},{name:`corrective_action`,label:{th:`การแก้ไข`,en:`Corrective Action`},type:`text`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},water_treatment:{grid:!0,label:{th:`กรอกข้อมูลของน้ำประปา/บำบัดน้ำ`,en:`Data Entry: Water Treatment`},icon:us,group:`operations`,fields:[{name:`reading_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`reading_hour`,label:{th:`ชั่วโมง (0-23)`,en:`Hour (0-23)`},type:`number`},{name:`stage`,label:{th:`ขั้นตอน`,en:`Stage`},type:`text`},{name:`ph`,label:{th:`pH`,en:`pH`},type:`number`},{name:`cod`,label:{th:`COD`,en:`COD`},type:`number`},{name:`bod`,label:{th:`BOD`,en:`BOD`},type:`number`},{name:`tss`,label:{th:`TSS`,en:`TSS`},type:`number`},{name:`tds`,label:{th:`TDS`,en:`TDS`},type:`number`},{name:`temperature`,label:{th:`อุณหภูมิ`,en:`Temperature`},type:`number`},{name:`do_level`,label:{th:`DO`,en:`DO`},type:`number`},{name:`flow_m3`,label:{th:`ปริมาณน้ำ (m3)`,en:`Water Flow (m3)`},type:`number`},{name:`chemicals_kg`,label:{th:`สารเคมี (กก.)`,en:`Chemicals (kg)`},type:`number`},{name:`chemical_type`,label:{th:`ชนิดสารเคมี`,en:`Chemical Type`},type:`text`},{name:`pass_fail`,label:{th:`ผ่าน/ไม่ผ่าน`,en:`Pass/Fail`},type:`select`,options:[`PASS`,`FAIL`]},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},product_mix:{grid:!0,label:{th:`กรอกข้อมูลของสัดส่วนการผลิต`,en:`Data Entry: Product Mix`},icon:Zo,group:`operations`,fields:[{name:`mix_date`,label:{th:`วันที่`,en:`Date`},type:`date`,required:!0},{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`sku_code`,label:{th:`รหัสสินค้า (SKU)`,en:`Product Code (SKU)`},type:`select`,dynamic:`product_sku`},{name:`production_ton`,label:{th:`ผลผลิต (ตัน)`,en:`Production (ton)`},type:`number`},{name:`batch_count`,label:{th:`จำนวนแบทช์`,en:`Batch Count`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},near_miss:{grid:!0,label:{th:`กรอกข้อมูลของ Near Miss`,en:`Data Entry: Near Miss`},icon:B,group:`quality`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`near_miss_plan_count`,label:{th:`แผน (ครั้ง)`,en:`Plan (count)`},type:`number`},{name:`near_miss_actual_count`,label:{th:`เกิดขึ้นจริง (ครั้ง)`,en:`Actual Occurrences (count)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},audit:{grid:!0,label:{th:`กรอกข้อมูลของผลตรวจ Audit`,en:`Data Entry: Audit Results`},icon:ps,group:`quality`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`audit_type`,label:{th:`ประเภทการตรวจ`,en:`Audit Type`},type:`text`},{name:`plan_count`,label:{th:`แผน (ครั้ง)`,en:`Plan (count)`},type:`number`},{name:`actual_count`,label:{th:`ดำเนินการจริง (ครั้ง)`,en:`Actual (count)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},actions:{grid:!0,label:{th:`กรอกข้อมูลของ RACI Action`,en:`Data Entry: RACI Action`},icon:ns,group:`quality`,fields:[{name:`meeting_date`,label:{th:`วันที่ประชุม`,en:`Meeting Date`},type:`date`},{name:`action`,label:{th:`Action`,en:`Action`},type:`text`,required:!0},{name:`description`,label:{th:`รายละเอียด`,en:`Description`},type:`text`},{name:`responsible`,label:{th:`ผู้รับผิดชอบ (R)`,en:`Responsible (R)`},type:`text`},{name:`accountable`,label:{th:`ผู้อนุมัติ (A)`,en:`Accountable (A)`},type:`text`},{name:`category`,label:{th:`หมวดหมู่`,en:`Category`},type:`text`},{name:`priority`,label:{th:`ความสำคัญ`,en:`Priority`},type:`select`,options:[`High`,`Medium`,`Low`]},{name:`due_date`,label:{th:`กำหนดเสร็จ`,en:`Due Date`},type:`date`},{name:`status`,label:{th:`สถานะ`,en:`Status`},type:`select`,options:[`Open`,`In Progress`,`Closed`,`Done`]},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},risks:{grid:!0,label:{th:`กรอกข้อมูลของ Risk Register`,en:`Data Entry: Risk Register`},icon:Js,group:`quality`,fields:[{name:`risk_name`,label:{th:`ชื่อความเสี่ยง`,en:`Risk Name`},type:`text`,required:!0},{name:`category`,label:{th:`หมวดหมู่`,en:`Category`},type:`text`},{name:`description`,label:{th:`รายละเอียด`,en:`Description`},type:`text`},{name:`probability`,label:{th:`โอกาสเกิด (1-5)`,en:`Probability (1-5)`},type:`number`},{name:`impact`,label:{th:`ผลกระทบ (1-5)`,en:`Impact (1-5)`},type:`number`},{name:`owner`,label:{th:`ผู้ดูแล`,en:`Owner`},type:`text`},{name:`mitigation_plan`,label:{th:`แผนลดความเสี่ยง`,en:`Mitigation Plan`},type:`text`},{name:`target_date`,label:{th:`เป้าหมายแก้ไข`,en:`Target Date`},type:`date`},{name:`status`,label:{th:`สถานะ`,en:`Status`},type:`select`,options:[`Open`,`In Progress`,`Closed`,`Done`]},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},capa:{grid:!0,label:{th:`กรอกข้อมูลของ CAPA`,en:`Data Entry: CAPA`},icon:mc,group:`quality`,fields:[{name:`capa_date`,label:{th:`วันที่`,en:`Date`},type:`date`},{name:`issue_title`,label:{th:`หัวข้อปัญหา`,en:`Issue Title`},type:`text`,required:!0},{name:`issue_description`,label:{th:`รายละเอียดปัญหา`,en:`Issue Description`},type:`text`},{name:`root_cause`,label:{th:`สาเหตุที่แท้จริง`,en:`Root Cause`},type:`text`},{name:`corrective_action`,label:{th:`การแก้ไข`,en:`Corrective Action`},type:`text`},{name:`action_owner`,label:{th:`ผู้รับผิดชอบ`,en:`Responsible`},type:`text`},{name:`completion_date`,label:{th:`วันที่แก้เสร็จ`,en:`Completion Date`},type:`date`},{name:`status`,label:{th:`สถานะ`,en:`Status`},type:`select`,options:[`Open`,`In Progress`,`Closed`,`Done`]},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},sales:{grid:!0,label:{th:`กรอกข้อมูลของยอดขาย`,en:`Data Entry: Sales`},icon:Xs,group:`business`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`sku_code`,label:{th:`รหัสสินค้า (SKU)`,en:`Product Code (SKU)`},type:`select`,dynamic:`product_sku`},{name:`sales_type`,label:{th:`ประเภทการขาย`,en:`Sales Type`},type:`select`,options:[`Domestic`,`Export`]},{name:`volume_ton`,label:{th:`ปริมาณ (ตัน)`,en:`Quantity (ton)`},type:`number`},{name:`shipped_ton`,label:{th:`ปริมาณการจัดส่ง (ตัน)`,en:`Shipped (ton)`},type:`number`},{name:`preorder_ton`,label:{th:`การสั่งซื้อล่วงหน้า (ตัน)`,en:`Pre-order (ton)`},type:`number`},{name:`revenue_thb`,label:{th:`รายได้ (บาท)`,en:`Revenue (THB)`},type:`number`},{name:`customer_name`,label:{th:`ลูกค้า`,en:`Customer`},type:`text`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},inventory:{grid:!0,label:{th:`กรอกข้อมูลของ Stock สินค้า`,en:`Data Entry: Stock`},icon:Uo,group:`business`,fields:[{name:`as_of_date`,label:{th:`ข้อมูล ณ วันที่`,en:`As of Date`},type:`date`,required:!0},{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`sku_code`,label:{th:`รหัสสินค้า (SKU)`,en:`Product Code (SKU)`},type:`select`,dynamic:`product_sku`},{name:`stock_ton`,label:{th:`คงเหลือ (ตัน)`,en:`Stock (ton)`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},forecasts:{grid:!0,label:{th:`กรอกข้อมูลของพยากรณ์`,en:`Data Entry: Forecast`},icon:Xo,group:`business`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`metric`,label:{th:`ตัวชี้วัด`,en:`Metric`},type:`text`,required:!0},{name:`actual`,label:{th:`ค่าจริง`,en:`Actual`},type:`number`},{name:`budget`,label:{th:`งบประมาณ`,en:`Budget`},type:`number`},{name:`forecast`,label:{th:`พยากรณ์`,en:`Forecast`},type:`number`},{name:`best_case`,label:{th:`กรณีดีที่สุด`,en:`Best Case`},type:`number`},{name:`worst_case`,label:{th:`กรณีแย่ที่สุด`,en:`Worst Case`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},it_helpdesk:{grid:!0,label:{th:`กรอกข้อมูลของ IT Helpdesk`,en:`Data Entry: IT Helpdesk`},icon:Cs,group:`business`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`category`,label:{th:`หมวดหมู่`,en:`Category`},type:`text`},{name:`open_cases`,label:{th:`เคสเปิด`,en:`Open Cases`},type:`number`},{name:`closed_cases`,label:{th:`เคสปิด`,en:`Closed Cases`},type:`number`},{name:`open_avg_days`,label:{th:`เฉลี่ยวันที่เปิดค้าง`,en:`Avg Days Open`},type:`number`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]},attachments:{grid:!0,label:{th:`กรอกข้อมูลของไฟล์แนบ`,en:`Data Entry: Attachments`},icon:Fs,group:`business`,fields:[{name:`month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12]},{name:`year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc},{name:`attachment_type`,label:{th:`ประเภทไฟล์`,en:`Attachment Type`},type:`text`},{name:`file_name`,label:{th:`ชื่อไฟล์`,en:`File Name`},type:`text`,required:!0},{name:`drive_url`,label:{th:`ลิงก์ Google Drive`,en:`Google Drive Link`},type:`text`,required:!0},{name:`department`,label:{th:`แผนก`,en:`Department`},type:`text`},{name:`tags`,label:{th:`แท็ก`,en:`Tags`},type:`text`},{name:`description`,label:{th:`รายละเอียด`,en:`Description`},type:`text`}]},competitors:{grid:!0,label:{th:`กรอกข้อมูลของคู่แข่ง`,en:`Data Entry: Competitors`},icon:nc,group:`business`,fields:[{name:`period_month`,label:{th:`เดือน (1-12)`,en:`Month (1-12)`},type:`select`,options:[1,2,3,4,5,6,7,8,9,10,11,12],required:!0},{name:`period_year`,label:{th:`ปี`,en:`Year`},type:`select`,options:Nc,required:!0},{name:`competitor_name`,label:{th:`ชื่อคู่แข่ง`,en:`Competitor Name`},type:`text`,required:!0},{name:`metric`,label:{th:`ตัวชี้วัด`,en:`Metric`},type:`text`},{name:`value`,label:{th:`ค่าคู่แข่ง`,en:`Competitor Value`},type:`number`},{name:`pqs_value`,label:{th:`ค่าของ PQS`,en:`PQS Value`},type:`number`},{name:`unit`,label:{th:`หน่วย`,en:`Unit`},type:`text`},{name:`source`,label:{th:`แหล่งข้อมูล`,en:`Source`},type:`text`},{name:`notes`,label:{th:`หมายเหตุ`,en:`Notes`},type:`text`}]}},Fc=`cassava_weighing.biomass_weighing.production_daily.energy_daily.cost.financial.esg.people.actions.risks.capa.sales.inventory.forecasts.fuel_monthly.fuel_daily.hourly_production.boiler_energy.production_order.machine_state.flour_loss.water_treatment.product_mix.near_miss.audit.it_helpdesk.attachments.production_daily_log.energy_daily_log.power_generation_daily`.split(`.`),Ic=[`cassava_weighing`,`biomass_weighing`,`production_daily`,`production_daily_log`,`cost`,`financial`,`esg`,`people`,`actions`,`risks`,`capa`,`sales`,`inventory`,`forecasts`,`fuel_monthly`,`fuel_daily`,`hourly_production`,`production_order`,`flour_loss`,`product_mix`,`attachments`,`power_generation_daily`],Lc=[`POWER_ADMIN`,`ADMIN`,`SUPERVISOR`,`OPERATOR`,`QA_QC`],Rc={QA_QC:[`qaqc`]},zc={production_energy:`operations`,import_weighing:`operations`,import_power_generation:`operations`,import_pbe_extras:`operations`,qa_import:`qaqc`};function H(e,t){if(!Lc.includes(e?.role))return!1;let n=Rc[e.role];return!n||n.includes(t)}function Bc(e,t){let n=Pc[t]?.group||zc[t];return n?H(e,n):Lc.includes(e?.role)}var Vc=[{id:`forecast`,label:{th:`พยากรณ์ต่อเนื่อง + สถานการณ์จำลอง`,en:`Rolling Forecast + Scenarios`},Icon:z},{id:`competitor`,label:{th:`เทียบเคียงคู่แข่ง`,en:`Competitor Benchmark`},Icon:Wo},{id:`machinestate`,label:{th:`สถานะเครื่องจักร`,en:`Machine State`},Icon:os}],Hc=[{id:`overview`,label:{th:`ภาพรวม`,en:`Overview`},Icon:Os},{id:`cassava_overview`,label:{th:`สกอร์การ์ดมัน`,en:`Cassava Scorecard`},Icon:sc},{id:`biomass_overview`,label:{th:`สกอร์การ์ดแกลบ`,en:`Biomass Scorecard`},Icon:gs},{id:`kpi_monthly`,label:{th:`KPI รายเดือน`,en:`Monthly KPI`},Icon:Ko},{id:`byplant`,label:{th:`รายโรงงาน`,en:`By Plant`},Icon:fs},{id:`top_cassava`,label:{th:`Top มัน`,en:`Top Cassava`},Icon:Bo},{id:`top_biomass`,label:{th:`Top แกลบ`,en:`Top Biomass`},Icon:gs},{id:`sourcetype`,label:{th:`ไร่ / ลาน`,en:`Field / Yard`},Icon:Qs},{id:`yield`,label:{th:`Yield (แป้ง)`,en:`Yield (Starch)`},Icon:Ls},{id:`deduction`,label:{th:`ดิน / หัก`,en:`Soil / Deduction`},Icon:Us},{id:`energy_biomass`,label:{th:`Energy แกลบ`,en:`Biomass Energy`},Icon:gc},{id:`customertype`,label:{th:`ลูกค้าเก่า / ใหม่`,en:`New / Returning`},Icon:uc},{id:`hourly`,label:{th:`ชั่วโมง / วัน`,en:`Hour / Day`},Icon:is},{id:`mom`,label:{th:`MoM`,en:`MoM`},Icon:z},{id:`yearcompare`,label:{th:`เทียบปี (YearxMonth)`,en:`Year Compare`},Icon:qo},{id:`pivot`,label:{th:`Pivot สาขา×เดือน`,en:`Pivot Plant×Month`},Icon:rc},{id:`heatmap`,label:{th:`Heatmap`,en:`Heatmap`},Icon:Ss},{id:`targets`,label:{th:`เป้าหมาย`,en:`Targets`},Icon:ic},{id:`dataquality`,label:{th:`คุณภาพข้อมูล`,en:`Data Quality`},Icon:Ys},{id:`diagnose`,label:{th:`Diagnose`,en:`Diagnose`},Icon:ec},{id:`entry_cassava`,label:{th:`ใบชั่งมัน`,en:`Cassava Tickets`},Icon:pc},{id:`entry_biomass`,label:{th:`ใบชั่งแกลบ`,en:`Biomass Tickets`},Icon:Is},{id:`import`,label:{th:`Import ใบชั่ง`,en:`Import Weighing`},Icon:lc}],Uc=[{id:`sankey`,label:{th:`ผังการไหลวัตถุดิบ/พลังงาน`,en:`Material/Energy Flow`},Icon:qs},{id:`pareto`,label:{th:`พาเรโต (ปัญหาหลัก)`,en:`Pareto (Top Issues)`},Icon:Yo},{id:`waterfall`,label:{th:`สะพานผลต่าง`,en:`Variance Bridge`},Icon:zo},{id:`heatmap`,label:{th:`ฮีทแมป (กะ x วัน)`,en:`Heatmap (Shift x Day)`},Icon:Ss},{id:`calendar`,label:{th:`ฮีทแมปปฏิทิน`,en:`Calendar Heatmap`},Icon:Ko},{id:`bullet`,label:{th:`บูลเล็ต (เทียบเป้าหมาย)`,en:`Bullet (vs Target)`},Icon:ic},{id:`radar`,label:{th:`เรดาร์ (หลายโรงงาน)`,en:`Radar (Multi-plant)`},Icon:Bs},{id:`spc`,label:{th:`กราฟควบคุม SPC`,en:`SPC Run Chart`},Icon:Ro}],Wc=[{id:`supply`,label:{th:`ซัพพลายหัวมัน`,en:`Cassava Supply`},Icon:cc,desc:{th:`ผู้ขาย (Top 15) → โรงงาน`,en:`Sellers (Top 15) → Plant`}},{id:`cash`,label:{th:`กระแสเงินสด`,en:`Cash Waterfall`},Icon:dc,desc:{th:`รายได้ → COGS/SGA → กำไรสุทธิ`,en:`Revenue → COGS/SGA → Net Profit`}},{id:`ghg`,label:{th:`การปล่อยก๊าซเรือนกระจก`,en:`GHG Flow`},Icon:as,desc:{th:`Scope 1+2 → ปริมาณปล่อยรวม`,en:`Scope 1+2 → Total Emission`}},{id:`workforce`,label:{th:`กำลังคน`,en:`Workforce`},Icon:uc,desc:{th:`พนักงานรวม → บริษัท`,en:`Total Employees → Company`}},{id:`product`,label:{th:`สัดส่วนผลิตภัณฑ์`,en:`Product Mix`},Icon:fs,desc:{th:`ผลผลิต → SKU`,en:`Production → SKU`}}],Gc=[{id:`capa`,label:{th:`CAPA (ปัญหา + แก้ไข)`,en:`CAPA (Issues + Fixes)`},Icon:Jo},{id:`risk`,label:{th:`แผนที่ความเสี่ยง`,en:`Risk Heat-Map`},Icon:B},{id:`actions`,label:{th:`รายการ Action (RACI)`,en:`Action Items (RACI)`},Icon:$s}],Kc=(0,p.lazy)(()=>P(()=>import(`./BonusPolicy-Cz5KGpzR.js`),__vite__mapDeps([0,1,2,3,4]))),qc=(0,p.lazy)(()=>P(()=>import(`./KpiExecutive-4GCMbT09.js`),__vite__mapDeps([5,1,2,6,3,4]))),Jc=(0,p.lazy)(()=>P(()=>import(`./KpiMatrix-Ckzdx3sq.js`),__vite__mapDeps([7,1,2,3,4,8]))),Yc=(0,p.lazy)(()=>P(()=>import(`./KpiForecast-CDZXHaIv.js`),__vite__mapDeps([9,1,2,3,4,7,8]))),Xc=(0,p.lazy)(()=>P(()=>import(`./MonthlyReport-C03txRu7.js`),__vite__mapDeps([10,1,2,11,6,8]))),Zc=(0,p.lazy)(()=>P(()=>import(`./OperationsDashboard-DBaD9u9P.js`),__vite__mapDeps([12,1,2,13,14,15,16,17,18,3,8]))),Qc=(0,p.lazy)(()=>P(()=>import(`./PeopleDashboard-C_ai0pyt.js`),__vite__mapDeps([19,1,2,13,14,15,20,21,22,17,18,8]))),$c=(0,p.lazy)(()=>P(()=>import(`./PredictiveYield-K00-wFq_.js`),__vite__mapDeps([23,1,2,24,18]))),el=(0,p.lazy)(()=>P(()=>import(`./ProductionDashboard-D6jG0xT5.js`),__vite__mapDeps([25,1,2,13,14,15,17,18]))),tl=(0,p.lazy)(()=>P(()=>import(`./SalesDashboard-D5LcZsyz.js`),__vite__mapDeps([26,1,2,13,14,15,16,17,18,8]))),nl=(0,p.lazy)(()=>P(()=>import(`./StrategicHub-dP4RueBQ.js`),__vite__mapDeps([27,1,2,13,14,20,22,18]))),rl=(0,p.lazy)(()=>P(()=>import(`./SupplierScorecard-7MZ0IRpT.js`),__vite__mapDeps([28,1,2,29,6,13,14,15,20,22,17,30,18]))),il=(0,p.lazy)(()=>P(()=>import(`./AdvancedAnalytics-C9_jz8C1.js`),__vite__mapDeps([31,1,2,32,24,18,33]))),al=(0,p.lazy)(()=>P(()=>import(`./AndonBoard-B_iUMrLc.js`),__vite__mapDeps([34,1,2,6,29,32]))),ol=(0,p.lazy)(()=>P(()=>import(`./AuditCoverage-BXlx4p9X.js`),__vite__mapDeps([35,1,2,11,6,29,8]))),sl=(0,p.lazy)(()=>P(()=>import(`./CostDashboard-j--3RCqD.js`),__vite__mapDeps([36,1,2,13,14,15,16,17,18,8]))),cl=(0,p.lazy)(()=>P(()=>import(`./ESGDashboard-CqxGKHrP.js`),__vite__mapDeps([37,1,2,13,14,15,16,17,18,8]))),ll=(0,p.lazy)(()=>P(()=>import(`./QaDashboard-D-QXxaPB.js`),__vite__mapDeps([38,1,2,13,14,15,20,21,22,17,30,18,39,40]))),U=(0,p.lazy)(()=>P(()=>import(`./DailySnapshot-BrM8y3Hm.js`),__vite__mapDeps([41,1,2,32,24,18]))),ul=(0,p.lazy)(()=>P(()=>import(`./FinancialDashboard-Cn3lCZjJ.js`),__vite__mapDeps([42,1,2,13,14,15,20,16,30,18,8]))),dl=(0,p.lazy)(()=>P(()=>import(`./FlowMapsHub-BuoBmsI7.js`),__vite__mapDeps([43,1,2,24,18,33]))),fl=(0,p.lazy)(()=>P(()=>import(`./GovernanceHub-JcClstyB.js`),__vite__mapDeps([44,1,2,6,24,18,33]))),pl=(0,p.lazy)(()=>P(()=>import(`./InventoryDashboard-Ded1AeOP.js`),__vite__mapDeps([45,1,2,13,15,16,17,18]))),ml=(0,p.lazy)(()=>P(()=>import(`./KpiDeepDive-DhU1tLlD.js`),__vite__mapDeps([46,1,2,13,20,21,22,18,3,4,8]))),hl=(0,p.lazy)(()=>P(()=>import(`./PlantCompare-X72GHZvd.js`),__vite__mapDeps([47,1,2,13,14,15,17,18]))),gl=(0,p.lazy)(()=>P(()=>import(`./WeighTurnaround--Zwhh127.js`),__vite__mapDeps([48,1,2,49,6,29,24,18]))),W={suppliers:{label:{th:`สกอร์การ์ดซัพพลายเออร์`,en:`Supplier Scorecard`},icon:cc,group:`insights`,component:rl,subTabs:Hc},advanced:{label:{th:`การวิเคราะห์ขั้นสูง`,en:`Advanced Analytics`},icon:Xo,group:`insights`,component:il,subTabs:Uc},andon:{label:{th:`บอร์ดแจ้งเตือน Andon`,en:`Andon Board`},icon:js,group:`insights`,component:al},audit_coverage:{label:{th:`ตรวจสอบความครบถ้วนของข้อมูล`,en:`Data Coverage Audit`},icon:ns,group:`insights`,component:ol},cost_dashboard:{label:{th:`ต้นทุน (แดชบอร์ด)`,en:`Cost (Dashboard)`},icon:Go,group:`insights`,component:sl},esg_dashboard:{label:{th:`ESG`,en:`ESG`},icon:Qs,group:`insights`,component:cl},qa_dashboard:{label:{th:`QA & QC Dashboard`,en:`QA & QC Dashboard`},icon:_s,group:`insights`,component:ll},snapshot:{label:{th:`ภาพรวมประจำวัน`,en:`Daily Snapshot`},icon:Ko,group:`insights`,component:U},financial_dashboard:{label:{th:`การเงิน (แดชบอร์ด)`,en:`Financial (Dashboard)`},icon:dc,group:`insights`,component:ul},flow_maps:{label:{th:`แผนผังกระบวนการ`,en:`Flow Maps Hub`},icon:fc,group:`insights`,component:dl,subTabs:Wc},governance:{label:{th:`ศูนย์กำกับดูแลกิจการ`,en:`Governance Hub`},icon:Ys,group:`insights`,component:fl,subTabs:Gc},inventory_dashboard:{label:{th:`สต๊อกสินค้า (แดชบอร์ด)`,en:`Inventory (Dashboard)`},icon:Uo,group:`insights`,component:pl},kpi_deepdive:{label:{th:`เจาะลึก KPI`,en:`KPI Deep Dive`},icon:_c,group:`insights`,component:ml},kpi_exec:{label:{th:`สรุป KPI ผู้บริหาร`,en:`KPI Executive Brief`},icon:ls,group:`insights`,component:qc},kpi_matrix:{label:{th:`ตาราง KPI`,en:`KPI Matrix`},icon:Ss,group:`insights`,component:Jc},kpi_forecast:{label:{th:`พยากรณ์ KPI`,en:`KPI Forecast`},icon:ys,group:`insights`,component:Yc},kpi_bonus:{label:{th:`KPI Bonus Policy`,en:`KPI Bonus Policy`},icon:bs,group:`insights`,component:Kc},monthly_report:{label:{th:`รายงานประจำเดือน`,en:`Monthly Report`},icon:zs,group:`insights`,component:Xc},operations_dashboard:{label:{th:`IT และความปลอดภัย`,en:`IT & Safety`},icon:Cs,group:`insights`,component:Zc},people_dashboard:{label:{th:`บุคคล (แดชบอร์ด)`,en:`People (Dashboard)`},icon:uc,group:`insights`,component:Qc},plant_compare:{label:{th:`เทียบข้ามโรงงาน`,en:`Plant Compare`},icon:xs,group:`insights`,component:hl},weigh_turnaround:{label:{th:`เวลาชั่งเข้าถึงชั่งออก`,en:`Weigh-in to Weigh-out Time`},icon:ac,group:`insights`,component:gl},predictive_yield:{label:{th:`พยากรณ์ Yield`,en:`Predictive Yield`},icon:Zs,group:`insights`,component:$c},production_dashboard:{label:{th:`การผลิต (แดชบอร์ด)`,en:`Production (Dashboard)`},icon:Ho,group:`insights`,component:el},sales_dashboard:{label:{th:`ยอดขาย (แดชบอร์ด)`,en:`Sales (Dashboard)`},icon:Xs,group:`insights`,component:tl},strategic:{label:{th:`ศูนย์วางแผนกลยุทธ์`,en:`Strategic Planning Hub`},icon:ss,group:`insights`,component:nl,subTabs:Vc}},_l=`pqs_theme`;function vl(){try{return localStorage.getItem(_l)===`dark`}catch{return!1}}function yl(e){document.documentElement.classList.toggle(`dark`,e)}var bl=new Set;function xl(e){return bl.add(e),()=>bl.delete(e)}function Sl(e){try{localStorage.setItem(_l,e?`dark`:`light`)}catch{}yl(e),bl.forEach(e=>e())}function Cl(){return(0,p.useSyncExternalStore)(xl,vl,()=>!1)}function wl(){yl(vl())}var Tl=`pqs_recent_views`,El=5;function Dl(){try{let e=JSON.parse(localStorage.getItem(Tl));return Array.isArray(e)?e:[]}catch{return[]}}function Ol(e){if(!(!e||e===`dashboard`))try{let t=[e,...Dl().filter(t=>t!==e)].slice(0,El);localStorage.setItem(Tl,JSON.stringify(t))}catch{}}var kl=`pqs_pinned_views`;function Al(){try{let e=JSON.parse(localStorage.getItem(kl));return Array.isArray(e)?e:[]}catch{return[]}}function jl(e){let t=Al(),n=t.includes(e)?t.filter(t=>t!==e):[e,...t];try{localStorage.setItem(kl,JSON.stringify(n))}catch{}return n}var Ml=[`POWER_ADMIN`,`ADMIN`,`MANAGER`,`SUPERVISOR`,`QA_QC`];function Nl(e){return Ml.includes(e?.role)}var Pl=new Set([`suppliers`,`ticket_search`,`people_dashboard`,`cost_dashboard`,`weigh_turnaround`]);function Fl(e){return Pl.has(String(e||``).split(`:`)[0])}function Il(e,t){return Fl(e)&&!Nl(t)}var Ll=u(),Rl=`pqs_seen_help_guide`;function zl(){try{return localStorage.getItem(Rl)===`1`}catch{return!0}}function G(){try{localStorage.setItem(Rl,`1`)}catch{}}var K={title:`วิธีใช้งานระบบ PQS KPI Dashboard`,intro:`ระบบนี้ใช้บันทึกข้อมูลการทำงานประจำวัน แล้วรวมเป็นภาพรวม/รายงาน/กราฟให้ดูง่าย ไม่ต้องนับมือ ไม่ต้องเปิดหลายไฟล์ — ข้อมูลบางส่วน (การผลิต, ยอดขาย, บุคคล, ESG ฯลฯ) เชื่อมกับ Mini KPI Dashboard แบบ real-time ด้วย กรอกที่นี่ครั้งเดียวเห็นทั้งสองระบบ`,stepsTitle:`ขั้นตอนการใช้งานหลัก`,steps:[{title:`1. กรอกข้อมูล`,desc:`เลือกหมวดในเมนูฝั่งซ้าย (เช่น การผลิต, พลังงาน, การเงิน, บุคคล, คุณภาพ+ความเสี่ยง) — แต่ละหัวข้อคือฟอร์มกรอกข้อมูลของเรื่องนั้นๆ กรอกแล้วกดบันทึก ระบบโชว์รายการล่าสุดด้านล่างฟอร์มทันที ช่องวันที่กดปุ่มปฏิทินเลือกได้ ไม่ต้องพิมพ์เอง ถ้ากรอกซ้ำช่วงเวลาเดิม ระบบจะเตือนก่อนบันทึกทับ`},{title:`2. ดูภาพรวมที่แดชบอร์ด`,desc:`หน้า "แดชบอร์ด" สรุปตัวเลขสำคัญของทั้งบริษัท ปีนี้/เดือนนี้ พร้อมกราฟแนวโน้มย้อนหลัง 3 ปี`},{title:`3. เช็คเกรด KPI + โบนัส`,desc:`หมวด "KPI ทุกแบบ" มีตาราง KPI ทั้งหมด (เกรด D/C/B/A ตามเป้าจริง), เจาะลึกรายตัว, พยากรณ์สิ้นปี และหน้า "KPI Bonus Policy" คำนวณเดือนโบนัสตามมติ ExCom แยก 3 บริษัท (PQS Group/PMS/PBE) — กดที่ตัว KPI แต่ละตัวดูรายละเอียดเพิ่มได้`},{title:`4. ดูรายงานเปรียบเทียบ`,desc:`หน้า "รายงาน" เทียบข้อมูล 3 โรงงาน (MUK/SKN/KAL) รายเดือน เทียบปีต่อปีได้ Export เป็น CSV หรือ Excel ได้`},{title:`5. วิเคราะห์เชิงลึก`,desc:`หมวด "Analytics" มีผังการไหลวัตถุดิบ/พลังงาน (Sankey), Pareto, Waterfall, Heatmap และกราฟวิเคราะห์อื่นๆ — ทุกตัวเลขเป็นข้อมูลจริง ไม่มีค่าประมาณการ`},{title:`6. ค้นหา/นำเข้าข้อมูล`,desc:`"ค้นหาตั๋วชั่ง" หาใบชั่งเก่าตามผู้ขาย/ทะเบียน/เลขที่ตั๋ว · หมวด "พลังงาน" มี Import ผลิตไฟฟ้า และ Import กากสด/Boiler จากไฟล์ PBE โดยตรง แทนกรอกทีละวัน`},{title:`7. ผู้ดูแลระบบ`,desc:`เมนู "ผู้ดูแลระบบ" (เห็นเฉพาะ Admin) จัดการผู้ใช้ เป้าหมาย ข้อมูลอ้างอิง และหน้า "Log กิจกรรมระบบ" — เห็นประวัติการเพิ่ม/แก้ไข/ลบข้อมูลทุกตาราง กรองตามตารางหรือช่วงวันที่ และ export เป็น Excel ได้`},{title:`8. โหมดกลางวัน/กลางคืน`,desc:`ปุ่มมุมล่างซ้ายของเมนู สลับธีมสว่าง/มืดได้ ระบบจำค่าที่เลือกไว้ในเครื่องนี้`}],menusTitle:`อธิบายเมนูแต่ละส่วน`,menus:[{Icon:Ds,name:`แดชบอร์ด`,desc:`หน้าแรกหลัง login — สรุปตัวเลขสำคัญของบริษัททั้งหมด`},{Icon:bs,name:`KPI ทุกแบบ / Bonus Policy`,desc:`ตาราง KPI, เจาะลึกรายตัว, พยากรณ์สิ้นปี และการคำนวณเดือนโบนัสตามเกรด (D=1.0 / C=2.0 / B=3.0 / A=4.0 เดือน)`},{Icon:Yo,name:`รายงาน / Analytics`,desc:`เปรียบเทียบ 3 โรงงานรายเดือน/รายปี ส่งออก CSV/Excel ได้ — และผังการไหลวัตถุดิบ/พลังงานเชิงลึก`},{Icon:Gs,name:`ค้นหาตั๋วชั่ง`,desc:`ค้นหาใบชั่งหัวมัน/ไบโอแมสที่บันทึกไว้แล้ว กรองตามวันที่ ผู้ขาย ทะเบียนรถ`},{Icon:lc,name:`Import (ใบชั่ง / PBE)`,desc:`อัพโหลดไฟล์ Excel — ใบชั่งหัวมัน/แกลบ, ผลิตไฟฟ้า, กากสด/Boiler — ระบบเช็คข้อมูลซ้ำให้อัตโนมัติก่อนบันทึก`},{Icon:Is,name:`หมวดข้อมูลต่างๆ`,desc:`การผลิต / พลังงาน / การเงิน / ESG / บุคคล / ยอดขาย / Governance / คุณภาพ+ความเสี่ยง — แต่ละหมวดมีฟอร์มกรอกข้อมูลของตัวเอง`},{Icon:Ss,name:`ข้อมูล Mini KPI`,desc:`รวมฟอร์มที่ข้อมูลไปโผล่ใน Mini KPI Dashboard ด้วย (การผลิต, ยอดขาย, บุคคล, ESG, พลังงาน ฯลฯ) — กรอกที่นี่ครั้งเดียว เห็นทั้งสองระบบ ไม่ต้องกรอกซ้ำ`}],tip:`กด Ctrl+K (หรือปุ่มค้นหาบนสุดของเมนู) เพื่อค้นหาและกระโดดไปหน้าไหนก็ได้เร็วๆ`};function q({open:e,onClose:t}){return e?(0,Ll.createPortal)((0,V.jsx)(`div`,{"data-menu-portal":!0,className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4 py-8`,onClick:t,children:(0,V.jsxs)(`div`,{className:`flex max-h-full w-full max-w-2xl flex-col overflow-hidden rounded-2xl bg-white shadow-xl`,onClick:e=>e.stopPropagation(),children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-between border-b border-gray-100 px-6 py-4`,children:[(0,V.jsxs)(`h2`,{className:`flex items-center gap-2 text-base font-semibold text-brand`,children:[(0,V.jsx)(Ts,{size:18,"aria-hidden":`true`}),` `,K.title]}),(0,V.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-lg p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-600`,"aria-label":`ปิด`,children:(0,V.jsx)(hc,{size:18,"aria-hidden":`true`})})]}),(0,V.jsxs)(`div`,{className:`overflow-y-auto px-6 py-5`,children:[(0,V.jsx)(`p`,{className:`mb-5 text-sm text-gray-600`,children:K.intro}),(0,V.jsx)(`h3`,{className:`mb-3 text-sm font-semibold text-gray-700`,children:K.stepsTitle}),(0,V.jsx)(`div`,{className:`mb-6 space-y-3`,children:K.steps.map(e=>(0,V.jsxs)(`div`,{className:`rounded-xl border border-gray-100 bg-gray-50 p-3`,children:[(0,V.jsx)(`div`,{className:`mb-0.5 text-sm font-medium text-brand`,children:e.title}),(0,V.jsx)(`div`,{className:`text-xs text-gray-600`,children:e.desc})]},e.title))}),(0,V.jsx)(`h3`,{className:`mb-3 text-sm font-semibold text-gray-700`,children:K.menusTitle}),(0,V.jsx)(`div`,{className:`mb-5 space-y-1.5`,children:K.menus.map(e=>(0,V.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded-lg px-2 py-1.5`,children:[(0,V.jsx)(e.Icon,{size:16,className:`mt-0.5 shrink-0 text-brand`,"aria-hidden":`true`}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`div`,{className:`text-sm font-medium text-gray-700`,children:e.name}),(0,V.jsx)(`div`,{className:`text-xs text-gray-500`,children:e.desc})]})]},e.name))}),(0,V.jsxs)(`p`,{className:`flex items-center gap-1.5 rounded-lg bg-brand-light px-3 py-2 text-xs text-brand`,children:[(0,V.jsx)($o,{size:12,"aria-hidden":`true`}),` `,K.tip]})]})]})}),document.body):null}function J(){let[e,t]=(0,p.useState)(!1);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{type:`button`,onClick:()=>t(!0),className:`mb-2 flex w-full items-center gap-2 rounded-lg border border-line px-3 py-2 text-sm text-gray-700 hover:bg-gray-100`,children:[(0,V.jsx)(Ts,{size:16,strokeWidth:2,"aria-hidden":`true`}),`วิธีใช้งาน`]}),(0,V.jsx)(q,{open:e,onClose:()=>t(!1)})]})}var Y={total:170,groups:[{title:`โครงหลักของระบบ`,items:[{name:`React / React DOM`,version:`19.2.8`,license:`MIT`,use:`สร้างหน้าจอ`,url:`https://github.com/react/react`},{name:`Vite`,version:`8.1.5`,license:`MIT`,use:`build เว็บ (ไม่ได้ส่งไปกับหน้าเว็บ)`,url:`https://github.com/vitejs/vite`},{name:`Tailwind CSS`,version:`4.3.3`,license:`MIT`,use:`จัดรูปแบบหน้าจอ`,url:`https://github.com/tailwindlabs/tailwindcss`}]},{title:`ฐานข้อมูลและการเข้าสู่ระบบ`,items:[{name:`Supabase JS`,version:`2.111.0`,license:`MIT`,use:`เชื่อมฐานข้อมูลและบัญชีผู้ใช้`,url:`https://github.com/supabase/supabase-js`}]},{title:`กราฟ`,items:[{name:`Recharts`,version:`3.10.1`,license:`MIT`,use:`กราฟส่วนใหญ่`,url:`https://github.com/recharts/recharts`},{name:`Apache ECharts`,version:`6.1.0`,license:`Apache-2.0`,use:`กราฟวิเคราะห์เชิงลึก`,url:`https://github.com/apache/echarts`},{name:`echarts-for-react`,version:`3.0.6`,license:`MIT`,use:`ใช้ ECharts ใน React`,url:`https://github.com/hustcc/echarts-for-react`}]},{title:`ไฟล์ Excel / PDF / รูปภาพ`,items:[{name:`SheetJS (xlsx)`,version:`0.20.3`,license:`Apache-2.0`,use:`อ่านไฟล์ Excel ที่นำเข้า`,url:`https://git.sheetjs.com/SheetJS/sheetjs`},{name:`ExcelJS`,version:`4.4.0`,license:`MIT`,use:`ออกไฟล์ Excel`,url:`https://github.com/exceljs/exceljs`},{name:`jsPDF`,version:`4.2.1`,license:`MIT`,use:`ออกไฟล์ PDF`,url:`https://github.com/parallax/jsPDF`},{name:`html-to-image`,version:`1.11.11`,license:`MIT`,use:`บันทึกกราฟเป็นรูป`,url:`https://github.com/bubkoo/html-to-image`}]},{title:`ฟอนต์และไอคอน`,items:[{name:`Lucide`,version:`1.27.0`,license:`ISC`,use:`ไอคอนเมนูและปุ่ม`,url:`https://github.com/lucide-icons/lucide`},{name:`Inter`,license:`SIL OFL 1.1`,use:`ฟอนต์ตัวอักษรอังกฤษ/ตัวเลข`,url:`https://fonts.google.com/specimen/Inter/license`},{name:`Noto Sans Thai`,license:`SIL OFL 1.1`,use:`ฟอนต์ภาษาไทย`,url:`https://fonts.google.com/specimen/Noto+Sans+Thai/license`},{name:`Saira Extra Condensed`,license:`SIL OFL 1.1`,use:`หัวข้อหน้าเข้าสู่ระบบ`,url:`https://fonts.google.com/specimen/Saira+Extra+Condensed/license`}]}]},Bl=`https://kpi-dashboard-green-one.vercel.app/licenses.txt`;function Vl({open:e,onClose:t}){return(0,p.useEffect)(()=>{if(!e)return;let n=e=>{e.key===`Escape`&&t()};return document.addEventListener(`keydown`,n),()=>document.removeEventListener(`keydown`,n)},[e,t]),e?(0,Ll.createPortal)((0,V.jsx)(`div`,{"data-menu-portal":!0,className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4 py-8`,onClick:t,children:(0,V.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lic-title`,className:`flex max-h-full w-full max-w-xl flex-col overflow-hidden rounded-2xl bg-white shadow-xl`,onClick:e=>e.stopPropagation(),children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-between border-b border-line px-5 py-3.5`,children:[(0,V.jsxs)(`h2`,{id:`lic-title`,className:`flex items-center gap-2 text-base font-semibold text-brand`,children:[(0,V.jsx)(hs,{size:18,"aria-hidden":`true`}),` ซอฟต์แวร์และสัญญาอนุญาต`]}),(0,V.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-lg p-1.5 text-gray-500 hover:bg-gray-100`,"aria-label":`ปิด`,children:(0,V.jsx)(hc,{size:18,"aria-hidden":`true`})})]}),(0,V.jsxs)(`div`,{className:`overflow-y-auto px-5 py-4 text-sm`,children:[(0,V.jsx)(`p`,{className:`mb-4 text-xs leading-relaxed text-muted`,children:`KPI Smart Dashboard เป็นซอฟต์แวร์ภายในของ Premier Quality Starch พัฒนาโดยแผนกพัฒนาองค์กรดิจิทัล และใช้ซอฟต์แวร์โอเพนซอร์สต่อไปนี้ ตามเงื่อนไขของสัญญาอนุญาตแต่ละตัว · กดชื่อเพื่อดูต้นทาง`}),Y.groups.map(e=>(0,V.jsxs)(`section`,{className:`mb-4`,children:[(0,V.jsx)(`h3`,{className:`mb-1 text-xs font-semibold text-gray-700`,children:e.title}),(0,V.jsx)(`ul`,{children:e.items.map(e=>(0,V.jsxs)(`li`,{className:`flex items-baseline gap-2 border-t border-line py-1.5`,children:[(0,V.jsxs)(`div`,{className:`min-w-0 flex-1 text-[12.5px]`,children:[(0,V.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:`font-semibold text-brand hover:underline`,children:e.name}),e.version&&(0,V.jsxs)(`span`,{className:`tabular-nums text-muted`,children:[` `,e.version]}),(0,V.jsxs)(`span`,{className:`text-gray-600`,children:[` · `,e.use]})]}),(0,V.jsx)(`span`,{className:`shrink-0 whitespace-nowrap rounded-full border border-line bg-well px-2 py-px text-[10.5px] font-semibold text-gray-600`,children:e.license})]},e.name))})]},e.title)),(0,V.jsxs)(`a`,{href:Bl,target:`_blank`,rel:`noopener noreferrer`,className:`flex items-center justify-between gap-2 rounded-lg bg-brand-light px-3 py-2 text-xs text-brand hover:underline`,children:[(0,V.jsxs)(`span`,{children:[`รายการทั้งหมด `,Y.total,` ไลบรารี พร้อมข้อความสัญญาฉบับเต็ม`]}),(0,V.jsx)(ds,{size:13,className:`shrink-0`,"aria-hidden":`true`})]})]})]})}),document.body):null}function Hl(){let[e,t]=(0,p.useState)(!1);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`button`,{type:`button`,onClick:()=>t(!0),className:`mb-2 flex w-full items-center gap-2 rounded-lg border border-line px-3 py-2 text-sm text-gray-700 hover:bg-gray-100`,children:[(0,V.jsx)(hs,{size:16,strokeWidth:2,"aria-hidden":`true`}),`ซอฟต์แวร์และสัญญาอนุญาต`]}),(0,V.jsx)(Vl,{open:e,onClose:()=>t(!1)})]})}var Ul=`/assets/logo-psq-CdisjvEH.png`,Wl=(0,p.createContext)({collapsed:!1,openSection:null,setOpenSection:()=>{}}),X=`pqs-kpi-sidebar-collapsed`;function Gl(){try{return localStorage.getItem(X)===`1`}catch{return!1}}function Kl(e){try{localStorage.setItem(X,e?`1`:`0`)}catch{}}var ql=[`ADMIN`,`POWER_ADMIN`],Jl=[{key:`admin_users`,tKey:`admin_users`,Icon:uc},{key:`admin_targets`,tKey:`admin_targets`,Icon:ic},{key:`admin_kpi_targets`,tKey:`admin_kpi_targets`,Icon:Bo},{key:`admin_reference`,tKey:`admin_reference`,Icon:Ks},{key:`admin_notify`,tKey:`admin_notify`,Icon:Vo},{key:`admin_imports`,tKey:`admin_imports`,Icon:Vs},{key:`admin_log`,tKey:`admin_log`,Icon:Ws},{key:`admin_api_usage`,tKey:`admin_api_usage`,Icon:Es},{key:`admin_sync_status`,tKey:`admin_sync_status`,Icon:Ro}],Yl=[{id:`cassava`,label:{th:`มัน`,en:`Cassava`},Icon:sc,color:`#16a34a`,tabIds:[`cassava_overview`,`top_cassava`,`sourcetype`,`yield`,`deduction`,`entry_cassava`]},{id:`biomass`,label:{th:`แกลบ`,en:`Biomass`},Icon:gs,color:`#ea580c`,tabIds:[`biomass_overview`,`top_biomass`,`energy_biomass`,`entry_biomass`]},{id:`analysis`,label:{th:`วิเคราะห์ / เปรียบเทียบ`,en:`Analysis / Compare`},Icon:Xo,color:`#ca8a04`,tabIds:[`kpi_monthly`,`byplant`,`mom`,`yearcompare`,`pivot`,`heatmap`,`customertype`,`hourly`]},{id:`quality`,label:{th:`คุณภาพข้อมูล`,en:`Data Quality`},Icon:_s,color:`#db2777`,tabIds:[`dataquality`,`diagnose`]}],Xl={ready:0,testing:1,development:2},Zl=[{id:`hub`,label:{th:`Hub หลัก`,en:`Main Hubs`},Icon:ws,color:`#0891b2`,status:`development`,keys:[`snapshot`,`andon`,`kpi_exec`]},{id:`kpi_all`,label:{th:`KPI ทุกแบบ`,en:`All KPIs`},Icon:Bo,color:`#9333ea`,status:`development`,keys:[`kpi_matrix`,`kpi_deepdive`,`kpi_forecast`,`kpi_bonus`]},{id:`reports`,label:{th:`รายงาน`,en:`Reports`},Icon:zs,color:`#e11d48`,keys:[`monthly_report`,`weigh_turnaround`]},{id:`mini_kpi`,label:{th:`ข้อมูล Mini KPI`,en:`Mini KPI Data`},Icon:Ss,color:`#c026d3`,keys:[`production_daily`,`cassava_weighing`,`sales`,`people`,`near_miss`,`esg`,`power_generation_daily`,`inventory`,`energy_daily`]},{id:`analytics`,label:{th:`Analytics`,en:`Analytics`},Icon:Yo,color:`#65a30d`,status:`development`,keys:[`advanced`,`flow_maps`,`plant_compare`]},{id:`suppliers`,label:{th:`หัวมัน + Biomass`,en:`Cassava + Biomass`},Icon:cc,color:`#0d9488`,special:!0},{id:`production`,label:{th:`การผลิต`,en:`Production`},Icon:Ho,color:`#ea580c`,status:`development`,keys:[`production_dashboard`,`predictive_yield`,`production_daily`,`hourly_production`,`flour_loss`,`production_order`,`machine_state`]},{id:`qaqc`,label:{th:`QA & QC`,en:`QA & QC`},Icon:_s,color:`#db2777`,status:`testing`,keys:[`qa_dashboard`,`qa_flour_report`,`qa_starch_milk`,`qa_ncr`,`qa_viscosity`,`qa_micro`,`qa_ash`]},{id:`energy`,label:{th:`พลังงาน + Boiler + Water`,en:`Energy + Boiler + Water`},Icon:gc,color:`#d97706`,status:`development`,keys:[`power_generation_daily`,`energy_daily`,`boiler_energy`,`water_treatment`,`fuel_monthly`,`fuel_daily`]},{id:`imports`,label:{th:`นำเข้าข้อมูล (Import)`,en:`Data Import`},Icon:lc,color:`#7c3aed`,keys:[]},{id:`finance`,label:{th:`การเงิน + ต้นทุน`,en:`Finance + Cost`},Icon:dc,color:`#059669`,status:`development`,keys:[`financial_dashboard`,`cost_dashboard`,`financial`,`cost`]},{id:`esg`,label:{th:`ESG + Sustainability`,en:`ESG + Sustainability`},Icon:Qs,color:`#16a34a`,status:`development`,keys:[`esg_dashboard`,`esg`]},{id:`people`,label:{th:`บุคคล + Safety + IT`,en:`People + Safety + IT`},Icon:uc,color:`#c026d3`,status:`development`,keys:[`people_dashboard`,`operations_dashboard`,`people`,`it_helpdesk`]},{id:`sales`,label:{th:`ยอดขาย + Stock`,en:`Sales + Stock`},Icon:Xs,color:`#0891b2`,status:`development`,keys:[`sales_dashboard`,`inventory_dashboard`,`sales`,`inventory`,`product_mix`,`forecasts`]},{id:`governance`,label:{th:`Governance + Strategic`,en:`Governance + Strategic`},Icon:ss,color:`#9333ea`,status:`development`,keys:[`governance`,`strategic`,`competitors`]},{id:`quality_risk`,label:{th:`คุณภาพ + ความเสี่ยง`,en:`Quality + Risk`},Icon:B,color:`#e11d48`,status:`development`,keys:[`audit_coverage`,`near_miss`,`audit`,`actions`,`risks`,`capa`]},{id:`export`,label:{th:`ข้อมูล + Export`,en:`Data + Export`},Icon:vs,color:`#65a30d`,status:`development`,keys:[`attachments`]}],Ql=`#d97706`,$l=[{key:`dashboard`,tKey:`dashboard`,Icon:Ds},{key:`reports`,tKey:`reports`,Icon:Yo},{key:`ticket_search`,tKey:`ticket_search`,Icon:Gs}];function eu({Icon:e,label:t,active:n,onClick:r,color:i,pinKey:a,pinned:o,onTogglePin:s,status:c}){let{collapsed:l}=(0,p.useContext)(Wl);return l?(0,V.jsx)(tu,{label:t,children:(0,V.jsx)(`button`,{type:`button`,onClick:r,"aria-label":t,className:`flex w-full items-center justify-center rounded-lg py-2 transition-colors ${n?`bg-brand-light text-brand`:`text-gray-600 hover:bg-gray-100`}`,children:(0,V.jsx)(e,{size:18,strokeWidth:2,"aria-hidden":`true`,style:i?{color:i}:void 0})})}):(0,V.jsxs)(`div`,{className:`group relative`,children:[(0,V.jsxs)(`button`,{type:`button`,onClick:r,className:`flex w-full items-center gap-2.5 rounded-lg py-2 pl-3 text-left text-sm transition-colors ${a?`pr-7`:`pr-3`} ${n?`bg-brand-light font-semibold text-brand`:`text-gray-700 hover:bg-gray-100`}`,children:[(0,V.jsx)(e,{size:16,strokeWidth:2,"aria-hidden":`true`,style:i?{color:i}:void 0}),(0,V.jsx)(`span`,{className:`truncate`,title:t,children:t}),c&&(0,V.jsx)(`span`,{className:`ml-auto shrink-0 rounded-full px-1.5 py-0.5 text-[9px] font-semibold leading-none ${c===`testing`?`bg-sky-50 text-sky-700`:`bg-amber-50 text-amber-700`}`,children:c===`testing`?`กำลังทดสอบ`:`กำลังพัฒนา`})]}),a&&(0,V.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s(a)},className:`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 transition-opacity ${o?`text-amber-500 opacity-100`:`opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 ${n?`text-brand/60 hover:text-brand`:`text-gray-400 hover:text-gray-700`}`}`,"aria-label":o?`Unpin`:`Pin to top`,title:o?`Unpin`:`Pin to top`,children:(0,V.jsx)(Rs,{size:12,strokeWidth:2,fill:o?`currentColor`:`none`,"aria-hidden":`true`})})]})}function tu({label:e,children:t,panel:n}){let[r,i]=(0,p.useState)(null),a=(0,p.useRef)(null),o=(0,p.useRef)(null),s=()=>{clearTimeout(o.current),i(a.current?.getBoundingClientRect()||null)},c=()=>{clearTimeout(o.current),o.current=setTimeout(()=>i(null),120)};(0,p.useEffect)(()=>()=>clearTimeout(o.current),[]),(0,p.useEffect)(()=>{if(!r)return;let e=e=>{e.key===`Escape`&&i(null)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r]);let l=r?Math.max(8,Math.min(r.top,window.innerHeight-(n?360:44))):0;return(0,V.jsxs)(`div`,{ref:a,onMouseEnter:s,onMouseLeave:c,onFocus:s,onBlur:c,onClick:e=>{e.target.closest(`[data-flyout-panel]`)||(r?i(null):s())},children:[t,r&&(0,V.jsx)(`div`,{"data-flyout-panel":!0,onMouseEnter:s,onMouseLeave:c,style:{position:`fixed`,left:r.right+8,top:l,zIndex:60},children:n?(0,V.jsxs)(`div`,{className:`w-72 rounded-xl border border-line bg-white p-2 shadow-xl`,role:`group`,"aria-label":e,children:[(0,V.jsx)(`div`,{className:`px-2 pb-1.5 pt-1 text-xs font-semibold text-gray-500`,children:e}),(0,V.jsx)(Wl.Provider,{value:{collapsed:!1,openSection:null,setOpenSection:()=>{}},children:(0,V.jsx)(`div`,{className:`max-h-[320px] space-y-0.5 overflow-y-auto`,onClick:e=>{e.target.closest(`[aria-expanded]`)||i(null)},children:n})})]}):(0,V.jsx)(`div`,{className:`whitespace-nowrap rounded-lg bg-gray-900 px-2.5 py-1.5 text-xs font-medium text-white shadow-lg`,children:e})})]})}function nu({title:e,Icon:t,items:n,view:r,onPick:i,pinned:a,onTogglePin:o,status:s}){let{collapsed:c,openSection:l,setOpenSection:u}=(0,p.useContext)(Wl),d=n.some(e=>e.key===r||r.startsWith(`${e.key}:`)),f=l===e,m=(0,p.useRef)(null),h=(0,p.useRef)(!1);(0,p.useEffect)(()=>{h.current&&(h.current=!1,m.current?.scrollIntoView({behavior:`smooth`,block:`nearest`}))},[f]);let g=n.map((e,t)=>(0,V.jsx)(ru,{item:e,view:r,onPick:i,pinned:a,onTogglePin:o},`${e.key}-${t}`));if(n.length===1&&!n[0].subTabs?.length){let e=n[0];return(0,V.jsx)(eu,{Icon:e.Icon||t,label:e.label,active:r===e.key,onClick:()=>i(e.key),color:e.color,status:e.status,pinKey:e.key,pinned:a?.includes(e.key),onTogglePin:o})}return c?(0,V.jsx)(tu,{label:s===`testing`?`${e} · กำลังทดสอบ`:e,panel:g,children:(0,V.jsx)(`button`,{type:`button`,"aria-label":e,"aria-haspopup":`menu`,className:`flex w-full items-center justify-center rounded-lg py-2 transition-colors ${d?`bg-brand-light text-brand`:`text-gray-600 hover:bg-gray-100`}`,children:(0,V.jsx)(t,{size:18,strokeWidth:2,"aria-hidden":`true`})})}):(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{ref:m,type:`button`,"aria-expanded":f,onClick:()=>{h.current=!0,u(t=>t===e?null:e)},className:`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm font-medium transition-colors hover:bg-gray-100 ${d&&!f?`text-brand`:`text-gray-800`}`,children:[(0,V.jsx)(t,{size:16,strokeWidth:2,"aria-hidden":`true`}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e}),s&&(0,V.jsx)(`span`,{className:`shrink-0 rounded-full px-1.5 py-0.5 text-[9px] font-semibold leading-none ${s===`testing`?`bg-sky-50 text-sky-700`:`bg-amber-50 text-amber-700`}`,children:s===`testing`?`กำลังทดสอบ`:`กำลังพัฒนา`}),(0,V.jsx)(Qo,{size:14,strokeWidth:2,className:`shrink-0 text-gray-400 transition-transform ${f?`rotate-180`:``}`,"aria-hidden":`true`})]}),f&&(0,V.jsx)(`div`,{className:`ml-2 mt-1 space-y-0.5 border-l border-line pl-3`,children:g})]})}function ru({item:e,view:t,onPick:n,pinned:r,onTogglePin:i}){let{key:a,label:o,Icon:s,subTabs:c,color:l,status:u}=e,d=c?.length?c.some(e=>t===`${a}:${e.id}`):t===a,[f,m]=(0,p.useState)(d),h=(0,p.useRef)(null),g=(0,p.useRef)(!1);return(0,p.useEffect)(()=>{g.current&&(g.current=!1,h.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},[f]),c?.length?(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`button`,{ref:h,type:`button`,"aria-expanded":f,onClick:()=>{g.current=!0,m(e=>!e)},className:`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm transition-colors ${d?`font-medium text-gray-900`:`text-gray-700 hover:bg-gray-100`}`,style:d&&l?{borderLeft:`2px solid ${l}`,paddingLeft:`10px`}:void 0,children:[(0,V.jsx)(s,{size:16,strokeWidth:2,"aria-hidden":`true`,style:l?{color:l}:void 0}),(0,V.jsx)(`span`,{className:`flex-1 truncate`,children:o}),(0,V.jsx)(Qo,{size:13,strokeWidth:2,className:`shrink-0 transition-transform ${f?`rotate-180`:``}`,"aria-hidden":`true`})]}),f&&(0,V.jsx)(`div`,{className:`ml-2 mt-1 space-y-0.5 border-l-2 pl-3`,style:{borderColor:l?`${l}55`:`var(--color-line)`},children:c.map(e=>{let o=`${a}:${e.id}`;return(0,V.jsx)(eu,{Icon:e.Icon||s,label:e.label,active:t===o,onClick:()=>n(o),color:l,status:u,pinKey:o,pinned:r?.includes(o),onTogglePin:i},e.id)})})]}):(0,V.jsx)(eu,{Icon:s,label:o,active:t===a,onClick:()=>n(a),color:l,status:u,pinKey:a,pinned:r?.includes(a),onTogglePin:i})}function iu(){let{t:e}=Tc(),[t,n]=(0,p.useState)(vl());return(0,V.jsxs)(`button`,{type:`button`,onClick:()=>{Sl(!t),n(!t)},className:`mb-2 flex w-full items-center gap-2 rounded-lg border border-line px-3 py-2 text-sm text-gray-700 hover:bg-gray-100`,children:[t?(0,V.jsx)(tc,{size:16,strokeWidth:2,"aria-hidden":`true`}):(0,V.jsx)(Ms,{size:16,strokeWidth:2,"aria-hidden":`true`}),e(t?`dark_mode_off`:`dark_mode_on`)]})}function au({role:e,onLogout:t}){let{t:n}=Tc(),{collapsed:r}=(0,p.useContext)(Wl),[i,a]=(0,p.useState)(!1),o=(0,p.useRef)(null);return(0,p.useEffect)(()=>{function e(e){e.target.closest?.(`[data-menu-portal]`)||o.current&&!o.current.contains(e.target)&&a(!1)}let t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[]),(0,V.jsxs)(`div`,{ref:o,className:`relative border-t border-line ${r?`px-2 py-3`:`p-3`}`,children:[(0,V.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-expanded":i,"aria-haspopup":`true`,title:r?e.display_name||e.email:void 0,className:`flex w-full items-center gap-2 rounded-lg px-1.5 py-1.5 text-left text-sm leading-tight text-gray-800 transition-colors hover:bg-gray-100 ${r?`justify-center`:``}`,children:[e.avatar_url?(0,V.jsx)(`img`,{src:e.avatar_url,alt:``,className:`h-8 w-8 shrink-0 rounded-full object-cover`,referrerPolicy:`no-referrer`}):(0,V.jsx)(`span`,{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-brand-light text-xs font-semibold text-brand`,"aria-hidden":`true`,children:(e.display_name||e.email||`?`).trim().charAt(0).toUpperCase()}),!r&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`div`,{className:`truncate font-medium`,children:e.display_name||e.email}),(0,V.jsxs)(`div`,{className:`text-xs text-muted`,children:[e.role,e.plant?` · `+e.plant:``]})]}),(0,V.jsx)(Ks,{size:15,className:`shrink-0 text-gray-400 transition-transform ${i?`rotate-90`:``}`,"aria-hidden":`true`})]})]}),i&&(0,V.jsxs)(`div`,{className:`rounded-xl border border-line bg-white p-2 shadow-xl ${r?`w-60`:`absolute inset-x-3 bottom-full mb-2`}`,style:r&&o.current?(()=>{let e=o.current.getBoundingClientRect();return{position:`fixed`,left:e.right+8,bottom:window.innerHeight-e.bottom+8,zIndex:60}})():void 0,children:[(0,V.jsx)(iu,{}),(0,V.jsx)(J,{}),(0,V.jsx)(Hl,{}),(0,V.jsx)(`div`,{className:`my-1 border-t border-line`}),(0,V.jsxs)(`button`,{type:`button`,onClick:t,className:`flex w-full items-center gap-2 rounded-lg border border-line px-3 py-2 text-sm text-gray-700 hover:bg-gray-100`,children:[(0,V.jsx)(ks,{size:16,strokeWidth:2,"aria-hidden":`true`}),n(`logout`)]})]})]})}function ou(e,t){return typeof e==`object`&&e?e[t]??e.th??e.en:e}function su(e,t,n){let r=$l.find(t=>t.key===e);if(r)return{label:t(r.tKey),Icon:r.Icon};if(e===`import_weighing`)return{label:t(`import_weighing`),Icon:lc};if(e===`production_energy`)return{label:n===`th`?`ผลผลิต + ไฟฟ้า`:`Production + Energy`,Icon:fs};if(Pc[e])return{label:ou(Pc[e].label,n),Icon:Pc[e].icon};let i=Jl.find(t=>t.key===e);if(i)return{label:t(i.tKey),Icon:i.Icon};let[a,o]=e.split(`:`),s=W[a];if(s){let e=o&&s.subTabs?.find(e=>e.id===o);return{label:ou(e?e.label:s.label,n),Icon:e&&e.Icon||s.icon}}return null}function cu({recent:e,view:t,onPick:n}){let{t:r,lang:i}=Tc(),a=e.map(e=>({key:e,meta:su(e,r,i)})).filter(e=>e.meta);return a.length?(0,V.jsxs)(`div`,{className:`mb-2 border-b border-line pb-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-1.5 px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400`,children:[(0,V.jsx)(is,{size:11,"aria-hidden":`true`}),` `,i===`th`?`ล่าสุด`:`Recent`]}),a.map(({key:e,meta:r})=>(0,V.jsx)(eu,{Icon:r.Icon,label:r.label,active:t===e,onClick:()=>n(e)},e))]}):null}function lu({pinned:e,view:t,onPick:n,onTogglePin:r}){let{t:i,lang:a}=Tc(),o=e.map(e=>({key:e,meta:su(e,i,a)})).filter(e=>e.meta);return o.length?(0,V.jsxs)(`div`,{className:`mb-2 border-b border-line pb-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-1.5 px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400`,children:[(0,V.jsx)(Rs,{size:11,"aria-hidden":`true`}),` `,a===`th`?`ปักหมุด`:`Pinned`]}),o.map(({key:e,meta:i})=>(0,V.jsx)(eu,{Icon:i.Icon,label:i.label,active:t===e,onClick:()=>n(e),pinKey:e,pinned:!0,onTogglePin:r},e))]}):null}function uu({onOpenPalette:e}){let{lang:t}=Tc(),{collapsed:n}=(0,p.useContext)(Wl);return n?(0,V.jsx)(`button`,{type:`button`,onClick:e,title:t===`th`?`ค้นหา (Ctrl+K)`:`Search (Ctrl+K)`,className:`mx-2 mb-2 flex items-center justify-center rounded-lg border border-line bg-surface py-2 text-gray-500 hover:bg-gray-100`,children:(0,V.jsx)(Gs,{size:16,strokeWidth:2,"aria-hidden":`true`})}):(0,V.jsxs)(`button`,{type:`button`,onClick:e,className:`mx-2 mb-2 flex items-center gap-2 rounded-lg border border-line bg-surface px-3 py-2 text-left text-sm text-gray-500 hover:bg-gray-100`,children:[(0,V.jsx)(Gs,{size:15,strokeWidth:2,"aria-hidden":`true`}),(0,V.jsx)(`span`,{className:`flex-1`,children:t===`th`?`ค้นหา...`:`Search...`}),(0,V.jsx)(`span`,{className:`rounded border border-line bg-white px-1.5 py-0.5 text-[10px] text-gray-400`,children:`Ctrl+K`})]})}function du({role:e,view:t,setView:n,onLogout:r,onNavigate:i,onOpenPalette:a,onToggleCollapse:o}){let{t:s,lang:c}=Tc(),{collapsed:l}=(0,p.useContext)(Wl),u=ql.includes(e.role),[d,f]=(0,p.useState)(Al);function m(e){f(jl(e))}function h(t){if(Il(t,e))return null;if(W[t]){let e=W[t];return{key:t,label:ou(e.label,c),Icon:e.icon,subTabs:e.subTabs?.map(e=>({...e,label:ou(e.label,c)}))}}return Pc[t]&&Bc(e,t)?{key:t,label:ou(Pc[t].label,c),Icon:Pc[t].icon}:null}let g=[{key:`suppliers`,label:ou(W.suppliers.label,c),Icon:W.suppliers.icon},...Yl.map(e=>({key:`suppliers`,label:ou(e.label,c),Icon:e.Icon,color:e.color,subTabs:Hc.filter(t=>e.tabIds.includes(t.id)).map(e=>({...e,label:ou(e.label,c)}))})),{key:`suppliers:targets`,label:ou({th:`เป้าหมาย`,en:`Targets`},c),Icon:ic,color:`#dc2626`}];function _(e){n(e),i?.()}let v=[...Zl].sort((e,t)=>Xl[e.status||`ready`]-Xl[t.status||`ready`]).map(t=>{let n=t.special?Il(`suppliers`,e)?[]:g:t.keys.map(h).filter(Boolean);t.id===`production`&&H(e,`operations`)&&n.unshift({key:`production_energy`,label:c===`th`?`ผลผลิต + ไฟฟ้า`:`Production + Energy`,Icon:fs}),t.id===`qaqc`&&(H(e,`qaqc`)&&n.push({key:`cut_yield_entry`,label:c===`th`?e.role===`QA_QC`?`ตัดยิว`:`ตัดยิว (กรอก)`:`Cut Yield`,Icon:Xo,wip:!0}),H(e,`qaqc`)&&n.push({key:`qa_daily_report_entry`,label:c===`th`?e.role===`QA_QC`?`รายงานคุณภาพประจำวัน`:`รายงานคุณภาพประจำวัน (กรอก)`:`Daily Quality Report`,Icon:_s,wip:!0}),n.push({key:`qa_export`,label:c===`th`?`Export ใบรายงาน`:`Export Reports`,Icon:ms}),H(e,`qaqc`)&&n.push({key:`qa_import`,label:c===`th`?`นำเข้าใบ QA (Excel)`:`Import QA Forms`,Icon:lc})),t.id===`imports`&&H(e,`operations`)&&(n.push({key:`suppliers:import`,label:ou({th:`Import ใบชั่ง`,en:`Import Weighing`},c),Icon:lc}),n.push({key:`import_power_generation`,label:c===`th`?`Import ผลิตไฟฟ้า (PBE)`:`Import Power Generation (PBE)`,Icon:ms}),n.push({key:`import_pbe_extras`,label:c===`th`?`Import กากสด/Boiler (PBE)`:`Import Pulp/Boiler (PBE)`,Icon:ms}));let r=t.status===`development`;return{cat:t,items:n.map(e=>({...e,color:e.color||t.color,status:r?void 0:e.status||(e.wip?`development`:void 0)}))}}).filter(e=>e.items.length).map((e,t,n)=>({...e,devHeading:e.cat.status===`development`&&n[t-1]?.cat.status!==`development`})),y=u?Jl.map(e=>({key:e.key,label:s(e.tKey),Icon:e.Icon})):[],b=e=>{let t=v.find(t=>t.items.some(t=>t.key===e))||v.find(t=>t.items.some(t=>e.startsWith(`${t.key}:`)));return t?ou(t.cat.label,c):y.some(t=>t.key===e)?s(`admin`):null},[x,ee]=(0,p.useState)(()=>b(t)),S=b(t);return(0,p.useEffect)(()=>{S&&ee(S)},[S]),(0,V.jsx)(Wl.Provider,{value:{collapsed:l,openSection:x,setOpenSection:ee},children:(0,V.jsxs)(`div`,{className:`flex h-full flex-col`,children:[l?(0,V.jsx)(`div`,{className:`flex justify-center px-2 py-4`,children:(0,V.jsx)(tu,{label:c===`th`?`ขยายเมนู (Ctrl+B)`:`Expand menu (Ctrl+B)`,children:(0,V.jsxs)(`button`,{type:`button`,onClick:o,"aria-label":c===`th`?`ขยายเมนู`:`Expand menu`,className:`group relative flex h-11 w-11 items-center justify-center rounded-xl hover:bg-gray-100`,children:[(0,V.jsx)(`img`,{src:Ul,alt:``,className:`h-10 w-10 rounded-full bg-white transition-opacity group-hover:opacity-0`}),(0,V.jsx)(Ps,{size:18,className:`absolute text-gray-600 opacity-0 transition-opacity group-hover:opacity-100`,"aria-hidden":`true`})]})})}):(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-4 py-5 text-2xl font-bold text-brand`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,V.jsx)(`div`,{className:`relative shrink-0`,children:(0,V.jsx)(`img`,{src:Ul,alt:`PSQ`,className:`relative h-12 w-12 rounded-full bg-white`})}),(0,V.jsx)(`span`,{className:`text-brand`,children:`PQS KPI`})]}),o&&(0,V.jsx)(`button`,{type:`button`,onClick:o,title:c===`th`?`ย่อเมนูเหลือแค่ไอคอน (Ctrl+B)`:`Collapse menu (Ctrl+B)`,"aria-label":c===`th`?`ย่อเมนู`:`Collapse menu`,className:`rounded-lg p-1.5 text-gray-500 hover:bg-gray-100`,children:(0,V.jsx)(Ns,{size:18,"aria-hidden":`true`})})]}),(0,V.jsx)(uu,{onOpenPalette:a}),(0,V.jsxs)(`nav`,{className:`sidebar-scroll flex-1 space-y-1.5 overflow-y-auto pb-3 px-2`,children:[!l&&(0,V.jsx)(lu,{pinned:d.filter(t=>!Il(t,e)),view:t,onPick:_,onTogglePin:m}),!l&&(0,V.jsx)(cu,{recent:Dl().filter(n=>n!==t&&!Il(n,e)).slice(0,3),view:t,onPick:_}),$l.filter(({key:t})=>!Il(t,e)).map(({key:e,tKey:n,Icon:r})=>(0,V.jsx)(eu,{Icon:r,label:s(n),active:t===e,onClick:()=>_(e),color:Ql},e)),(0,V.jsx)(`div`,{className:`my-2 border-t border-line`}),v.map(({cat:e,items:n,devHeading:r})=>(0,V.jsxs)(p.Fragment,{children:[r&&(l?(0,V.jsx)(`div`,{className:`mx-2 my-2 border-t border-dashed border-line`,title:`กำลังพัฒนา`}):(0,V.jsx)(`div`,{className:`mt-3 border-t border-line px-3 pb-1 pt-3 text-[11px] font-semibold tracking-wide text-gray-400`,children:c===`th`?`กำลังพัฒนา · ข้อมูลอาจยังไม่ครบ`:`In development`})),(0,V.jsx)(nu,{title:ou(e.label,c),Icon:e.Icon,items:n,view:t,onPick:_,pinned:d,onTogglePin:m,status:e.status===`testing`?`testing`:void 0})]},e.id)),u&&(0,V.jsx)(nu,{title:s(`admin`),Icon:Ys,items:y,view:t,onPick:_,pinned:d,onTogglePin:m})]}),(0,V.jsx)(au,{role:e,onLogout:r})]})})}function fu({role:e,onLogout:t,onClose:n}){let{t:r}=Tc();return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[n]),(0,V.jsxs)(`div`,{className:`fixed inset-0 z-40 md:hidden`,role:`dialog`,"aria-modal":`true`,"aria-label":r(`logout`),children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`ปิด`,className:`absolute inset-0 bg-black/30`,onClick:n}),(0,V.jsxs)(`div`,{className:`absolute inset-x-0 bottom-0 rounded-t-2xl border-t border-line bg-white p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] shadow-2xl`,children:[(0,V.jsxs)(`div`,{className:`mb-3 flex items-center gap-3`,children:[(0,V.jsx)(`span`,{className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-brand-light text-sm font-semibold text-brand`,"aria-hidden":`true`,children:(e?.display_name||e?.email||`?`).trim().charAt(0).toUpperCase()}),(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`div`,{className:`truncate text-sm font-medium text-gray-800`,children:e?.display_name||e?.email}),(0,V.jsxs)(`div`,{className:`text-xs text-muted`,children:[e?.role,e?.plant?` · `+e.plant:``]})]})]}),(0,V.jsx)(iu,{}),(0,V.jsx)(J,{}),(0,V.jsx)(Hl,{}),(0,V.jsx)(`div`,{className:`my-2 border-t border-line`}),(0,V.jsxs)(`button`,{type:`button`,onClick:()=>{n(),t()},className:`flex w-full items-center gap-2 rounded-lg border border-line px-3 py-2.5 text-sm text-gray-700 hover:bg-gray-100`,children:[(0,V.jsx)(ks,{size:16,strokeWidth:2,"aria-hidden":`true`}),` `,r(`logout`)]})]})]})}function pu({view:e,setView:t,onOpenPalette:n,onOpenAccount:r,role:i}){let{t:a,lang:o}=Tc();return(0,V.jsx)(`nav`,{className:`fixed inset-x-0 bottom-0 z-30 flex items-stretch border-t border-line bg-white pb-[env(safe-area-inset-bottom)] shadow-[0_-4px_16px_rgba(16,24,40,0.06)] md:hidden`,children:[...$l.filter(({key:e})=>!Il(e,i)).map(({key:e,tKey:n,Icon:r})=>({key:e,label:a(n),Icon:r,onClick:()=>t(e)})),{key:`__menu`,label:o===`th`?`เมนู`:`Menu`,Icon:As,onClick:n},{key:`__account`,label:o===`th`?`บัญชี`:`Account`,Icon:Ks,onClick:r}].map(({key:t,label:n,Icon:r,onClick:i})=>{let a=t.startsWith(`__`)?!1:e===t||e.startsWith(`${t}:`);return(0,V.jsxs)(`button`,{type:`button`,onClick:i,className:`flex flex-1 flex-col items-center gap-0.5 py-2 text-[11px] transition-colors ${a?`font-semibold text-brand`:`text-gray-500`}`,"aria-current":a?`page`:void 0,children:[(0,V.jsx)(r,{size:20,strokeWidth:2,"aria-hidden":`true`}),(0,V.jsx)(`span`,{className:`truncate`,children:n})]},t)})})}function mu({role:e,view:t,setView:n,onLogout:r,onOpenPalette:i}){let[a,o]=(0,p.useState)(Gl),[s,c]=(0,p.useState)(!1),l=(0,p.useCallback)(()=>c(!1),[]);function u(e){n(e)}function d(){o(e=>(Kl(!e),!e))}return(0,p.useEffect)(()=>{let e=e=>{!(e.ctrlKey||e.metaKey)||e.key.toLowerCase()!==`b`||e.target.closest?.(`input, textarea, select, [contenteditable="true"]`)||(e.preventDefault(),d())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[]),(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`aside`,{className:`sticky top-0 z-40 hidden h-screen shrink-0 overflow-hidden border-r border-line bg-white transition-[width] duration-200 md:block ${a?`w-[68px]`:`w-64`}`,children:(0,V.jsx)(Wl.Provider,{value:{collapsed:a,openSection:null,setOpenSection:()=>{}},children:(0,V.jsx)(du,{role:e,view:t,setView:n,onLogout:r,onOpenPalette:i,onToggleCollapse:d})})}),(0,V.jsx)(pu,{role:e,view:t,setView:u,onOpenPalette:i,onOpenAccount:()=>c(!0)}),s&&(0,V.jsx)(fu,{role:e,onLogout:r,onClose:l})]})}function hu(e,t){return typeof e==`object`&&e?e[t]??e.th??e.en:e}function gu({role:e,setView:t,open:n,setOpen:r}){let{t:i,lang:a}=Tc(),[o,s]=(0,p.useState)(``),[c,l]=(0,p.useState)(0),u=(0,p.useRef)(null);(0,p.useEffect)(()=>{function e(e){(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`?(e.preventDefault(),r(e=>!e)):e.key===`Escape`&&r(!1)}return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]),(0,p.useEffect)(()=>{n&&(s(``),l(0),setTimeout(()=>u.current?.focus(),0))},[n]);let d=(0,p.useMemo)(()=>{if(!e)return[];let t=Lc.includes(e.role),n=ql.includes(e.role),r=[];if($l.forEach(({key:e,tKey:t,Icon:n})=>r.push({key:e,label:i(t),Icon:n})),H(e,`operations`)&&r.push({key:`import_weighing`,label:i(`import_weighing`)}),t){let t=[`production_daily`,`production_daily_log`,`energy_daily`,`energy_daily_log`];H(e,`operations`)&&r.push({key:`production_energy`,label:a===`th`?`ผลผลิต + ไฟฟ้า`:`Production + Energy`,Icon:fs}),Object.keys(Pc).forEach(n=>{t.includes(n)||!Bc(e,n)||r.push({key:n,label:hu(Pc[n].label,a),Icon:Pc[n].icon})})}return Object.keys(W).forEach(e=>{let t=W[e];r.push({key:e,label:hu(t.label,a),Icon:t.icon}),(t.subTabs||[]).forEach(n=>{r.push({key:`${e}:${n.id}`,label:`${hu(t.label,a)} · ${hu(n.label,a)}`,Icon:n.Icon||t.icon})})}),n&&Jl.forEach(e=>r.push({key:e.key,label:i(e.tKey),Icon:e.Icon})),r.filter(t=>!Il(t.key,e))},[e,a,i]),f=(0,p.useMemo)(()=>{let e=o.trim().toLowerCase();return e?d.filter(t=>t.label.toLowerCase().includes(e)).slice(0,50):d.slice(0,50)},[d,o]);function m(e){t(e.key),r(!1)}function h(e){e.key===`ArrowDown`?(e.preventDefault(),l(e=>Math.min(e+1,f.length-1))):e.key===`ArrowUp`?(e.preventDefault(),l(e=>Math.max(e-1,0))):e.key===`Enter`&&(e.preventDefault(),f[c]&&m(f[c]))}return n?(0,V.jsx)(`div`,{className:`fixed inset-0 z-[60] flex items-start justify-center bg-black/40 px-4 pt-24`,onClick:()=>r(!1),children:(0,V.jsxs)(`div`,{className:`w-full max-w-lg overflow-hidden rounded-2xl bg-white shadow-2xl`,onClick:e=>e.stopPropagation(),children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-gray-100 px-4 py-3`,children:[(0,V.jsx)(Gs,{size:16,className:`text-gray-500`,"aria-hidden":`true`}),(0,V.jsx)(`input`,{ref:u,value:o,onChange:e=>{s(e.target.value),l(0)},onKeyDown:h,placeholder:a===`th`?`ค้นหาเมนู/ฟอร์ม/แดชบอร์ด...`:`Search menus, forms, dashboards...`,className:`flex-1 text-sm outline-none`}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>r(!1),className:`rounded-lg p-1 text-gray-500 hover:bg-gray-100`,"aria-label":i(`close`),children:(0,V.jsx)(hc,{size:16,"aria-hidden":`true`})})]}),(0,V.jsx)(`div`,{className:`max-h-80 overflow-y-auto p-1.5`,children:f.length===0?(0,V.jsx)(`p`,{className:`py-8 text-center text-sm text-gray-500`,children:a===`th`?`ไม่พบผลลัพธ์`:`No results`}):f.map((e,t)=>(0,V.jsxs)(`button`,{type:`button`,onClick:()=>m(e),onMouseEnter:()=>l(t),className:`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm ${t===c?`bg-brand-light text-brand`:`text-gray-700 hover:bg-gray-50`}`,children:[e.Icon&&(0,V.jsx)(e.Icon,{size:15,"aria-hidden":`true`}),(0,V.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),t===c&&(0,V.jsx)(cs,{size:13,className:`shrink-0 opacity-60`,"aria-hidden":`true`})]},e.key))})]})}):null}var _u=`pqs_seen_feature_intro`;function vu(){try{return localStorage.getItem(_u)===`1`}catch{return!0}}function yu({onOpenPalette:e}){let{lang:t,t:n}=Tc(),[r,i]=(0,p.useState)(vu);function a(){try{localStorage.setItem(_u,`1`)}catch{}i(!0)}return r?null:(0,V.jsx)(`div`,{className:`fixed bottom-36 right-4 z-40 w-full max-w-xs md:bottom-24`,children:(0,V.jsxs)(`div`,{className:`data-card p-4 shadow-xl`,children:[(0,V.jsxs)(`div`,{className:`mb-2 flex items-center justify-between`,children:[(0,V.jsxs)(`h4`,{className:`flex items-center gap-1.5 text-sm font-semibold text-brand`,children:[(0,V.jsx)(Zs,{size:15,"aria-hidden":`true`}),` `,t===`th`?`มีของใหม่`:`What's new`]}),(0,V.jsx)(`button`,{type:`button`,onClick:a,className:`rounded-lg p-1 text-gray-500 hover:bg-gray-100`,"aria-label":n(`close`),children:(0,V.jsx)(hc,{size:15,"aria-hidden":`true`})})]}),(0,V.jsxs)(`ul`,{className:`space-y-2 text-xs text-gray-600`,children:[(0,V.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,V.jsx)(Gs,{size:13,className:`mt-0.5 shrink-0 text-brand`,"aria-hidden":`true`}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>{e(),a()},className:`text-left hover:underline`,children:t===`th`?`กด Ctrl+K (หรือปุ่มค้นหาบน sidebar) เพื่อไปหน้าไหนก็ได้เร็วๆ`:`Press Ctrl+K (or the sidebar search button) to jump anywhere fast`})]}),(0,V.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,V.jsx)(Ks,{size:13,className:`mt-0.5 shrink-0 text-brand`,"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:t===`th`?`ปรับแต่งแดชบอร์ดได้ที่ปุ่มเฟือง (มุมขวาบนของหน้าแดชบอร์ด) — เลือกได้ถึงระดับการ์ด KPI แต่ละตัว`:`Customize the dashboard via the gear icon (top-right) — down to individual KPI cards`})]}),(0,V.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,V.jsx)(Ms,{size:13,className:`mt-0.5 shrink-0 text-brand`,"aria-hidden":`true`}),(0,V.jsx)(`span`,{children:t===`th`?`โหมดกลางคืนและวิธีใช้งาน อยู่ในเมนูโปรไฟล์ — คลิกชื่อ/รูปที่มุมล่าง sidebar`:`Dark mode and help are under the profile menu — click your name/photo at the bottom of the sidebar`})]})]})]})})}function bu(){let{t:e}=Tc();return(0,V.jsx)(`p`,{className:`py-16 text-center text-sm text-gray-500`,children:e(`loading`)})}function xu({label:e,value:t,unit:n,target:r,color:i}){return(0,V.jsxs)(`div`,{className:`data-card p-3`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-[13px] font-medium text-gray-700`,children:[(0,V.jsx)(`span`,{className:`h-2 w-2 shrink-0 rounded-full`,style:{background:i||`#94a3b8`},"aria-hidden":`true`}),(0,V.jsx)(`span`,{className:`min-w-0 leading-tight`,children:e})]}),(0,V.jsxs)(`div`,{className:`mt-2.5 rounded-lg bg-well px-3 py-2`,children:[t==null||t===``||t===`-`||t===`—`?(0,V.jsx)(`div`,{className:`py-1 text-sm text-muted`,children:`ยังไม่มีข้อมูล`}):(0,V.jsxs)(`div`,{className:`flex items-baseline gap-1`,children:[(0,V.jsx)(`span`,{className:`text-xl font-bold tabular-nums`,style:{color:i||void 0},children:t}),n&&(0,V.jsx)(`span`,{className:`text-[11px] text-muted`,children:n})]}),r?(0,V.jsxs)(`div`,{className:`text-[11px] text-muted`,children:[`เป้า `,r]}):null]})]})}var Su={PQS:`#1e3a8a`,PMS:`#0f766e`,PBE:`#c2410c`,PQS2012:`#7c3aed`,ALL:`#64748b`};function Cu(e){if(e==null||e===``)return`–`;let t=Number(e);if(!Number.isFinite(t))return e;let n=Math.abs(t),r=n===0?0:n<1?4:n<100?2:+(n<1e3);return t.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:r})}var wu=class extends p.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`[PageErrorBoundary]`,e,t?.componentStack)}componentDidUpdate(e){e.resetKey!==this.props.resetKey&&this.state.error&&this.setState({error:null})}render(){let{error:e}=this.state;return e?(0,V.jsxs)(`div`,{className:`mx-auto max-w-2xl rounded-xl border border-red-400/40 bg-red-500/5 p-5`,children:[(0,V.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 text-sm font-semibold text-red-500`,children:[(0,V.jsx)(B,{size:16,"aria-hidden":`true`}),` หน้านี้แสดงผลไม่สำเร็จ`]}),(0,V.jsx)(`p`,{className:`text-sm text-muted`,children:`หน้าอื่นยังใช้งานได้ตามปกติ — เลือกเมนูอื่นทางซ้ายได้เลย ถ้าอยากให้แก้ ส่งข้อความด้านล่างนี้ให้ผู้ดูแลระบบ`}),(0,V.jsx)(`pre`,{className:`mt-3 max-h-48 overflow-auto rounded-lg bg-black/40 p-3 text-[11px] whitespace-pre-wrap text-red-300`,children:String(e?.message||e)}),(0,V.jsxs)(`button`,{type:`button`,onClick:()=>this.setState({error:null}),className:`mt-3 flex items-center gap-1.5 rounded-lg border border-line px-3 py-1.5 text-sm`,children:[(0,V.jsx)(Hs,{size:14,"aria-hidden":`true`}),` ลองแสดงผลใหม่`]})]}):this.props.children}},Tu=(0,p.lazy)(()=>P(()=>import(`./Dashboard-BujJ3s7W.js`),__vite__mapDeps([50,1,2,6,11,51,13,14,20,22,18,39,52,3,4,8]))),Eu=(0,p.lazy)(()=>P(()=>import(`./Reports-DG7EoJZH.js`),__vite__mapDeps([53,1,2,6,54,49,51,55,13,14,15,20,22,17,30,18,52,8]))),Du=(0,p.lazy)(()=>P(()=>import(`./TicketSearch-CsBxvBUP.js`),__vite__mapDeps([56,1,2]))),Ou=(0,p.lazy)(()=>P(()=>import(`./DataEntry-BY9Jyb5N.js`),__vite__mapDeps([57,1,2,6,58,52]))),ku=(0,p.lazy)(()=>P(()=>import(`./QaGridEntry-BmvPpQ1W.js`),__vite__mapDeps([59,1,2,6,49,60,61,39,52,62,40]))),Au=(0,p.lazy)(()=>P(()=>import(`./QaExport-BtOvF2Uv.js`),__vite__mapDeps([63,1,2,55,6,61,39,52,62,40]))),ju=(0,p.lazy)(()=>P(()=>import(`./QaImport-BJK2Uc2U.js`),__vite__mapDeps([64,1,2,6,39,62,40]))),Mu=(0,p.lazy)(()=>P(()=>import(`./ProductionEnergyEntry-BZOQGFeq.js`),__vite__mapDeps([65,1,2,57,6,58,52,59,49,60,61,39,62,40]))),Nu=(0,p.lazy)(()=>P(()=>import(`./CutYieldHub-RKNfTNy2.js`),__vite__mapDeps([66,1,2,61]))),Pu=(0,p.lazy)(()=>P(()=>import(`./QaDailyReportHub-lmFiQnJN.js`),__vite__mapDeps([67,1,2,6,49]))),Fu=(0,p.lazy)(()=>P(()=>import(`./UserManagement--3YDrBcx.js`),__vite__mapDeps([68,1,2,6,58]))),Iu=(0,p.lazy)(()=>P(()=>import(`./WeighingTargets-IzkB-FK8.js`),__vite__mapDeps([69,1,2,54,6]))),Lu=(0,p.lazy)(()=>P(()=>import(`./KpiTargets-DPvhyaFX.js`),__vite__mapDeps([70,1,2,60,6]))),Ru=(0,p.lazy)(()=>P(()=>import(`./ImportHistory-ccPvJr3r.js`),__vite__mapDeps([71,1,2]))),zu=(0,p.lazy)(()=>P(()=>import(`./AuditLog-Be-lAO5O.js`),__vite__mapDeps([72,1,2,49,6]))),Bu=(0,p.lazy)(()=>P(()=>import(`./ApiUsage-Bijkviyg.js`),__vite__mapDeps([73,1,2]))),Vu=(0,p.lazy)(()=>P(()=>import(`./SyncStatus-B97z9pqx.js`),__vite__mapDeps([74,1,2,29,6]))),Hu=(0,p.lazy)(()=>P(()=>import(`./ReferenceConfig-BeBWV5oU.js`),__vite__mapDeps([75,1,2]))),Uu=(0,p.lazy)(()=>P(()=>import(`./NotifyCenter-CtKzikvz.js`),__vite__mapDeps([76,1,2]))),Wu=(0,p.lazy)(()=>P(()=>import(`./ImportWeighing-k7HB83kB.js`),__vite__mapDeps([77,1,2,6]))),Z=(0,p.lazy)(()=>P(()=>import(`./ImportPowerGeneration-CAS19Zn1.js`),__vite__mapDeps([78,1,2,79,6]))),Gu=(0,p.lazy)(()=>P(()=>import(`./ImportPbeExtras-Dapuf_yL.js`),__vite__mapDeps([80,1,2,79,6]))),Ku=(0,p.lazy)(()=>P(()=>import(`./SellerOnlyPage-D174mJBH.js`),__vite__mapDeps([81,1,2])));function qu(){let{t:e}=Tc(),t=e(`no_access`),[n,r]=(0,p.useState)(null),[i,a]=(0,p.useState)(!1);(0,p.useEffect)(()=>{n&&!zl()&&a(!0)},[n]);function o(){G(),a(!1)}let[s,c]=(0,p.useState)(!1),[l,u]=(0,p.useState)(!0),[d,f]=(0,p.useState)(()=>new URLSearchParams(window.location.search).get(`view`)||`dashboard`),m=new URLSearchParams(window.location.search).get(`seller`),[h,g]=(0,p.useState)(``),[_,v]=(0,p.useState)(!1),[y,b]=(0,p.useState)(!1),x=(0,p.useRef)(null),ee=(0,p.useRef)(!1);(0,p.useEffect)(()=>{x.current?.scrollTo({top:0})},[d]);let[S,te]=(0,p.useState)(null);function ne(e){if(_){te(e);return}f(e),Ol(e)}function re(){v(!1),f(S),Ol(S),te(null)}(0,p.useEffect)(()=>{(async()=>{let{data:{session:e}}=await Do.auth.getSession();if(window.location.hash.includes(`access_token`)&&window.history.replaceState(null,``,window.location.pathname+window.location.search),e){e.provider_token&&wo(e.user.email,e.provider_token);let n=e.user.user_metadata?.avatar_url||e.user.user_metadata?.picture;n&&Eo(e.user.email,n),c(!0);let i=await Oo();i&&i.role!==`EXTERNAL_VIEWER`?r(i):m||(await Do.auth.signOut({scope:`local`}),c(!1),g(t))}u(!1)})()},[]);async function ie(){Lo(),c(!0);let{data:{user:e}}=await Do.auth.getUser(),n=e?.user_metadata?.avatar_url||e?.user_metadata?.picture;n&&Eo(e.email,n);let i=await Oo();if(i&&i.role!==`EXTERNAL_VIEWER`)r(i);else if(!m)throw await Do.auth.signOut({scope:`local`}),c(!1),Error(t)}async function ae(){ee.current=!0,v(!1),await Do.auth.signOut({scope:`local`}),Lo(),r(null),c(!1),f(`dashboard`)}function oe(){Lo(),v(!1),r(null),c(!1),g(`เซสชันหมดอายุ กรุณาเข้าสู่ระบบใหม่ (เปิดแอปหลายแท็บพร้อมกันทำให้เกิดอาการนี้ได้)`)}if((0,p.useEffect)(()=>{let{data:e}=Do.auth.onAuthStateChange((e,t)=>{if(!(e!==`SIGNED_OUT`||t)){if(ee.current){ee.current=!1;return}oe()}});return()=>e?.subscription?.unsubscribe()},[]),(0,p.useEffect)(()=>{if(!s)return;let e=!1;async function t(){if(!(e||ee.current)){e=!0;try{let{data:{user:e},error:t}=await Do.auth.getUser();if(e)return;let n=t?.status??0;(n===400||n===401||n===403)&&oe()}catch{}finally{e=!1}}}let n=setInterval(t,6e4),r=()=>{document.visibilityState===`visible`&&t()};return document.addEventListener(`visibilitychange`,r),window.addEventListener(`focus`,t),()=>{clearInterval(n),document.removeEventListener(`visibilitychange`,r),window.removeEventListener(`focus`,t)}},[s]),l)return null;if(!s)return(0,V.jsx)(Mc,{onLoggedIn:ie,initialError:h});if(m)return(0,V.jsx)(`div`,{className:`flex min-h-screen items-center justify-center bg-surface p-4`,children:(0,V.jsx)(p.Suspense,{fallback:(0,V.jsx)(bu,{}),children:(0,V.jsx)(Ku,{seller:m})})});if(!n)return(0,V.jsx)(Mc,{onLoggedIn:ie,initialError:h});let[se,ce]=d.split(`:`),le=d!==`dashboard`&&Pc[d],ue=le&&Pc[d].grid,de=W[se]?.component,fe=n.role===`ADMIN`||n.role===`POWER_ADMIN`,C=d.startsWith(`admin_`)&&!fe||Il(d,n)||(le||[`production_energy`,`import_weighing`,`import_power_generation`,`import_pbe_extras`,`qa_import`].includes(d))&&!Bc(n,d);return(0,V.jsxs)(`div`,{className:`flex min-h-screen bg-surface md:h-screen`,children:[(0,V.jsx)(`div`,{className:`print-hide`,children:(0,V.jsx)(mu,{role:n,view:d,setView:ne,onLogout:ae,onOpenPalette:()=>b(!0)})}),(0,V.jsx)(gu,{role:n,setView:ne,open:y,setOpen:b}),(0,V.jsx)(yu,{onOpenPalette:()=>b(!0)}),(0,V.jsx)(q,{open:i,onClose:o}),(0,V.jsx)(`main`,{ref:x,className:`print-area min-w-0 flex-1 overflow-y-auto px-4 py-6 pb-24 md:px-8 md:pb-6`,children:(0,V.jsx)(`div`,{className:`mx-auto w-full max-w-[1600px]`,children:(0,V.jsx)(wu,{resetKey:d,children:(0,V.jsx)(p.Suspense,{fallback:(0,V.jsx)(bu,{}),children:C?(0,V.jsxs)(`div`,{className:`data-card mx-auto mt-10 max-w-md p-6 text-center`,children:[(0,V.jsx)(`p`,{className:`text-base font-semibold text-gray-800`,children:`ไม่มีสิทธิ์เปิดหน้านี้`}),(0,V.jsxs)(`p`,{className:`mt-1 text-sm text-muted`,children:[`บทบาทของคุณ (`,n.role,`) ใช้หน้านี้ไม่ได้ · ถ้าต้องใช้ ติดต่อผู้ดูแลระบบ`]}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>ne(`dashboard`),className:`mt-4 rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white`,children:`กลับแดชบอร์ด`})]}):(0,V.jsxs)(V.Fragment,{children:[!Nl(n)&&n.role!==`EXTERNAL_VIEWER`&&(d===`dashboard`||d===`reports`||de)&&(0,V.jsx)(`div`,{className:`mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-2 text-sm text-amber-800`,children:`บทบาทของคุณไม่เห็นข้อมูลใบชั่งมันและแกลบ (ปริมาณรับซื้อ ราคา มูลค่า) ข้อมูลบุคลากร และต้นทุน · ส่วนที่ใช้ข้อมูลเหล่านี้จะว่าง · ถ้าต้องใช้ ติดต่อผู้ดูแลระบบ`}),d===`dashboard`&&(0,V.jsx)(Tu,{role:n,setView:ne}),d===`reports`&&(0,V.jsx)(Eu,{role:n,setView:ne}),d===`ticket_search`&&(0,V.jsx)(Du,{}),d===`admin_users`&&(0,V.jsx)(Fu,{}),d===`admin_targets`&&(0,V.jsx)(Iu,{}),d===`admin_kpi_targets`&&(0,V.jsx)(Lu,{}),d===`admin_reference`&&(0,V.jsx)(Hu,{}),d===`admin_notify`&&(0,V.jsx)(Uu,{}),d===`admin_imports`&&(0,V.jsx)(Ru,{}),d===`admin_log`&&(0,V.jsx)(zu,{}),d===`admin_api_usage`&&(0,V.jsx)(Bu,{}),d===`admin_sync_status`&&(0,V.jsx)(Vu,{}),le&&!ue&&(0,V.jsx)(Ou,{role:n,table:d,onDirtyChange:v}),ue&&(0,V.jsx)(ku,{role:n,table:d,onDirtyChange:v},d),d===`qa_export`&&(0,V.jsx)(Au,{role:n}),d===`qa_import`&&(0,V.jsx)(ju,{role:n}),d===`production_energy`&&(0,V.jsx)(Mu,{role:n,onDirtyChange:v}),d===`cut_yield_entry`&&(0,V.jsx)(Nu,{role:n,onDirtyChange:v}),d===`qa_daily_report_entry`&&(0,V.jsx)(Pu,{role:n,onDirtyChange:v}),d===`import_weighing`&&(0,V.jsx)(Wu,{}),d===`import_power_generation`&&(0,V.jsx)(Z,{}),d===`import_pbe_extras`&&(0,V.jsx)(Gu,{}),de&&(0,V.jsx)(de,{activeTab:ce,role:n,onDirtyChange:v})]})})})})}),(0,V.jsx)(yc,{open:!!S,type:`error`,title:e(`unsaved_confirm_title`),message:e(`unsaved_confirm`),onClose:()=>te(null),children:(0,V.jsxs)(`div`,{className:`mt-4 flex gap-2`,children:[(0,V.jsx)(`button`,{onClick:()=>te(null),className:`flex-1 rounded-lg border border-gray-300 py-2 text-sm hover:bg-gray-50`,children:e(`cancel_edit`)}),(0,V.jsx)(`button`,{onClick:re,className:`flex-1 rounded-lg bg-red-600 py-2 text-sm text-white hover:bg-red-700`,children:e(`leave_page`)})]})})]})}wl();function Ju(e){return typeof e==`string`&&(/dynamically imported module/i.test(e)||/vite:preloadError/i.test(e))}window.addEventListener(`vite:preloadError`,()=>Yu()),window.addEventListener(`unhandledrejection`,e=>{Ju(e.reason?.message)&&Yu()}),window.addEventListener(`error`,e=>{Ju(e.message)&&Yu()});function Yu(){sessionStorage.getItem(`pqs_stale_chunk_reload`)||(sessionStorage.setItem(`pqs_stale_chunk_reload`,`1`),window.location.reload())}document.querySelectorAll(`link[rel="stylesheet"][media="print"]`).forEach(e=>{e.media=`all`}),(0,m.createRoot)(document.getElementById(`root`)).render((0,V.jsx)(p.StrictMode,{children:(0,V.jsx)(wc,{children:(0,V.jsx)(qu,{})})})),setTimeout(()=>sessionStorage.removeItem(`pqs_stale_chunk_reload`),5e3);export{rs as $,ic as A,js as B,uc as C,z as D,B as E,Ys as F,ys as G,Ss as H,Js as I,ms as J,_s as K,Gs as L,Qs as M,Zs as N,oc as O,Xs as P,is as Q,Hs as R,dc as S,cc as T,xs as U,Cs as V,bs as W,us as X,fs as Y,ss as Z,gc as _,P as _t,Cl as a,Yo as at,pc as b,u as bt,Uc as c,Go as ct,Pc as d,Io as dt,ns as et,Ic as f,Lo as ft,_c as g,Do as gt,yc as h,No as ht,Cu as i,Qo as it,rc as j,ac as k,Hc as l,Uo as lt,Tc as m,jo as mt,bu as n,es as nt,Gc as o,qo as ot,Fc as p,Mo as pt,gs as q,xu as r,$o as rt,Wc as s,Ko as st,Su as t,ts as tt,Vc as u,Ho as ut,hc as v,De as vt,lc as w,fc as x,mc as y,h as yt,zs as z};