diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 562f0bc..5c2cb0c 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -28,7 +28,8 @@ "Bash(bash:*)", "Bash(dos2unix:*)", "WebSearch", - "WebFetch(domain:ai.google.dev)" + "WebFetch(domain:ai.google.dev)", + "Bash(xargs:*)" ] } } diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index eb4afda..6eb551a 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -68,10 +68,11 @@ Create the following directories on your server: ``` /var/www/html/lux-studio/ -├── api/ # Create this directory -├── generated_videos/ # Create this directory -├── generated_images/ # Create this directory -└── uploads/ # Create this directory +├── api/ # PHP files go here +├── generated_videos/ # Video output (writable) +├── generated_images/ # Image output (writable) +└── uploads/ # Session uploads (writable) + └── sessions/ # Auto-created per user session ``` **Commands to create directories:** @@ -79,9 +80,11 @@ Create the following directories on your server: sudo mkdir -p /var/www/html/lux-studio/api sudo mkdir -p /var/www/html/lux-studio/generated_videos sudo mkdir -p /var/www/html/lux-studio/generated_images -sudo mkdir -p /var/www/html/lux-studio/uploads +sudo mkdir -p /var/www/html/lux-studio/uploads/sessions ``` +**Important**: PHP files use `dirname(__DIR__)` to store uploads/videos at `/var/www/html/lux-studio/` (NOT inside `/api/`). This keeps generated content separate from code. + --- ## Step 3: Files to Upload @@ -208,6 +211,9 @@ sudo chmod -R 755 assets/ sudo chmod -R 755 api/ # Writable directories for generated content +sudo chown -R www-data:www-data generated_videos/ +sudo chown -R www-data:www-data generated_images/ +sudo chown -R www-data:www-data uploads/ sudo chmod -R 775 generated_videos/ sudo chmod -R 775 generated_images/ sudo chmod -R 775 uploads/ @@ -216,17 +222,31 @@ sudo chmod -R 775 uploads/ sudo chmod 640 api/config.php ``` +**Note**: The `uploads/sessions/` subdirectories are created automatically by PHP when users start sessions. + --- -## Step 6: Enable Apache Rewrite Module +## Step 6: Apache Configuration +### 6.1 Check if mod_rewrite is enabled +```bash +apache2ctl -M | grep rewrite +``` + +If not enabled: ```bash sudo a2enmod rewrite sudo systemctl restart apache2 ``` -Ensure your Apache virtual host has `AllowOverride All`: +### 6.2 Enable AllowOverride for lux-studio +Edit your Apache site config: +```bash +sudo nano /etc/apache2/sites-enabled/000-default.conf +``` + +Add inside the `` block: ```apache AllowOverride All @@ -238,6 +258,8 @@ Then restart Apache: sudo systemctl restart apache2 ``` +**Note**: This only affects the `/lux-studio/` directory and won't impact other apps on the server. + --- ## Complete Directory Structure After Deployment @@ -261,11 +283,18 @@ sudo systemctl restart apache2 │ ├── webhook_logger.php # Webhook logging │ ├── env_loader.php # Environment loading │ └── config.php # Created on server -├── generated_videos/ # Empty, writable -├── generated_images/ # Empty, writable -└── uploads/ # Empty, writable +├── generated_videos/ # Video output (writable, www-data owned) +├── generated_images/ # Image output (writable, www-data owned) +└── uploads/ # Session data (writable, www-data owned) + └── sessions/ # Auto-created per-user session directories + └── {session_id}/ # Created automatically + └── images/ # User uploaded/generated images ``` +**Storage Paths** (configured in PHP files using `dirname(__DIR__)`): +- Images: `/var/www/html/lux-studio/uploads/sessions/{session_id}/images/` +- Videos: `/var/www/html/lux-studio/generated_videos/` + --- ## Azure AD Configuration @@ -308,12 +337,14 @@ You have **two separate Azure AD App Registrations**: | Issue | Solution | |-------|----------| | 404 on assets | Verify all files from `dist/` are uploaded, check `base` path in vite.config.js | +| 404 on logo | Ensure `LUX_STUDIO_LOGO.svg` exists at `/var/www/html/lux-studio/LUX_STUDIO_LOGO.svg` | | SSO login fails | Verify redirect URI in Azure Portal matches exactly: `https://ai-sandbox.oliver.solutions/lux-studio/` | | SSO uses wrong Client ID | Ensure you built with `npm run build` (uses `.env.production`), not `npm run dev` | | SSO redirect loop | Clear browser localStorage, check Azure AD redirect URI configuration | | API 500 errors | Check PHP logs: `sudo tail -f /var/log/apache2/error.log` | -| .htaccess not working | Ensure `mod_rewrite` is enabled and `AllowOverride All` is set | -| Generation fails | Check directories exist and are writable by Apache user | +| .htaccess not working | Ensure `mod_rewrite` is enabled and `AllowOverride All` is set for lux-studio directory | +| Failed to save image | Create `uploads/sessions` directory and set ownership: `sudo mkdir -p /var/www/html/lux-studio/uploads/sessions && sudo chown -R www-data:www-data /var/www/html/lux-studio/uploads` | +| Generation fails | Check directories exist and are writable by Apache user (www-data) | ### SSO Debug Tips diff --git a/backend/video_api.php b/backend/video_api.php index 1c19b2b..223b386 100644 --- a/backend/video_api.php +++ b/backend/video_api.php @@ -28,6 +28,16 @@ class VeoVideoAPI { private $baseUrl = 'https://generativelanguage.googleapis.com/v1beta/models'; private $model; + /** + * Get API base path for URLs (production-aware) + */ + private function getApiBasePath() { + // Check if we're in production (lux-studio subdirectory) + return (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '/lux-studio/') !== false) + ? '/lux-studio/api' + : '/api'; + } + // Available models private static $models = [ 'standard' => 'veo-3.1-generate-preview', @@ -449,7 +459,7 @@ try { 'video' => [ 'filename' => $filename, 'mime_type' => $videoData['mime_type'], - 'url' => '/api/stream_video.php?file=' . urlencode($filename) + 'url' => $this->getApiBasePath() . '/stream_video.php?file=' . urlencode($filename) ] ]); } else if ($videoData['type'] === 'uri') { @@ -491,7 +501,7 @@ try { 'video' => [ 'filename' => $filename, 'mime_type' => $videoData['mime_type'], - 'url' => '/api/stream_video.php?file=' . urlencode($filename) + 'url' => $this->getApiBasePath() . '/stream_video.php?file=' . urlencode($filename) ] ]); } else { @@ -571,7 +581,7 @@ try { echo json_encode([ 'success' => true, 'video' => [ - 'url' => '/api/stream_video.php?file=' . urlencode($filename), + 'url' => $this->getApiBasePath() . '/stream_video.php?file=' . urlencode($filename), 'filename' => $filename, 'mime_type' => 'video/mp4' ] diff --git a/frontend/dist/assets/index-CQhyuIyu.js b/frontend/dist/assets/index-5_WjmgQu.js similarity index 97% rename from frontend/dist/assets/index-CQhyuIyu.js rename to frontend/dist/assets/index-5_WjmgQu.js index bcec080..97d6ded 100644 --- a/frontend/dist/assets/index-CQhyuIyu.js +++ b/frontend/dist/assets/index-5_WjmgQu.js @@ -5,9 +5,9 @@ `);for(p=u=0;up||fe[u]!==Qe[p]){var Me=` `+fe[u].replace(" at new "," at ");return r.displayName&&Me.includes("")&&(Me=Me.replace("",r.displayName)),Me}while(1<=u&&0<=p);break}}}finally{X=!1,Error.prepareStackTrace=o}return(o=r?r.displayName||r.name:"")?nt(o):""}function Tt(r,i){switch(r.tag){case 26:case 27:case 5:return nt(r.type);case 16:return nt("Lazy");case 13:return r.child!==i&&i!==null?nt("Suspense Fallback"):nt("Suspense");case 19:return nt("SuspenseList");case 0:case 15:return We(r.type,!1);case 11:return We(r.type.render,!1);case 1:return We(r.type,!0);case 31:return nt("Activity");default:return""}}function Fe(r){try{var i="",o=null;do i+=Tt(r,o),o=r,r=r.return;while(r);return i}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var Se=Object.prototype.hasOwnProperty,Ye=A.unstable_scheduleCallback,Ze=A.unstable_cancelCallback,At=A.unstable_shouldYield,st=A.unstable_requestPaint,ht=A.unstable_now,Ut=A.unstable_getCurrentPriorityLevel,Be=A.unstable_ImmediatePriority,Ve=A.unstable_UserBlockingPriority,lt=A.unstable_NormalPriority,it=A.unstable_LowPriority,ct=A.unstable_IdlePriority,rt=A.log,rA=A.unstable_setDisableYieldValue,zt=null,St=null;function _t(r){if(typeof rt=="function"&&rA(r),St&&typeof St.setStrictMode=="function")try{St.setStrictMode(zt,r)}catch{}}var Vt=Math.clz32?Math.clz32:It,bt=Math.log,fA=Math.LN2;function It(r){return r>>>=0,r===0?32:31-(bt(r)/fA|0)|0}var Nt=256,Zt=262144,pe=4194304;function Le(r){var i=r&42;if(i!==0)return i;switch(r&-r){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 r&261888;case 262144:case 524288:case 1048576:case 2097152:return r&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return r&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return r}}function at(r,i,o){var u=r.pendingLanes;if(u===0)return 0;var p=0,w=r.suspendedLanes,F=r.pingedLanes;r=r.warmLanes;var j=u&134217727;return j!==0?(u=j&~w,u!==0?p=Le(u):(F&=j,F!==0?p=Le(F):o||(o=j&~r,o!==0&&(p=Le(o))))):(j=u&~w,j!==0?p=Le(j):F!==0?p=Le(F):o||(o=u&~r,o!==0&&(p=Le(o)))),p===0?0:i!==0&&i!==p&&(i&w)===0&&(w=p&-p,o=i&-i,w>=o||w===32&&(o&4194048)!==0)?i:p}function jt(r,i){return(r.pendingLanes&~(r.suspendedLanes&~r.pingedLanes)&i)===0}function $t(r,i){switch(r){case 1:case 2:case 4:case 8:case 64:return i+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 i+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 xA(){var r=pe;return pe<<=1,(pe&62914560)===0&&(pe=4194304),r}function eA(r){for(var i=[],o=0;31>o;o++)i.push(r);return i}function mt(r,i){r.pendingLanes|=i,i!==268435456&&(r.suspendedLanes=0,r.pingedLanes=0,r.warmLanes=0)}function FA(r,i,o,u,p,w){var F=r.pendingLanes;r.pendingLanes=o,r.suspendedLanes=0,r.pingedLanes=0,r.warmLanes=0,r.expiredLanes&=o,r.entangledLanes&=o,r.errorRecoveryDisabledLanes&=o,r.shellSuspendCounter=0;var j=r.entanglements,fe=r.expirationTimes,Qe=r.hiddenUpdates;for(o=F&~o;0"u")return null;try{return r.activeElement||r.body}catch{return r.body}}var kn=/[\n"\\]/g;function Sn(r){return r.replace(kn,function(i){return"\\"+i.charCodeAt(0).toString(16)+" "})}function Qo(r,i,o,u,p,w,F,j){r.name="",F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"?r.type=F:r.removeAttribute("type"),i!=null?F==="number"?(i===0&&r.value===""||r.value!=i)&&(r.value=""+BA(i)):r.value!==""+BA(i)&&(r.value=""+BA(i)):F!=="submit"&&F!=="reset"||r.removeAttribute("value"),i!=null?Vl(r,F,BA(i)):o!=null?Vl(r,F,BA(o)):u!=null&&r.removeAttribute("value"),p==null&&w!=null&&(r.defaultChecked=!!w),p!=null&&(r.checked=p&&typeof p!="function"&&typeof p!="symbol"),j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"?r.name=""+BA(j):r.removeAttribute("name")}function Xc(r,i,o,u,p,w,F,j){if(w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"&&(r.type=w),i!=null||o!=null){if(!(w!=="submit"&&w!=="reset"||i!=null)){ps(r);return}o=o!=null?""+BA(o):"",i=i!=null?""+BA(i):o,j||i===r.value||(r.value=i),r.defaultValue=i}u=u??p,u=typeof u!="function"&&typeof u!="symbol"&&!!u,r.checked=j?r.checked:!!u,r.defaultChecked=!!u,F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"&&(r.name=F),ps(r)}function Vl(r,i,o){i==="number"&&Br(r.ownerDocument)===r||r.defaultValue===""+o||(r.defaultValue=""+o)}function Cr(r,i,o,u){if(r=r.options,i){i={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Zl=!1;if($n)try{var Js={};Object.defineProperty(Js,"passive",{get:function(){Zl=!0}}),window.addEventListener("test",Js,Js),window.removeEventListener("test",Js,Js)}catch{Zl=!1}var Zr=null,Ws=null,Aa=null;function tu(){if(Aa)return Aa;var r,i=Ws,o=i.length,u,p="value"in Zr?Zr.value:Zr.textContent,w=p.length;for(r=0;r=ji),qn=" ",ws=!1;function vs(r,i){switch(r){case"keyup":return ko.indexOf(i.keyCode)!==-1;case"keydown":return i.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ho(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var ia=!1;function br(r,i){switch(r){case"compositionend":return Ho(i);case"keypress":return i.which!==32?null:(ws=!0,qn);case"textInput":return r=i.data,r===qn&&ws?null:r;default:return null}}function Da(r,i){if(ia)return r==="compositionend"||!ra&&vs(r,i)?(r=tu(),Aa=Ws=Zr=null,ia=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(i.ctrlKey||i.altKey||i.metaKey)||i.ctrlKey&&i.altKey){if(i.char&&1=i)return{node:o,offset:i-r};r=u}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=jo(o)}}function Ka(r,i){return r&&i?r===i?!0:r&&r.nodeType===3?!1:i&&i.nodeType===3?Ka(r,i.parentNode):"contains"in r?r.contains(i):r.compareDocumentPosition?!!(r.compareDocumentPosition(i)&16):!1:!1}function Ga(r){r=r!=null&&r.ownerDocument!=null&&r.ownerDocument.defaultView!=null?r.ownerDocument.defaultView:window;for(var i=Br(r.document);i instanceof r.HTMLIFrameElement;){try{var o=typeof i.contentWindow.location.href=="string"}catch{o=!1}if(o)r=i.contentWindow;else break;i=Br(r.document)}return i}function ca(r){var i=r&&r.nodeName&&r.nodeName.toLowerCase();return i&&(i==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||i==="textarea"||r.contentEditable==="true")}var to=$n&&"documentMode"in document&&11>=document.documentMode,ei=null,za=null,ur=null,ui=!1;function CA(r,i,o){var u=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;ui||ei==null||ei!==Br(u)||(u=ei,"selectionStart"in u&&ca(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),ur&&ja(ur,u)||(ur=u,u=Wd(za,"onSelect"),0>=F,p-=F,mi=1<<32-Vt(i)+p|o<AA?(uA=xt,xt=null):uA=xt.sibling;var IA=Oe(xe,xt,_e[AA],Ge);if(IA===null){xt===null&&(xt=uA);break}r&&xt&&IA.alternate===null&&i(xe,xt),we=w(IA,we,AA),UA===null?Ot=IA:UA.sibling=IA,UA=IA,xt=uA}if(AA===_e.length)return o(xe,xt),sA&&Ai(xe,AA),Ot;if(xt===null){for(;AA<_e.length;AA++)xt=ze(xe,_e[AA],Ge),xt!==null&&(we=w(xt,we,AA),UA===null?Ot=xt:UA.sibling=xt,UA=xt);return sA&&Ai(xe,AA),Ot}for(xt=u(xt);AA<_e.length;AA++)uA=Re(xt,xe,AA,_e[AA],Ge),uA!==null&&(r&&uA.alternate!==null&&xt.delete(uA.key===null?AA:uA.key),we=w(uA,we,AA),UA===null?Ot=uA:UA.sibling=uA,UA=uA);return r&&xt.forEach(function(hl){return i(xe,hl)}),sA&&Ai(xe,AA),Ot}function Dt(xe,we,_e,Ge){if(_e==null)throw Error(n(151));for(var Ot=null,UA=null,xt=we,AA=we=0,uA=null,IA=_e.next();xt!==null&&!IA.done;AA++,IA=_e.next()){xt.index>AA?(uA=xt,xt=null):uA=xt.sibling;var hl=Oe(xe,xt,IA.value,Ge);if(hl===null){xt===null&&(xt=uA);break}r&&xt&&hl.alternate===null&&i(xe,xt),we=w(hl,we,AA),UA===null?Ot=hl:UA.sibling=hl,UA=hl,xt=uA}if(IA.done)return o(xe,xt),sA&&Ai(xe,AA),Ot;if(xt===null){for(;!IA.done;AA++,IA=_e.next())IA=ze(xe,IA.value,Ge),IA!==null&&(we=w(IA,we,AA),UA===null?Ot=IA:UA.sibling=IA,UA=IA);return sA&&Ai(xe,AA),Ot}for(xt=u(xt);!IA.done;AA++,IA=_e.next())IA=Re(xt,xe,AA,IA.value,Ge),IA!==null&&(r&&IA.alternate!==null&&xt.delete(IA.key===null?AA:IA.key),we=w(IA,we,AA),UA===null?Ot=IA:UA.sibling=IA,UA=IA);return r&&xt.forEach(function(aI){return i(xe,aI)}),sA&&Ai(xe,AA),Ot}function YA(xe,we,_e,Ge){if(typeof _e=="object"&&_e!==null&&_e.type===x&&_e.key===null&&(_e=_e.props.children),typeof _e=="object"&&_e!==null){switch(_e.$$typeof){case v:e:{for(var Ot=_e.key;we!==null;){if(we.key===Ot){if(Ot=_e.type,Ot===x){if(we.tag===7){o(xe,we.sibling),Ge=p(we,_e.props.children),Ge.return=xe,xe=Ge;break e}}else if(we.elementType===Ot||typeof Ot=="object"&&Ot!==null&&Ot.$$typeof===$&&Ie(Ot)===we.type){o(xe,we.sibling),Ge=p(we,_e.props),Kt(Ge,_e),Ge.return=xe,xe=Ge;break e}o(xe,we);break}else i(xe,we);we=we.sibling}_e.type===x?(Ge=Bs(_e.props.children,xe.mode,Ge,_e.key),Ge.return=xe,xe=Ge):(Ge=Go(_e.type,_e.key,_e.props,null,xe.mode,Ge),Kt(Ge,_e),Ge.return=xe,xe=Ge)}return F(xe);case I:e:{for(Ot=_e.key;we!==null;){if(we.key===Ot)if(we.tag===4&&we.stateNode.containerInfo===_e.containerInfo&&we.stateNode.implementation===_e.implementation){o(xe,we.sibling),Ge=p(we,_e.children||[]),Ge.return=xe,xe=Ge;break e}else{o(xe,we);break}else i(xe,we);we=we.sibling}Ge=zo(_e,xe.mode,Ge),Ge.return=xe,xe=Ge}return F(xe);case $:return _e=Ie(_e),YA(xe,we,_e,Ge)}if(Ce(_e))return yt(xe,we,_e,Ge);if(V(_e)){if(Ot=V(_e),typeof Ot!="function")throw Error(n(150));return _e=Ot.call(_e),Dt(xe,we,_e,Ge)}if(typeof _e.then=="function")return YA(xe,we,dt(_e),Ge);if(_e.$$typeof===z)return YA(xe,we,gu(xe,_e),Ge);wt(xe,_e)}return typeof _e=="string"&&_e!==""||typeof _e=="number"||typeof _e=="bigint"?(_e=""+_e,we!==null&&we.tag===6?(o(xe,we.sibling),Ge=p(we,_e),Ge.return=xe,xe=Ge):(o(xe,we),Ge=lc(_e,xe.mode,Ge),Ge.return=xe,xe=Ge),F(xe)):o(xe,we)}return function(xe,we,_e,Ge){try{Bt=0;var Ot=YA(xe,we,_e,Ge);return qe=null,Ot}catch(xt){if(xt===me||xt===ee)throw xt;var UA=fr(29,xt,null,xe.mode);return UA.lanes=Ge,UA.return=xe,UA}finally{}}}var WA=aA(!0),Yt=aA(!1),gt=!1;function ot(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function on(r,i){r=r.updateQueue,i.updateQueue===r&&(i.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,callbacks:null})}function Ht(r){return{lane:r,tag:0,payload:null,callback:null,next:null}}function tA(r,i,o){var u=r.updateQueue;if(u===null)return null;if(u=u.shared,(NA&2)!==0){var p=u.pending;return p===null?i.next=i:(i.next=p.next,p.next=i),u.pending=i,i=hr(r),sc(r,null,o),i}return ac(r,u,i,o),hr(r)}function TA(r,i,o){if(i=i.updateQueue,i!==null&&(i=i.shared,(o&4194048)!==0)){var u=i.lanes;u&=r.pendingLanes,o|=u,i.lanes=o,tn(r,o)}}function Dn(r,i){var o=r.updateQueue,u=r.alternate;if(u!==null&&(u=u.updateQueue,o===u)){var p=null,w=null;if(o=o.firstBaseUpdate,o!==null){do{var F={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};w===null?p=w=F:w=w.next=F,o=o.next}while(o!==null);w===null?p=w=i:w=w.next=i}else p=w=i;o={baseState:u.baseState,firstBaseUpdate:p,lastBaseUpdate:w,shared:u.shared,callbacks:u.callbacks},r.updateQueue=o;return}r=o.lastBaseUpdate,r===null?o.firstBaseUpdate=i:r.next=i,o.lastBaseUpdate=i}var ar=!1;function zA(){if(ar){var r=m;if(r!==null)throw r}}function In(r,i,o,u){ar=!1;var p=r.updateQueue;gt=!1;var w=p.firstBaseUpdate,F=p.lastBaseUpdate,j=p.shared.pending;if(j!==null){p.shared.pending=null;var fe=j,Qe=fe.next;fe.next=null,F===null?w=Qe:F.next=Qe,F=fe;var Me=r.alternate;Me!==null&&(Me=Me.updateQueue,j=Me.lastBaseUpdate,j!==F&&(j===null?Me.firstBaseUpdate=Qe:j.next=Qe,Me.lastBaseUpdate=fe))}if(w!==null){var ze=p.baseState;F=0,Me=Qe=fe=null,j=w;do{var Oe=j.lane&-536870913,Re=Oe!==j.lane;if(Re?(cA&Oe)===Oe:(u&Oe)===Oe){Oe!==0&&Oe===d&&(ar=!0),Me!==null&&(Me=Me.next={lane:0,tag:j.tag,payload:j.payload,callback:null,next:null});e:{var yt=r,Dt=j;Oe=i;var YA=o;switch(Dt.tag){case 1:if(yt=Dt.payload,typeof yt=="function"){ze=yt.call(YA,ze,Oe);break e}ze=yt;break e;case 3:yt.flags=yt.flags&-65537|128;case 0:if(yt=Dt.payload,Oe=typeof yt=="function"?yt.call(YA,ze,Oe):yt,Oe==null)break e;ze=y({},ze,Oe);break e;case 2:gt=!0}}Oe=j.callback,Oe!==null&&(r.flags|=64,Re&&(r.flags|=8192),Re=p.callbacks,Re===null?p.callbacks=[Oe]:Re.push(Oe))}else Re={lane:Oe,tag:j.tag,payload:j.payload,callback:j.callback,next:null},Me===null?(Qe=Me=Re,fe=ze):Me=Me.next=Re,F|=Oe;if(j=j.next,j===null){if(j=p.shared.pending,j===null)break;Re=j,j=Re.next,Re.next=null,p.lastBaseUpdate=Re,p.shared.pending=null}}while(!0);Me===null&&(fe=ze),p.baseState=fe,p.firstBaseUpdate=Qe,p.lastBaseUpdate=Me,w===null&&(p.shared.lanes=0),Al|=F,r.lanes=F,r.memoizedState=ze}}function dr(r,i){if(typeof r!="function")throw Error(n(191,r));r.call(i)}function Fn(r,i){var o=r.callbacks;if(o!==null)for(r.callbacks=null,r=0;rw?w:8;var F=N.T,j={};N.T=j,O0(r,!1,i,o);try{var fe=p(),Qe=N.S;if(Qe!==null&&Qe(j,fe),fe!==null&&typeof fe=="object"&&typeof fe.then=="function"){var Me=O(fe,u);Kh(r,i,Me,Xi(r))}else Kh(r,i,u,Xi(r))}catch(ze){Kh(r,i,{then:function(){},status:"rejected",reason:ze},Xi())}finally{G.p=w,F!==null&&j.types!==null&&(F.types=j.types),N.T=F}}function t3(){}function Q0(r,i,o,u){if(r.tag!==5)throw Error(n(476));var p=Rv(r).queue;Ov(r,p,i,W,o===null?t3:function(){return kv(r),o(u)})}function Rv(r){var i=r.memoizedState;if(i!==null)return i;i={memoizedState:W,baseState:W,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:fa,lastRenderedState:W},next:null};var o={};return i.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:fa,lastRenderedState:o},next:null},r.memoizedState=i,r=r.alternate,r!==null&&(r.memoizedState=i),i}function kv(r){var i=Rv(r);i.next===null&&(i=r.alternate.memoizedState),Kh(r,i.next.queue,{},Xi())}function L0(){return ir(sf)}function Hv(){return gn().memoizedState}function Dv(){return gn().memoizedState}function A3(r){for(var i=r.return;i!==null;){switch(i.tag){case 24:case 3:var o=Xi();r=Ht(o);var u=tA(i,r,o);u!==null&&(xi(u,i,o),TA(u,i,o)),i={cache:Xo()},r.payload=i;return}i=i.return}}function n3(r,i,o){var u=Xi();o={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Nd(r)?Pv(i,o):(o=au(r,i,o,u),o!==null&&(xi(o,r,u),jv(o,i,u)))}function Mv(r,i,o){var u=Xi();Kh(r,i,o,u)}function Kh(r,i,o,u){var p={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Nd(r))Pv(i,p);else{var w=r.alternate;if(r.lanes===0&&(w===null||w.lanes===0)&&(w=i.lastRenderedReducer,w!==null))try{var F=i.lastRenderedState,j=w(F,o);if(p.hasEagerState=!0,p.eagerState=j,tr(j,F))return ac(r,i,p,0),ZA===null&&ic(),!1}catch{}finally{}if(o=au(r,i,p,u),o!==null)return xi(o,r,u),jv(o,i,u),!0}return!1}function O0(r,i,o,u){if(u={lane:2,revertLane:fm(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Nd(r)){if(i)throw Error(n(479))}else i=au(r,o,u,2),i!==null&&xi(i,r,2)}function Nd(r){var i=r.alternate;return r===Qt||i!==null&&i===Qt}function Pv(r,i){yi=kr=!0;var o=r.pending;o===null?i.next=i:(i.next=o.next,o.next=i),r.pending=i}function jv(r,i,o){if((o&4194048)!==0){var u=i.lanes;u&=r.pendingLanes,o|=u,i.lanes=o,tn(r,o)}}var Gh={readContext:ir,use:Jo,useCallback:VA,useContext:VA,useEffect:VA,useImperativeHandle:VA,useLayoutEffect:VA,useInsertionEffect:VA,useMemo:VA,useReducer:VA,useRef:VA,useState:VA,useDebugValue:VA,useDeferredValue:VA,useTransition:VA,useSyncExternalStore:VA,useId:VA,useHostTransitionStatus:VA,useFormState:VA,useActionState:VA,useOptimistic:VA,useMemoCache:VA,useCacheRefresh:VA};Gh.useEffectEvent=VA;var Kv={readContext:ir,use:Jo,useCallback:function(r,i){return Yn().memoizedState=[r,i===void 0?null:i],r},useContext:ir,useEffect:Sv,useImperativeHandle:function(r,i,o){o=o!=null?o.concat([r]):null,Zo(4194308,4,Tv.bind(null,i,r),o)},useLayoutEffect:function(r,i){return Zo(4194308,4,r,i)},useInsertionEffect:function(r,i){Zo(4,2,r,i)},useMemo:function(r,i){var o=Yn();i=i===void 0?null:i;var u=r();if(Sr){_t(!0);try{r()}finally{_t(!1)}}return o.memoizedState=[u,i],u},useReducer:function(r,i,o){var u=Yn();if(o!==void 0){var p=o(i);if(Sr){_t(!0);try{o(i)}finally{_t(!1)}}}else p=i;return u.memoizedState=u.baseState=p,r={pending:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:p},u.queue=r,r=r.dispatch=n3.bind(null,Qt,r),[u.memoizedState,r]},useRef:function(r){var i=Yn();return r={current:r},i.memoizedState=r},useState:function(r){r=_s(r);var i=r.queue,o=Mv.bind(null,Qt,i);return i.dispatch=o,[r.memoizedState,o]},useDebugValue:_0,useDeferredValue:function(r,i){var o=Yn();return N0(o,r,i)},useTransition:function(){var r=_s(!1);return r=Ov.bind(null,Qt,r.queue,!0,!1),Yn().memoizedState=r,[!1,r]},useSyncExternalStore:function(r,i,o){var u=Qt,p=Yn();if(sA){if(o===void 0)throw Error(n(407));o=o()}else{if(o=i(),ZA===null)throw Error(n(349));(cA&127)!==0||Xa(u,i,o)}p.memoizedState=o;var w={value:o,getSnapshot:i};return p.queue=w,Sv(Mh.bind(null,u,w,r),[r]),u.flags|=2048,co(9,{destroy:void 0},Dh.bind(null,u,w,o,i),null),o},useId:function(){var r=Yn(),i=ZA.identifierPrefix;if(sA){var o=wi,u=mi;o=(u&~(1<<32-Vt(u)-1)).toString(32)+o,i="_"+i+"R_"+o,o=Nn++,0<\/script>",w=w.removeChild(w.firstChild);break;case"select":w=typeof u.is=="string"?F.createElement("select",{is:u.is}):F.createElement("select"),u.multiple?w.multiple=!0:u.size&&(w.size=u.size);break;default:w=typeof u.is=="string"?F.createElement(p,{is:u.is}):F.createElement(p)}}w[RA]=i,w[an]=u;e:for(F=i.child;F!==null;){if(F.tag===5||F.tag===6)w.appendChild(F.stateNode);else if(F.tag!==4&&F.tag!==27&&F.child!==null){F.child.return=F,F=F.child;continue}if(F===i)break e;for(;F.sibling===null;){if(F.return===null||F.return===i)break e;F=F.return}F.sibling.return=F.return,F=F.sibling}i.stateNode=w;e:switch(Ir(w,p,u),p){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&ho(i)}}return un(i),X0(i,i.type,r===null?null:r.memoizedProps,i.pendingProps,o),null;case 6:if(r&&i.stateNode!=null)r.memoizedProps!==u&&ho(i);else{if(typeof u!="string"&&i.stateNode===null)throw Error(n(166));if(r=se.current,rr(i)){if(r=i.stateNode,o=i.memoizedProps,u=null,p=nr,p!==null)switch(p.tag){case 27:case 5:u=p.memoizedProps}r[RA]=i,r=!!(r.nodeValue===o||u!==null&&u.suppressHydrationWarning===!0||oB(r.nodeValue,o)),r||bs(i,!0)}else r=Zd(r).createTextNode(u),r[RA]=i,i.stateNode=r}return un(i),null;case 31:if(o=i.memoizedState,r===null||r.memoizedState!==null){if(u=rr(i),o!==null){if(r===null){if(!u)throw Error(n(318));if(r=i.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(n(557));r[RA]=i}else ao(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;un(i),r=!1}else o=Lh(),r!==null&&r.memoizedState!==null&&(r.memoizedState.hydrationErrors=o),r=!0;if(!r)return i.flags&256?(kA(i),i):(kA(i),null);if((i.flags&128)!==0)throw Error(n(558))}return un(i),null;case 13:if(u=i.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(p=rr(i),u!==null&&u.dehydrated!==null){if(r===null){if(!p)throw Error(n(318));if(p=i.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(n(317));p[RA]=i}else ao(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;un(i),p=!1}else p=Lh(),r!==null&&r.memoizedState!==null&&(r.memoizedState.hydrationErrors=p),p=!0;if(!p)return i.flags&256?(kA(i),i):(kA(i),null)}return kA(i),(i.flags&128)!==0?(i.lanes=o,i):(o=u!==null,r=r!==null&&r.memoizedState!==null,o&&(u=i.child,p=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(p=u.alternate.memoizedState.cachePool.pool),w=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(w=u.memoizedState.cachePool.pool),w!==p&&(u.flags|=2048)),o!==r&&o&&(i.child.flags|=8192),kd(i,i.updateQueue),un(i),null);case 4:return oe(),r===null&&mm(i.stateNode.containerInfo),un(i),null;case 10:return vi(i.type),un(i),null;case 19:if(S(pA),u=i.memoizedState,u===null)return un(i),null;if(p=(i.flags&128)!==0,w=u.rendering,w===null)if(p)Vh(u,!1);else{if(Qn!==0||r!==null&&(r.flags&128)!==0)for(r=i.child;r!==null;){if(w=gr(r),w!==null){for(i.flags|=128,Vh(u,!1),r=w.updateQueue,i.updateQueue=r,kd(i,r),i.subtreeFlags=0,r=o,o=i.child;o!==null;)oc(o,r),o=o.sibling;return Q(pA,pA.current&1|2),sA&&Ai(i,u.treeForkCount),i.child}r=r.sibling}u.tail!==null&&ht()>jd&&(i.flags|=128,p=!0,Vh(u,!1),i.lanes=4194304)}else{if(!p)if(r=gr(w),r!==null){if(i.flags|=128,p=!0,r=r.updateQueue,i.updateQueue=r,kd(i,r),Vh(u,!0),u.tail===null&&u.tailMode==="hidden"&&!w.alternate&&!sA)return un(i),null}else 2*ht()-u.renderingStartTime>jd&&o!==536870912&&(i.flags|=128,p=!0,Vh(u,!1),i.lanes=4194304);u.isBackwards?(w.sibling=i.child,i.child=w):(r=u.last,r!==null?r.sibling=w:i.child=w,u.last=w)}return u.tail!==null?(r=u.tail,u.rendering=r,u.tail=r.sibling,u.renderingStartTime=ht(),r.sibling=null,o=pA.current,Q(pA,p?o&1|2:o&1),sA&&Ai(i,u.treeForkCount),r):(un(i),null);case 22:case 23:return kA(i),Mn(),u=i.memoizedState!==null,r!==null?r.memoizedState!==null!==u&&(i.flags|=8192):u&&(i.flags|=8192),u?(o&536870912)!==0&&(i.flags&128)===0&&(un(i),i.subtreeFlags&6&&(i.flags|=8192)):un(i),o=i.updateQueue,o!==null&&kd(i,o.retryQueue),o=null,r!==null&&r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),u=null,i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(u=i.memoizedState.cachePool.pool),u!==o&&(i.flags|=2048),r!==null&&S(M),null;case 24:return o=null,r!==null&&(o=r.memoizedState.cache),i.memoizedState.cache!==o&&(i.flags|=2048),vi(En),un(i),null;case 25:return null;case 30:return null}throw Error(n(156,i.tag))}function o3(r,i){switch(hu(i),i.tag){case 1:return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 3:return vi(En),oe(),r=i.flags,(r&65536)!==0&&(r&128)===0?(i.flags=r&-65537|128,i):null;case 26:case 27:case 5:return He(i),null;case 31:if(i.memoizedState!==null){if(kA(i),i.alternate===null)throw Error(n(340));ao()}return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 13:if(kA(i),r=i.memoizedState,r!==null&&r.dehydrated!==null){if(i.alternate===null)throw Error(n(340));ao()}return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 19:return S(pA),null;case 4:return oe(),null;case 10:return vi(i.type),null;case 22:case 23:return kA(i),Mn(),r!==null&&S(M),r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 24:return vi(En),null;case 25:return null;default:return null}}function fy(r,i){switch(hu(i),i.tag){case 3:vi(En),oe();break;case 26:case 27:case 5:He(i);break;case 4:oe();break;case 31:i.memoizedState!==null&&kA(i);break;case 13:kA(i);break;case 19:S(pA);break;case 10:vi(i.type);break;case 22:case 23:kA(i),Mn(),r!==null&&S(M);break;case 24:vi(En)}}function qh(r,i){try{var o=i.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var p=u.next;o=p;do{if((o.tag&r)===r){u=void 0;var w=o.create,F=o.inst;u=w(),F.destroy=u}o=o.next}while(o!==p)}}catch(j){DA(i,i.return,j)}}function el(r,i,o){try{var u=i.updateQueue,p=u!==null?u.lastEffect:null;if(p!==null){var w=p.next;u=w;do{if((u.tag&r)===r){var F=u.inst,j=F.destroy;if(j!==void 0){F.destroy=void 0,p=i;var fe=o,Qe=j;try{Qe()}catch(Me){DA(p,fe,Me)}}}u=u.next}while(u!==w)}}catch(Me){DA(i,i.return,Me)}}function dy(r){var i=r.updateQueue;if(i!==null){var o=r.stateNode;try{Fn(i,o)}catch(u){DA(r,r.return,u)}}}function gy(r,i,o){o.props=gc(r.type,r.memoizedProps),o.state=r.memoizedState;try{o.componentWillUnmount()}catch(u){DA(r,i,u)}}function Yh(r,i){try{var o=r.ref;if(o!==null){switch(r.tag){case 26:case 27:case 5:var u=r.stateNode;break;case 30:u=r.stateNode;break;default:u=r.stateNode}typeof o=="function"?r.refCleanup=o(u):o.current=u}}catch(p){DA(r,i,p)}}function Ns(r,i){var o=r.ref,u=r.refCleanup;if(o!==null)if(typeof u=="function")try{u()}catch(p){DA(r,i,p)}finally{r.refCleanup=null,r=r.alternate,r!=null&&(r.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(p){DA(r,i,p)}else o.current=null}function py(r){var i=r.type,o=r.memoizedProps,u=r.stateNode;try{e:switch(i){case"button":case"input":case"select":case"textarea":o.autoFocus&&u.focus();break e;case"img":o.src?u.src=o.src:o.srcSet&&(u.srcset=o.srcSet)}}catch(p){DA(r,r.return,p)}}function J0(r,i,o){try{var u=r.stateNode;T3(u,r.type,o,i),u[an]=i}catch(p){DA(r,r.return,p)}}function my(r){return r.tag===5||r.tag===3||r.tag===26||r.tag===27&&sl(r.type)||r.tag===4}function W0(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||my(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.tag===27&&sl(r.type)||r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Z0(r,i,o){var u=r.tag;if(u===5||u===6)r=r.stateNode,i?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(r,i):(i=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,i.appendChild(r),o=o._reactRootContainer,o!=null||i.onclick!==null||(i.onclick=Mi));else if(u!==4&&(u===27&&sl(r.type)&&(o=r.stateNode,i=null),r=r.child,r!==null))for(Z0(r,i,o),r=r.sibling;r!==null;)Z0(r,i,o),r=r.sibling}function Hd(r,i,o){var u=r.tag;if(u===5||u===6)r=r.stateNode,i?o.insertBefore(r,i):o.appendChild(r);else if(u!==4&&(u===27&&sl(r.type)&&(o=r.stateNode),r=r.child,r!==null))for(Hd(r,i,o),r=r.sibling;r!==null;)Hd(r,i,o),r=r.sibling}function wy(r){var i=r.stateNode,o=r.memoizedProps;try{for(var u=r.type,p=i.attributes;p.length;)i.removeAttributeNode(p[0]);Ir(i,u,o),i[RA]=r,i[an]=o}catch(w){DA(r,r.return,w)}}var fo=!1,Jn=!1,$0=!1,vy=typeof WeakSet=="function"?WeakSet:Set,pr=null;function l3(r,i){if(r=r.containerInfo,ym=ig,r=Ga(r),ca(r)){if("selectionStart"in r)var o={start:r.selectionStart,end:r.selectionEnd};else e:{o=(o=r.ownerDocument)&&o.defaultView||window;var u=o.getSelection&&o.getSelection();if(u&&u.rangeCount!==0){o=u.anchorNode;var p=u.anchorOffset,w=u.focusNode;u=u.focusOffset;try{o.nodeType,w.nodeType}catch{o=null;break e}var F=0,j=-1,fe=-1,Qe=0,Me=0,ze=r,Oe=null;t:for(;;){for(var Re;ze!==o||p!==0&&ze.nodeType!==3||(j=F+p),ze!==w||u!==0&&ze.nodeType!==3||(fe=F+u),ze.nodeType===3&&(F+=ze.nodeValue.length),(Re=ze.firstChild)!==null;)Oe=ze,ze=Re;for(;;){if(ze===r)break t;if(Oe===o&&++Qe===p&&(j=F),Oe===w&&++Me===u&&(fe=F),(Re=ze.nextSibling)!==null)break;ze=Oe,Oe=ze.parentNode}ze=Re}o=j===-1||fe===-1?null:{start:j,end:fe}}else o=null}o=o||{start:0,end:0}}else o=null;for(Bm={focusedElem:r,selectionRange:o},ig=!1,pr=i;pr!==null;)if(i=pr,r=i.child,(i.subtreeFlags&1028)!==0&&r!==null)r.return=i,pr=r;else for(;pr!==null;){switch(i=pr,w=i.alternate,r=i.flags,i.tag){case 0:if((r&4)!==0&&(r=i.updateQueue,r=r!==null?r.events:null,r!==null))for(o=0;o title"))),Ir(w,u,o),w[RA]=r,yn(w),u=w;break e;case"link":var F=xB("link","href",p).get(u+(o.href||""));if(F){for(var j=0;jYA&&(F=YA,YA=Dt,Dt=F);var xe=Ko(j,Dt),we=Ko(j,YA);if(xe&&we&&(Re.rangeCount!==1||Re.anchorNode!==xe.node||Re.anchorOffset!==xe.offset||Re.focusNode!==we.node||Re.focusOffset!==we.offset)){var _e=ze.createRange();_e.setStart(xe.node,xe.offset),Re.removeAllRanges(),Dt>YA?(Re.addRange(_e),Re.extend(we.node,we.offset)):(_e.setEnd(we.node,we.offset),Re.addRange(_e))}}}}for(ze=[],Re=j;Re=Re.parentNode;)Re.nodeType===1&&ze.push({element:Re,left:Re.scrollLeft,top:Re.scrollTop});for(typeof j.focus=="function"&&j.focus(),j=0;jo?32:o,N.T=null,o=am,am=null;var w=rl,F=vo;if(sr=0,Tu=rl=null,vo=0,(NA&6)!==0)throw Error(n(331));var j=NA;if(NA|=4,Ty(w.current),Uy(w,w.current,F,o),NA=j,ef(0,!1),St&&typeof St.onPostCommitFiberRoot=="function")try{St.onPostCommitFiberRoot(zt,w)}catch{}return!0}finally{G.p=p,N.T=u,Yy(r,i)}}function Jy(r,i,o){i=di(o,i),i=D0(r.stateNode,i,2),r=tA(r,i,2),r!==null&&(mt(r,2),Qs(r))}function DA(r,i,o){if(r.tag===3)Jy(r,r,o);else for(;i!==null;){if(i.tag===3){Jy(i,r,o);break}else if(i.tag===1){var u=i.stateNode;if(typeof i.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(nl===null||!nl.has(u))){r=di(o,r),o=Wv(2),u=tA(i,o,2),u!==null&&(Zv(o,u,i,r),mt(u,2),Qs(u));break}}i=i.return}}function cm(r,i,o){var u=r.pingCache;if(u===null){u=r.pingCache=new h3;var p=new Set;u.set(i,p)}else p=u.get(i),p===void 0&&(p=new Set,u.set(i,p));p.has(o)||(Am=!0,p.add(o),r=m3.bind(null,r,i,o),i.then(r,r))}function m3(r,i,o){var u=r.pingCache;u!==null&&u.delete(i),r.pingedLanes|=r.suspendedLanes&o,r.warmLanes&=~o,ZA===r&&(cA&o)===o&&(Qn===4||Qn===3&&(cA&62914560)===cA&&300>ht()-Pd?(NA&2)===0&&_u(r,0):nm|=o,Fu===cA&&(Fu=0)),Qs(r)}function Wy(r,i){i===0&&(i=xA()),r=Va(r,i),r!==null&&(mt(r,i),Qs(r))}function w3(r){var i=r.memoizedState,o=0;i!==null&&(o=i.retryLane),Wy(r,o)}function v3(r,i){var o=0;switch(r.tag){case 31:case 13:var u=r.stateNode,p=r.memoizedState;p!==null&&(o=p.retryLane);break;case 19:u=r.stateNode;break;case 22:u=r.stateNode._retryCache;break;default:throw Error(n(314))}u!==null&&u.delete(i),Wy(r,o)}function y3(r,i){return Ye(r,i)}var Yd=null,Qu=null,um=!1,Xd=!1,hm=!1,al=0;function Qs(r){r!==Qu&&r.next===null&&(Qu===null?Yd=Qu=r:Qu=Qu.next=r),Xd=!0,um||(um=!0,C3())}function ef(r,i){if(!hm&&Xd){hm=!0;do for(var o=!1,u=Yd;u!==null;){if(r!==0){var p=u.pendingLanes;if(p===0)var w=0;else{var F=u.suspendedLanes,j=u.pingedLanes;w=(1<<31-Vt(42|r)+1)-1,w&=p&~(F&~j),w=w&201326741?w&201326741|1:w?w|2:0}w!==0&&(o=!0,tB(u,w))}else w=cA,w=at(u,u===ZA?w:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(w&3)===0||jt(u,w)||(o=!0,tB(u,w));u=u.next}while(o);hm=!1}}function B3(){Zy()}function Zy(){Xd=um=!1;var r=0;al!==0&&N3()&&(r=al);for(var i=ht(),o=null,u=Yd;u!==null;){var p=u.next,w=$y(u,i);w===0?(u.next=null,o===null?Yd=p:o.next=p,p===null&&(Qu=o)):(o=u,(r!==0||(w&3)!==0)&&(Xd=!0)),u=p}sr!==0&&sr!==5||ef(r),al!==0&&(al=0)}function $y(r,i){for(var o=r.suspendedLanes,u=r.pingedLanes,p=r.expirationTimes,w=r.pendingLanes&-62914561;0j)break;var Me=fe.transferSize,ze=fe.initiatorType;Me&&lB(ze)&&(fe=fe.responseEnd,F+=Me*(fe"u"?null:document;function BB(r,i,o){var u=Lu;if(u&&typeof i=="string"&&i){var p=Sn(i);p='link[rel="'+r+'"][href="'+p+'"]',typeof o=="string"&&(p+='[crossorigin="'+o+'"]'),yB.has(p)||(yB.add(p),r={rel:r,crossOrigin:o,href:i},u.querySelector(p)===null&&(i=u.createElement("link"),Ir(i,"link",r),yn(i),u.head.appendChild(i)))}}function P3(r){yo.D(r),BB("dns-prefetch",r,null)}function j3(r,i){yo.C(r,i),BB("preconnect",r,i)}function K3(r,i,o){yo.L(r,i,o);var u=Lu;if(u&&r&&i){var p='link[rel="preload"][as="'+Sn(i)+'"]';i==="image"&&o&&o.imageSrcSet?(p+='[imagesrcset="'+Sn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(p+='[imagesizes="'+Sn(o.imageSizes)+'"]')):p+='[href="'+Sn(r)+'"]';var w=p;switch(i){case"style":w=Ou(r);break;case"script":w=Ru(r)}pa.has(w)||(r=y({rel:"preload",href:i==="image"&&o&&o.imageSrcSet?void 0:r,as:i},o),pa.set(w,r),u.querySelector(p)!==null||i==="style"&&u.querySelector(rf(w))||i==="script"&&u.querySelector(af(w))||(i=u.createElement("link"),Ir(i,"link",r),yn(i),u.head.appendChild(i)))}}function G3(r,i){yo.m(r,i);var o=Lu;if(o&&r){var u=i&&typeof i.as=="string"?i.as:"script",p='link[rel="modulepreload"][as="'+Sn(u)+'"][href="'+Sn(r)+'"]',w=p;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":w=Ru(r)}if(!pa.has(w)&&(r=y({rel:"modulepreload",href:r},i),pa.set(w,r),o.querySelector(p)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(af(w)))return}u=o.createElement("link"),Ir(u,"link",r),yn(u),o.head.appendChild(u)}}}function z3(r,i,o){yo.S(r,i,o);var u=Lu;if(u&&r){var p=ea(u).hoistableStyles,w=Ou(r);i=i||"default";var F=p.get(w);if(!F){var j={loading:0,preload:null};if(F=u.querySelector(rf(w)))j.loading=5;else{r=y({rel:"stylesheet",href:r,"data-precedence":i},o),(o=pa.get(w))&&Im(r,o);var fe=F=u.createElement("link");yn(fe),Ir(fe,"link",r),fe._p=new Promise(function(Qe,Me){fe.onload=Qe,fe.onerror=Me}),fe.addEventListener("load",function(){j.loading|=1}),fe.addEventListener("error",function(){j.loading|=2}),j.loading|=4,eg(F,i,u)}F={type:"stylesheet",instance:F,count:1,state:j},p.set(w,F)}}}function V3(r,i){yo.X(r,i);var o=Lu;if(o&&r){var u=ea(o).hoistableScripts,p=Ru(r),w=u.get(p);w||(w=o.querySelector(af(p)),w||(r=y({src:r,async:!0},i),(i=pa.get(p))&&Fm(r,i),w=o.createElement("script"),yn(w),Ir(w,"link",r),o.head.appendChild(w)),w={type:"script",instance:w,count:1,state:null},u.set(p,w))}}function q3(r,i){yo.M(r,i);var o=Lu;if(o&&r){var u=ea(o).hoistableScripts,p=Ru(r),w=u.get(p);w||(w=o.querySelector(af(p)),w||(r=y({src:r,async:!0,type:"module"},i),(i=pa.get(p))&&Fm(r,i),w=o.createElement("script"),yn(w),Ir(w,"link",r),o.head.appendChild(w)),w={type:"script",instance:w,count:1,state:null},u.set(p,w))}}function CB(r,i,o,u){var p=(p=se.current)?$d(p):null;if(!p)throw Error(n(446));switch(r){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(i=Ou(o.href),o=ea(p).hoistableStyles,u=o.get(i),u||(u={type:"style",instance:null,count:0,state:null},o.set(i,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){r=Ou(o.href);var w=ea(p).hoistableStyles,F=w.get(r);if(F||(p=p.ownerDocument||p,F={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},w.set(r,F),(w=p.querySelector(rf(r)))&&!w._p&&(F.instance=w,F.state.loading=5),pa.has(r)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},pa.set(r,o),w||Y3(p,r,o,F.state))),i&&u===null)throw Error(n(528,""));return F}if(i&&u!==null)throw Error(n(529,""));return null;case"script":return i=o.async,o=o.src,typeof o=="string"&&i&&typeof i!="function"&&typeof i!="symbol"?(i=Ru(o),o=ea(p).hoistableScripts,u=o.get(i),u||(u={type:"script",instance:null,count:0,state:null},o.set(i,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(n(444,r))}}function Ou(r){return'href="'+Sn(r)+'"'}function rf(r){return'link[rel="stylesheet"]['+r+"]"}function bB(r){return y({},r,{"data-precedence":r.precedence,precedence:null})}function Y3(r,i,o,u){r.querySelector('link[rel="preload"][as="style"]['+i+"]")?u.loading=1:(i=r.createElement("link"),u.preload=i,i.addEventListener("load",function(){return u.loading|=1}),i.addEventListener("error",function(){return u.loading|=2}),Ir(i,"link",o),yn(i),r.head.appendChild(i))}function Ru(r){return'[src="'+Sn(r)+'"]'}function af(r){return"script[async]"+r}function EB(r,i,o){if(i.count++,i.instance===null)switch(i.type){case"style":var u=r.querySelector('style[data-href~="'+Sn(o.href)+'"]');if(u)return i.instance=u,yn(u),u;var p=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return u=(r.ownerDocument||r).createElement("style"),yn(u),Ir(u,"style",p),eg(u,o.precedence,r),i.instance=u;case"stylesheet":p=Ou(o.href);var w=r.querySelector(rf(p));if(w)return i.state.loading|=4,i.instance=w,yn(w),w;u=bB(o),(p=pa.get(p))&&Im(u,p),w=(r.ownerDocument||r).createElement("link"),yn(w);var F=w;return F._p=new Promise(function(j,fe){F.onload=j,F.onerror=fe}),Ir(w,"link",u),i.state.loading|=4,eg(w,o.precedence,r),i.instance=w;case"script":return w=Ru(o.src),(p=r.querySelector(af(w)))?(i.instance=p,yn(p),p):(u=o,(p=pa.get(w))&&(u=y({},o),Fm(u,p)),r=r.ownerDocument||r,p=r.createElement("script"),yn(p),Ir(p,"link",u),r.head.appendChild(p),i.instance=p);case"void":return null;default:throw Error(n(443,i.type))}else i.type==="stylesheet"&&(i.state.loading&4)===0&&(u=i.instance,i.state.loading|=4,eg(u,o.precedence,r));return i.instance}function eg(r,i,o){for(var u=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=u.length?u[u.length-1]:null,w=p,F=0;F title"):null)}function X3(r,i,o){if(o===1||i.itemProp!=null)return!1;switch(r){case"meta":case"title":return!0;case"style":if(typeof i.precedence!="string"||typeof i.href!="string"||i.href==="")break;return!0;case"link":if(typeof i.rel!="string"||typeof i.href!="string"||i.href===""||i.onLoad||i.onError)break;switch(i.rel){case"stylesheet":return r=i.disabled,typeof i.precedence=="string"&&r==null;default:return!0}case"script":if(i.async&&typeof i.async!="function"&&typeof i.async!="symbol"&&!i.onLoad&&!i.onError&&i.src&&typeof i.src=="string")return!0}return!1}function UB(r){return!(r.type==="stylesheet"&&(r.state.loading&3)===0)}function J3(r,i,o,u){if(o.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var p=Ou(u.href),w=i.querySelector(rf(p));if(w){i=w._p,i!==null&&typeof i=="object"&&typeof i.then=="function"&&(r.count++,r=Ag.bind(r),i.then(r,r)),o.state.loading|=4,o.instance=w,yn(w);return}w=i.ownerDocument||i,u=bB(u),(p=pa.get(p))&&Im(u,p),w=w.createElement("link"),yn(w);var F=w;F._p=new Promise(function(j,fe){F.onload=j,F.onerror=fe}),Ir(w,"link",u),o.instance=w}r.stylesheets===null&&(r.stylesheets=new Map),r.stylesheets.set(o,i),(i=o.state.preload)&&(o.state.loading&3)===0&&(r.count++,o=Ag.bind(r),i.addEventListener("load",o),i.addEventListener("error",o))}}var Tm=0;function W3(r,i){return r.stylesheets&&r.count===0&&rg(r,r.stylesheets),0Tm?50:800)+i);return r.unsuspend=o,function(){r.unsuspend=null,clearTimeout(u),clearTimeout(p)}}:null}function Ag(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)rg(this,this.stylesheets);else if(this.unsuspend){var r=this.unsuspend;this.unsuspend=null,r()}}}var ng=null;function rg(r,i){r.stylesheets=null,r.unsuspend!==null&&(r.count++,ng=new Map,i.forEach(Z3,r),ng=null,Ag.call(r))}function Z3(r,i){if(!(i.state.loading&4)){var o=ng.get(r);if(o)var u=o.get(null);else{o=new Map,ng.set(r,o);for(var p=r.querySelectorAll("link[data-precedence],style[data-precedence]"),w=0;w"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(A)}catch(e){console.error(e)}}return A(),Dm.exports=dI(),Dm.exports}var pI=gI();const mI="msal.js.common",XE="https://login.microsoftonline.com/common/",wI="login.microsoftonline.com",JE="common",vI="adfs",yI="dstsv2",BI=`${XE}discovery/instance?api-version=1.1&authorization_endpoint=`,WB=".ciamlogin.com",CI=".onmicrosoft.com",z1="|",WE="openid",ZE="profile",Jw="offline_access",bI="email",Ww="S256",EI="application/x-www-form-urlencoded;charset=utf-8",ff="Not Available",V1="/",ZB="http://169.254.169.254/metadata/instance/compute/location",xI="2020-06-01",SI=2e3,UI="TryAutoDetect",II="login.microsoft.com",FI=["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],$B=240,TI="invalid_instance",eC=200,_I=400,tC=400,NI=499,QI=500,LI=599,rh={GET:"GET",POST:"POST"},yh=[WE,ZE,Jw],AC=[...yh,bI],si={CONTENT_TYPE:"Content-Type",CONTENT_LENGTH:"Content-Length",RETRY_AFTER:"Retry-After",CCS_HEADER:"X-AnchorMailbox",WWWAuthenticate:"WWW-Authenticate",AuthenticationInfo:"Authentication-Info",X_MS_REQUEST_ID:"x-ms-request-id",X_MS_HTTP_VERSION:"x-ms-httpver"},nC={ACTIVE_ACCOUNT_FILTERS:"active-account-filters"},Tl={COMMON:"common",ORGANIZATIONS:"organizations",CONSUMERS:"consumers"},hg={ACCESS_TOKEN:"access_token",XMS_CC:"xms_cc"},Ii={LOGIN:"login",SELECT_ACCOUNT:"select_account",CONSENT:"consent",NONE:"none",NO_SESSION:"no_session"},Zw={CODE:"code",IDTOKEN_TOKEN_REFRESHTOKEN:"id_token token refresh_token"},$w={QUERY:"query",FRAGMENT:"fragment"},$E={AUTHORIZATION_CODE_GRANT:"authorization_code",REFRESH_TOKEN_GRANT:"refresh_token"},OI="MSSTS",RI="ADFS",ex="Generic",tx="-",q1=".",_r={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},e2="appmetadata",kI="client_info",gp="1",Y1="authority-metadata",HI=3600*24,es={CONFIG:"config",CACHE:"cache",NETWORK:"network",HARDCODED_VALUES:"hardcoded_values"},rC=5,DI=330,MI=50,Ax="server-telemetry",iC="|",Hu=",",PI="1",jI="0",KI="unknown_error",MA={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},GI=60,zI=3600,nx="throttling",VI="retry-after, h429",qI="invalid_grant",YI="client_mismatch",Du={FAILED_AUTO_DETECTION:"1",INTERNAL_CACHE:"2",ENVIRONMENT_VARIABLE:"3",IMDS:"4"},Km={CONFIGURED_NO_AUTO_DETECTION:"2",AUTO_DETECTION_REQUESTED_SUCCESSFUL:"4",AUTO_DETECTION_REQUESTED_FAILED:"5"},vc={NOT_APPLICABLE:"0",FORCE_REFRESH_OR_CLAIMS:"1",NO_CACHED_ACCESS_TOKEN:"2",CACHED_ACCESS_TOKEN_EXPIRED:"3",PROACTIVELY_REFRESHED:"4"},XI={Pop:"pop"},rx=300;const Oc="client_id",ix="redirect_uri",JI="response_type",WI="response_mode",ZI="grant_type",$I="claims",eF="scope",tF="refresh_token",AF="state",nF="nonce",rF="prompt",iF="code",aF="code_challenge",sF="code_challenge_method",oF="code_verifier",lF="client-request-id",cF="x-client-SKU",uF="x-client-VER",hF="x-client-OS",fF="x-client-CPU",dF="x-client-current-telemetry",gF="x-client-last-telemetry",pF="x-ms-lib-capability",mF="x-app-name",wF="x-app-ver",vF="post_logout_redirect_uri",yF="id_token_hint",BF="client_secret",CF="client_assertion",bF="client_assertion_type",ax="token_type",sx="req_cnf",aC="return_spa_code",EF="nativebroker",xF="logout_hint",SF="sid",UF="login_hint",IF="domain_hint",FF="x-client-xtra-sku",pp="brk_client_id",mp="brk_redirect_uri",X1="instance_aware",TF="ear_jwk",_F="ear_jwe_crypto";function t2(A){return`See https://aka.ms/msal.js.errors#${A} for details`}class en extends Error{constructor(e,t,n){const a=t||(e?t2(e):""),s=a?`${e}: ${a}`:e;super(s),Object.setPrototypeOf(this,en.prototype),this.errorCode=e||"",this.errorMessage=a||"",this.subError=n||"",this.name="AuthError"}setCorrelationId(e){this.correlationId=e}}function J1(A,e){return new en(A,e||t2(A))}class A2 extends en{constructor(e){super(e),this.name="ClientConfigurationError",Object.setPrototypeOf(this,A2.prototype)}}function An(A){return new A2(A)}class Ea{static isEmptyObj(e){if(e)try{const t=JSON.parse(e);return Object.keys(t).length===0}catch{}return!0}static startsWith(e,t){return e.indexOf(t)===0}static endsWith(e,t){return e.length>=t.length&&e.lastIndexOf(t)===e.length-t.length}static queryStringToObject(e){const t={},n=e.split("&"),a=s=>decodeURIComponent(s.replace(/\+/g," "));return n.forEach(s=>{if(s.trim()){const[l,c]=s.split(/=(.+)/g,2);l&&c&&(t[a(l)]=a(c))}}),t}static trimArrayEntries(e){return e.map(t=>t.trim())}static removeEmptyStringsFromArray(e){return e.filter(t=>!!t)}static jsonParseHelper(e){try{return JSON.parse(e)}catch{return null}}static matchPattern(e,t){return new RegExp(e.replace(/\\/g,"\\\\").replace(/\*/g,"[^ ]*").replace(/\?/g,"\\?")).test(t)}}class n2 extends en{constructor(e,t){super(e,t),this.name="ClientAuthError",Object.setPrototypeOf(this,n2.prototype)}}function tt(A,e){return new n2(A,e)}const NF="redirect_uri_empty",QF="authority_uri_insecure",fg="url_parse_error",LF="empty_url_error",OF="empty_input_scopes_error",ox="invalid_claims",RF="token_request_empty",kF="logout_request_empty",lx="pkce_params_missing",cx="invalid_cloud_discovery_metadata",HF="invalid_authority_metadata",DF="untrusted_authority",r2="missing_ssh_jwk",MF="missing_ssh_kid",PF="cannot_set_OIDCOptions",jF="cannot_allow_platform_broker",KF="authority_mismatch",GF="invalid_request_method_for_EAR";const ux="client_info_decoding_error",zF="client_info_empty_error",hx="token_parsing_error",VF="null_or_empty_token",pl="endpoints_resolution_error",qF="network_error",YF="openid_config_error",XF="hash_not_deserialized",Vf="invalid_state",JF="state_mismatch",sC="state_not_found",WF="nonce_mismatch",fx="auth_time_not_found",ZF="max_age_transpired",$F="multiple_matching_appMetadata",eT="request_cannot_be_made",tT="cannot_remove_empty_scope",AT="cannot_append_scopeset",oC="empty_input_scopeset",dx="no_account_in_silent_request",nT="invalid_cache_record",gx="invalid_cache_environment",lC="no_account_found",px="no_crypto_object",Ic="token_refresh_required",rT="token_claims_cnf_required_for_signedjwt",iT="authorization_code_missing_from_server_response",aT="binding_key_not_removed",sT="end_session_endpoint_not_supported",mx="key_id_missing",iA="method_not_implemented";class qr{constructor(e){const t=e?Ea.trimArrayEntries([...e]):[],n=t?Ea.removeEmptyStringsFromArray(t):[];if(!n||!n.length)throw An(OF);this.scopes=new Set,n.forEach(a=>this.scopes.add(a))}static fromString(e){const n=(e||"").split(" ");return new qr(n)}static createSearchScopes(e){const t=e&&e.length>0?e:[...yh],n=new qr(t);return n.containsOnlyOIDCScopes()?n.removeScope(Jw):n.removeOIDCScopes(),n}containsScope(e){const t=this.printScopesLowerCase().split(" "),n=new qr(t);return e?n.scopes.has(e.toLowerCase()):!1}containsScopeSet(e){return!e||e.scopes.size<=0?!1:this.scopes.size>=e.scopes.size&&e.asArray().every(t=>this.containsScope(t))}containsOnlyOIDCScopes(){let e=0;return AC.forEach(t=>{this.containsScope(t)&&(e+=1)}),this.scopes.size===e}appendScope(e){e&&this.scopes.add(e.trim())}appendScopes(e){try{e.forEach(t=>this.appendScope(t))}catch{throw tt(AT)}}removeScope(e){if(!e)throw tt(tT);this.scopes.delete(e.trim())}removeOIDCScopes(){AC.forEach(e=>{this.scopes.delete(e)})}unionScopeSets(e){if(!e)throw tt(oC);const t=new Set;return e.scopes.forEach(n=>t.add(n.toLowerCase())),this.scopes.forEach(n=>t.add(n.toLowerCase())),t}intersectingScopeSets(e){if(!e)throw tt(oC);e.containsOnlyOIDCScopes()||e.removeOIDCScopes();const t=this.unionScopeSets(e),n=e.getScopeCount(),a=this.getScopeCount();return t.sizee.push(t)),e}printScopes(){return this.scopes?this.asArray().join(" "):""}printScopesLowerCase(){return this.printScopes().toLowerCase()}}function Wp(A,e,t){if(!e)return;const n=A.get(Oc);n&&A.has(pp)&&t?.addFields({embeddedClientId:n,embeddedRedirectUri:A.get(ix)},e)}function i2(A,e){A.set(JI,e)}function oT(A,e){A.set(WI,e||$w.QUERY)}function lT(A){A.set(EF,"1")}function a2(A,e,t=!0,n=yh){t&&!n.includes("openid")&&!e.includes("openid")&&n.push("openid");const a=t?[...e||[],...n]:e||[],s=new qr(a);A.set(eF,s.printScopes())}function s2(A,e){A.set(Oc,e)}function o2(A,e){A.set(ix,e)}function cT(A,e){A.set(vF,e)}function uT(A,e){A.set(yF,e)}function hT(A,e){A.set(IF,e)}function dg(A,e){A.set(UF,e)}function wp(A,e){A.set(si.CCS_HEADER,`UPN:${e}`)}function _f(A,e){A.set(si.CCS_HEADER,`Oid:${e.uid}@${e.utid}`)}function cC(A,e){A.set(SF,e)}function l2(A,e,t){const n=wT(e,t);try{JSON.parse(n)}catch{throw An(ox)}A.set($I,n)}function c2(A,e){A.set(lF,e)}function u2(A,e){A.set(cF,e.sku),A.set(uF,e.version),e.os&&A.set(hF,e.os),e.cpu&&A.set(fF,e.cpu)}function h2(A,e){e?.appName&&A.set(mF,e.appName),e?.appVersion&&A.set(wF,e.appVersion)}function fT(A,e){A.set(rF,e)}function wx(A,e){e&&A.set(AF,e)}function dT(A,e){A.set(nF,e)}function f2(A,e,t){if(e&&t)A.set(aF,e),A.set(sF,t);else throw An(lx)}function gT(A,e){A.set(iF,e)}function pT(A,e){A.set(tF,e)}function mT(A,e){A.set(oF,e)}function vx(A,e){A.set(BF,e)}function yx(A,e){e&&A.set(CF,e)}function Bx(A,e){e&&A.set(bF,e)}function Cx(A,e){A.set(ZI,e)}function d2(A){A.set(kI,"1")}function bx(A){A.has(X1)||A.set(X1,"true")}function Ps(A,e){Object.entries(e).forEach(([t,n])=>{!A.has(t)&&n&&A.set(t,n)})}function wT(A,e){let t;if(!A)t={};else try{t=JSON.parse(A)}catch{throw An(ox)}return e&&e.length>0&&(t.hasOwnProperty(hg.ACCESS_TOKEN)||(t[hg.ACCESS_TOKEN]={}),t[hg.ACCESS_TOKEN][hg.XMS_CC]={values:e}),JSON.stringify(t)}function g2(A,e){e&&(A.set(ax,MA.POP),A.set(sx,e))}function Ex(A,e){e&&(A.set(ax,MA.SSH),A.set(sx,e))}function xx(A,e){A.set(dF,e.generateCurrentRequestHeaderValue()),A.set(gF,e.generateLastRequestHeaderValue())}function Sx(A){A.set(pF,VI)}function vT(A,e){A.set(xF,e)}function Zp(A,e,t){A.has(pp)||A.set(pp,e),A.has(mp)||A.set(mp,t)}function yT(A,e){A.set(TF,encodeURIComponent(e)),A.set(_F,"eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0")}function uC(A){if(!A)return A;let e=A.toLowerCase();return Ea.endsWith(e,"?")?e=e.slice(0,-1):Ea.endsWith(e,"?/")&&(e=e.slice(0,-2)),Ea.endsWith(e,"/")||(e+="/"),e}function Ux(A){return A.startsWith("#/")?A.substring(2):A.startsWith("#")||A.startsWith("?")?A.substring(1):A}function vp(A){if(!A||A.indexOf("=")<0)return null;try{const e=Ux(A),t=Object.fromEntries(new URLSearchParams(e));if(t.code||t.ear_jwe||t.error||t.error_description||t.state)return t}catch{throw tt(XF)}return null}function qf(A){const e=new Array;return A.forEach((t,n)=>{e.push(`${n}=${encodeURIComponent(t)}`)}),e.join("&")}function hC(A){if(!A)return A;const e=A.split("#")[0];try{const t=new URL(e),n=t.origin+t.pathname+t.search;return uC(n)}catch{return uC(e)}}const yp={createNewGuid:()=>{throw tt(iA)},base64Decode:()=>{throw tt(iA)},base64Encode:()=>{throw tt(iA)},base64UrlEncode:()=>{throw tt(iA)},encodeKid:()=>{throw tt(iA)},async getPublicKeyThumbprint(){throw tt(iA)},async removeTokenBindingKey(){throw tt(iA)},async clearKeystore(){throw tt(iA)},async signJwt(){throw tt(iA)},async hashString(){throw tt(iA)}};var vn;(function(A){A[A.Error=0]="Error",A[A.Warning=1]="Warning",A[A.Info=2]="Info",A[A.Verbose=3]="Verbose",A[A.Trace=4]="Trace"})(vn||(vn={}));const BT=50,CT=500,Bc=new Map;function bT(A,e){Bc.delete(A),Bc.set(A,e)}function ET(A,e){const t=Date.now();let n=Bc.get(A);if(n)bT(A,n);else if(n={logs:[],firstEventTime:t},Bc.set(A,n),Bc.size>BT){const a=Bc.keys().next().value;a&&Bc.delete(a)}n.logs.push({...e,milliseconds:t-n.firstEventTime}),n.logs.length>CT&&n.logs.shift()}function xT(A){if(A.length!==6)return!1;for(let e=0;e="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"))return!1}return!0}let Dl=class W1{constructor(e,t,n){this.level=vn.Info;const a=()=>{},s=e||W1.createDefaultLoggerOptions();this.localCallback=s.loggerCallback||a,this.piiLoggingEnabled=s.piiLoggingEnabled||!1,this.level=typeof s.logLevel=="number"?s.logLevel:vn.Info,this.packageName=t||"",this.packageVersion=n||""}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:vn.Info}}clone(e,t){return new W1({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level},e,t)}logMessage(e,t){const n=t.correlationId;if(xT(e)){const h={hash:e,level:t.logLevel,containsPii:t.containsPii||!1,milliseconds:0};ET(n,h)}if(t.logLevel>this.level||!this.piiLoggingEnabled&&t.containsPii)return;const c=`${`[${new Date().toUTCString()}] : [${n}]`} : ${this.packageName}@${this.packageVersion} : ${vn[t.logLevel]} - ${e}`;this.executeCallback(t.logLevel,c,t.containsPii||!1)}executeCallback(e,t,n){this.localCallback&&this.localCallback(e,t,n)}error(e,t){this.logMessage(e,{logLevel:vn.Error,containsPii:!1,correlationId:t})}errorPii(e,t){this.logMessage(e,{logLevel:vn.Error,containsPii:!0,correlationId:t})}warning(e,t){this.logMessage(e,{logLevel:vn.Warning,containsPii:!1,correlationId:t})}warningPii(e,t){this.logMessage(e,{logLevel:vn.Warning,containsPii:!0,correlationId:t})}info(e,t){this.logMessage(e,{logLevel:vn.Info,containsPii:!1,correlationId:t})}infoPii(e,t){this.logMessage(e,{logLevel:vn.Info,containsPii:!0,correlationId:t})}verbose(e,t){this.logMessage(e,{logLevel:vn.Verbose,containsPii:!1,correlationId:t})}verbosePii(e,t){this.logMessage(e,{logLevel:vn.Verbose,containsPii:!0,correlationId:t})}trace(e,t){this.logMessage(e,{logLevel:vn.Trace,containsPii:!1,correlationId:t})}tracePii(e,t){this.logMessage(e,{logLevel:vn.Trace,containsPii:!0,correlationId:t})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}};const $p="@azure/msal-common",ld="16.0.3";const p2={None:"none"};function fC(A,e){return!!A&&!!e&&A===e.split(".")[1]}function Bh(A,e,t,n){if(n){const{oid:a,sub:s,tid:l,name:c,tfp:h,acr:f,preferred_username:g,upn:y,login_hint:C}=n,v=l||h||f||"";return{tenantId:v,localAccountId:a||s||"",name:c,username:g||y||"",loginHint:C,isHomeTenant:fC(v,A)}}else return{tenantId:t,localAccountId:e,username:"",isHomeTenant:fC(t,A)}}function m2(A,e,t,n){let a=A;if(e){const{isHomeTenant:s,...l}=e;a={...A,...l}}if(t){const{isHomeTenant:s,...l}=Bh(A.homeAccountId,A.localAccountId,A.tenantId,t);return a={...a,...l,idTokenClaims:t,idToken:n},a}return a}function Uo(A,e){const t=ST(A);try{const n=e(t);return JSON.parse(n)}catch{throw tt(hx)}}function Fc(A){if(!A.signin_state)return!1;const e=["kmsi","dvc_dmjd"];return A.signin_state.some(t=>e.includes(t.trim().toLowerCase()))}function ST(A){if(!A)throw tt(VF);const t=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(A);if(!t||t.length<4)throw tt(hx);return t[2]}function Ix(A,e){if(e===0||Date.now()-3e5>A+e)throw tt(ZF)}class QA{get urlString(){return this._urlString}constructor(e){if(this._urlString=e,!this._urlString)throw An(LF);e.includes("#")||(this._urlString=QA.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return Ea.endsWith(t,"?")?t=t.slice(0,-1):Ea.endsWith(t,"?/")&&(t=t.slice(0,-2)),Ea.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch{throw An(fg)}if(!e.HostNameAndPort||!e.PathSegments)throw An(fg);if(!e.Protocol||e.Protocol.toLowerCase()!=="https:")throw An(QF)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return QA.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),n=t.PathSegments;return e&&n.length!==0&&(n[0]===Tl.COMMON||n[0]===Tl.ORGANIZATIONS)&&(n[0]=e),QA.constructAuthorityUriFromObject(t)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw An(fg);const n={Protocol:t[1],HostNameAndPort:t[4],AbsolutePath:t[5],QueryString:t[7]};let a=n.AbsolutePath.split("/");return a=a.filter(s=>s&&s.length>0),n.PathSegments=a,n.QueryString&&n.QueryString.endsWith("/")&&(n.QueryString=n.QueryString.substring(0,n.QueryString.length-1)),n}static getDomainFromUrl(e){const t=RegExp("^([^:/?#]+://)?([^/?#]*)"),n=e.match(t);if(!n)throw An(fg);return n[2]}static getAbsoluteUrl(e,t){if(e[0]===V1){const a=new QA(t).getUrlComponents();return a.Protocol+"//"+a.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e){return new QA(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"))}}const UT=[{host:"login.microsoftonline.com"},{host:"login.chinacloudapi.cn",issuerHost:"login.partner.microsoftonline.cn"},{host:"login.microsoftonline.us"},{host:"login.sovcloud-identity.fr"},{host:"login.sovcloud-identity.de"},{host:"login.sovcloud-identity.sg"}];function IT(A,e){return{token_endpoint:`https://${A}/{tenantid}/oauth2/v2.0/token`,jwks_uri:`https://${A}/{tenantid}/discovery/v2.0/keys`,issuer:`https://${e}/{tenantid}/v2.0`,authorization_endpoint:`https://${A}/{tenantid}/oauth2/v2.0/authorize`,end_session_endpoint:`https://${A}/{tenantid}/oauth2/v2.0/logout`}}const FT=UT.reduce((A,{host:e,issuerHost:t})=>(A[e]=IT(e,t||e),A),{}),Fx={endpointMetadata:FT,instanceDiscoveryMetadata:{metadata:[{preferred_network:"login.microsoftonline.com",preferred_cache:"login.windows.net",aliases:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"]},{preferred_network:"login.partner.microsoftonline.cn",preferred_cache:"login.partner.microsoftonline.cn",aliases:["login.partner.microsoftonline.cn","login.chinacloudapi.cn"]},{preferred_network:"login.microsoftonline.de",preferred_cache:"login.microsoftonline.de",aliases:["login.microsoftonline.de"]},{preferred_network:"login.microsoftonline.us",preferred_cache:"login.microsoftonline.us",aliases:["login.microsoftonline.us","login.usgovcloudapi.net"]},{preferred_network:"login-us.microsoftonline.com",preferred_cache:"login-us.microsoftonline.com",aliases:["login-us.microsoftonline.com"]}]}},dC=Fx.endpointMetadata,w2=Fx.instanceDiscoveryMetadata,Tx=new Set;w2.metadata.forEach(A=>{A.aliases.forEach(e=>{Tx.add(e)})});function TT(A,e,t){let n;const a=A.canonicalAuthority;if(a){const s=new QA(a).getUrlComponents().HostNameAndPort;n=gC(e,t,s,A.cloudDiscoveryMetadata?.metadata)||gC(e,t,s,w2.metadata)||A.knownAuthorities}return n||[]}function gC(A,e,t,n,a){if(A.trace("1bmquz",e),t&&n){const s=Bp(n,t);if(s)return A.trace("1fotbt",e),s.aliases;A.trace("14avvj",e)}return null}function _T(A){return Bp(w2.metadata,A)}function Bp(A,e){for(let t=0;t[t.tenantId,t])),dataBoundary:A.dataBoundary}}function QT(A,e,t){let n;e.authorityType===rs.Adfs?n=RI:e.protocolMode===Fi.OIDC?n=ex:n=OI;let a,s;A.clientInfo&&t&&(a=Cp(A.clientInfo,t),a.xms_tdbr&&(s=a.xms_tdbr==="EU"?"EU":"None"));const l=A.environment||e&&e.getPreferredCache();if(!l)throw tt(gx);const c=A.idTokenClaims?.preferred_username||A.idTokenClaims?.upn,h=A.idTokenClaims?.emails?A.idTokenClaims.emails[0]:null,f=c||h||"",g=A.idTokenClaims?.login_hint,y=a?.utid||v2(A.idTokenClaims)||"",C=a?.uid||A.idTokenClaims?.oid||A.idTokenClaims?.sub||"";let v;return A.tenantProfiles?v=A.tenantProfiles:v=[Bh(A.homeAccountId,C,y,A.idTokenClaims)],{homeAccountId:A.homeAccountId,environment:l,realm:y,localAccountId:C,username:f,authorityType:n,loginHint:g,clientInfo:A.clientInfo,name:A.idTokenClaims?.name||"",lastModificationTime:void 0,lastModificationApp:void 0,cloudGraphHostName:A.cloudGraphHostName,msGraphHost:A.msGraphHost,nativeAccountId:A.nativeAccountId,tenantProfiles:v,dataBoundary:s}}function LT(A,e,t){const n=Array.from(A.tenantProfiles?.values()||[]);return n.length===0&&A.tenantId&&A.localAccountId&&n.push(Bh(A.homeAccountId,A.localAccountId,A.tenantId,A.idTokenClaims)),{authorityType:A.authorityType||ex,homeAccountId:A.homeAccountId,localAccountId:A.localAccountId,nativeAccountId:A.nativeAccountId,realm:A.tenantId,environment:A.environment,username:A.username,loginHint:A.loginHint,name:A.name,cloudGraphHostName:e,msGraphHost:t,tenantProfiles:n,dataBoundary:A.dataBoundary}}function _x(A,e,t,n,a,s){if(!(e===rs.Adfs||e===rs.Dsts)){if(A)try{const l=Cp(A,n.base64Decode);if(l.uid&&l.utid)return`${l.uid}.${l.utid}`}catch{}t.warning("1ub6wv",a)}return s?.sub||""}function OT(A){return A?A.hasOwnProperty("homeAccountId")&&A.hasOwnProperty("environment")&&A.hasOwnProperty("realm")&&A.hasOwnProperty("localAccountId")&&A.hasOwnProperty("username")&&A.hasOwnProperty("authorityType"):!1}class ew{constructor(e,t,n,a,s){this.clientId=e,this.cryptoImpl=t,this.commonLogger=n.clone($p,ld),this.staticAuthorityOptions=s,this.performanceClient=a}getAllAccounts(e={},t){return this.buildTenantProfiles(this.getAccountsFilteredBy(e,t),t,e)}getAccountInfoFilteredBy(e,t){const n=this.getAllAccounts(e,t);return n.length>1?n.sort(s=>s.idTokenClaims?-1:1)[0]:n.length===1?n[0]:null}getBaseAccountInfo(e,t){const n=this.getAccountsFilteredBy(e,t);return n.length>0?Rc(n[0]):null}buildTenantProfiles(e,t,n){return e.flatMap(a=>this.getTenantProfilesFromAccountEntity(a,t,n?.tenantId,n))}getTenantedAccountInfoByFilter(e,t,n,a,s){let l=null,c;if(s&&!this.tenantProfileMatchesFilter(n,s))return null;const h=this.getIdToken(e,a,t,n.tenantId);return h&&(c=Uo(h.secret,this.cryptoImpl.base64Decode),!this.idTokenClaimsMatchTenantProfileFilter(c,s))?null:(l=m2(e,n,c,h?.secret),l)}getTenantProfilesFromAccountEntity(e,t,n,a){const s=Rc(e);let l=s.tenantProfiles||new Map;const c=this.getTokenKeys();if(n){const f=l.get(n);if(f)l=new Map([[n,f]]);else return[]}const h=[];return l.forEach(f=>{const g=this.getTenantedAccountInfoByFilter(s,c,f,t,a);g&&h.push(g)}),h}tenantProfileMatchesFilter(e,t){return!(t.localAccountId&&!this.matchLocalAccountIdFromTenantProfile(e,t.localAccountId)||t.name&&e.name!==t.name||t.isHomeTenant!==void 0&&e.isHomeTenant!==t.isHomeTenant)}idTokenClaimsMatchTenantProfileFilter(e,t){return!(t&&(t.localAccountId&&!this.matchLocalAccountIdFromTokenClaims(e,t.localAccountId)||t.loginHint&&!this.matchLoginHintFromTokenClaims(e,t.loginHint)||t.username&&!this.matchUsername(e.preferred_username,t.username)||t.name&&!this.matchName(e,t.name)||t.sid&&!this.matchSid(e,t.sid)))}async saveCacheRecord(e,t,n,a,s){if(!e)throw tt(nT);try{e.account&&await this.setAccount(e.account,t,n,a),e.idToken&&s?.idToken!==!1&&await this.setIdTokenCredential(e.idToken,t,n),e.accessToken&&s?.accessToken!==!1&&await this.saveAccessToken(e.accessToken,t,n),e.refreshToken&&s?.refreshToken!==!1&&await this.setRefreshTokenCredential(e.refreshToken,t,n),e.appMetadata&&this.setAppMetadata(e.appMetadata,t)}catch(l){throw this.commonLogger?.error("0j476p",t),l instanceof en?l:$1(l)}}async saveAccessToken(e,t,n){const a={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType},s=this.getTokenKeys(),l=qr.fromString(e.target);s.accessToken.forEach(c=>{if(!this.accessTokenKeyMatchesFilter(c,a,!1))return;const h=this.getAccessTokenCredential(c,t);h&&this.credentialMatchesFilter(h,a,t)&&qr.fromString(h.target).intersectingScopeSets(l)&&this.removeAccessToken(c,t)}),await this.setAccessTokenCredential(e,t,n)}getAccountsFilteredBy(e,t){const n=this.getAccountKeys(),a=[];return n.forEach(s=>{const l=this.getAccount(s,t);if(!l||e.homeAccountId&&!this.matchHomeAccountId(l,e.homeAccountId)||e.username&&!this.matchUsername(l.username,e.username)||e.environment&&!this.matchEnvironment(l,e.environment,t)||e.realm&&!this.matchRealm(l,e.realm)||e.nativeAccountId&&!this.matchNativeAccountId(l,e.nativeAccountId)||e.authorityType&&!this.matchAuthorityType(l,e.authorityType))return;const c={localAccountId:e?.localAccountId,name:e?.name},h=l.tenantProfiles?.filter(f=>this.tenantProfileMatchesFilter(f,c));h&&h.length===0||a.push(l)}),a}credentialMatchesFilter(e,t,n){return!(t.clientId&&!this.matchClientId(e,t.clientId)||t.userAssertionHash&&!this.matchUserAssertionHash(e,t.userAssertionHash)||typeof t.homeAccountId=="string"&&!this.matchHomeAccountId(e,t.homeAccountId)||t.environment&&!this.matchEnvironment(e,t.environment,n)||t.realm&&!this.matchRealm(e,t.realm)||t.credentialType&&!this.matchCredentialType(e,t.credentialType)||t.familyId&&!this.matchFamilyId(e,t.familyId)||t.target&&!this.matchTarget(e,t.target)||e.credentialType===_r.ACCESS_TOKEN_WITH_AUTH_SCHEME&&(t.tokenType&&!this.matchTokenType(e,t.tokenType)||t.tokenType===MA.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId)))}getAppMetadataFilteredBy(e,t){const n=this.getKeys(),a={};return n.forEach(s=>{if(!this.isAppMetadata(s))return;const l=this.getAppMetadata(s,t);l&&(e.environment&&!this.matchEnvironment(l,e.environment,t)||e.clientId&&!this.matchClientId(l,e.clientId)||(a[s]=l))}),a}getAuthorityMetadataByAlias(e,t){const n=this.getAuthorityMetadataKeys();let a=null;return n.forEach(s=>{if(!this.isAuthorityMetadata(s)||s.indexOf(this.clientId)===-1)return;const l=this.getAuthorityMetadata(s,t);l&&l.aliases.indexOf(e)!==-1&&(a=l)}),a}removeAllAccounts(e){this.getAllAccounts({},e).forEach(n=>{this.removeAccount(n,e)})}removeAccount(e,t){this.removeAccountContext(e,t);const n=this.getAccountKeys(),a=s=>s.includes(e.homeAccountId)&&s.includes(e.environment);n.filter(a).forEach(s=>{this.removeItem(s,t),this.performanceClient.incrementFields({accountsRemoved:1},t)})}removeAccountContext(e,t){const n=this.getTokenKeys(),a=s=>s.includes(e.homeAccountId)&&s.includes(e.environment);n.idToken.filter(a).forEach(s=>{this.removeIdToken(s,t)}),n.accessToken.filter(a).forEach(s=>{this.removeAccessToken(s,t)}),n.refreshToken.filter(a).forEach(s=>{this.removeRefreshToken(s,t)})}removeAccessToken(e,t){const n=this.getAccessTokenCredential(e,t);if(n&&(this.removeItem(e,t),this.performanceClient.incrementFields({accessTokensRemoved:1},t),n.credentialType.toLowerCase()===_r.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()&&n.tokenType===MA.POP)){const s=n.keyId;s&&this.cryptoImpl.removeTokenBindingKey(s,t).catch(()=>{this.commonLogger.error("0cx291",t),this.performanceClient?.incrementFields({removeTokenBindingKeyFailure:1},t)})}}removeAppMetadata(e){return this.getKeys().forEach(n=>{this.isAppMetadata(n)&&this.removeItem(n,e)}),!0}getIdToken(e,t,n,a){this.commonLogger.trace("1drz22",t);const s={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:_r.ID_TOKEN,clientId:this.clientId,realm:a},l=this.getIdTokensByFilter(s,t,n),c=l.size;if(c<1)return this.commonLogger.info("1atvtd",t),null;if(c>1){let h=l;if(!a){const f=new Map;l.forEach((y,C)=>{y.realm===e.tenantId&&f.set(C,y)});const g=f.size;if(g<1)return this.commonLogger.info("0ooalx",t),l.values().next().value;if(g===1)return this.commonLogger.info("1eq2vc",t),f.values().next().value;h=f}return this.commonLogger.info("1ws328",t),h.forEach((f,g)=>{this.removeIdToken(g,t)}),this.performanceClient.addFields({multiMatchedID:l.size},t),null}return this.commonLogger.info("1sm769",t),l.values().next().value}getIdTokensByFilter(e,t,n){const a=n&&n.idToken||this.getTokenKeys().idToken,s=new Map;return a.forEach(l=>{if(!this.idTokenKeyMatchesFilter(l,{clientId:this.clientId,...e}))return;const c=this.getIdTokenCredential(l,t);c&&this.credentialMatchesFilter(c,e,t)&&s.set(l,c)}),s}idTokenKeyMatchesFilter(e,t){const n=e.toLowerCase();return!(t.clientId&&n.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&n.indexOf(t.homeAccountId.toLowerCase())===-1)}removeIdToken(e,t){this.removeItem(e,t)}removeRefreshToken(e,t){this.removeItem(e,t)}getAccessToken(e,t,n,a){const s=t.correlationId;this.commonLogger.trace("1t7hz1",s);const l=qr.createSearchScopes(t.scopes),c=t.authenticationScheme||MA.BEARER,h=c.toLowerCase()!==MA.BEARER.toLowerCase()?_r.ACCESS_TOKEN_WITH_AUTH_SCHEME:_r.ACCESS_TOKEN,f={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:h,clientId:this.clientId,realm:a||e.tenantId,target:l,tokenType:c,keyId:t.sshKid},g=n&&n.accessToken||this.getTokenKeys().accessToken,y=[];g.forEach(v=>{if(this.accessTokenKeyMatchesFilter(v,f,!0)){const I=this.getAccessTokenCredential(v,s);I&&this.credentialMatchesFilter(I,f,s)&&y.push(I)}});const C=y.length;return C<1?(this.commonLogger.info("1nckna",s),null):C>1?(this.commonLogger.info("1wkfwp",s),y.forEach(v=>{this.removeAccessToken(this.generateCredentialKey(v),s)}),this.performanceClient.addFields({multiMatchedAT:y.length},s),null):(this.commonLogger.info("06yt98",s),y[0])}accessTokenKeyMatchesFilter(e,t,n){const a=e.toLowerCase();if(t.clientId&&a.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&a.indexOf(t.homeAccountId.toLowerCase())===-1||t.realm&&a.indexOf(t.realm.toLowerCase())===-1)return!1;if(t.target){const s=t.target.asArray();for(let l=0;l{if(!this.accessTokenKeyMatchesFilter(s,e,!0))return;const l=this.getAccessTokenCredential(s,t);l&&this.credentialMatchesFilter(l,e,t)&&a.push(l)}),a}getRefreshToken(e,t,n,a){this.commonLogger.trace("0x53vi",n);const s=t?gp:void 0,l={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:_r.REFRESH_TOKEN,clientId:this.clientId,familyId:s},c=a&&a.refreshToken||this.getTokenKeys().refreshToken,h=[];c.forEach(g=>{if(this.refreshTokenKeyMatchesFilter(g,l)){const y=this.getRefreshTokenCredential(g,n);y&&this.credentialMatchesFilter(y,l,n)&&h.push(y)}});const f=h.length;return f<1?(this.commonLogger.info("0dlw11",n),null):(f>1&&this.performanceClient.addFields({multiMatchedRT:f},n),this.commonLogger.info("0wcnep",n),h[0])}refreshTokenKeyMatchesFilter(e,t){const n=e.toLowerCase();return!(t.familyId&&n.indexOf(t.familyId.toLowerCase())===-1||!t.familyId&&t.clientId&&n.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&n.indexOf(t.homeAccountId.toLowerCase())===-1)}readAppMetadataFromCache(e,t){const n={environment:e,clientId:this.clientId},a=this.getAppMetadataFilteredBy(n,t),s=Object.keys(a).map(c=>a[c]),l=s.length;if(l<1)return null;if(l>1)throw tt($F);return s[0]}isAppMetadataFOCI(e,t){const n=this.readAppMetadataFromCache(e,t);return!!(n&&n.familyId===gp)}matchHomeAccountId(e,t){return typeof e.homeAccountId=="string"&&t===e.homeAccountId}matchLocalAccountIdFromTokenClaims(e,t){const n=e.oid||e.sub;return t===n}matchLocalAccountIdFromTenantProfile(e,t){return e.localAccountId===t}matchName(e,t){return t.toLowerCase()===e.name?.toLowerCase()}matchUsername(e,t){return!!(e&&typeof e=="string"&&t?.toLowerCase()===e.toLowerCase())}matchUserAssertionHash(e,t){return!!(e.userAssertionHash&&t===e.userAssertionHash)}matchEnvironment(e,t,n){if(this.staticAuthorityOptions){const s=TT(this.staticAuthorityOptions,this.commonLogger,n);if(s.includes(t)&&s.includes(e.environment))return!0}const a=this.getAuthorityMetadataByAlias(t,n);return!!(a&&a.aliases.indexOf(e.environment)>-1)}matchCredentialType(e,t){return e.credentialType&&t.toLowerCase()===e.credentialType.toLowerCase()}matchClientId(e,t){return!!(e.clientId&&t===e.clientId)}matchFamilyId(e,t){return!!(e.familyId&&t===e.familyId)}matchRealm(e,t){return e.realm?.toLowerCase()===t.toLowerCase()}matchNativeAccountId(e,t){return!!(e.nativeAccountId&&t===e.nativeAccountId)}matchLoginHintFromTokenClaims(e,t){return e.login_hint===t||e.preferred_username===t||e.upn===t}matchSid(e,t){return e.sid===t}matchAuthorityType(e,t){return!!(e.authorityType&&t.toLowerCase()===e.authorityType.toLowerCase())}matchTarget(e,t){return e.credentialType!==_r.ACCESS_TOKEN&&e.credentialType!==_r.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target?!1:qr.fromString(e.target).containsScopeSet(t)}matchTokenType(e,t){return!!(e.tokenType&&e.tokenType===t)}matchKeyId(e,t){return!!(e.keyId&&e.keyId===t)}isAppMetadata(e){return e.indexOf(e2)!==-1}isAuthorityMetadata(e){return e.indexOf(Y1)!==-1}generateAuthorityMetadataCacheKey(e){return`${Y1}-${this.clientId}-${e}`}static toObject(e,t){for(const n in t)e[n]=t[n];return e}}class RT extends ew{async setAccount(){throw tt(iA)}getAccount(){throw tt(iA)}async setIdTokenCredential(){throw tt(iA)}getIdTokenCredential(){throw tt(iA)}async setAccessTokenCredential(){throw tt(iA)}getAccessTokenCredential(){throw tt(iA)}async setRefreshTokenCredential(){throw tt(iA)}getRefreshTokenCredential(){throw tt(iA)}setAppMetadata(){throw tt(iA)}getAppMetadata(){throw tt(iA)}setServerTelemetry(){throw tt(iA)}getServerTelemetry(){throw tt(iA)}setAuthorityMetadata(){throw tt(iA)}getAuthorityMetadata(){throw tt(iA)}getAuthorityMetadataKeys(){throw tt(iA)}setThrottlingCache(){throw tt(iA)}getThrottlingCache(){throw tt(iA)}removeItem(){throw tt(iA)}getKeys(){throw tt(iA)}getAccountKeys(){throw tt(iA)}getTokenKeys(){throw tt(iA)}generateCredentialKey(){throw tt(iA)}generateAccountKey(){throw tt(iA)}}const kT={InProgress:1};class Nx{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:kT.InProgress,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""}}}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}incrementFields(){}cacheEventByCorrelationId(){}}const Qx={tokenRenewalOffsetSeconds:rx,preventCorsPreflight:!1},HT={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:vn.Info,correlationId:""},DT={async sendGetRequestAsync(){throw tt(iA)},async sendPostRequestAsync(){throw tt(iA)}},MT={sku:mI,version:ld,cpu:"",os:""},PT={clientSecret:"",clientAssertion:void 0},jT={azureCloudInstance:p2.None,tenant:`${JE}`},KT={application:{appName:"",appVersion:""}};function y2({authOptions:A,systemOptions:e,loggerOptions:t,storageInterface:n,networkInterface:a,cryptoInterface:s,clientCredentials:l,libraryInfo:c,telemetry:h,serverTelemetryManager:f,persistencePlugin:g,serializableCache:y}){const C={...HT,...t};return{authOptions:GT(A),systemOptions:{...Qx,...e},loggerOptions:C,storageInterface:n||new RT(A.clientId,yp,new Dl(C),new Nx),networkInterface:a||DT,cryptoInterface:s||yp,clientCredentials:l||PT,libraryInfo:{...MT,...c},telemetry:{...KT,...h},serverTelemetryManager:f||null,persistencePlugin:g||null,serializableCache:y||null}}function GT(A){return{clientCapabilities:[],azureCloudOptions:jT,instanceAware:!1,...A}}function Lx(A){return A.authOptions.authority.options.protocolMode===Fi.OIDC}class zc extends en{constructor(e,t,n,a,s){super(e,t,n),this.name="ServerError",this.errorNo=a,this.status=s,Object.setPrototypeOf(this,zc.prototype)}}const tw="no_tokens_found",zT="native_account_unavailable",Ox="refresh_token_expired",Rx="ux_not_allowed",VT="interaction_required",qT="consent_required",YT="login_required",B2="bad_token";const pC=[VT,qT,YT,B2,Rx],XT=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token","ux_not_allowed"];class os extends en{constructor(e,t,n,a,s,l,c,h){super(e,t,n),Object.setPrototypeOf(this,os.prototype),this.timestamp=a||"",this.traceId=s||"",this.correlationId=l||"",this.claims=c||"",this.name="InteractionRequiredAuthError",this.errorNo=h}}function kx(A,e,t){const n=!!A&&pC.indexOf(A)>-1,a=!!t&&XT.indexOf(t)>-1,s=!!e&&pC.some(l=>e.indexOf(l)>-1);return n||s||a}function bp(A,e){return new os(A,e)}function JT(A,e,t){const n=WT(A,t);return e?`${n}${z1}${e}`:n}function WT(A,e){if(!A)throw tt(px);const t={id:A.createNewGuid()};e&&(t.meta=e);const n=JSON.stringify(t);return A.base64Encode(n)}function cd(A,e){if(!A)throw tt(px);if(!e)throw tt(Vf);try{const t=e.split(z1),n=t[0],a=t.length>1?t.slice(1).join(z1):"",s=A(n),l=JSON.parse(s);return{userRequestState:a||"",libraryState:l}}catch{throw tt(Vf)}}function ls(){return Math.round(new Date().getTime()/1e3)}function mC(A){return A.getTime()/1e3}function Zg(A){return A?new Date(Number(A)*1e3):new Date}function Ep(A,e){const t=Number(A)||0;return ls()+e>t}function wC(A,e){const t=Number(A)+e*24*60*60*1e3;return Date.now()>t}function ZT(A){return Number(A)>ls()}const $T="networkClientSendPostRequestAsync",e_="refreshTokenClientExecutePostToTokenEndpoint",t_="authorizationCodeClientExecutePostToTokenEndpoint",A_="refreshTokenClientExecuteTokenRequest",n_="refreshTokenClientAcquireToken",Gm="refreshTokenClientAcquireTokenWithCachedRefreshToken",r_="refreshTokenClientCreateTokenRequestBody",i_="silentFlowClientGenerateResultFromCacheRecord",C2="getAuthCodeUrl",Hx="handleCodeResponseFromServer",a_="authClientExecuteTokenRequest",s_="authClientCreateTokenRequestBody",o_="updateTokenEndpointAuthority",ud="popTokenGenerateCnf",b2="handleServerTokenResponse",l_="authorityResolveEndpointsAsync",c_="authorityGetCloudDiscoveryMetadataFromNetwork",u_="authorityUpdateCloudDiscoveryMetadata",h_="authorityGetEndpointMetadataFromNetwork",f_="authorityUpdateEndpointMetadata",vC="authorityUpdateMetadataWithRegionalInformation",d_="regionDiscoveryDetectRegion",yC="regionDiscoveryGetRegionFromIMDS",g_="regionDiscoveryGetCurrentVersion",p_="cacheManagerGetRefreshToken",m_="setUserData";const as=(A,e,t,n,a)=>(...s)=>{t.trace("1plfzx",a);const l=n.startMeasurement(e,a);if(a){const c=e+"CallCount";n.incrementFields({[c]:1},a)}try{const c=A(...s);return l.end({success:!0}),t.trace("1g8n6a",a),c}catch(c){t.trace("0cfd8i",a);try{t.trace(JSON.stringify(c),a)}catch{t.trace("00dty7",a)}throw l.end({success:!1},c),c}},Ke=(A,e,t,n,a)=>(...s)=>{t.trace("1plfzx",a);const l=n.startMeasurement(e,a);if(a){const c=e+"CallCount";n.incrementFields({[c]:1},a)}return A(...s).then(c=>(t.trace("1g8n6a",a),l.end({success:!0}),c)).catch(c=>{t.trace("0cfd8i",a);try{t.trace(JSON.stringify(c),a)}catch{t.trace("00dty7",a)}throw l.end({success:!1},c),c})};const w_={SW:"sw"};class mh{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){const n=await Ke(this.generateKid.bind(this),ud,t,this.performanceClient,e.correlationId)(e),a=this.cryptoUtils.base64UrlEncode(JSON.stringify(n));return{kid:n.kid,reqCnfString:a}}async generateKid(e){return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:w_.SW}}async signPopToken(e,t,n){return this.signPayload(e,t,n)}async signPayload(e,t,n,a){const{resourceRequestMethod:s,resourceRequestUri:l,shrClaims:c,shrNonce:h,shrOptions:f}=n,y=(l?new QA(l):void 0)?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:ls(),m:s?.toUpperCase(),u:y?.HostNameAndPort,nonce:h||this.cryptoUtils.createNewGuid(),p:y?.AbsolutePath,q:y?.QueryString?[[],y.QueryString]:void 0,client_claims:c||void 0,...a},t,f,n.correlationId)}}class v_{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}function E2(A,e,t,n,a){return{credentialType:_r.ID_TOKEN,homeAccountId:A,environment:e,clientId:n,secret:t,realm:a,lastUpdatedAt:Date.now().toString()}}function x2(A,e,t,n,a,s,l,c,h,f,g,y,C){const v={homeAccountId:A,credentialType:_r.ACCESS_TOKEN,secret:t,cachedAt:ls().toString(),expiresOn:l.toString(),extendedExpiresOn:c.toString(),environment:e,clientId:n,realm:a,target:s,tokenType:g||MA.BEARER,lastUpdatedAt:Date.now().toString()};if(y&&(v.userAssertionHash=y),f&&(v.refreshOn=f.toString()),v.tokenType?.toLowerCase()!==MA.BEARER.toLowerCase())switch(v.credentialType=_r.ACCESS_TOKEN_WITH_AUTH_SCHEME,v.tokenType){case MA.POP:const I=Uo(t,h);if(!I?.cnf?.kid)throw tt(rT);v.keyId=I.cnf.kid;break;case MA.SSH:v.keyId=C}return v}function y_(A,e,t,n,a,s,l){const c={credentialType:_r.REFRESH_TOKEN,homeAccountId:A,environment:e,clientId:n,secret:t,lastUpdatedAt:Date.now().toString()};return s&&(c.userAssertionHash=s),a&&(c.familyId=a),l&&(c.expiresOn=l.toString()),c}function e0(A){return A.hasOwnProperty("homeAccountId")&&A.hasOwnProperty("environment")&&A.hasOwnProperty("credentialType")&&A.hasOwnProperty("clientId")&&A.hasOwnProperty("secret")}function BC(A){return A?e0(A)&&A.hasOwnProperty("realm")&&A.hasOwnProperty("target")&&(A.credentialType===_r.ACCESS_TOKEN||A.credentialType===_r.ACCESS_TOKEN_WITH_AUTH_SCHEME):!1}function B_(A){return A?e0(A)&&A.hasOwnProperty("realm")&&A.credentialType===_r.ID_TOKEN:!1}function CC(A){return A?e0(A)&&A.credentialType===_r.REFRESH_TOKEN:!1}function C_(A,e){const t=A.indexOf(Ax)===0;let n=!0;return e&&(n=e.hasOwnProperty("failedRequests")&&e.hasOwnProperty("errors")&&e.hasOwnProperty("cacheHits")),t&&n}function b_(A,e){let t=!1;A&&(t=A.indexOf(nx)===0);let n=!0;return e&&(n=e.hasOwnProperty("throttleTime")),t&&n}function E_({environment:A,clientId:e}){return[e2,A,e].join(tx).toLowerCase()}function x_(A,e){return e?A.indexOf(e2)===0&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("environment"):!1}function S_(A,e){return e?A.indexOf(Y1)===0&&e.hasOwnProperty("aliases")&&e.hasOwnProperty("preferred_cache")&&e.hasOwnProperty("preferred_network")&&e.hasOwnProperty("canonical_authority")&&e.hasOwnProperty("authorization_endpoint")&&e.hasOwnProperty("token_endpoint")&&e.hasOwnProperty("issuer")&&e.hasOwnProperty("aliasesFromNetwork")&&e.hasOwnProperty("endpointsFromNetwork")&&e.hasOwnProperty("expiresAt")&&e.hasOwnProperty("jwks_uri"):!1}function bC(){return ls()+HI}function gg(A,e,t){A.authorization_endpoint=e.authorization_endpoint,A.token_endpoint=e.token_endpoint,A.end_session_endpoint=e.end_session_endpoint,A.issuer=e.issuer,A.endpointsFromNetwork=t,A.jwks_uri=e.jwks_uri}function zm(A,e,t){A.aliases=e.aliases,A.preferred_cache=e.preferred_cache,A.preferred_network=e.preferred_network,A.aliasesFromNetwork=t}function EC(A){return A.expiresAt<=ls()}class kc{constructor(e,t,n,a,s,l,c){this.clientId=e,this.cacheStorage=t,this.cryptoObj=n,this.logger=a,this.performanceClient=s,this.serializableCache=l,this.persistencePlugin=c}validateTokenResponse(e,t,n){if(e.error||e.error_description||e.suberror){const a=`Error(s): ${e.error_codes||ff} - Timestamp: ${e.timestamp||ff} - Description: ${e.error_description||ff} - Correlation ID: ${e.correlation_id||ff} - Trace ID: ${e.trace_id||ff}`,s=e.error_codes?.length?e.error_codes[0]:void 0,l=new zc(e.error,a,e.suberror,s,e.status);if(n&&e.status&&e.status>=QI&&e.status<=LI){this.logger.warning("16ks7j",t);return}else if(n&&e.status&&e.status>=_I&&e.status<=NI){this.logger.warning("0g61x3",t);return}throw kx(e.error,e.error_description,e.suberror)?new os(e.error,e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.correlation_id||"",e.claims||"",s):l}}async handleServerTokenResponse(e,t,n,a,s,l,c,h,f,g){let y;if(e.id_token){if(y=Uo(e.id_token||"",this.cryptoObj.base64Decode),l&&l.nonce&&y.nonce!==l.nonce)throw tt(WF);if(a.maxAge||a.maxAge===0){const x=y.auth_time;if(!x)throw tt(fx);Ix(x,a.maxAge)}}this.homeAccountIdentifier=_x(e.client_info||"",t.authorityType,this.logger,this.cryptoObj,a.correlationId,y);let C;l&&l.state&&(C=cd(this.cryptoObj.base64Decode,l.state)),e.key_id=e.key_id||a.sshKid||void 0;const v=this.generateCacheRecord(e,t,n,a,y,c,l);let I;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("0jbz5k",a.correlationId),I=new v_(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(I)),h&&!f&&v.account&&this.cacheStorage.getAllAccounts({homeAccountId:v.account.homeAccountId,environment:v.account.environment},a.correlationId).length<1)return this.logger.warning("1gmt66",a.correlationId),this.performanceClient?.addFields({acntLoggedOut:!0},a.correlationId),await kc.generateAuthenticationResult(this.cryptoObj,t,v,!1,a,this.performanceClient,y,C,void 0,g);await this.cacheStorage.saveCacheRecord(v,a.correlationId,Fc(y||{}),s,a.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&I&&(this.logger.verbose("1bh17u",a.correlationId),await this.persistencePlugin.afterCacheAccess(I))}return kc.generateAuthenticationResult(this.cryptoObj,t,v,!1,a,this.performanceClient,y,C,e,g)}generateCacheRecord(e,t,n,a,s,l,c){const h=t.getPreferredCache();if(!h)throw tt(gx);const f=v2(s);let g,y;e.id_token&&s&&(g=E2(this.homeAccountIdentifier,h,e.id_token,this.clientId,f||""),y=Dx(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,a.correlationId,s,e.client_info,h,f,c,void 0,this.logger));let C=null;if(e.access_token){const x=e.scope?qr.fromString(e.scope):new qr(a.scopes||[]),_=(typeof e.expires_in=="string"?parseInt(e.expires_in,10):e.expires_in)||0,T=(typeof e.ext_expires_in=="string"?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,k=(typeof e.refresh_in=="string"?parseInt(e.refresh_in,10):e.refresh_in)||void 0,z=n+_,H=z+T,re=k&&k>0?n+k:void 0;C=x2(this.homeAccountIdentifier,h,e.access_token,this.clientId,f||t.tenant||"",x.printScopes(),z,H,this.cryptoObj.base64Decode,re,e.token_type,l,e.key_id)}let v=null;if(e.refresh_token){let x;if(e.refresh_token_expires_in){const _=typeof e.refresh_token_expires_in=="string"?parseInt(e.refresh_token_expires_in,10):e.refresh_token_expires_in;x=n+_,this.performanceClient?.addFields({ntwkRtExpiresOnSeconds:x},a.correlationId)}v=y_(this.homeAccountIdentifier,h,e.refresh_token,this.clientId,e.foci,l,x)}let I=null;return e.foci&&(I={clientId:this.clientId,environment:h,familyId:e.foci}),{account:y,idToken:g,accessToken:C,refreshToken:v,appMetadata:I}}static async generateAuthenticationResult(e,t,n,a,s,l,c,h,f,g){let y="",C=[],v=null,I,x,_="";if(n.accessToken){if(n.accessToken.tokenType===MA.POP&&!s.popKid){const H=new mh(e,l),{secret:re,keyId:le}=n.accessToken;if(!le)throw tt(mx);y=await H.signPopToken(re,le,s)}else y=n.accessToken.secret;C=qr.fromString(n.accessToken.target).asArray(),v=Zg(n.accessToken.expiresOn),I=Zg(n.accessToken.extendedExpiresOn),n.accessToken.refreshOn&&(x=Zg(n.accessToken.refreshOn))}n.appMetadata&&(_=n.appMetadata.familyId===gp?gp:"");const T=c?.oid||c?.sub||"",k=c?.tid||"";f?.spa_accountid&&n.account&&(n.account.nativeAccountId=f?.spa_accountid);const z=n.account?m2(Rc(n.account),void 0,c,n.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:T,tenantId:k,scopes:C,account:z,idToken:n?.idToken?.secret||"",idTokenClaims:c||{},accessToken:y,fromCache:a,expiresOn:v,extExpiresOn:I,refreshOn:x,correlationId:s.correlationId,requestId:g||"",familyId:_,tokenType:n.accessToken?.tokenType||"",state:h?h.userRequestState:"",cloudGraphHostName:n.account?.cloudGraphHostName||"",msGraphHost:n.account?.msGraphHost||"",code:f?.spa_code,fromPlatformBroker:!1}}}function Dx(A,e,t,n,a,s,l,c,h,f,g,y){y?.verbose("09jz0t",a);const v=A.getAccountKeys().find(k=>k.startsWith(t));let I=null;v&&(I=A.getAccount(v,a));const x=I||QT({homeAccountId:t,idTokenClaims:s,clientInfo:l,environment:c,cloudGraphHostName:f?.cloud_graph_host_name,msGraphHost:f?.msgraph_host,nativeAccountId:g},e,n),_=x.tenantProfiles||[],T=h||x.realm;if(T&&!_.find(k=>k.tenantId===T)){const k=Bh(t,x.localAccountId,T,s);_.push(k)}return x.tenantProfiles=_,x}const is={HOME_ACCOUNT_ID:"home_account_id",UPN:"UPN"};async function Mx(A,e,t){return typeof A=="string"?A:A({clientId:e,tokenEndpoint:t})}function t0(A,e,t){return{clientId:A,authority:e.authority,scopes:e.scopes,homeAccountIdentifier:t,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid,embeddedClientId:e.embeddedClientId||e.extraParameters?.clientId}}class ks{static generateThrottlingStorageKey(e){return`${nx}.${JSON.stringify(e)}`}static preProcess(e,t,n){const a=ks.generateThrottlingStorageKey(t),s=e.getThrottlingCache(a,n);if(s){if(s.throttleTime=500&&e.status<600}static checkResponseForRetryAfter(e){return e.headers?e.headers.hasOwnProperty(si.RETRY_AFTER)&&(e.status<200||e.status>=300):!1}static calculateThrottleTime(e){const t=e<=0?0:e,n=Date.now()/1e3;return Math.floor(Math.min(n+(t||GI),n+zI)*1e3)}static removeThrottle(e,t,n,a){const s=t0(t,n,a),l=this.generateThrottlingStorageKey(s);e.removeItem(l,n.correlationId)}}class A0 extends en{constructor(e,t,n){super(e.errorCode,e.errorMessage,e.subError),Object.setPrototypeOf(this,A0.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=n}}function Cf(A,e,t,n){return A.errorMessage=`${A.errorMessage}, additionalErrorInfo: error.name:${n?.name}, error.message:${n?.message}`,new A0(A,e,t)}function Px(A,e,t){const n={};if(n[si.CONTENT_TYPE]=EI,!e&&t)switch(t.type){case is.HOME_ACCOUNT_ID:try{const a=ah(t.credential);n[si.CCS_HEADER]=`Oid:${a.uid}@${a.utid}`}catch{A.verbose("1qhtee","")}break;case is.UPN:n[si.CCS_HEADER]=`UPN: ${t.credential}`;break}return n}function jx(A,e,t,n){const a=new Map;return A.embeddedClientId&&Zp(a,e,t),A.extraQueryParameters&&Ps(a,A.extraQueryParameters),c2(a,A.correlationId),Wp(a,A.correlationId,n),qf(a)}async function Kx(A,e,t,n,a,s,l,c,h,f){const g=await U_(n,A,{body:e,headers:t},a,s,l,c,h);return f&&g.status<500&&g.status!==429&&f.clearTelemetryCache(),g}async function U_(A,e,t,n,a,s,l,c){ks.preProcess(a,A,n);let h;try{h=await Ke(s.sendPostRequestAsync.bind(s),$T,l,c,n)(e,t);const f=h.headers||{};c?.addFields({refreshTokenSize:h.body.refresh_token?.length||0,httpVerToken:f[si.X_MS_HTTP_VERSION]||"",requestId:f[si.X_MS_REQUEST_ID]||""},n)}catch(f){if(f instanceof A0){const g=f.responseHeaders;throw g&&c?.addFields({httpVerToken:g[si.X_MS_HTTP_VERSION]||"",requestId:g[si.X_MS_REQUEST_ID]||"",contentTypeHeader:g[si.CONTENT_TYPE]||void 0,contentLengthHeader:g[si.CONTENT_LENGTH]||void 0,httpStatus:f.httpStatus},n),f.error}throw f instanceof en?f:tt(qF)}return ks.postProcess(a,A,h,n),h}function I_(A){return A.hasOwnProperty("authorization_endpoint")&&A.hasOwnProperty("token_endpoint")&&A.hasOwnProperty("issuer")&&A.hasOwnProperty("jwks_uri")}function F_(A){return A.hasOwnProperty("tenant_discovery_endpoint")&&A.hasOwnProperty("metadata")}function T_(A){return A.hasOwnProperty("error")&&A.hasOwnProperty("error_description")}class n0{constructor(e,t,n,a){this.networkInterface=e,this.logger=t,this.performanceClient=n,this.correlationId=a}async detectRegion(e,t){let n=e;if(n)t.region_source=Du.ENVIRONMENT_VARIABLE;else{const a=n0.IMDS_OPTIONS;try{const s=await Ke(this.getRegionFromIMDS.bind(this),yC,this.logger,this.performanceClient,this.correlationId)(xI,a);if(s.status===eC&&(n=s.body,t.region_source=Du.IMDS),s.status===tC){const l=await Ke(this.getCurrentVersion.bind(this),g_,this.logger,this.performanceClient,this.correlationId)(a);if(!l)return t.region_source=Du.FAILED_AUTO_DETECTION,null;const c=await Ke(this.getRegionFromIMDS.bind(this),yC,this.logger,this.performanceClient,this.correlationId)(l,a);c.status===eC&&(n=c.body,t.region_source=Du.IMDS)}}catch{return t.region_source=Du.FAILED_AUTO_DETECTION,null}}return n||(t.region_source=Du.FAILED_AUTO_DETECTION),n||null}async getRegionFromIMDS(e,t){return this.networkInterface.sendGetRequestAsync(`${ZB}?api-version=${e}&format=text`,t,SI)}async getCurrentVersion(e){try{const t=await this.networkInterface.sendGetRequestAsync(`${ZB}?format=json`,e);return t.status===tC&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch{return null}}}n0.IMDS_OPTIONS={headers:{Metadata:"true"}};class Si{constructor(e,t,n,a,s,l,c,h){this.canonicalAuthority=e,this._canonicalAuthority.validateAsUri(),this.networkInterface=t,this.cacheManager=n,this.authorityOptions=a,this.regionDiscoveryMetadata={region_used:void 0,region_source:void 0,region_outcome:void 0},this.logger=s,this.performanceClient=c,this.correlationId=l,this.managedIdentity=h||!1,this.regionDiscovery=new n0(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(WB))return rs.Ciam;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case vI:return rs.Adfs;case yI:return rs.Dsts}return rs.Default}get authorityType(){return this.getAuthorityType(this.canonicalAuthorityUrlComponents)}get protocolMode(){return this.authorityOptions.protocolMode}get options(){return this.authorityOptions}get canonicalAuthority(){return this._canonicalAuthority.urlString}set canonicalAuthority(e){this._canonicalAuthority=new QA(e),this._canonicalAuthority.validateAsUri(),this._canonicalAuthorityUrlComponents=null}get canonicalAuthorityUrlComponents(){return this._canonicalAuthorityUrlComponents||(this._canonicalAuthorityUrlComponents=this._canonicalAuthority.getUrlComponents()),this._canonicalAuthorityUrlComponents}get hostnameAndPort(){return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase()}get tenant(){return this.canonicalAuthorityUrlComponents.PathSegments[0]}get authorizationEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.authorization_endpoint);throw tt(pl)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw tt(pl)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw tt(pl)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw tt(sT);return this.replacePath(this.metadata.end_session_endpoint)}else throw tt(pl)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw tt(pl)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw tt(pl)}canReplaceTenant(e){return e.PathSegments.length===1&&!Si.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===rs.Default&&this.protocolMode!==Fi.OIDC}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const a=new QA(this.metadata.canonical_authority).getUrlComponents(),s=a.PathSegments;return this.canonicalAuthorityUrlComponents.PathSegments.forEach((c,h)=>{let f=s[h];if(h===0&&this.canReplaceTenant(a)){const g=new QA(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];f!==g&&(this.logger.verbose("1q3g2x",this.correlationId),f=g)}c!==f&&(t=t.replace(`/${f}/`,`/${c}/`))}),this.replaceTenant(t)}get defaultOpenIdConfigurationEndpoint(){const e=this.hostnameAndPort;return this.canonicalAuthority.endsWith("v2.0/")||this.authorityType===rs.Adfs||this.protocolMode===Fi.OIDC&&!this.isAliasOfKnownMicrosoftAuthority(e)?`${this.canonicalAuthority}.well-known/openid-configuration`:`${this.canonicalAuthority}v2.0/.well-known/openid-configuration`}discoveryComplete(){return!!this.metadata}async resolveEndpointsAsync(){const e=this.getCurrentMetadataEntity(),t=await Ke(this.updateCloudDiscoveryMetadata.bind(this),u_,this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const n=await Ke(this.updateEndpointMetadata.bind(this),f_,this.logger,this.performanceClient,this.correlationId)(e);this.updateCachedMetadata(e,t,{source:n}),this.performanceClient?.addFields({cloudDiscoverySource:t,authorityEndpointSource:n},this.correlationId)}getCurrentMetadataEntity(){let e=this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort,this.correlationId);return e||(e={aliases:[],preferred_cache:this.hostnameAndPort,preferred_network:this.hostnameAndPort,canonical_authority:this.canonicalAuthority,authorization_endpoint:"",token_endpoint:"",end_session_endpoint:"",issuer:"",aliasesFromNetwork:!1,endpointsFromNetwork:!1,expiresAt:bC(),jwks_uri:""}),e}updateCachedMetadata(e,t,n){t!==es.CACHE&&n?.source!==es.CACHE&&(e.expiresAt=bC(),e.canonical_authority=this.canonicalAuthority);const a=this.cacheManager.generateAuthorityMetadataCacheKey(e.preferred_cache,this.correlationId);this.cacheManager.setAuthorityMetadata(a,e,this.correlationId),this.metadata=e}async updateEndpointMetadata(e){const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===es.HARDCODED_VALUES&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){const a=await Ke(this.updateMetadataWithRegionalInformation.bind(this),vC,this.logger,this.performanceClient,this.correlationId)(t.metadata);gg(e,a,!1),e.canonical_authority=this.canonicalAuthority}return t.source}let n=await Ke(this.getEndpointMetadataFromNetwork.bind(this),h_,this.logger,this.performanceClient,this.correlationId)();if(n)return this.authorityOptions.azureRegionConfiguration?.azureRegion&&(n=await Ke(this.updateMetadataWithRegionalInformation.bind(this),vC,this.logger,this.performanceClient,this.correlationId)(n)),gg(e,n,!0),es.NETWORK;throw tt(YF,this.defaultOpenIdConfigurationEndpoint)}updateEndpointMetadataFromLocalSources(e){this.logger.verbose("1fi0kc",this.correlationId);const t=this.getEndpointMetadataFromConfig();if(t)return this.logger.verbose("06t0uj",this.correlationId),gg(e,t,!1),{source:es.CONFIG};this.logger.verbose("151k0p",this.correlationId);const n=this.getEndpointMetadataFromHardcodedValues();if(n)return gg(e,n,!1),{source:es.HARDCODED_VALUES,metadata:n};this.logger.verbose("1imop5",this.correlationId);const a=EC(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!a?(this.logger.verbose("16uq31",""),{source:es.CACHE}):(a&&this.logger.verbose("0uoibc",""),null)}isAuthoritySameType(e){return new QA(e.canonical_authority).getUrlComponents().PathSegments.length===this.canonicalAuthorityUrlComponents.PathSegments.length}getEndpointMetadataFromConfig(){if(this.authorityOptions.authorityMetadata)try{return JSON.parse(this.authorityOptions.authorityMetadata)}catch{throw An(HF)}return null}async getEndpointMetadataFromNetwork(){const e={},t=this.defaultOpenIdConfigurationEndpoint;this.logger.verbose("1y65x6",this.correlationId);try{const n=await this.networkInterface.sendGetRequestAsync(t,e);return I_(n.body)?n.body:(this.logger.verbose("1koyv8",this.correlationId),null)}catch{return this.logger.verbose("0a9wik",this.correlationId),null}}getEndpointMetadataFromHardcodedValues(){return this.hostnameAndPort in dC?dC[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if(t!==UI)return this.regionDiscoveryMetadata.region_outcome=Km.CONFIGURED_NO_AUTO_DETECTION,this.regionDiscoveryMetadata.region_used=t,Si.replaceWithRegionalInformation(e,t);const n=await Ke(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),d_,this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(n)return this.regionDiscoveryMetadata.region_outcome=Km.AUTO_DETECTION_REQUESTED_SUCCESSFUL,this.regionDiscoveryMetadata.region_used=n,Si.replaceWithRegionalInformation(e,n);this.regionDiscoveryMetadata.region_outcome=Km.AUTO_DETECTION_REQUESTED_FAILED}return e}async updateCloudDiscoveryMetadata(e){const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const n=await Ke(this.getCloudDiscoveryMetadataFromNetwork.bind(this),c_,this.logger,this.performanceClient,this.correlationId)();if(n)return zm(e,n,!0),es.NETWORK;throw An(DF)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("0jhlgt",this.correlationId),this.logger.verbosePii("1fy7uz",this.correlationId),this.logger.verbosePii("08zabj",this.correlationId),this.logger.verbosePii("1o1kv3",this.correlationId);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("1nakio",this.correlationId),zm(e,t,!1),es.CONFIG;this.logger.verbose("1x74aj",this.correlationId);const n=_T(this.hostnameAndPort);if(n)return this.logger.verbose("0by47c",this.correlationId),zm(e,n,!1),es.HARDCODED_VALUES;this.logger.verbose("0r2fzy",this.correlationId);const a=EC(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!a?(this.logger.verbose("1uffgh",""),es.CACHE):(a&&this.logger.verbose("0uoibc",""),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===rs.Ciam)return this.logger.verbose("04y84h",this.correlationId),Si.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);if(this.authorityOptions.cloudDiscoveryMetadata){this.logger.verbose("0gszr3",this.correlationId);try{this.logger.verbose("1iifkx",this.correlationId);const e=JSON.parse(this.authorityOptions.cloudDiscoveryMetadata),t=Bp(e.metadata,this.hostnameAndPort);if(this.logger.verbose("0q67e3",""),t)return this.logger.verbose("0hzfao",this.correlationId),t;this.logger.verbose("1ajz3u",this.correlationId)}catch{throw this.logger.verbose("1wq5tu",this.correlationId),An(cx)}}return this.isInKnownAuthorities()?(this.logger.verbose("0mt9al",this.correlationId),Si.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){const e=`${BI}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let n=null;try{const a=await this.networkInterface.sendGetRequestAsync(e,t);let s,l;if(F_(a.body))s=a.body,l=s.metadata,this.logger.verbosePii("1vglyt",this.correlationId);else if(T_(a.body)){if(this.logger.warning("062uto",this.correlationId),s=a.body,s.error===TI)return this.logger.error("1x90tm",this.correlationId),null;this.logger.warning("0wchdm",this.correlationId),this.logger.warning("1s5mpv",this.correlationId),this.logger.warning("1yhqpw",this.correlationId),l=[]}else return this.logger.error("0768g0",this.correlationId),null;this.logger.verbose("1lrobr",this.correlationId),n=Bp(l,this.hostnameAndPort)}catch(a){return a instanceof en?this.logger.error("0vwhc7",this.correlationId):this.logger.error("0s2z41",this.correlationId),null}return n||(this.logger.warning("0jp28q",this.correlationId),this.logger.verbose("130sd8",this.correlationId),n=Si.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),n}isInKnownAuthorities(){return this.authorityOptions.knownAuthorities.filter(t=>t&&QA.getDomainFromUrl(t).toLowerCase()===this.hostnameAndPort).length>0}static generateAuthority(e,t){let n;if(t&&t.azureCloudInstance!==p2.None){const a=t.tenant?t.tenant:JE;n=`${t.azureCloudInstance}/${a}/`}return n||e}static createCloudDiscoveryMetadataFromHost(e){return{preferred_network:e,preferred_cache:e,aliases:[e]}}getPreferredCache(){if(this.managedIdentity)return wI;if(this.discoveryComplete())return this.metadata.preferred_cache;throw tt(pl)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return Tx.has(e)}static isPublicCloudAuthority(e){return FI.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,n){const a=new QA(e);a.validateAsUri();const s=a.getUrlComponents();let l=`${t}.${s.HostNameAndPort}`;this.isPublicCloudAuthority(s.HostNameAndPort)&&(l=`${t}.${II}`);const c=QA.constructAuthorityUriFromObject({...a.getUrlComponents(),HostNameAndPort:l}).urlString;return n?`${c}?${n}`:c}static replaceWithRegionalInformation(e,t){const n={...e};return n.authorization_endpoint=Si.buildRegionalAuthorityString(n.authorization_endpoint,t),n.token_endpoint=Si.buildRegionalAuthorityString(n.token_endpoint,t),n.end_session_endpoint&&(n.end_session_endpoint=Si.buildRegionalAuthorityString(n.end_session_endpoint,t)),n}static transformCIAMAuthority(e){let t=e;const a=new QA(e).getUrlComponents();if(a.PathSegments.length===0&&a.HostNameAndPort.endsWith(WB)){const s=a.HostNameAndPort.split(".")[0];t=`${t}${s}${CI}`}return t}}Si.reservedTenantDomains=new Set(["{tenant}","{tenantid}",Tl.COMMON,Tl.CONSUMERS,Tl.ORGANIZATIONS]);function __(A){const n=new QA(A).getUrlComponents().PathSegments.slice(-1)[0]?.toLowerCase();switch(n){case Tl.COMMON:case Tl.ORGANIZATIONS:case Tl.CONSUMERS:return;default:return n}}function Gx(A){return A.endsWith(V1)?A:`${A}${V1}`}function N_(A){const e=A.cloudDiscoveryMetadata;let t;if(e)try{t=JSON.parse(e)}catch{throw An(cx)}return{canonicalAuthority:A.authority?Gx(A.authority):void 0,knownAuthorities:A.knownAuthorities,cloudDiscoveryMetadata:t}}async function zx(A,e,t,n,a,s,l){const c=Si.transformCIAMAuthority(Gx(A)),h=new Si(c,e,t,n,a,s,l);try{return await Ke(h.resolveEndpointsAsync.bind(h),l_,a,l,s)(),h}catch{throw tt(pl)}}class Vx{constructor(e,t){this.includeRedirectUri=!0,this.config=y2(e),this.logger=new Dl(this.config.loggerOptions,$p,ld),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async acquireToken(e,t,n){if(!e.code)throw tt(eT);n&&n.cloud_instance_host_name&&await Ke(this.updateTokenEndpointAuthority.bind(this),o_,this.logger,this.performanceClient,e.correlationId)(n.cloud_instance_host_name,e.correlationId);const a=ls(),s=await Ke(this.executeTokenRequest.bind(this),a_,this.logger,this.performanceClient,e.correlationId)(this.authority,e,this.serverTelemetryManager),l=s.headers?.[si.X_MS_REQUEST_ID],c=new kc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.performanceClient,this.config.serializableCache,this.config.persistencePlugin);return c.validateTokenResponse(s.body,e.correlationId),Ke(c.handleServerTokenResponse.bind(c),b2,this.logger,this.performanceClient,e.correlationId)(s.body,this.authority,a,e,t,n,void 0,void 0,void 0,l)}getLogoutUri(e){if(!e)throw An(kF);const t=this.createLogoutUrlQueryString(e);return QA.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t,n){const a=jx(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri,this.performanceClient),s=QA.appendQueryString(e.tokenEndpoint,a),l=await Ke(this.createTokenRequestBody.bind(this),s_,this.logger,this.performanceClient,t.correlationId)(t);let c;if(t.clientInfo)try{const g=Cp(t.clientInfo,this.cryptoUtils.base64Decode);c={credential:`${g.uid}${q1}${g.utid}`,type:is.HOME_ACCOUNT_ID}}catch{this.logger.verbose("0wznt3",t.correlationId)}const h=Px(this.logger,this.config.systemOptions.preventCorsPreflight,c||t.ccsCredential),f=t0(this.config.authOptions.clientId,t);return Ke(Kx,t_,this.logger,this.performanceClient,t.correlationId)(s,l,h,f,t.correlationId,this.cacheManager,this.networkClient,this.logger,this.performanceClient,n)}async createTokenRequestBody(e){const t=new Map;if(s2(t,e.embeddedClientId||e.extraParameters?.[Oc]||this.config.authOptions.clientId),this.includeRedirectUri)o2(t,e.redirectUri);else if(!e.redirectUri)throw An(NF);if(a2(t,e.scopes,!0,this.oidcDefaultScopes),gT(t,e.code),u2(t,this.config.libraryInfo),h2(t,this.config.telemetry.application),Sx(t),this.serverTelemetryManager&&!Lx(this.config)&&xx(t,this.serverTelemetryManager),e.codeVerifier&&mT(t,e.codeVerifier),this.config.clientCredentials.clientSecret&&vx(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const a=this.config.clientCredentials.clientAssertion;yx(t,await Mx(a.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),Bx(t,a.assertionType)}if(Cx(t,$E.AUTHORIZATION_CODE_GRANT),d2(t),e.authenticationScheme===MA.POP){const a=new mh(this.cryptoUtils,this.performanceClient);let s;e.popKid?s=this.cryptoUtils.encodeKid(e.popKid):s=(await Ke(a.generateCnf.bind(a),ud,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString,g2(t,s)}else if(e.authenticationScheme===MA.SSH)if(e.sshJwk)Ex(t,e.sshJwk);else throw An(r2);(!Ea.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&l2(t,e.claims,this.config.authOptions.clientCapabilities);let n;if(e.clientInfo)try{const a=Cp(e.clientInfo,this.cryptoUtils.base64Decode);n={credential:`${a.uid}${q1}${a.utid}`,type:is.HOME_ACCOUNT_ID}}catch{this.logger.verbose("0wznt3",e.correlationId)}else n=e.ccsCredential;if(this.config.systemOptions.preventCorsPreflight&&n)switch(n.type){case is.HOME_ACCOUNT_ID:try{const a=ah(n.credential);_f(t,a)}catch{this.logger.verbose("1qhtee",e.correlationId)}break;case is.UPN:wp(t,n.credential);break}return e.embeddedClientId&&Zp(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.extraParameters&&Ps(t,e.extraParameters),e.enableSpaAuthorizationCode&&(!e.extraParameters||!e.extraParameters[aC])&&Ps(t,{[aC]:"1"}),Wp(t,e.correlationId,this.performanceClient),qf(t)}createLogoutUrlQueryString(e){const t=new Map;return e.postLogoutRedirectUri&&cT(t,e.postLogoutRedirectUri),e.correlationId&&c2(t,e.correlationId),e.idTokenHint&&uT(t,e.idTokenHint),e.state&&wx(t,e.state),e.logoutHint&&vT(t,e.logoutHint),e.extraQueryParameters&&Ps(t,e.extraQueryParameters),this.config.authOptions.instanceAware&&bx(t),qf(t)}async updateTokenEndpointAuthority(e,t){const n=`https://${e}/${this.authority.tenant}/`,a=await zx(n,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=a}}const Q_=300;class L_{constructor(e,t){this.config=y2(e),this.logger=new Dl(this.config.loggerOptions,$p,ld),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}async acquireToken(e,t){const n=ls(),a=await Ke(this.executeTokenRequest.bind(this),A_,this.logger,this.performanceClient,e.correlationId)(e,this.authority),s=a.headers?.[si.X_MS_REQUEST_ID],l=new kc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.performanceClient,this.config.serializableCache,this.config.persistencePlugin);return l.validateTokenResponse(a.body,e.correlationId),Ke(l.handleServerTokenResponse.bind(l),b2,this.logger,this.performanceClient,e.correlationId)(a.body,this.authority,n,e,t,void 0,void 0,!0,e.forceCache,s)}async acquireTokenByRefreshToken(e,t){if(!e)throw An(RF);if(!e.account)throw tt(dx);if(this.cacheManager.isAppMetadataFOCI(e.account.environment,e.correlationId))try{return await Ke(this.acquireTokenWithCachedRefreshToken.bind(this),Gm,this.logger,this.performanceClient,e.correlationId)(e,!0,t)}catch(a){const s=a instanceof os&&a.errorCode===tw,l=a instanceof zc&&a.errorCode===qI&&a.subError===YI;if(s||l)return Ke(this.acquireTokenWithCachedRefreshToken.bind(this),Gm,this.logger,this.performanceClient,e.correlationId)(e,!1,t);throw a}return Ke(this.acquireTokenWithCachedRefreshToken.bind(this),Gm,this.logger,this.performanceClient,e.correlationId)(e,!1,t)}async acquireTokenWithCachedRefreshToken(e,t,n){const a=as(this.cacheManager.getRefreshToken.bind(this.cacheManager),p_,this.logger,this.performanceClient,e.correlationId)(e.account,t,e.correlationId,void 0);if(!a)throw bp(tw);if(a.expiresOn){const l=e.refreshTokenExpirationOffsetSeconds||Q_;if(this.performanceClient?.addFields({cacheRtExpiresOnSeconds:Number(a.expiresOn),rtOffsetSeconds:l},e.correlationId),Ep(a.expiresOn,l))throw bp(Ox)}const s={...e,refreshToken:a.secret,authenticationScheme:e.authenticationScheme||MA.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:is.HOME_ACCOUNT_ID}};try{return await Ke(this.acquireToken.bind(this),n_,this.logger,this.performanceClient,e.correlationId)(s,n)}catch(l){if(l instanceof os&&l.subError===B2){this.logger.verbose("1pg3ap",e.correlationId);const c=this.cacheManager.generateCredentialKey(a);this.cacheManager.removeRefreshToken(c,e.correlationId)}throw l}}async executeTokenRequest(e,t){const n=jx(e,this.config.authOptions.clientId,this.config.authOptions.redirectUri,this.performanceClient),a=QA.appendQueryString(t.tokenEndpoint,n),s=await Ke(this.createTokenRequestBody.bind(this),r_,this.logger,this.performanceClient,e.correlationId)(e),l=Px(this.logger,this.config.systemOptions.preventCorsPreflight,e.ccsCredential),c=t0(this.config.authOptions.clientId,e);return Ke(Kx,e_,this.logger,this.performanceClient,e.correlationId)(a,s,l,c,e.correlationId,this.cacheManager,this.networkClient,this.logger,this.performanceClient,this.serverTelemetryManager)}async createTokenRequestBody(e){const t=new Map;if(s2(t,e.embeddedClientId||e.extraParameters?.[Oc]||this.config.authOptions.clientId),e.redirectUri&&o2(t,e.redirectUri),a2(t,e.scopes,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),Cx(t,$E.REFRESH_TOKEN_GRANT),d2(t),u2(t,this.config.libraryInfo),h2(t,this.config.telemetry.application),Sx(t),this.serverTelemetryManager&&!Lx(this.config)&&xx(t,this.serverTelemetryManager),pT(t,e.refreshToken),this.config.clientCredentials.clientSecret&&vx(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const n=this.config.clientCredentials.clientAssertion;yx(t,await Mx(n.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),Bx(t,n.assertionType)}if(e.authenticationScheme===MA.POP){const n=new mh(this.cryptoUtils,this.performanceClient);let a;e.popKid?a=this.cryptoUtils.encodeKid(e.popKid):a=(await Ke(n.generateCnf.bind(n),ud,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString,g2(t,a)}else if(e.authenticationScheme===MA.SSH)if(e.sshJwk)Ex(t,e.sshJwk);else throw An(r2);if((!Ea.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&l2(t,e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case is.HOME_ACCOUNT_ID:try{const n=ah(e.ccsCredential.credential);_f(t,n)}catch{this.logger.verbose("1qhtee",e.correlationId)}break;case is.UPN:wp(t,e.ccsCredential.credential);break}return e.embeddedClientId&&Zp(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.extraParameters&&Ps(t,{...e.extraParameters}),Wp(t,e.correlationId,this.performanceClient),qf(t)}}class O_{constructor(e,t){this.config=y2(e),this.logger=new Dl(this.config.loggerOptions,$p,ld),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}async acquireCachedToken(e){let t=vc.NOT_APPLICABLE;if(e.forceRefresh||!Ea.isEmptyObj(e.claims))throw this.setCacheOutcome(vc.FORCE_REFRESH_OR_CLAIMS,e.correlationId),tt(Ic);if(!e.account)throw tt(dx);const n=e.account.tenantId||__(e.authority),a=this.cacheManager.getTokenKeys(),s=this.cacheManager.getAccessToken(e.account,e,a,n);if(s){if(ZT(s.cachedAt)||Ep(s.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(vc.CACHED_ACCESS_TOKEN_EXPIRED,e.correlationId),tt(Ic);s.refreshOn&&Ep(s.refreshOn,0)&&(t=vc.PROACTIVELY_REFRESHED)}else throw this.setCacheOutcome(vc.NO_CACHED_ACCESS_TOKEN,e.correlationId),tt(Ic);const l=e.authority||this.authority.getPreferredCache(),c={account:this.cacheManager.getAccount(this.cacheManager.generateAccountKey(e.account),e.correlationId),accessToken:s,idToken:this.cacheManager.getIdToken(e.account,e.correlationId,a,n),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(l,e.correlationId)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await Ke(this.generateResultFromCacheRecord.bind(this),i_,this.logger,this.performanceClient,e.correlationId)(c,e),t]}setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==vc.NOT_APPLICABLE&&this.logger.info("09ingz",t)}async generateResultFromCacheRecord(e,t){let n;if(e.idToken&&(n=Uo(e.idToken.secret,this.config.cryptoInterface.base64Decode)),t.maxAge||t.maxAge===0){const a=n?.auth_time;if(!a)throw tt(fx);Ix(a,t.maxAge)}return kc.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,this.performanceClient,n)}}const R_={sendGetRequestAsync:()=>Promise.reject(tt(iA)),sendPostRequestAsync:()=>Promise.reject(tt(iA))};function k_(A,e,t,n){const a=e.correlationId,s=new Map;s2(s,e.embeddedClientId||e.extraQueryParameters?.[Oc]||A.clientId);const l=[...e.scopes||[],...e.extraScopesToConsent||[]];if(a2(s,l,!0,A.authority.options.OIDCOptions?.defaultScopes),o2(s,e.redirectUri),c2(s,a),oT(s,e.responseMode),d2(s),e.prompt&&(fT(s,e.prompt),n?.addFields({prompt:e.prompt},a)),e.domainHint&&(hT(s,e.domainHint),n?.addFields({domainHintFromRequest:!0},a)),e.prompt!==Ii.SELECT_ACCOUNT)if(e.sid&&e.prompt===Ii.NONE)t.verbose("1tvqyx",e.correlationId),cC(s,e.sid),n?.addFields({sidFromRequest:!0},a);else if(e.account){const c=M_(e.account);let h=P_(e.account);if(h&&e.domainHint&&(t.warning("0wkg3v",e.correlationId),h=null),h){t.verbose("1eyfsw",e.correlationId),dg(s,h),n?.addFields({loginHintFromClaim:!0},a);try{const f=ah(e.account.homeAccountId);_f(s,f)}catch{t.verbose("12ugck",e.correlationId)}}else if(c&&e.prompt===Ii.NONE){t.verbose("1rmd8s",e.correlationId),cC(s,c),n?.addFields({sidFromClaim:!0},a);try{const f=ah(e.account.homeAccountId);_f(s,f)}catch{t.verbose("12ugck",e.correlationId)}}else if(e.loginHint)t.verbose("0y3007",e.correlationId),dg(s,e.loginHint),wp(s,e.loginHint),n?.addFields({loginHintFromRequest:!0},a);else if(e.account.username){t.verbose("02f507",e.correlationId),dg(s,e.account.username),n?.addFields({loginHintFromUpn:!0},a);try{const f=ah(e.account.homeAccountId);_f(s,f)}catch{t.verbose("12ugck",e.correlationId)}}}else e.loginHint&&(t.verbose("0g01ey",e.correlationId),dg(s,e.loginHint),wp(s,e.loginHint),n?.addFields({loginHintFromRequest:!0},a));else t.verbose("169k9v",e.correlationId);return e.nonce&&dT(s,e.nonce),e.state&&wx(s,e.state),(e.claims||A.clientCapabilities&&A.clientCapabilities.length>0)&&l2(s,e.claims,A.clientCapabilities),e.embeddedClientId&&Zp(s,A.clientId,A.redirectUri),A.instanceAware&&(!e.extraQueryParameters||!Object.keys(e.extraQueryParameters).includes(X1))&&bx(s),s}function S2(A,e){const t=qf(e);return QA.appendQueryString(A.authorizationEndpoint,t)}function H_(A,e){if(qx(A,e),!A.code)throw tt(iT);return A}function qx(A,e){if(!A.state||!e)throw A.state?tt(sC,"Cached State"):tt(sC,"Server State");let t,n;try{t=decodeURIComponent(A.state)}catch{throw tt(Vf,A.state)}try{n=decodeURIComponent(e)}catch{throw tt(Vf,A.state)}if(t!==n)throw tt(JF);if(A.error||A.error_description||A.suberror){const a=D_(A);throw kx(A.error,A.error_description,A.suberror)?new os(A.error||"",A.error_description,A.suberror,A.timestamp||"",A.trace_id||"",A.correlation_id||"",A.claims||"",a):new zc(A.error||"",A.error_description,A.suberror,a)}}function D_(A){const e="code=",t=A.error_uri?.lastIndexOf(e);return t&&t>=0?A.error_uri?.substring(t+e.length):void 0}function M_(A){return A.idTokenClaims?.sid||null}function P_(A){return A.loginHint||A.idTokenClaims?.login_hint||null}const Aw="unexpected_error";const xC=",",Yx="|";function j_(A){const{skus:e,libraryName:t,libraryVersion:n,extensionName:a,extensionVersion:s}=A,l=new Map([[0,[t,n]],[2,[a,s]]]);let c=[];if(e?.length){if(c=e.split(xC),c.length<4)return e}else c=Array.from({length:4},()=>Yx);return l.forEach((h,f)=>{h.length===2&&h[0]?.length&&h[1]?.length&&K_({skuArr:c,index:f,skuName:h[0],skuVersion:h[1]})}),c.join(xC)}function K_(A){const{skuArr:e,index:t,skuName:n,skuVersion:a}=A;t>=e.length||(e[t]=[n,a].join(Yx))}class Yf{constructor(e,t){this.cacheOutcome=vc.NOT_APPLICABLE,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||"",this.wrapperVer=e.wrapperVer||"",this.telemetryCacheKey=Ax+tx+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${Hu}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],n=this.getNativeBrokerErrorCode();n?.length&&t.push(`broker_error=${n}`);const a=t.join(Hu),s=this.getRegionDiscoveryFields(),l=[e,s].join(Hu);return[rC,l,a].join(iC)}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=Yf.maxErrorsToSend(e),n=e.failedRequests.slice(0,2*t).join(Hu),a=e.errors.slice(0,t).join(Hu),s=e.errors.length,l=t=MI&&(t.failedRequests.shift(),t.failedRequests.shift(),t.errors.shift()),t.failedRequests.push(this.apiId,this.correlationId),e instanceof Error&&e&&e.toString()?e instanceof en?e.subError?t.errors.push(e.subError):e.errorCode?t.errors.push(e.errorCode):t.errors.push(e.toString()):t.errors.push(e.toString()):t.errors.push(KI),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId),e.cacheHits}getLastRequests(){const e={failedRequests:[],errors:[],cacheHits:0};return this.cacheManager.getServerTelemetry(this.telemetryCacheKey,this.correlationId)||e}clearTelemetryCache(){const e=this.getLastRequests(),t=Yf.maxErrorsToSend(e),n=e.errors.length;if(t===n)this.cacheManager.removeItem(this.telemetryCacheKey,this.correlationId);else{const a={failedRequests:e.failedRequests.slice(t*2),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,a,this.correlationId)}}static maxErrorsToSend(e){let t,n=0,a=0;const s=e.errors.length;for(t=0;ttypeof A=="number"&&A in IC?IC[A]:"unknown";var Mt;(function(A){A.Redirect="redirect",A.Popup="popup",A.Silent="silent",A.None="none"})(Mt||(Mt={}));const Fr={Startup:"startup",Logout:"logout",AcquireToken:"acquireToken",HandleRedirect:"handleRedirect",None:"none"},FC={scopes:yh},Xx="jwk",q_={React:"@azure/msal-react"},nw="msal.db",Y_=1,X_=`${nw}.keys`,ri={Default:0,AccessToken:1,AccessTokenAndRefreshToken:2,RefreshToken:3,RefreshTokenAndNetwork:4,Skip:5},J_=[ri.Default,ri.Skip,ri.RefreshTokenAndNetwork];function mg(A){return encodeURIComponent(Xf(A).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"))}function Rl(A){return Jx(A).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Xf(A){return Jx(new TextEncoder().encode(A))}function Jx(A){const e=Array.from(A,t=>String.fromCodePoint(t)).join("");return btoa(e)}const Wx="pkce_not_created",Zx="ear_jwk_empty",W_="ear_jwe_empty",TC="crypto_nonexistent",F2="empty_navigate_uri",Z_="hash_empty_error",T2="no_state_in_hash",$_="hash_does_not_contain_known_properties",$x="unable_to_parse_state",eN="state_interaction_type_mismatch",tN="interaction_in_progress",AN="interaction_in_progress_cancelled",nN="popup_window_error",rN="empty_window_error",rw="user_cancelled",iN="redirect_bridge_empty_response",aN="redirect_in_iframe",sN="block_iframe_reload",oN="block_nested_popups",_2="silent_logout_unsupported",lN="no_account_error",cN="no_token_request_cache_error",uN="unable_to_parse_token_request_cache_error",e4="non_browser_environment",gf="database_not_open",iw="no_network_connectivity",hN="post_request_failed",fN="get_request_failed",_C="failed_to_parse_response",t4="crypto_key_not_found",dN="auth_code_required",gN="auth_code_or_nativeAccountId_required",pN="spa_code_and_nativeAccountId_present",A4="database_unavailable",mN="unable_to_acquire_token_from_native_platform",wN="native_handshake_timeout",vN="native_extension_not_installed",n4="native_connection_not_established",$g="uninitialized_public_client_application",yN="native_prompt_not_supported",BN="invalid_base64_string",CN="invalid_pop_token_request",bN="failed_to_build_headers",EN="failed_to_parse_headers",Vm="failed_to_decrypt_ear_response",xp="timed_out",xN="empty_response";function Zi(A){return new TextDecoder().decode(_l(A))}function _l(A){let e=A.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw ut(BN)}const t=atob(e);return Uint8Array.from(t,n=>n.codePointAt(0)||0)}const SN="RSASSA-PKCS1-v1_5",Ch="AES-GCM",r4="HKDF",N2="SHA-256",UN=2048,IN=new Uint8Array([1,0,1]),NC="0123456789abcdef",QC=new Uint32Array(1),Q2="raw",i4="encrypt",L2="decrypt",FN="deriveKey",TN="crypto_subtle_undefined",O2={name:SN,hash:N2,modulusLength:UN,publicExponent:IN};function _N(A){if(!window)throw ut(e4);if(!window.crypto)throw ut(TC);if(!A&&!window.crypto.subtle)throw ut(TC,TN)}async function a4(A){const t=new TextEncoder().encode(A);return window.crypto.subtle.digest(N2,t)}function NN(A){return window.crypto.getRandomValues(A)}function qm(){return window.crypto.getRandomValues(QC),QC[0]}function Hc(){const A=Date.now(),e=qm()*1024+(qm()&1023),t=new Uint8Array(16),n=Math.trunc(e/2**30),a=e&2**30-1,s=qm();t[0]=A/2**40,t[1]=A/2**32,t[2]=A/2**24,t[3]=A/2**16,t[4]=A/2**8,t[5]=A,t[6]=112|n>>>8,t[7]=n,t[8]=128|a>>>24,t[9]=a>>>16,t[10]=a>>>8,t[11]=a,t[12]=s>>>24,t[13]=s>>>16,t[14]=s>>>8,t[15]=s;let l="";for(let c=0;c>>4),l+=NC.charAt(t[c]&15),(c===3||c===5||c===7||c===9)&&(l+="-");return l}async function QN(A,e){return window.crypto.subtle.generateKey(O2,A,e)}async function Ym(A){return window.crypto.subtle.exportKey(Xx,A)}async function LN(A,e,t){return window.crypto.subtle.importKey(Xx,A,O2,e,t)}async function ON(A,e){return window.crypto.subtle.sign(O2,A,e)}async function R2(){const A=await s4(),t={alg:"dir",kty:"oct",k:Rl(new Uint8Array(A))};return Xf(JSON.stringify(t))}async function RN(A){const e=Zi(A),n=JSON.parse(e).k,a=_l(n);return window.crypto.subtle.importKey(Q2,a,Ch,!1,[L2])}async function kN(A,e){const t=e.split(".");if(t.length!==5)throw ut(Vm,"jwe_length");const n=await RN(A).catch(()=>{throw ut(Vm,"import_key")});try{const a=new TextEncoder().encode(t[0]),s=_l(t[2]),l=_l(t[3]),c=_l(t[4]),h=c.byteLength*8,f=new Uint8Array(l.length+c.length);f.set(l),f.set(c,l.length);const g=await window.crypto.subtle.decrypt({name:Ch,iv:s,tagLength:h,additionalData:a},n,f);return new TextDecoder().decode(g)}catch{throw ut(Vm,"decrypt")}}async function s4(){const A=await window.crypto.subtle.generateKey({name:Ch,length:256},!0,[i4,L2]);return window.crypto.subtle.exportKey(Q2,A)}async function LC(A){return window.crypto.subtle.importKey(Q2,A,r4,!1,[FN])}async function o4(A,e,t){return window.crypto.subtle.deriveKey({name:r4,salt:e,hash:N2,info:new TextEncoder().encode(t)},A,{name:Ch,length:256},!1,[i4,L2])}async function HN(A,e,t){const n=new TextEncoder().encode(e),a=window.crypto.getRandomValues(new Uint8Array(16)),s=await o4(A,a,t),l=await window.crypto.subtle.encrypt({name:Ch,iv:new Uint8Array(12)},s,n);return{data:Rl(new Uint8Array(l)),nonce:Rl(a)}}async function OC(A,e,t,n){const a=_l(n),s=await o4(A,_l(e),t),l=await window.crypto.subtle.decrypt({name:Ch,iv:new Uint8Array(12)},s,a);return new TextDecoder().decode(l)}async function DN(A){const e=await a4(A),t=new Uint8Array(e);return Rl(t)}class k2 extends en{constructor(e,t){super(e,t),this.name="BrowserConfigurationAuthError",Object.setPrototypeOf(this,k2.prototype)}}function wr(A){return new k2(A,r0(A))}const l4="storage_not_supported",ni="stubbed_public_client_application_called",MN="in_mem_redirect_unavailable";function PN(){const A=window.location.hash,e=window.location.search;let t=!1,n=!1,a="",s;if(A&&A.length>1){const g=A.charAt(0)==="#"?A.substring(1):A,y=new URLSearchParams(g);y.has("state")&&(t=!0,a=g,s=y)}if(e&&e.length>1){const g=e.charAt(0)==="?"?e.substring(1):e,y=new URLSearchParams(g);y.has("state")&&(n=!0,a=g,s=y)}if(t&&n){const g=e.charAt(0)==="?"?e.substring(1):e,y=A.charAt(0)==="#"?A.substring(1):A;a=`${g}${y}`,s=new URLSearchParams(a)}if(!a||!s)throw ut(xN);const l=s.get("state");if(!l)throw ut(T2);const{libraryState:c}=cd(Zi,l),{id:h,meta:f}=c;if(!h||!f)throw ut($x,"missing_library_state");return{params:s,payload:a,urlHash:A,urlQuery:e,hasResponseInHash:t,hasResponseInQuery:n,libraryState:{id:h,meta:f}}}function c4(A){A.location.hash="",typeof A.history.replaceState=="function"&&A.history.replaceState(null,"",`${A.location.origin}${A.location.pathname}${A.location.search}`)}function jN(A){const e=A.split("#");e.shift(),window.location.hash=e.length>0?e.join("#"):""}function i0(){return window.parent!==window}function KN(){if(i0())return!1;try{const{libraryState:A}=PN(),{meta:e}=A;return e.interactionType===Mt.Popup}catch{return!1}}let El=null;function GN(A,e){El&&(A.verbose("18y01k",e),clearTimeout(El.timeoutId),El.channel.close(),El.reject(ut(AN)),El=null)}async function th(A,e,t,n){return new Promise((a,s)=>{e.verbose("1rf6em",n.correlationId);const{libraryState:l}=cd(t.base64Decode,n.state||""),c=new BroadcastChannel(l.id);let h;const f=window.setTimeout(()=>{El=null,c.close(),s(ut(xp,"redirect_bridge_timeout"))},A);El={timeoutId:f,channel:c,reject:s},c.onmessage=g=>{h=g.data.payload,El=null,clearTimeout(f),c.close(),h?a(h):s(ut(iN))}})}function xl(){return typeof window<"u"&&window.location?window.location.href.split("?")[0].split("#")[0]:""}function zN(){const e=new QA(window.location.href).getUrlComponents();return`${e.Protocol}//${e.HostNameAndPort}/`}function VN(){if(vp(window.location.hash)&&i0())throw ut(sN)}function qN(A){if(i0()&&!A)throw ut(aN)}function YN(){if(KN())throw ut(oN)}function u4(){if(typeof window>"u")throw ut(e4)}function h4(A){if(!A)throw ut($g)}function H2(A){u4(),VN(),YN(),h4(A)}function RC(A,e){if(H2(A),qN(e.system.allowRedirectInIframe),e.cache.cacheLocation===xa.MemoryStorage)throw wr(MN)}function f4(A){const e=document.createElement("link");e.rel="preconnect",e.href=new URL(A).origin,e.crossOrigin="anonymous",document.head.appendChild(e),window.setTimeout(()=>{try{document.head.removeChild(e)}catch{}},1e4)}function aw(){return Hc()}const XN="acquireTokenFromCache",JN="acquireTokenByRefreshToken",WN="acquireTokenSilentAsync",ZN="cryptoOptsGetPublicKeyThumbprint",$N="cryptoOptsSignJwt",eQ="silentCacheClientAcquireToken",tQ="silentIframeClientAcquireToken",AQ="awaitConcurrentIframe",nQ="silentRefreshClientAcquireToken",Tc="standardInteractionClientGetDiscoveredAuthority",d4="nativeInteractionClientAcquireToken",rQ="refreshTokenClientAcquireTokenByRefreshToken",kC="acquireTokenBySilentIframe",D2="initializeBaseRequest",iQ="initializeSilentRequest",aQ="initializeCache",HC="silentIframeClientTokenHelper",Xm="silentHandlerInitiateAuthRequest",Sp="silentHandlerMonitorIframeForHash",sQ="silentHandlerLoadFrameSync",Nl="standardInteractionClientCreateAuthCodeClient",a0="standardInteractionClientGetClientConfiguration",s0="standardInteractionClientInitializeAuthorizationRequest",oQ="silentFlowClientAcquireCachedToken",lQ="getStandardParams",cQ="handleCodeResponse",M2="handleResponseEar",g4="handleResponsePlatformBroker",sh="handleResponseCode",uQ="authClientAcquireToken",Nf="deserializeResponse",hQ="authorityFactoryCreateDiscoveredInstance",fQ="acquireTokenByCodeAsync",dQ="handleRedirectPromise",gQ="handleNativeRedirectPromise",pQ="nativeMessageHandlerHandshake",mQ="importExistingCache",Dc="generatePkceCodes",wQ="generateCodeVerifier",vQ="generateCodeChallengeFromVerifier",yQ="sha256Digest",BQ="getRandomValues",DC="generateHKDF",CQ="generateBaseKey",bQ="base64Decode",EQ="urlEncodeArr",xQ="encrypt",MC="decrypt",P2="generateEarKey",SQ="decryptEarResponse";class UQ{constructor(){this.dbName=nw,this.version=Y_,this.tableName=X_,this.dbOpen=!1}async open(){return new Promise((e,t)=>{const n=window.indexedDB.open(this.dbName,this.version);n.addEventListener("upgradeneeded",a=>{a.target.result.createObjectStore(this.tableName)}),n.addEventListener("success",a=>{const s=a;this.db=s.target.result,this.dbOpen=!0,e()}),n.addEventListener("error",()=>t(ut(A4)))})}closeConnection(){const e=this.db;e&&this.dbOpen&&(e.close(),this.dbOpen=!1)}async validateDbIsOpen(){if(!this.dbOpen)return this.open()}async getItem(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(ut(gf));const l=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).get(e);l.addEventListener("success",c=>{const h=c;this.closeConnection(),t(h.target.result)}),l.addEventListener("error",c=>{this.closeConnection(),n(c)})})}async setItem(e,t){return await this.validateDbIsOpen(),new Promise((n,a)=>{if(!this.db)return a(ut(gf));const c=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).put(t,e);c.addEventListener("success",()=>{this.closeConnection(),n()}),c.addEventListener("error",h=>{this.closeConnection(),a(h)})})}async removeItem(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(ut(gf));const l=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).delete(e);l.addEventListener("success",()=>{this.closeConnection(),t()}),l.addEventListener("error",c=>{this.closeConnection(),n(c)})})}async getKeys(){return await this.validateDbIsOpen(),new Promise((e,t)=>{if(!this.db)return t(ut(gf));const s=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).getAllKeys();s.addEventListener("success",l=>{const c=l;this.closeConnection(),e(c.target.result)}),s.addEventListener("error",l=>{this.closeConnection(),t(l)})})}async containsKey(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(ut(gf));const l=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).count(e);l.addEventListener("success",c=>{const h=c;this.closeConnection(),t(h.target.result===1)}),l.addEventListener("error",c=>{this.closeConnection(),n(c)})})}async deleteDatabase(){return this.db&&this.dbOpen&&this.closeConnection(),new Promise((e,t)=>{const n=window.indexedDB.deleteDatabase(nw),a=setTimeout(()=>t(!1),200);n.addEventListener("success",()=>(clearTimeout(a),e(!0))),n.addEventListener("blocked",()=>(clearTimeout(a),e(!0))),n.addEventListener("error",()=>(clearTimeout(a),t(!1)))})}}class o0{constructor(){this.cache=new Map}async initialize(){}getItem(e){return this.cache.get(e)||null}getUserData(e){return this.getItem(e)}setItem(e,t){this.cache.set(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){this.cache.delete(e)}getKeys(){const e=[];return this.cache.forEach((t,n)=>{e.push(n)}),e}containsKey(e){return this.cache.has(e)}clear(){this.cache.clear()}decryptData(){return Promise.resolve(null)}}class IQ{constructor(e){this.inMemoryCache=new o0,this.indexedDBCache=new UQ,this.logger=e}handleDatabaseAccessError(e,t){if(e instanceof hd&&e.errorCode===A4)this.logger.error("1wx7zz",t);else throw e}async getItem(e,t){const n=this.inMemoryCache.getItem(e);if(!n)try{return this.logger.verbose("0naxpl",t),await this.indexedDBCache.getItem(e)}catch(a){this.handleDatabaseAccessError(a,t)}return n}async setItem(e,t,n){this.inMemoryCache.setItem(e,t);try{await this.indexedDBCache.setItem(e,t)}catch(a){this.handleDatabaseAccessError(a,n)}}async removeItem(e,t){this.inMemoryCache.removeItem(e);try{await this.indexedDBCache.removeItem(e)}catch(n){this.handleDatabaseAccessError(n,t)}}async getKeys(e){const t=this.inMemoryCache.getKeys();if(t.length===0)try{return this.logger.verbose("1iqrbq",e),await this.indexedDBCache.getKeys()}catch(n){this.handleDatabaseAccessError(n,e)}return t}async containsKey(e,t){const n=this.inMemoryCache.containsKey(e);if(!n)try{return this.logger.verbose("03zl2j",t),await this.indexedDBCache.containsKey(e)}catch(a){this.handleDatabaseAccessError(a,t)}return n}clearInMemory(e){this.logger.verbose("03r21p",e),this.inMemoryCache.clear(),this.logger.verbose("0uksk1",e)}async clearPersistent(e){try{this.logger.verbose("0rdqut",e);const t=await this.indexedDBCache.deleteDatabase();return t&&this.logger.verbose("149ouc",e),t}catch(t){return this.handleDatabaseAccessError(t,e),!1}}}class _o{constructor(e,t,n){this.logger=e,_N(n??!1),this.cache=new IQ(this.logger),this.performanceClient=t}createNewGuid(){return Hc()}base64Encode(e){return Xf(e)}base64Decode(e){return Zi(e)}base64UrlEncode(e){return mg(e)}encodeKid(e){return this.base64UrlEncode(JSON.stringify({kid:e}))}async getPublicKeyThumbprint(e){const t=this.performanceClient?.startMeasurement(ZN,e.correlationId),n=await QN(_o.EXTRACTABLE,_o.POP_KEY_USAGES),a=await Ym(n.publicKey),s={e:a.e,kty:a.kty,n:a.n},l=PC(s),c=await this.hashString(l),h=await Ym(n.privateKey),f=await LN(h,!1,["sign"]);return await this.cache.setItem(c,{privateKey:f,publicKey:n.publicKey,requestMethod:e.resourceRequestMethod,requestUri:e.resourceRequestUri},e.correlationId),t&&t.end({success:!0}),c}async removeTokenBindingKey(e,t){if(await this.cache.removeItem(e,t),await this.cache.containsKey(e,t))throw tt(aT)}async clearKeystore(e){this.cache.clearInMemory(e);try{return await this.cache.clearPersistent(e),!0}catch(t){return t instanceof Error?this.logger.error("1owpn8",e):this.logger.error("0yrmwo",e),!1}}async signJwt(e,t,n,a){const s=this.performanceClient?.startMeasurement($N,a),l=await this.cache.getItem(t,a||"");if(!l)throw ut(t4);const c=await Ym(l.publicKey),h=PC(c),f=mg(JSON.stringify({kid:t})),g=I2.getShrHeaderString({...n?.header,alg:c.alg,kid:f}),y=mg(g);e.cnf={jwk:JSON.parse(h)};const C=mg(JSON.stringify(e)),v=`${y}.${C}`,x=new TextEncoder().encode(v),_=await ON(l.privateKey,x),T=Rl(new Uint8Array(_)),k=`${v}.${T}`;return s&&s.end({success:!0}),k}async hashString(e){return DN(e)}}_o.POP_KEY_USAGES=["sign","verify"];_o.EXTRACTABLE=!0;function PC(A){return JSON.stringify(A,Object.keys(A).sort())}const FQ="acquireTokenSilent",TQ="acquireTokenByCode",_Q="acquireTokenPopup",NQ="acquireTokenPreRedirect",Jm="acquireTokenRedirect",QQ="ssoSilent",LQ="initializeClientApplication",OQ="localStorageUpdated";const Nr="msal",j2="browser",jC="|",Kr=2,ep=2,RQ=`${Nr}.${j2}.log.level`,kQ=`${Nr}.${j2}.log.pii`,HQ=`${Nr}.${j2}.platform.auth.dom`,KC=`${Nr}.version`,GC="account.keys",zC="token.keys";function oh(A=ep){return A<1?`${Nr}.${GC}`:`${Nr}.${A}.${GC}`}function lh(A,e=Kr){return e<1?`${Nr}.${zC}.${A}`:`${Nr}.${e}.${zC}.${A}`}const DQ=1440*60*1e3,sw={Lax:"Lax",None:"None"};class p4{initialize(){return Promise.resolve()}getItem(e){const t=`${encodeURIComponent(e)}`,n=document.cookie.split(";");for(let a=0;a{const a=decodeURIComponent(n).trim().split("=");t.push(a[0])}),t}containsKey(e){return this.getKeys().includes(e)}decryptData(){return Promise.resolve(null)}}function MQ(A){const e=new Date;return new Date(e.getTime()+A*DQ).toUTCString()}function vl(A,e){const t=A.getItem(oh(e));return t?JSON.parse(t):[]}function ns(A,e,t){const n=e.getItem(lh(A,t));if(n){const a=JSON.parse(n);if(a&&a.hasOwnProperty("idToken")&&a.hasOwnProperty("accessToken")&&a.hasOwnProperty("refreshToken"))return a}return{idToken:[],accessToken:[],refreshToken:[]}}function tp(A){return A.hasOwnProperty("id")&&A.hasOwnProperty("nonce")&&A.hasOwnProperty("data")}const VC="msal.cache.encryption",PQ="msal.broadcast.cache";class jQ{constructor(e,t,n){if(!window.localStorage)throw wr(l4);this.memoryStorage=new o0,this.initialized=!1,this.clientId=e,this.logger=t,this.performanceClient=n,this.broadcast=new BroadcastChannel(PQ)}async initialize(e){const t=new p4,n=t.getItem(VC);let a={key:"",id:""};if(n)try{a=JSON.parse(n)}catch{}if(a.key&&a.id){const s=as(_l,bQ,this.logger,this.performanceClient,e)(a.key);this.encryptionCookie={id:a.id,key:await Ke(LC,DC,this.logger,this.performanceClient,e)(s)}}else{const s=Hc(),l=await Ke(s4,CQ,this.logger,this.performanceClient,e)(),c=as(Rl,EQ,this.logger,this.performanceClient,e)(new Uint8Array(l));this.encryptionCookie={id:s,key:await Ke(LC,DC,this.logger,this.performanceClient,e)(l)};const h={id:s,key:c};t.setItem(VC,JSON.stringify(h),0,!0,sw.None)}await Ke(this.importExistingCache.bind(this),mQ,this.logger,this.performanceClient,e)(e),this.broadcast.addEventListener("message",s=>{this.updateCache(s,e)}),this.initialized=!0}getItem(e){return window.localStorage.getItem(e)}getUserData(e){if(!this.initialized)throw ut($g);return this.memoryStorage.getItem(e)}async decryptData(e,t,n){if(!this.initialized||!this.encryptionCookie)throw ut($g);if(t.id!==this.encryptionCookie.id)return this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},n),null;const a=await Ke(OC,MC,this.logger,this.performanceClient,n)(this.encryptionCookie.key,t.nonce,this.getContext(e),t.data);if(!a)return null;try{return{...JSON.parse(a),lastUpdatedAt:t.lastUpdatedAt}}catch{return this.performanceClient.incrementFields({encryptedCacheCorruptionCount:1},n),null}}setItem(e,t){window.localStorage.setItem(e,t)}async setUserData(e,t,n,a,s){if(!this.initialized||!this.encryptionCookie)throw ut($g);if(s)this.setItem(e,t);else{const{data:l,nonce:c}=await Ke(HN,xQ,this.logger,this.performanceClient,n)(this.encryptionCookie.key,t,this.getContext(e)),h={id:this.encryptionCookie.id,nonce:c,data:l,lastUpdatedAt:a};this.setItem(e,JSON.stringify(h))}this.memoryStorage.setItem(e,t),this.broadcast.postMessage({key:e,value:t,context:this.getContext(e)})}removeItem(e){this.memoryStorage.containsKey(e)&&(this.memoryStorage.removeItem(e),this.broadcast.postMessage({key:e,value:null,context:this.getContext(e)})),window.localStorage.removeItem(e)}getKeys(){return Object.keys(window.localStorage)}containsKey(e){return window.localStorage.hasOwnProperty(e)}clear(){this.memoryStorage.clear(),vl(this).forEach(n=>this.removeItem(n));const t=ns(this.clientId,this);t.idToken.forEach(n=>this.removeItem(n)),t.accessToken.forEach(n=>this.removeItem(n)),t.refreshToken.forEach(n=>this.removeItem(n)),this.getKeys().forEach(n=>{(n.startsWith(Nr)||n.indexOf(this.clientId)!==-1)&&this.removeItem(n)})}async importExistingCache(e){if(!this.encryptionCookie)return;let t=vl(this);t=await this.importArray(t,e),t.length?this.setItem(oh(),JSON.stringify(t)):this.removeItem(oh());const n=ns(this.clientId,this);n.idToken=await this.importArray(n.idToken,e),n.accessToken=await this.importArray(n.accessToken,e),n.refreshToken=await this.importArray(n.refreshToken,e),n.idToken.length||n.accessToken.length||n.refreshToken.length?this.setItem(lh(this.clientId),JSON.stringify(n)):this.removeItem(lh(this.clientId))}async getItemFromEncryptedCache(e,t){if(!this.encryptionCookie)return null;const n=this.getItem(e);if(!n)return null;let a;try{a=JSON.parse(n)}catch{return null}return tp(a)?a.id!==this.encryptionCookie.id?(this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},t),null):(this.performanceClient.incrementFields({encryptedCacheCount:1},t),Ke(OC,MC,this.logger,this.performanceClient,t)(this.encryptionCookie.key,a.nonce,this.getContext(e),a.data)):(this.performanceClient.incrementFields({unencryptedCacheCount:1},t),n)}async importArray(e,t){const n=[],a=[];return e.forEach(s=>{const l=this.getItemFromEncryptedCache(s,t).then(c=>{c?(this.memoryStorage.setItem(s,c),n.push(s)):this.removeItem(s)});a.push(l)}),await Promise.all(a),n}getContext(e){let t="";return e.includes(this.clientId)&&(t=this.clientId),t}updateCache(e,t){this.logger.trace("17cxcm",t);const n=this.performanceClient.startMeasurement(OQ);n.add({isBackground:!0});const{key:a,value:s,context:l}=e.data;if(!a){this.logger.error("0e10qr",t),n.end({success:!1,errorCode:"noKey"});return}if(l&&l!==this.clientId){this.logger.trace("04rtdy",t),n.end({success:!1,errorCode:"contextMismatch"});return}s?(this.memoryStorage.setItem(a,s),this.logger.verbose("1vzsgt",t)):(this.memoryStorage.removeItem(a),this.logger.verbose("04ypih",t)),n.end({success:!0})}}class KQ{constructor(){if(!window.sessionStorage)throw wr(l4)}async initialize(){}getItem(e){return window.sessionStorage.getItem(e)}getUserData(e){return this.getItem(e)}setItem(e,t){window.sessionStorage.setItem(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){window.sessionStorage.removeItem(e)}getKeys(){return Object.keys(window.sessionStorage)}containsKey(e){return window.sessionStorage.hasOwnProperty(e)}decryptData(){return Promise.resolve(null)}}const Rt={INITIALIZE_START:"msal:initializeStart",INITIALIZE_END:"msal:initializeEnd",ACTIVE_ACCOUNT_CHANGED:"msal:activeAccountChanged",LOGIN_SUCCESS:"msal:loginSuccess",ACQUIRE_TOKEN_START:"msal:acquireTokenStart",BROKERED_REQUEST_START:"msal:brokeredRequestStart",ACQUIRE_TOKEN_SUCCESS:"msal:acquireTokenSuccess",BROKERED_REQUEST_SUCCESS:"msal:brokeredRequestSuccess",ACQUIRE_TOKEN_FAILURE:"msal:acquireTokenFailure",BROKERED_REQUEST_FAILURE:"msal:brokeredRequestFailure",ACQUIRE_TOKEN_NETWORK_START:"msal:acquireTokenFromNetworkStart",HANDLE_REDIRECT_START:"msal:handleRedirectStart",HANDLE_REDIRECT_END:"msal:handleRedirectEnd",POPUP_OPENED:"msal:popupOpened",LOGOUT_START:"msal:logoutStart",LOGOUT_SUCCESS:"msal:logoutSuccess",LOGOUT_FAILURE:"msal:logoutFailure",LOGOUT_END:"msal:logoutEnd",RESTORE_FROM_BFCACHE:"msal:restoreFromBFCache",BROKER_CONNECTION_ESTABLISHED:"msal:brokerConnectionEstablished"};const GQ="@azure/msal-browser",Mc="5.1.0";function fl(A,e){const t=A.indexOf(e);t>-1&&A.splice(t,1)}class ow extends ew{constructor(e,t,n,a,s,l,c){super(e,n,a,s,c),this.cacheConfig=t,this.logger=a,this.internalStorage=new o0,this.browserStorage=qC(e,t.cacheLocation,a,s),this.temporaryCacheStorage=qC(e,xa.SessionStorage,a,s),this.cookieStorage=new p4,this.eventHandler=l}async initialize(e){this.performanceClient.addFields({cacheLocation:this.cacheConfig.cacheLocation,cacheRetentionDays:this.cacheConfig.cacheRetentionDays},e),await this.browserStorage.initialize(e),await this.migrateExistingCache(e),this.trackVersionChanges(e)}async migrateExistingCache(e){let t=vl(this.browserStorage),n=ns(this.clientId,this.browserStorage);this.performanceClient.addFields({preMigrateAcntCount:t.length,preMigrateATCount:n.accessToken.length,preMigrateITCount:n.idToken.length,preMigrateRTCount:n.refreshToken.length},e);for(let s=0;sh.includes(l)).forEach(h=>{this.browserStorage.removeItem(h),fl(c.idToken,h)}),[...c.accessToken].filter(h=>h.includes(l)).forEach(h=>{this.browserStorage.removeItem(h),fl(c.accessToken,h)}),[...c.refreshToken].filter(h=>h.includes(l)).forEach(h=>{this.browserStorage.removeItem(h),fl(c.refreshToken,h)}),this.setTokenKeys(c,a,n)}this.performanceClient.incrementFields({expiredAcntRemovedCount:1},a),this.browserStorage.removeItem(e)}getKMSIValues(){const e={},t=this.getTokenKeys().idToken;for(const n of t){const a=this.browserStorage.getUserData(n);if(a){const s=JSON.parse(a),l=Uo(s.secret,Zi);l&&(e[s.homeAccountId]=Fc(l))}}return e}async migrateIdTokens(e,t,n){const a=ns(this.clientId,this.browserStorage,e);if(a.idToken.length===0)return;const s=ns(this.clientId,this.browserStorage,Kr),l=vl(this.browserStorage),c=vl(this.browserStorage,t);for(const h of[...a.idToken]){this.performanceClient.incrementFields({oldITCount:1},n);const f=await this.updateOldEntry(h,n);if(!f){fl(a.idToken,h);continue}const g=l.find(k=>k.includes(f.homeAccountId)),y=c.find(k=>k.includes(f.homeAccountId));let C=null;if(g)C=this.getAccount(g,n);else if(y){const k=this.browserStorage.getItem(y),z=this.validateAndParseJson(k||"");C=z&&tp(z)?await this.browserStorage.decryptData(y,z,n):z}if(!C){this.performanceClient.incrementFields({skipITMigrateCount:1},n);continue}const v=Uo(f.secret,Zi),I=this.generateCredentialKey(f),x=this.getIdTokenCredential(I,n),_=Object.keys(v).includes("signin_state"),T=x&&Object.keys(Uo(x.secret,Zi)||{}).includes("signin_state");if(!x||f.lastUpdatedAt>x.lastUpdatedAt&&(_||!T)){const k=C.tenantProfiles||[],z=v2(v)||C.realm;if(z&&!k.find(le=>le.tenantId===z)){const le=Bh(C.homeAccountId,C.localAccountId,z,v);k.push(le)}C.tenantProfiles=k;const H=this.generateAccountKey(Rc(C)),re=Fc(v);await this.setUserData(H,JSON.stringify(C),n,C.lastUpdatedAt,re),l.includes(H)||l.push(H),await this.setUserData(I,JSON.stringify(f),n,f.lastUpdatedAt,re),this.performanceClient.incrementFields({migratedITCount:1},n),s.idToken.push(I)}}this.setTokenKeys(a,n,e),this.setTokenKeys(s,n),this.setAccountKeys(l,n)}async migrateAccessTokens(e,t,n){const a=ns(this.clientId,this.browserStorage,e);if(a.accessToken.length===0)return;const s=ns(this.clientId,this.browserStorage,Kr);for(const l of[...a.accessToken]){this.performanceClient.incrementFields({oldATCount:1},n);const c=await this.updateOldEntry(l,n);if(!c){fl(a.accessToken,l);continue}if(!(c.homeAccountId in t)){this.performanceClient.incrementFields({skipATMigrateCount:1},n);continue}const h=this.generateCredentialKey(c),f=t[c.homeAccountId];if(!s.accessToken.includes(h))await this.setUserData(h,JSON.stringify(c),n,c.lastUpdatedAt,f),this.performanceClient.incrementFields({migratedATCount:1},n),s.accessToken.push(h);else{const g=this.getAccessTokenCredential(h,n);(!g||c.lastUpdatedAt>g.lastUpdatedAt)&&(await this.setUserData(h,JSON.stringify(c),n,c.lastUpdatedAt,f),this.performanceClient.incrementFields({migratedATCount:1},n))}}this.setTokenKeys(a,n,e),this.setTokenKeys(s,n)}async migrateRefreshTokens(e,t,n){const a=ns(this.clientId,this.browserStorage,e);if(a.refreshToken.length===0)return;const s=ns(this.clientId,this.browserStorage,Kr);for(const l of[...a.refreshToken]){this.performanceClient.incrementFields({oldRTCount:1},n);const c=await this.updateOldEntry(l,n);if(!c){fl(a.refreshToken,l);continue}if(!(c.homeAccountId in t)){this.performanceClient.incrementFields({skipRTMigrateCount:1},n);continue}const h=this.generateCredentialKey(c),f=t[c.homeAccountId];if(!s.refreshToken.includes(h))await this.setUserData(h,JSON.stringify(c),n,c.lastUpdatedAt,f),this.performanceClient.incrementFields({migratedRTCount:1},n),s.refreshToken.push(h);else{const g=this.getRefreshTokenCredential(h,n);(!g||c.lastUpdatedAt>g.lastUpdatedAt)&&(await this.setUserData(h,JSON.stringify(c),n,c.lastUpdatedAt,f),this.performanceClient.incrementFields({migratedRTCount:1},n))}}this.setTokenKeys(a,n,e),this.setTokenKeys(s,n)}trackVersionChanges(e){const t=this.browserStorage.getItem(KC);t&&(this.logger.info("1wuc87",e),this.performanceClient.addFields({previousLibraryVersion:t},e)),t!==Mc&&this.setItem(KC,Mc,e)}validateAndParseJson(e){if(!e)return null;try{const t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}setItem(e,t,n){const a=new Array(Kr+1).fill(0),s=[],l=20;for(let c=0;c<=l;c++)try{if(this.browserStorage.setItem(e,t),c>0)for(let h=0;h<=Kr;h++){const f=a.slice(0,h).reduce((y,C)=>y+C,0);if(f>=c)break;const g=c>f+a[h]?f+a[h]:c;c>f&&a[h]>0&&this.removeAccessTokenKeys(s.slice(f,g),n,h)}break}catch(h){const f=$1(h);if(f.errorCode===Z1&&c0)for(let g=0;g<=Kr;g++){const y=l.slice(0,g).reduce((v,I)=>v+I,0);if(y>=f)break;const C=f>y+l[g]?y+l[g]:f;f>y&&l[g]>0&&this.removeAccessTokenKeys(c.slice(y,C),n,g)}break}catch(g){const y=$1(g);if(y.errorCode===Z1&&f-1?(n.splice(a,1),this.setAccountKeys(n,t)):this.logger.trace("1dytu2",t)}removeAccount(e,t){const n=this.getActiveAccount(t);n?.homeAccountId===e.homeAccountId&&n?.environment===e.environment&&this.setActiveAccount(null,t),super.removeAccount(e,t),this.removeAccountKeyFromMap(this.generateAccountKey(e),t),this.browserStorage.getKeys().forEach(a=>{a.includes(e.homeAccountId)&&a.includes(e.environment)&&this.browserStorage.removeItem(a)})}removeIdToken(e,t){super.removeIdToken(e,t);const n=this.getTokenKeys(),a=n.idToken.indexOf(e);a>-1&&(this.logger.info("05udv9",t),n.idToken.splice(a,1),this.setTokenKeys(n,t))}removeAccessToken(e,t,n=!0){super.removeAccessToken(e,t),n&&this.removeAccessTokenKeys([e],t)}removeAccessTokenKeys(e,t,n=Kr){this.logger.trace("17o18n",t);const a=this.getTokenKeys(n);let s=0;if(e.forEach(l=>{const c=a.accessToken.indexOf(l);c>-1&&(a.accessToken.splice(c,1),s++)}),s>0){this.logger.info("15i5d5",t),this.setTokenKeys(a,t,n);return}}removeRefreshToken(e,t){super.removeRefreshToken(e,t);const n=this.getTokenKeys(),a=n.refreshToken.indexOf(e);a>-1&&(this.logger.info("1f4fq3",t),n.refreshToken.splice(a,1),this.setTokenKeys(n,t))}getTokenKeys(e=Kr){return ns(this.clientId,this.browserStorage,e)}setTokenKeys(e,t,n=Kr){if(e.idToken.length===0&&e.accessToken.length===0&&e.refreshToken.length===0){this.removeItem(lh(this.clientId,n));return}else this.setItem(lh(this.clientId,n),JSON.stringify(e),t)}getIdTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("1jukz6",t),this.removeIdToken(e,t),null;const a=this.validateAndParseJson(n);return!a||!B_(a)?(this.logger.trace("1jukz6",t),null):(this.logger.trace("01ju66",t),a)}async setIdTokenCredential(e,t,n){this.logger.trace("13hjll",t);const a=this.generateCredentialKey(e),s=Date.now().toString();e.lastUpdatedAt=s,await this.setUserData(a,JSON.stringify(e),t,s,n);const l=this.getTokenKeys();l.idToken.indexOf(a)===-1&&(this.logger.info("07jy92",t),l.idToken.push(a),this.setTokenKeys(l,t))}getAccessTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("0bqvx8",t),this.removeAccessTokenKeys([e],t),null;const a=this.validateAndParseJson(n);return!a||!BC(a)?(this.logger.trace("0bqvx8",t),null):(this.logger.trace("1o81rl",t),a)}async setAccessTokenCredential(e,t,n){this.logger.trace("1pondb",t);const a=this.generateCredentialKey(e),s=Date.now().toString();e.lastUpdatedAt=s,await this.setUserData(a,JSON.stringify(e),t,s,n);const l=this.getTokenKeys(),c=l.accessToken.indexOf(a);c!==-1&&l.accessToken.splice(c,1),this.logger.trace("1onhey",t),l.accessToken.push(a),this.setTokenKeys(l,t)}getRefreshTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("0jlizt",t),this.removeRefreshToken(e,t),null;const a=this.validateAndParseJson(n);return!a||!CC(a)?(this.logger.trace("0jlizt",t),null):(this.logger.trace("0nokxi",t),a)}async setRefreshTokenCredential(e,t,n){this.logger.trace("0tcg8d",t);const a=this.generateCredentialKey(e),s=Date.now().toString();e.lastUpdatedAt=s,await this.setUserData(a,JSON.stringify(e),t,s,n);const l=this.getTokenKeys();l.refreshToken.indexOf(a)===-1&&(this.logger.info("0eckjs",t),l.refreshToken.push(a),this.setTokenKeys(l,t))}getAppMetadata(e,t){const n=this.browserStorage.getItem(e);if(!n)return this.logger.trace("1q101h",t),null;const a=this.validateAndParseJson(n);return!a||!x_(e,a)?(this.logger.trace("1q101h",t),null):(this.logger.trace("19pvg2",t),a)}setAppMetadata(e,t){this.logger.trace("0cyma6",t);const n=E_(e);this.setItem(n,JSON.stringify(e),t)}getServerTelemetry(e,t){const n=this.browserStorage.getItem(e);if(!n)return this.logger.trace("0jk19c",t),null;const a=this.validateAndParseJson(n);return!a||!C_(e,a)?(this.logger.trace("0jk19c",t),null):(this.logger.trace("12jguk",t),a)}setServerTelemetry(e,t,n){this.logger.trace("1poh61",n),this.setItem(e,JSON.stringify(t),n)}getAuthorityMetadata(e,t){const n=this.internalStorage.getItem(e);if(!n)return this.logger.trace("1r39oe",t),null;const a=this.validateAndParseJson(n);return a&&S_(e,a)?(this.logger.trace("1ohvk3",t),a):null}getAuthorityMetadataKeys(){return this.internalStorage.getKeys().filter(t=>this.isAuthorityMetadata(t))}setWrapperMetadata(e,t){this.internalStorage.setItem(pg.WRAPPER_SKU,e),this.internalStorage.setItem(pg.WRAPPER_VER,t)}getWrapperMetadata(){const e=this.internalStorage.getItem(pg.WRAPPER_SKU)||"",t=this.internalStorage.getItem(pg.WRAPPER_VER)||"";return[e,t]}setAuthorityMetadata(e,t,n){this.logger.trace("07w8n2",n),this.internalStorage.setItem(e,JSON.stringify(t))}getActiveAccount(e){const t=this.generateCacheKey(nC.ACTIVE_ACCOUNT_FILTERS),n=this.browserStorage.getItem(t);if(!n)return this.logger.trace("08gw0e",e),null;const a=this.validateAndParseJson(n);return a?(this.logger.trace("1t3ch7",e),this.getAccountInfoFilteredBy({homeAccountId:a.homeAccountId,localAccountId:a.localAccountId,tenantId:a.tenantId},e)):(this.logger.trace("0me1up",e),null)}setActiveAccount(e,t){const n=this.generateCacheKey(nC.ACTIVE_ACCOUNT_FILTERS);if(e){this.logger.verbose("0rsj80",t);const a={homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,tenantId:e.tenantId};this.setItem(n,JSON.stringify(a),t)}else this.logger.verbose("1bp5z5",t),this.browserStorage.removeItem(n);this.eventHandler.emitEvent(Rt.ACTIVE_ACCOUNT_CHANGED)}getThrottlingCache(e,t){const n=this.browserStorage.getItem(e);if(!n)return this.logger.trace("1h4wa6",t),null;const a=this.validateAndParseJson(n);return!a||!b_(e,a)?(this.logger.trace("1h4wa6",t),null):(this.logger.trace("0of6n8",t),a)}setThrottlingCache(e,t,n){this.logger.trace("0wfgh6",n),this.setItem(e,JSON.stringify(t),n)}getTemporaryCache(e,t,n){const a=n?this.generateCacheKey(e):e,s=this.temporaryCacheStorage.getItem(a);if(!s){if(this.cacheConfig.cacheLocation===xa.LocalStorage){const l=this.browserStorage.getItem(a);if(l)return this.logger.trace("1yt61y",t),l}return this.logger.trace("1qhy81",t),null}return s}setTemporaryCache(e,t,n){const a=n?this.generateCacheKey(e):e;this.temporaryCacheStorage.setItem(a,t)}removeItem(e){this.browserStorage.removeItem(e)}removeTemporaryItem(e){this.temporaryCacheStorage.removeItem(e)}getKeys(){return this.browserStorage.getKeys()}clear(e){this.removeAllAccounts(e),this.removeAppMetadata(e),this.temporaryCacheStorage.getKeys().forEach(t=>{(t.indexOf(Nr)!==-1||t.indexOf(this.clientId)!==-1)&&this.removeTemporaryItem(t)}),this.browserStorage.getKeys().forEach(t=>{(t.indexOf(Nr)!==-1||t.indexOf(this.clientId)!==-1)&&this.browserStorage.removeItem(t)}),this.internalStorage.clear()}generateCacheKey(e){return Ea.startsWith(e,Nr)?e:`${Nr}.${this.clientId}.${e}`}generateCredentialKey(e){const t=e.credentialType===_r.REFRESH_TOKEN&&e.familyId||e.clientId,n=e.tokenType&&e.tokenType.toLowerCase()!==MA.BEARER.toLowerCase()?e.tokenType.toLowerCase():"";return[`${Nr}.${Kr}`,e.homeAccountId,e.environment,e.credentialType,t,e.realm||"",e.target||"",n].join(jC).toLowerCase()}generateAccountKey(e){const t=e.homeAccountId.split(".")[1];return[`${Nr}.${ep}`,e.homeAccountId,e.environment,t||e.tenantId||""].join(jC).toLowerCase()}resetRequestCache(e){this.logger.trace("0h0ynu",e),this.removeTemporaryItem(this.generateCacheKey(Wn.REQUEST_PARAMS)),this.removeTemporaryItem(this.generateCacheKey(Wn.VERIFIER)),this.removeTemporaryItem(this.generateCacheKey(Wn.ORIGIN_URI)),this.removeTemporaryItem(this.generateCacheKey(Wn.URL_HASH)),this.removeTemporaryItem(this.generateCacheKey(Wn.NATIVE_REQUEST)),this.setInteractionInProgress(!1,void 0)}cacheAuthorizeRequest(e,t,n){this.logger.trace("1tzef5",t);const a=Xf(JSON.stringify(e));if(this.setTemporaryCache(Wn.REQUEST_PARAMS,a,!0),n){const s=Xf(n);this.setTemporaryCache(Wn.VERIFIER,s,!0)}}getCachedRequest(e){this.logger.trace("0uen20",e);const t=this.getTemporaryCache(Wn.REQUEST_PARAMS,e,!0);if(!t)throw ut(cN);const n=this.getTemporaryCache(Wn.VERIFIER,e,!0);let a,s="";try{a=JSON.parse(Zi(t)),n&&(s=Zi(n))}catch{throw this.logger.errorPii("0ewsey",e),this.logger.error("0tvdic",e),ut(uN)}return[a,s]}getCachedNativeRequest(){this.logger.trace("1yxcdm","");const e=this.getTemporaryCache(Wn.NATIVE_REQUEST,"",!0);if(!e)return this.logger.trace("0mnxd4",""),null;const t=this.validateAndParseJson(e);return t||(this.logger.error("0rrkip",""),null)}isInteractionInProgress(e){const t=this.getInteractionInProgress()?.clientId;return e?t===this.clientId:!!t}getInteractionInProgress(){const e=`${Nr}.${Wn.INTERACTION_STATUS_KEY}`,t=this.getTemporaryCache(e,"",!1);try{return t?JSON.parse(t):null}catch{return this.logger.error("0jjyys",""),this.removeTemporaryItem(e),this.resetRequestCache(""),c4(window),null}}setInteractionInProgress(e,t=bl.SIGNIN,n=!1,a=""){const s=`${Nr}.${Wn.INTERACTION_STATUS_KEY}`;if(e){if(this.getInteractionInProgress())if(n)this.logger.warning("1pmscr",a),GN(this.logger,a),this.removeTemporaryItem(s);else throw ut(tN);this.setTemporaryCache(s,JSON.stringify({clientId:this.clientId,type:t}),!1)}else!e&&this.getInteractionInProgress()?.clientId===this.clientId&&this.removeTemporaryItem(s)}async hydrateCache(e,t){const n=E2(e.account.homeAccountId,e.account.environment,e.idToken,this.clientId,e.tenantId),a=x2(e.account.homeAccountId,e.account.environment,e.accessToken,this.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?mC(e.expiresOn):0,e.extExpiresOn?mC(e.extExpiresOn):0,Zi,void 0,e.tokenType,void 0,t.sshKid),s={idToken:n,accessToken:a};return this.saveCacheRecord(s,e.correlationId,Fc(Uo(e.idToken,Zi)),EA.hydrateCache)}async saveCacheRecord(e,t,n,a,s){try{await super.saveCacheRecord(e,t,n,a,s)}catch(l){if(l instanceof ih&&this.performanceClient&&t)try{const c=this.getTokenKeys();this.performanceClient.addFields({cacheRtCount:c.refreshToken.length,cacheIdCount:c.idToken.length,cacheAtCount:c.accessToken.length},t)}catch{}throw l}}}function qC(A,e,t,n){try{switch(e){case xa.LocalStorage:return new jQ(A,t,n);case xa.SessionStorage:return new KQ;case xa.MemoryStorage:default:break}}catch(a){t.error(a,"")}return new o0}const zQ=(A,e,t,n)=>{const a={cacheLocation:xa.MemoryStorage,cacheRetentionDays:5};return new ow(A,a,yp,e,t,n)};function VQ(A,e,t,n,a){return A.verbose("1yd030",n),t?e.getAllAccounts(a,n):[]}function qQ(A,e,t,n){if(e.trace("0u7b90",n),Object.keys(A).length===0)return e.warning("1kz0cu",n),null;const a=t.getAccountInfoFilteredBy(A,n);return a?(e.verbose("0btgll",n),a):(e.verbose("0ltaj5",n),null)}function YQ(A,e,t){e.setActiveAccount(A,t)}function XQ(A,e){return A.getActiveAccount(e)}const JQ="msal.broadcast.event";class WQ{constructor(e){this.eventCallbacks=new Map,this.logger=e||new Dl({}),typeof BroadcastChannel<"u"&&(this.broadcastChannel=new BroadcastChannel(JQ)),this.invokeCrossTabCallbacks=this.invokeCrossTabCallbacks.bind(this)}addEventCallback(e,t,n){if(typeof window<"u"){const a=n||aw();return this.eventCallbacks.has(a)?(this.logger.error("1578i0",""),null):(this.eventCallbacks.set(a,[e,t||[]]),this.logger.verbose("1cnec4",""),a)}return null}removeEventCallback(e){this.eventCallbacks.delete(e),this.logger.verbose("12zotd","")}emitEvent(e,t,n,a){const s={eventType:e,interactionType:t||null,payload:n||null,error:a||null,timestamp:Date.now()};switch(e){case Rt.LOGIN_SUCCESS:case Rt.LOGOUT_SUCCESS:case Rt.ACTIVE_ACCOUNT_CHANGED:this.broadcastChannel?.postMessage(s)}this.invokeCallbacks(s)}invokeCallbacks(e){this.eventCallbacks.forEach(([t,n],a)=>{(n.length===0||n.includes(e.eventType))&&(this.logger.verbose("15jpwk",""),t.apply(null,[e]))})}invokeCrossTabCallbacks(e){const t=e.data;this.invokeCallbacks(t)}subscribeCrossTab(){this.broadcastChannel?.addEventListener("message",this.invokeCrossTabCallbacks)}unsubscribeCrossTab(){this.broadcastChannel?.removeEventListener("message",this.invokeCrossTabCallbacks)}}class m4{constructor(e,t,n,a,s,l,c,h,f){this.config=e,this.browserStorage=t,this.browserCrypto=n,this.networkClient=this.config.system.networkClient,this.eventHandler=s,this.navigationClient=l,this.platformAuthProvider=f,this.correlationId=h,this.logger=a.clone(va.MSAL_SKU,Mc),this.performanceClient=c}}function Up(A,e,t,n){t.verbose("0bd1la",n);const a=A||e||"";return QA.getAbsoluteUrl(a,xl())}function Ti(A,e,t,n,a,s){a.verbose("1p12tq",t);const l={clientId:e,correlationId:t,apiId:A,forceRefresh:!1,wrapperSKU:n.getWrapperMetadata()[0],wrapperVer:n.getWrapperMetadata()[1]};return new Yf(l,n)}async function Fo(A,e,t,n,a,s,l,c,h){const f=c&&c.hasOwnProperty("instance_aware")?c.instance_aware:void 0,g={protocolMode:A.system.protocolMode,OIDCOptions:A.auth.OIDCOptions,knownAuthorities:A.auth.knownAuthorities,cloudDiscoveryMetadata:A.auth.cloudDiscoveryMetadata,authorityMetadata:A.auth.authorityMetadata},y=s||A.auth.authority,C=f?.length?f==="true":A.auth.instanceAware,v=h&&C?A.auth.authority.replace(QA.getDomainFromUrl(y),h.environment):y,I=Si.generateAuthority(v,l||A.auth.azureCloudOptions),x=await Ke(zx,hQ,a,t,e)(I,A.system.networkClient,n,g,a,e,t);if(h&&!x.isAlias(h.environment))throw An(KF);return x}async function K2(A,e,t,n,a){if(a)try{A.removeAccount(a,n),t.verbose("0s4z6h",n)}catch{t.error("0mgg1d",n)}else try{t.verbose("0zj631",n),A.clear(n),await e.clearKeystore(n)}catch{t.error("12ih0c",n)}}async function G2(A,e,t,n,a){const s=A.authority||e.auth.authority,l=[...A&&A.scopes||[]],c={...A,correlationId:A.correlationId,authority:s,scopes:l};if(!c.authenticationScheme)c.authenticationScheme=MA.BEARER,n.verbose("1l4fwv",a);else{if(c.authenticationScheme===MA.SSH){if(!A.sshJwk)throw An(r2);if(!A.sshKid)throw An(MF)}n.verbose("1ecmns",a)}return c}async function ZQ(A,e,t,n,a){const s=await Ke(G2,D2,a,n,A.correlationId)(A,t,n,a,A.correlationId);return{...A,...s,account:e,forceRefresh:A.forceRefresh||!1}}function w4(A,e){let t;const n=A.httpMethod;if(e===Fi.EAR){if(n&&n!==rh.POST)throw An(GF);t=rh.POST}else t=n||rh.GET;return t}class bh extends m4{initializeLogoutRequest(e){this.logger.verbose("0546u4",this.correlationId);const t={correlationId:this.correlationId,...e};if(e)if(e.logoutHint)this.logger.verbose("12k4l4",this.correlationId);else if(e.account){const n=this.getLogoutHintFromIdTokenClaims(e.account);n&&(this.logger.verbose("0st5di",this.correlationId),t.logoutHint=n)}else this.logger.verbose("0pdtc3",this.correlationId);else this.logger.verbose("07ndze",this.correlationId);return!e||e.postLogoutRedirectUri!==null?e&&e.postLogoutRedirectUri?(this.logger.verbose("1vamm6",t.correlationId),t.postLogoutRedirectUri=QA.getAbsoluteUrl(e.postLogoutRedirectUri,xl())):this.config.auth.postLogoutRedirectUri===null?this.logger.verbose("15m5g7",t.correlationId):this.config.auth.postLogoutRedirectUri?(this.logger.verbose("1f4xlz",t.correlationId),t.postLogoutRedirectUri=QA.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri,xl())):(this.logger.verbose("17s5rf",t.correlationId),t.postLogoutRedirectUri=QA.getAbsoluteUrl(xl(),xl())):this.logger.verbose("0ljv63",t.correlationId),t}getLogoutHintFromIdTokenClaims(e){const t=e.idTokenClaims;if(t){if(t.login_hint)return t.login_hint;this.logger.verbose("0mvp54",this.correlationId)}else this.logger.verbose("1e7bdp",this.correlationId);return null}async createAuthCodeClient(e){const t=await Ke(this.getClientConfiguration.bind(this),a0,this.logger,this.performanceClient,this.correlationId)(e);return new Vx(t,this.performanceClient)}async getClientConfiguration(e){const{serverTelemetryManager:t,requestAuthority:n,requestAzureCloudOptions:a,requestExtraQueryParameters:s,account:l}=e,c=e.authority||await Ke(Fo,Tc,this.logger,this.performanceClient,this.correlationId)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,a,s,l),h=this.config.system.loggerOptions;return{authOptions:{clientId:this.config.auth.clientId,authority:c,clientCapabilities:this.config.auth.clientCapabilities,redirectUri:this.config.auth.redirectUri},systemOptions:{tokenRenewalOffsetSeconds:this.config.system.tokenRenewalOffsetSeconds,preventCorsPreflight:!0},loggerOptions:{loggerCallback:h.loggerCallback,piiLoggingEnabled:h.piiLoggingEnabled,logLevel:h.logLevel,correlationId:this.correlationId},cryptoInterface:this.browserCrypto,networkInterface:this.networkClient,storageInterface:this.browserStorage,serverTelemetryManager:t,libraryInfo:{sku:va.MSAL_SKU,version:Mc,cpu:"",os:""},telemetry:this.config.telemetry}}}async function l0(A,e,t,n,a,s,l,c){const h=Up(A.redirectUri,t.auth.redirectUri,s,c),f={interactionType:e},g=JT(n,A&&A.state||"",f),C={...await Ke(G2,D2,s,l,c)({...A,correlationId:c},t,l,s,c),redirectUri:h,state:g,nonce:A.nonce||Hc(),responseMode:t.auth.OIDCOptions.responseMode},v={...C,httpMethod:w4(C,t.system.protocolMode)};if(A.loginHint||A.sid)return v;const I=A.account||a.getActiveAccount(c);return I&&(s.verbose("1eqlb3",c),s.verbosePii("0tf99t",c),v.account=I),v}function $Q(A,e){if(!e)return null;try{return cd(A.base64Decode,e).libraryState.meta}catch{throw tt(Vf)}}function Qf(A,e,t,n){const a=vp(A);if(!a)throw Ux(A)?(t.error("13pl0s",n),t.errorPii("1097vx",n),ut($_)):(t.error("18h0l1",n),ut(Z_));return a}function eL(A,e,t){if(!A.state)throw ut(T2);const n=$Q(e,A.state);if(!n)throw ut($x);if(n.interactionType!==t)throw ut(eN)}class v4{constructor(e,t,n,a,s){this.authModule=e,this.browserStorage=t,this.authCodeRequest=n,this.logger=a,this.performanceClient=s}async handleCodeResponse(e,t,n){let a;try{a=H_(e,t.state)}catch(s){throw s instanceof zc&&s.subError===rw?ut(rw):s}return Ke(this.handleCodeResponseFromServer.bind(this),Hx,this.logger,this.performanceClient,t.correlationId)(a,t,n)}async handleCodeResponseFromServer(e,t,n,a=!0){if(this.logger.trace("0mf2hb",t.correlationId),this.authCodeRequest.code=e.code,a&&(e.nonce=t.nonce||void 0),e.state=t.state,e.client_info)this.authCodeRequest.clientInfo=e.client_info;else{const l=this.createCcsCredentials(t);l&&(this.authCodeRequest.ccsCredential=l)}return await Ke(this.authModule.acquireToken.bind(this.authModule),uQ,this.logger,this.performanceClient,t.correlationId)(this.authCodeRequest,n,e)}createCcsCredentials(e){return e.account?{credential:e.account.homeAccountId,type:is.HOME_ACCOUNT_ID}:e.loginHint?{credential:e.loginHint,type:is.UPN}:null}}const tL="ContentError",AL="PageException",nL="user_switch";const rL="USER_INTERACTION_REQUIRED",iL="USER_CANCEL",aL="NO_NETWORK",sL="PERSISTENT_ERROR",oL="DISABLED",lL="ACCOUNT_UNAVAILABLE",cL="UX_NOT_ALLOWED";const uL=-2147186943;class Hs extends en{constructor(e,t,n){super(e,t||r0(e)),Object.setPrototypeOf(this,Hs.prototype),this.name="NativeAuthError",this.ext=n}}function Ju(A){if(A.ext&&A.ext.status&&(A.ext.status===sL||A.ext.status===oL)||A.ext&&A.ext.error&&A.ext.error===uL)return!0;switch(A.errorCode){case tL:case AL:return!0;default:return!1}}function Ip(A,e,t){if(t&&t.status)switch(t.status){case lL:return bp(zT,r0(A));case rL:return new os(A,e);case iL:return ut(rw);case aL:return ut(iw);case cL:return bp(Rx)}return new Hs(A,e,t)}class y4 extends bh{async acquireToken(e){const t=Ti(EA.acquireTokenSilent_silentFlow,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),n=await Ke(this.getClientConfiguration.bind(this),a0,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,account:e.account}),a=new O_(n,this.performanceClient);this.logger.verbose("0wa871",this.correlationId);try{const l=(await Ke(a.acquireCachedToken.bind(a),oQ,this.logger,this.performanceClient,e.correlationId)(e))[0];return this.performanceClient.addFields({fromCache:!0},e.correlationId),l}catch(s){throw s instanceof hd&&s.errorCode===t4&&this.logger.verbose("06wena",this.correlationId),s}}logout(e){this.logger.verbose("1rkurh",this.correlationId);const t=this.initializeLogoutRequest(e);return K2(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,t.account)}}class Ap extends m4{constructor(e,t,n,a,s,l,c,h,f,g,y,C){super(e,t,n,a,s,l,h,C,f),this.apiId=c,this.accountId=g,this.platformAuthProvider=f,this.nativeStorageManager=y,this.silentCacheClient=new y4(e,this.nativeStorageManager,n,a,s,l,h,C,f);const v=this.platformAuthProvider.getExtensionName();this.skus=Yf.makeExtraSkuString({libraryName:va.MSAL_SKU,libraryVersion:Mc,extensionName:v,extensionVersion:this.platformAuthProvider.getExtensionVersion()})}addRequestSKUs(e){e.extraParameters={...e.extraParameters,[FF]:this.skus}}async acquireToken(e,t){this.logger.trace("03qeos",this.correlationId);const n=this.performanceClient.startMeasurement(d4,e.correlationId),a=ls(),s=Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{const l=await this.initializeNativeRequest(e);try{const h=await this.acquireTokensFromCache(this.accountId,l);return n.end({success:!0,isNativeBroker:!1,fromCache:!0}),h}catch(h){if(t===ri.AccessToken)throw this.logger.info("0eitbc",this.correlationId),h;this.logger.info("0957j1",this.correlationId)}const c=await this.platformAuthProvider.sendMessage(l);return await this.handleNativeResponse(c,l,a).then(h=>(n.end({success:!0,isNativeBroker:!0,requestId:h.requestId}),s.clearNativeBrokerErrorCode(),h)).catch(h=>{throw n.end({success:!1,errorCode:h.errorCode,subErrorCode:h.subError,isNativeBroker:!0}),h})}catch(l){throw l instanceof Hs&&s.setNativeBrokerErrorCode(l.errorCode),l}}createSilentCacheRequest(e,t){return{authority:e.authority,correlationId:this.correlationId,scopes:qr.fromString(e.scope).asArray(),account:t,forceRefresh:!1}}async acquireTokensFromCache(e,t){if(!e)throw this.logger.warning("1ndf3e",this.correlationId),tt(lC);const n=this.browserStorage.getBaseAccountInfo({nativeAccountId:e},t.correlationId);if(!n)throw tt(lC);try{const a=this.createSilentCacheRequest(t,n),s=await this.silentCacheClient.acquireToken(a),l={...n,idTokenClaims:s?.idTokenClaims,idToken:s?.idToken};return{...s,account:l}}catch(a){throw a}}async acquireTokenRedirect(e,t,n){this.logger.trace("0luikq",this.correlationId);const a=await this.initializeNativeRequest(e),s=n?.navigateToLoginRequestUrl??!0;try{await this.platformAuthProvider.sendMessage(a)}catch(h){if(h instanceof Hs&&(Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger).setNativeBrokerErrorCode(h.errorCode),Ju(h)))throw h}this.browserStorage.setTemporaryCache(Wn.NATIVE_REQUEST,JSON.stringify(a),!0);const l={apiId:EA.acquireTokenRedirect,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},c=s?window.location.href:Up(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId);t.end({success:!0}),await this.navigationClient.navigateExternal(c,l)}async handleRedirectPromise(e,t){if(this.logger.trace("1c5lhw",this.correlationId),!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("0le6uv",this.correlationId),null;const n=this.browserStorage.getCachedNativeRequest();if(!n)return this.logger.verbose("0a6zjb",this.correlationId),e&&t&&e?.addFields({errorCode:"no_cached_request"},t),null;const{prompt:a,...s}=n;a&&this.logger.verbose("0ac34v",this.correlationId),this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Wn.NATIVE_REQUEST));const l=ls();try{this.logger.verbose("003x5a",this.correlationId);const c=await this.platformAuthProvider.sendMessage(s),h=await this.handleNativeResponse(c,s,l);return Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger).clearNativeBrokerErrorCode(),h}catch(c){throw c}}logout(){return this.logger.trace("0u2sjm",this.correlationId),Promise.reject("Logout not implemented yet")}async handleNativeResponse(e,t,n){this.logger.trace("1bojln",this.correlationId);const a=Uo(e.id_token,Zi),s=this.createHomeAccountIdentifier(e,a),l=this.browserStorage.getAccountInfoFilteredBy({nativeAccountId:t.accountId},this.correlationId)?.homeAccountId;if(t.extraParameters?.child_client_id&&e.account.id!==t.accountId)this.logger.info("1ub1in",this.correlationId);else if(s!==l&&e.account.id!==t.accountId)throw Ip(nL);const c=await Fo(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,t.authority),h=Dx(this.browserStorage,c,s,Zi,this.correlationId,a,e.client_info,void 0,a.tid,void 0,e.account.id);e.expires_in=Number(e.expires_in);const f=await this.generateAuthenticationResult(e,t,a,h,c.canonicalAuthority,n);return await this.cacheAccount(h,Fc(a)),await this.cacheNativeTokens(e,t,s,a,e.access_token,f.tenantId,n),f}createHomeAccountIdentifier(e,t){return _x(e.client_info||"",rs.Default,this.logger,this.browserCrypto,this.correlationId,t)}generateScopes(e,t){return t?qr.fromString(t):qr.fromString(e)}async generatePopAccessToken(e,t){if(t.tokenType===MA.POP&&t.signPopToken){if(e.shr)return this.logger.trace("0coqhu",this.correlationId),e.shr;const n=new mh(this.browserCrypto,this.performanceClient),a={resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,shrNonce:t.shrNonce,correlationId:this.correlationId};if(!t.keyId)throw tt(mx);return n.signPopToken(e.access_token,t.keyId,a)}else return e.access_token}async generateAuthenticationResult(e,t,n,a,s,l){const c=this.addTelemetryFromNativeResponse(e.properties.MATS),h=this.generateScopes(t.scope,e.scope),f=e.account.properties||{},g=f.UID||n.oid||n.sub||"",y=f.TenantId||n.tid||"",C=m2(Rc(a),void 0,n,e.id_token);C.nativeAccountId!==e.account.id&&(C.nativeAccountId=e.account.id);const v=await this.generatePopAccessToken(e,t),I=t.tokenType===MA.POP?MA.POP:MA.BEARER;return{authority:s,uniqueId:g,tenantId:y,scopes:h.asArray(),account:C,idToken:e.id_token,idTokenClaims:n,accessToken:v,fromCache:c?this.isResponseFromCache(c):!1,expiresOn:Zg(l+e.expires_in),tokenType:I,correlationId:this.correlationId,state:e.state,fromPlatformBroker:!0}}async cacheAccount(e,t){await this.browserStorage.setAccount(e,this.correlationId,t,this.apiId),this.browserStorage.removeAccountContext(Rc(e),this.correlationId)}cacheNativeTokens(e,t,n,a,s,l,c){const h=E2(n,t.authority,e.id_token||"",t.clientId,a.tid||""),f=t.tokenType===MA.POP?$B:(typeof e.expires_in=="string"?parseInt(e.expires_in,10):e.expires_in)||0,g=c+f,y=this.generateScopes(e.scope,t.scope),C=x2(n,t.authority,s,t.clientId,a.tid||l,y.printScopes(),g,0,Zi,void 0,t.tokenType,void 0,t.keyId),v={idToken:h,accessToken:C};return this.nativeStorageManager.saveCacheRecord(v,this.correlationId,Fc(a),this.apiId,t.storeInCache)}getExpiresInValue(e,t){return e===MA.POP?$B:(typeof t=="string"?parseInt(t,10):t)||0}addTelemetryFromNativeResponse(e){const t=this.getMATSFromResponse(e);return t?(this.performanceClient.addFields({extensionId:this.platformAuthProvider.getExtensionId(),extensionVersion:this.platformAuthProvider.getExtensionVersion(),matsBrokerVersion:t.broker_version,matsAccountJoinOnStart:t.account_join_on_start,matsAccountJoinOnEnd:t.account_join_on_end,matsDeviceJoin:t.device_join,matsPromptBehavior:t.prompt_behavior,matsApiErrorCode:t.api_error_code,matsUiVisible:t.ui_visible,matsSilentCode:t.silent_code,matsSilentBiSubCode:t.silent_bi_sub_code,matsSilentMessage:t.silent_message,matsSilentStatus:t.silent_status,matsHttpStatus:t.http_status,matsHttpEventCount:t.http_event_count},this.correlationId),t):null}getMATSFromResponse(e){if(e)try{return JSON.parse(e)}catch{this.logger.error("0b3l57",this.correlationId)}return null}isResponseFromCache(e){return typeof e.is_cached>"u"?(this.logger.verbose("1okqev",this.correlationId),!1):!!e.is_cached}async initializeNativeRequest(e){this.logger.trace("04j6wj",this.correlationId);const t=await this.getCanonicalAuthority(e),{scopes:n,...a}=e,s=new qr(n||[]);s.appendScopes(yh);const l={...a,accountId:this.accountId,clientId:this.config.auth.clientId,authority:t.urlString,scope:s.printScopes(),redirectUri:Up(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId),prompt:this.getPrompt(e.prompt),correlationId:this.correlationId,tokenType:e.authenticationScheme,windowTitleSubstring:document.title,extraParameters:{...e.extraParameters},extendedExpiryToken:!1,keyId:e.popKid};if(l.signPopToken&&e.popKid)throw ut(CN);if(this.handleExtraBrokerParams(l),l.extraParameters=l.extraParameters||{},l.extraParameters.telemetry=ya.MATS_TELEMETRY,e.authenticationScheme===MA.POP){const c={resourceRequestUri:e.resourceRequestUri,resourceRequestMethod:e.resourceRequestMethod,shrClaims:e.shrClaims,shrNonce:e.shrNonce,correlationId:this.correlationId},h=new mh(this.browserCrypto,this.performanceClient);let f;if(l.keyId)f=this.browserCrypto.base64UrlEncode(JSON.stringify({kid:l.keyId})),l.signPopToken=!1;else{const g=await Ke(h.generateCnf.bind(h),ud,this.logger,this.performanceClient,this.correlationId)(c,this.logger);f=g.reqCnfString,l.keyId=g.kid,l.signPopToken=!0}l.reqCnf=f}return this.addRequestSKUs(l),l}async getCanonicalAuthority(e){const t=e.authority||this.config.auth.authority,{azureCloudOptions:n,account:a}=e;a&&await Fo(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,t,n,void 0,a);const s=new QA(t);return s.validateAsUri(),s}getPrompt(e){switch(this.apiId){case EA.ssoSilent:case EA.acquireTokenSilent_silentFlow:return this.logger.trace("1hiwaz",this.correlationId),Ii.NONE}if(!e){this.logger.trace("1qlu04",this.correlationId);return}switch(e){case Ii.NONE:case Ii.CONSENT:case Ii.LOGIN:return this.logger.trace("1ynje4",this.correlationId),e;default:throw this.logger.trace("0nkr6q",this.correlationId),ut(yN)}}handleExtraBrokerParams(e){const t=e.extraParameters&&e.extraParameters.hasOwnProperty(pp)&&e.extraParameters.hasOwnProperty(mp)&&e.extraParameters.hasOwnProperty(Oc);if(!e.embeddedClientId&&!t)return;let n="";const a=e.redirectUri;e.embeddedClientId?(e.redirectUri=this.config.auth.redirectUri,n=e.embeddedClientId):e.extraParameters&&(e.redirectUri=e.extraParameters[mp],n=e.extraParameters[Oc]),e.extraParameters={child_client_id:n,child_redirect_uri:a},this.performanceClient?.addFields({embeddedClientId:n,embeddedRedirectUri:a},e.correlationId)}}async function z2(A,e,t,n,a){const s=k_({...A.auth,authority:e},t,n,a);if(u2(s,{sku:va.MSAL_SKU,version:Mc,os:"",cpu:""}),A.system.protocolMode!==Fi.OIDC&&h2(s,A.telemetry.application),t.platformBroker&&(lT(s),t.authenticationScheme===MA.POP)){const l=new _o(n,a),c=new mh(l,a);let h;t.popKid?h=l.encodeKid(t.popKid):h=(await Ke(c.generateCnf.bind(c),ud,n,a,t.correlationId)(t,n)).reqCnfString,g2(s,h)}return Wp(s,t.correlationId,a),s}async function V2(A,e,t,n,a){if(!t.codeChallenge)throw An(lx);const s=await Ke(z2,lQ,n,a,t.correlationId)(A,e,t,n,a);return i2(s,Zw.CODE),f2(s,t.codeChallenge,Ww),Ps(s,{...t.extraQueryParameters,...t.extraParameters}),S2(e,s)}async function q2(A,e,t,n,a,s){if(!n.earJwk)throw ut(Zx);const l=await z2(e,t,n,a,s);i2(l,Zw.IDTOKEN_TOKEN_REFRESHTOKEN),yT(l,n.earJwk),f2(l,n.codeChallenge,Ww),Ps(l,{...n.extraParameters});const c=new Map;Ps(c,n.extraQueryParameters||{});const h=S2(t,c);return B4(A,h,l)}async function Y2(A,e,t,n,a,s){const l=await z2(e,t,n,a,s);i2(l,Zw.CODE),f2(l,n.codeChallenge,n.codeChallengeMethod||Ww),Ps(l,{...n.extraParameters});const c=new Map;Ps(c,n.extraQueryParameters||{});const h=S2(t,c);return B4(A,h,l)}function B4(A,e,t){const n=A.createElement("form");return n.method="post",n.action=e,t.forEach((a,s)=>{const l=A.createElement("input");l.hidden=!0,l.name=s,l.value=a,n.appendChild(l)}),A.body.appendChild(n),n}async function C4(A,e,t,n,a,s,l,c,h,f){if(c.verbose("11qcow",A.correlationId),!f)throw ut(n4);const g=new _o(c,h),y=new Ap(n,a,g,c,l,n.system.navigationClient,t,h,f,e,s,A.correlationId),{userRequestState:C}=cd(g.base64Decode,A.state);return Ke(y.acquireToken.bind(y),d4,c,h,A.correlationId)({...A,state:C,prompt:void 0})}async function ch(A,e,t,n,a,s,l,c,h,f,g,y){if(ks.removeThrottle(l,a.auth.clientId,A),e.accountId)return Ke(C4,g4,f,g,A.correlationId)(A,e.accountId,n,a,l,c,h,f,g,y);const C={...A,code:e.code||"",codeVerifier:t},v=new v4(s,l,C,f,g);return await Ke(v.handleCodeResponse.bind(v),cQ,f,g,A.correlationId)(e,A,n)}async function X2(A,e,t,n,a,s,l,c,h,f,g){if(ks.removeThrottle(s,n.auth.clientId,A),qx(e,A.state),!e.ear_jwe)throw ut(W_);if(!A.earJwk)throw ut(Zx);const y=JSON.parse(await Ke(kN,SQ,h,f,A.correlationId)(A.earJwk,e.ear_jwe));if(y.accountId)return Ke(C4,g4,h,f,A.correlationId)(A,y.accountId,t,n,s,l,c,h,f,g);const C=new kc(n.auth.clientId,s,new _o(h,f),h,f,null,null);C.validateTokenResponse(y,A.correlationId);const v={code:"",state:A.state,nonce:A.nonce,client_info:y.client_info,cloud_graph_host_name:y.cloud_graph_host_name,cloud_instance_host_name:y.cloud_instance_host_name,cloud_instance_name:y.cloud_instance_name,msgraph_host:y.msgraph_host};return await Ke(C.handleServerTokenResponse.bind(C),b2,h,f,A.correlationId)(y,a,ls(),A,t,v,void 0,void 0,void 0,void 0)}const hL=32;async function Pc(A,e,t){const n=as(fL,wQ,e,A,t)(A,e,t),a=await Ke(dL,vQ,e,A,t)(n,A,e,t);return{verifier:n,challenge:a}}function fL(A,e,t){try{const n=new Uint8Array(hL);return as(NN,BQ,e,A,t)(n),Rl(n)}catch{throw ut(Wx)}}async function dL(A,e,t,n){try{const a=await Ke(a4,yQ,t,e,n)(A);return Rl(new Uint8Array(a))}catch{throw ut(Wx)}}class Fp{navigateInternal(e,t){return Fp.defaultNavigateWindow(e,t)}navigateExternal(e,t){return Fp.defaultNavigateWindow(e,t)}static defaultNavigateWindow(e,t){return t.noHistory?window.location.replace(e):window.location.assign(e),new Promise((n,a)=>{setTimeout(()=>{a(ut(xp,"failed_to_redirect"))},t.timeout)})}}class gL{async sendGetRequestAsync(e,t){let n,a={},s=0;const l=YC(t);try{n=await fetch(e,{method:UC.GET,headers:l})}catch(c){throw Cf(ut(window.navigator.onLine?fN:iw),void 0,void 0,c)}a=XC(n.headers);try{return s=n.status,{headers:a,body:await n.json(),status:s}}catch(c){throw Cf(ut(_C),s,a,c)}}async sendPostRequestAsync(e,t){const n=t&&t.body||"",a=YC(t);let s,l=0,c={};try{s=await fetch(e,{method:UC.POST,headers:a,body:n})}catch(h){throw Cf(ut(window.navigator.onLine?hN:iw),void 0,void 0,h)}c=XC(s.headers);try{return l=s.status,{headers:c,body:await s.json(),status:l}}catch(h){throw Cf(ut(_C),l,c,h)}}}function YC(A){try{const e=new Headers;if(!(A&&A.headers))return e;const t=A.headers;return Object.entries(t).forEach(([n,a])=>{e.append(n,a)}),e}catch(e){throw Cf(ut(bN),void 0,void 0,e)}}function XC(A){try{const e={};return A.forEach((t,n)=>{e[n]=t}),e}catch{throw ut(EN)}}const pL=6e4,mL=1e4,wL=3e4,b4=2e3;function vL({auth:A,cache:e,system:t,telemetry:n},a){const s={clientId:"",authority:`${XE}`,knownAuthorities:[],cloudDiscoveryMetadata:"",authorityMetadata:"",redirectUri:typeof window<"u"&&window.location?window.location.href.split("?")[0].split("#")[0]:"",postLogoutRedirectUri:"",clientCapabilities:[],OIDCOptions:{responseMode:$w.FRAGMENT,defaultScopes:[WE,ZE,Jw]},azureCloudOptions:{azureCloudInstance:p2.None,tenant:""},instanceAware:!1},l={cacheLocation:xa.SessionStorage,cacheRetentionDays:5},c={loggerCallback:()=>{},logLevel:vn.Info,piiLoggingEnabled:!1},f={...{...Qx,loggerOptions:c,networkClient:a?new gL:R_,navigationClient:new Fp,popupBridgeTimeout:t?.popupBridgeTimeout||pL,iframeBridgeTimeout:t?.iframeBridgeTimeout||mL,redirectNavigationTimeout:wL,allowRedirectInIframe:!1,navigatePopups:!0,allowPlatformBroker:!1,nativeBrokerHandshakeTimeout:t?.nativeBrokerHandshakeTimeout||b4,protocolMode:Fi.AAD},...t,loggerOptions:t?.loggerOptions||c},g={application:{appName:"",appVersion:""},client:new Nx};if(t?.protocolMode!==Fi.OIDC&&A?.OIDCOptions&&new Dl(f.loggerOptions).warning(JSON.stringify(An(PF)),""),t?.protocolMode&&t.protocolMode===Fi.OIDC&&f?.allowPlatformBroker)throw An(jF);return{auth:{...s,...A,OIDCOptions:{...s.OIDCOptions,...A?.OIDCOptions}},cache:{...l,...e},system:f,telemetry:{...g,...n}}}class Tp{constructor(e,t,n,a){this.logger=e,this.handshakeTimeoutMs=t,this.extensionId=a,this.resolvers=new Map,this.handshakeResolvers=new Map,this.messageChannel=new MessageChannel,this.windowListener=this.onWindowMessage.bind(this),this.performanceClient=n,this.handshakeEvent=n.startMeasurement(pQ),this.platformAuthType=ya.PLATFORM_EXTENSION_PROVIDER}async sendMessage(e){this.logger.trace("0on4p2",e.correlationId);const t={method:df.GetToken,request:e},n={channel:ya.CHANNEL_ID,extensionId:this.extensionId,responseId:Hc(),body:t};this.logger.trace("1qadfi",e.correlationId),this.logger.tracePii("1xm533",e.correlationId),this.messageChannel.port1.postMessage(n);const a=await new Promise((l,c)=>{this.resolvers.set(n.responseId,{resolve:l,reject:c})});return this.validatePlatformBrokerResponse(a)}static async createProvider(e,t,n,a){e.trace("15zfnw",a);try{const s=new Tp(e,t,n,ya.PREFERRED_EXTENSION_ID);return await s.sendHandshakeRequest(a),s}catch{const l=new Tp(e,t,n);return await l.sendHandshakeRequest(a),l}}async sendHandshakeRequest(e){this.logger.trace("1dpg9o",e),window.addEventListener("message",this.windowListener,!1);const t={channel:ya.CHANNEL_ID,extensionId:this.extensionId,responseId:Hc(),body:{method:df.HandshakeRequest}};return this.handshakeEvent.add({extensionId:this.extensionId,extensionHandshakeTimeoutMs:this.handshakeTimeoutMs}),this.messageChannel.port1.onmessage=n=>{this.onChannelMessage(n)},window.postMessage(t,window.origin,[this.messageChannel.port2]),new Promise((n,a)=>{this.handshakeResolvers.set(t.responseId,{resolve:n,reject:a}),this.timeoutId=window.setTimeout(()=>{window.removeEventListener("message",this.windowListener,!1),this.messageChannel.port1.close(),this.messageChannel.port2.close(),this.handshakeEvent.end({extensionHandshakeTimedOut:!0,success:!1}),a(ut(wN)),this.handshakeResolvers.delete(t.responseId)},this.handshakeTimeoutMs)})}onWindowMessage(e){const t=aw();if(this.logger.trace("0jpn5u",t),e.source!==window)return;const n=e.data;if(!(!n.channel||n.channel!==ya.CHANNEL_ID)&&!(n.extensionId&&n.extensionId!==this.extensionId)&&n.body.method===df.HandshakeRequest){const a=this.handshakeResolvers.get(n.responseId);if(!a){this.logger.trace("07buhm",t);return}this.logger.verbose(n.extensionId?"0xrkug":"No extension installed",t),clearTimeout(this.timeoutId),this.messageChannel.port1.close(),this.messageChannel.port2.close(),window.removeEventListener("message",this.windowListener,!1),this.handshakeEvent.end({success:!1,extensionInstalled:!1}),a.reject(ut(vN))}}onChannelMessage(e){const t=aw();this.logger.trace("1py8yf",t);const n=e.data,a=this.resolvers.get(n.responseId),s=this.handshakeResolvers.get(n.responseId);try{const l=n.body.method;if(l===df.Response){if(!a)return;const c=n.body.response;if(this.logger.trace("19hpgm",t),this.logger.tracePii("179a24",t),c.status!=="Success")a.reject(Ip(c.code,c.description,c.ext));else if(c.result)c.result.code&&c.result.description?a.reject(Ip(c.result.code,c.result.description,c.result.ext)):a.resolve(c.result);else throw J1(Aw,"Event does not contain result.");this.resolvers.delete(n.responseId)}else if(l===df.HandshakeResponse){if(!s){this.logger.trace("082qnt",t);return}clearTimeout(this.timeoutId),window.removeEventListener("message",this.windowListener,!1),this.extensionId=n.extensionId,this.extensionVersion=n.body.version,this.logger.verbose("0yf5ib",t),this.handshakeEvent.end({extensionInstalled:!0,success:!0}),s.resolve(),this.handshakeResolvers.delete(n.responseId)}}catch(l){this.logger.error("0xf978",t),this.logger.errorPii("04i99o",t),this.logger.errorPii("0xdvsy",t),a?a.reject(l):s&&s.reject(l)}}validatePlatformBrokerResponse(e){if(e.hasOwnProperty("access_token")&&e.hasOwnProperty("id_token")&&e.hasOwnProperty("client_info")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scope")&&e.hasOwnProperty("expires_in"))return e;throw J1(Aw,"Response missing expected properties.")}getExtensionId(){return this.extensionId}getExtensionVersion(){return this.extensionVersion}getExtensionName(){return this.getExtensionId()===ya.PREFERRED_EXTENSION_ID?"chrome":this.getExtensionId()?.length?"unknown":void 0}}class J2{constructor(e,t,n){this.logger=e,this.performanceClient=t,this.correlationId=n,this.platformAuthType=ya.PLATFORM_DOM_PROVIDER}static async createProvider(e,t,n){if(e.trace("12mj4a",n),window.navigator?.platformAuthentication&&(await window.navigator.platformAuthentication.getSupportedContracts(ya.MICROSOFT_ENTRA_BROKERID))?.includes(ya.PLATFORM_DOM_APIS))return e.trace("1h5q1r",n),new J2(e,t,n)}getExtensionId(){return ya.MICROSOFT_ENTRA_BROKERID}getExtensionVersion(){return""}getExtensionName(){return ya.DOM_API_NAME}async sendMessage(e){this.logger.trace("02bcil",e.correlationId);try{const t=this.initializePlatformDOMRequest(e),n=await window.navigator.platformAuthentication.executeGetToken(t);return this.validatePlatformBrokerResponse(n,e.correlationId)}catch(t){throw this.logger.error("11im7g",e.correlationId),t}}initializePlatformDOMRequest(e){this.logger.trace("15d6yv",e.correlationId);const{accountId:t,clientId:n,authority:a,scope:s,redirectUri:l,correlationId:c,state:h,storeInCache:f,embeddedClientId:g,extraParameters:y,...C}=e,v=this.getDOMExtraParams(C);return{accountId:t,brokerId:this.getExtensionId(),authority:a,clientId:n,correlationId:c||this.correlationId,extraParameters:{...y,...v},isSecurityTokenService:!1,redirectUri:l,scope:s,state:h,storeInCache:f,embeddedClientId:g}}validatePlatformBrokerResponse(e,t){if(e.hasOwnProperty("isSuccess")){if(e.hasOwnProperty("accessToken")&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("clientInfo")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scopes")&&e.hasOwnProperty("expiresIn"))return this.logger.trace("0h4vei",t),this.convertToPlatformBrokerResponse(e,t);if(e.hasOwnProperty("error")){const n=e;if(n.isSuccess===!1&&n.error&&n.error.code)throw this.logger.trace("0g92vm",t),Ip(n.error.code,n.error.description,{error:parseInt(n.error.errorCode),protocol_error:n.error.protocolError,status:n.error.status,properties:n.error.properties})}}throw J1(Aw,"Response missing expected properties.")}convertToPlatformBrokerResponse(e,t){return this.logger.trace("14913t",t),{access_token:e.accessToken,id_token:e.idToken,client_info:e.clientInfo,account:e.account,expires_in:e.expiresIn,scope:e.scopes,state:e.state||"",properties:e.properties||{},extendedLifetimeToken:e.extendedLifetimeToken??!1,shr:e.proofOfPossessionPayload}}getDOMExtraParams(e){return{...Object.entries(e).reduce((a,[s,l])=>(a[s]=String(l),a),{})}}}async function yL(A,e,t,n){A.trace("134j0v",t);const a=BL();A.trace("04c81g",t);let s;try{a&&(s=await J2.createProvider(A,e,t)),s||(A.trace("0l3na8",t),s=await Tp.createProvider(A,n||b4,e,t))}catch(l){A.trace("0icbd7",l)}return s}function BL(){let A;try{return A=window[xa.SessionStorage],A?.getItem(HQ)==="true"}catch{return!1}}function Jf(A,e,t,n,a){if(e.trace("0uko3r",t),!A.system.allowPlatformBroker)return e.trace("04hozs",t),!1;if(!n)return e.trace("0kvv1r",t),!1;if(a)switch(a){case MA.BEARER:case MA.POP:return e.trace("18tev1",t),!0;default:return e.trace("1dd2nh",t),!1}return!0}class CL extends bh{constructor(e,t,n,a,s,l,c,h,f,g){super(e,t,n,a,s,l,c,f,g),this.nativeStorage=h,this.eventHandler=s}acquireToken(e,t){let n;try{if(n={popupName:this.generatePopupName(e.scopes||yh,e.authority||this.config.auth.authority),popupWindowAttributes:e.popupWindowAttributes||{},popupWindowParent:e.popupWindowParent??window},this.performanceClient.addFields({isAsyncPopup:!this.config.system.navigatePopups},this.correlationId),this.config.system.navigatePopups){const s={...e,httpMethod:w4(e,this.config.system.protocolMode)};return this.logger.verbose("1f9ok3",this.correlationId),n.popup=this.openSizedPopup("about:blank",n),this.acquireTokenPopupAsync(s,n,t)}else return this.logger.verbose("162h4u",this.correlationId),this.acquireTokenPopupAsync(e,n,t)}catch(a){return Promise.reject(a)}}logout(e){try{this.logger.verbose("068rup",this.correlationId);const t=this.initializeLogoutRequest(e),n={popupName:this.generateLogoutPopupName(t),popupWindowAttributes:e?.popupWindowAttributes||{},popupWindowParent:e?.popupWindowParent??window},a=e&&e.authority,s=e&&e.mainWindowRedirectUri;return this.config.system.navigatePopups?(this.logger.verbose("1a28da",this.correlationId),n.popup=this.openSizedPopup("about:blank",n),this.logoutPopupAsync(t,n,a,s)):(this.logger.verbose("1phd8u",this.correlationId),this.logoutPopupAsync(t,n,a,s))}catch(t){return Promise.reject(t)}}async acquireTokenPopupAsync(e,t,n){this.logger.verbose("1g77pg",this.correlationId);const a=await Ke(l0,s0,this.logger,this.performanceClient,this.correlationId)(e,Mt.Popup,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);t.popup&&f4(a.authority);const s=Jf(this.config,this.logger,this.correlationId,this.platformAuthProvider,e.authenticationScheme);return a.platformBroker=s,this.config.system.protocolMode===Fi.EAR?this.executeEarFlow(a,t,n):this.executeCodeFlow(a,t,n)}async executeCodeFlow(e,t,n){const a=e.correlationId,s=Ti(EA.acquireTokenPopup,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),l=n||await Ke(Pc,Dc,this.logger,this.performanceClient,a)(this.performanceClient,this.logger,a),c={...e,codeChallenge:l.challenge};try{const h=await Ke(this.createAuthCodeClient.bind(this),Nl,this.logger,this.performanceClient,a)({serverTelemetryManager:s,requestAuthority:c.authority,requestAzureCloudOptions:c.azureCloudOptions,requestExtraQueryParameters:c.extraQueryParameters,account:c.account});if(c.httpMethod===rh.POST)return await this.executeCodeFlowWithPost(c,t,h,l.verifier);{const f=await Ke(V2,C2,this.logger,this.performanceClient,a)(this.config,h.authority,c,this.logger,this.performanceClient),g=this.initiateAuthRequest(f,t);this.eventHandler.emitEvent(Rt.POPUP_OPENED,Mt.Popup,{popupWindow:g},null);const y=await th(this.config.system.popupBridgeTimeout,this.logger,this.browserCrypto,e),C=as(Qf,Nf,this.logger,this.performanceClient,this.correlationId)(y,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);return await Ke(ch,sh,this.logger,this.performanceClient,a)(e,C,l.verifier,EA.acquireTokenPopup,this.config,h,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}catch(h){throw t.popup?.close(),h instanceof en&&(h.setCorrelationId(this.correlationId),s.cacheFailedRequest(h)),h}}async executeEarFlow(e,t,n){const{correlationId:a,authority:s,azureCloudOptions:l,extraQueryParameters:c,account:h}=e,f=await Ke(Fo,Tc,this.logger,this.performanceClient,a)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,s,l,c,h),g=await Ke(R2,P2,this.logger,this.performanceClient,a)(),y=n||await Ke(Pc,Dc,this.logger,this.performanceClient,a)(this.performanceClient,this.logger,a),C={...e,earJwk:g,codeChallenge:y.challenge},v=t.popup||this.openPopup("about:blank",t);(await q2(v.document,this.config,f,C,this.logger,this.performanceClient)).submit();const x=await Ke(th,Sp,this.logger,this.performanceClient,a)(this.config.system.popupBridgeTimeout,this.logger,this.browserCrypto,C),_=as(Qf,Nf,this.logger,this.performanceClient,this.correlationId)(x,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);if(!_.ear_jwe&&_.code){const T=await Ke(this.createAuthCodeClient.bind(this),Nl,this.logger,this.performanceClient,a)({serverTelemetryManager:Ti(EA.acquireTokenPopup,this.config.auth.clientId,a,this.browserStorage,this.logger),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:f});return Ke(ch,sh,this.logger,this.performanceClient,a)(C,_,y.verifier,EA.acquireTokenPopup,this.config,T,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}else return Ke(X2,M2,this.logger,this.performanceClient,a)(C,_,EA.acquireTokenPopup,this.config,f,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async executeCodeFlowWithPost(e,t,n,a){const s=e.correlationId,l=await Ke(Fo,Tc,this.logger,this.performanceClient,s)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger),c=t.popup||this.openPopup("about:blank",t);(await Y2(c.document,this.config,l,e,this.logger,this.performanceClient)).submit();const f=await Ke(th,Sp,this.logger,this.performanceClient,s)(this.config.system.popupBridgeTimeout,this.logger,this.browserCrypto,e),g=as(Qf,Nf,this.logger,this.performanceClient,this.correlationId)(f,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);return Ke(ch,sh,this.logger,this.performanceClient,s)(e,g,a,EA.acquireTokenPopup,this.config,n,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async logoutPopupAsync(e,t,n,a){this.logger.verbose("0b7yrk",this.correlationId),this.eventHandler.emitEvent(Rt.LOGOUT_START,Mt.Popup,e);const s=Ti(EA.logoutPopup,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{await K2(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,e.account);const l=await Ke(this.createAuthCodeClient.bind(this),Nl,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:s,requestAuthority:n,account:e.account||void 0});try{l.authority.endSessionEndpoint}catch{if(e.account?.homeAccountId&&e.postLogoutRedirectUri&&l.authority.protocolMode===Fi.OIDC){if(this.eventHandler.emitEvent(Rt.LOGOUT_SUCCESS,Mt.Popup,e),a){const f={apiId:EA.logoutPopup,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},g=QA.getAbsoluteUrl(a,xl());await this.navigationClient.navigateInternal(g,f)}t.popup?.close();return}}const c=l.getLogoutUri(e);this.eventHandler.emitEvent(Rt.LOGOUT_SUCCESS,Mt.Popup,e);const h=this.openPopup(c,t);if(this.eventHandler.emitEvent(Rt.POPUP_OPENED,Mt.Popup,{popupWindow:h},null),await th(this.config.system.popupBridgeTimeout,this.logger,this.browserCrypto,e).catch(()=>{}),a){const f={apiId:EA.logoutPopup,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},g=QA.getAbsoluteUrl(a,xl());this.logger.verbose("0qcur2",this.correlationId),this.logger.verbosePii("0oj7lk",this.correlationId),await this.navigationClient.navigateInternal(g,f)}else this.logger.verbose("03zgcf",this.correlationId)}catch(l){throw t.popup?.close(),l instanceof en&&(l.setCorrelationId(this.correlationId),s.cacheFailedRequest(l)),this.eventHandler.emitEvent(Rt.LOGOUT_FAILURE,Mt.Popup,null,l),this.eventHandler.emitEvent(Rt.LOGOUT_END,Mt.Popup),l}this.eventHandler.emitEvent(Rt.LOGOUT_END,Mt.Popup)}initiateAuthRequest(e,t){if(e)return this.logger.infoPii("1kcr9k",this.correlationId),this.openPopup(e,t);throw this.logger.error("1l7hyp",this.correlationId),ut(F2)}openPopup(e,t){try{let n;if(t.popup?(n=t.popup,this.logger.verbosePii("0cgeo7",this.correlationId),n.location.assign(e)):typeof t.popup>"u"&&(this.logger.verbosePii("0c2awd",this.correlationId),n=this.openSizedPopup(e,t)),!n)throw ut(rN);return n.focus&&n.focus(),this.currentWindow=n,n}catch{throw this.logger.error("0dxfb9",this.correlationId),ut(nN)}}openSizedPopup(e,{popupName:t,popupWindowAttributes:n,popupWindowParent:a}){const s=a.screenLeft?a.screenLeft:a.screenX,l=a.screenTop?a.screenTop:a.screenY,c=a.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,h=a.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;let f=n.popupSize?.width,g=n.popupSize?.height,y=n.popupPosition?.top,C=n.popupPosition?.left;return(!f||f<0||f>c)&&(this.logger.verbose("08vfmo",this.correlationId),f=va.POPUP_WIDTH),(!g||g<0||g>h)&&(this.logger.verbose("09cxa0",this.correlationId),g=va.POPUP_HEIGHT),(!y||y<0||y>h)&&(this.logger.verbose("1qh4wo",this.correlationId),y=Math.max(0,h/2-va.POPUP_HEIGHT/2+l)),(!C||C<0||C>c)&&(this.logger.verbose("1sz3en",this.correlationId),C=Math.max(0,c/2-va.POPUP_WIDTH/2+s)),a.open(e,t,`width=${f}, height=${g}, top=${y}, left=${C}, scrollbars=yes`)}generatePopupName(e,t){return`${va.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${e.join("-")}.${t}.${this.correlationId}`}generateLogoutPopupName(e){const t=e.account&&e.account.homeAccountId;return`${va.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${t}.${this.correlationId}`}}function bL(){if(typeof window>"u"||typeof window.performance>"u"||typeof window.performance.getEntriesByType!="function")return;const A=window.performance.getEntriesByType("navigation");return(A.length?A[0]:void 0)?.type}class EL extends bh{constructor(e,t,n,a,s,l,c,h,f,g){super(e,t,n,a,s,l,c,f,g),this.nativeStorage=h}async acquireToken(e){const t=await Ke(l0,s0,this.logger,this.performanceClient,this.correlationId)(e,Mt.Redirect,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);t.platformBroker=Jf(this.config,this.logger,this.correlationId,this.platformAuthProvider,e.authenticationScheme);const n=s=>{s.persisted&&(this.logger.verbose("0udvtt",this.correlationId),this.browserStorage.resetRequestCache(this.correlationId),this.eventHandler.emitEvent(Rt.RESTORE_FROM_BFCACHE,Mt.Redirect))},a=this.getRedirectStartPage(e.redirectStartPage);this.logger.verbosePii("0zao0a",this.correlationId),this.browserStorage.setTemporaryCache(Wn.ORIGIN_URI,a,!0),window.addEventListener("pageshow",n);try{this.config.system.protocolMode===Fi.EAR?await this.executeEarFlow(t):await this.executeCodeFlow(t)}catch(s){throw s instanceof en&&s.setCorrelationId(this.correlationId),window.removeEventListener("pageshow",n),s}}async executeCodeFlow(e){const t=e.correlationId,n=Ti(EA.acquireTokenRedirect,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),a=await Ke(Pc,Dc,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),s={...e,codeChallenge:a.challenge};this.browserStorage.cacheAuthorizeRequest(s,this.correlationId,a.verifier);try{if(s.httpMethod===rh.POST)return await this.executeCodeFlowWithPost(s);{const l=await Ke(this.createAuthCodeClient.bind(this),Nl,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:s.authority,requestAzureCloudOptions:s.azureCloudOptions,requestExtraQueryParameters:s.extraQueryParameters,account:s.account}),c=await Ke(V2,C2,this.logger,this.performanceClient,e.correlationId)(this.config,l.authority,s,this.logger,this.performanceClient);return await this.initiateAuthRequest(c)}}catch(l){throw l instanceof en&&(l.setCorrelationId(this.correlationId),n.cacheFailedRequest(l)),l}}async executeEarFlow(e){const{correlationId:t,authority:n,azureCloudOptions:a,extraQueryParameters:s,account:l}=e,c=await Ke(Fo,Tc,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,a,s,l),h=await Ke(R2,P2,this.logger,this.performanceClient,t)(),f=await Ke(Pc,Dc,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),g={...e,earJwk:h,codeChallenge:f.challenge};return this.browserStorage.cacheAuthorizeRequest(g,this.correlationId,f.verifier),(await q2(document,this.config,c,g,this.logger,this.performanceClient)).submit(),new Promise((C,v)=>{setTimeout(()=>{v(ut(xp,"failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async executeCodeFlowWithPost(e){const t=e.correlationId,n=await Ke(Fo,Tc,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger);return this.browserStorage.cacheAuthorizeRequest(e,this.correlationId),(await Y2(document,this.config,n,e,this.logger,this.performanceClient)).submit(),new Promise((s,l)=>{setTimeout(()=>{l(ut(xp,"failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async handleRedirectPromise(e,t,n,a){const s=Ti(EA.handleRedirectPromise,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),l=a?.navigateToLoginRequestUrl??!0;try{const[c,h]=this.getRedirectResponse(a?.hash||"");if(!c)return this.logger.info("1qmv0q",this.correlationId),this.browserStorage.resetRequestCache(this.correlationId),bL()!=="back_forward"?n.event.errorCode="no_server_response":this.logger.verbose("1eqegq",this.correlationId),null;const f=this.browserStorage.getTemporaryCache(Wn.ORIGIN_URI,this.correlationId,!0)||"",g=hC(f),y=hC(window.location.href);if(g===y&&l)return this.logger.verbose("11yred",this.correlationId),f.indexOf("#")>-1&&jN(f),await this.handleResponse(c,e,t,s);if(l){if(!i0()||this.config.system.allowRedirectInIframe){this.browserStorage.setTemporaryCache(Wn.URL_HASH,h,!0);const C={apiId:EA.handleRedirectPromise,timeout:this.config.system.redirectNavigationTimeout,noHistory:!0};let v=!0;if(!f||f==="null"){const I=zN();this.browserStorage.setTemporaryCache(Wn.ORIGIN_URI,I,!0),this.logger.warning("1dutq1",this.correlationId),v=await this.navigationClient.navigateInternal(I,C)}else this.logger.verbose("08jpy1",this.correlationId),v=await this.navigationClient.navigateInternal(f,C);if(!v)return await this.handleResponse(c,e,t,s)}}else return this.logger.verbose("0v4sdv",this.correlationId),await this.handleResponse(c,e,t,s);return null}catch(c){throw c instanceof en&&(c.setCorrelationId(this.correlationId),s.cacheFailedRequest(c)),c}}getRedirectResponse(e){this.logger.verbose("1c5i8m",this.correlationId);let t=e;t||(this.config.auth.OIDCOptions.responseMode===$w.QUERY?t=window.location.search:t=window.location.hash);let n=vp(t);if(n){try{eL(n,this.browserCrypto,Mt.Redirect)}catch(s){return s instanceof en&&this.logger.error("0bkq6p",this.correlationId),[null,""]}return c4(window),this.logger.verbose("00uvho",this.correlationId),[n,t]}const a=this.browserStorage.getTemporaryCache(Wn.URL_HASH,this.correlationId,!0);return this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Wn.URL_HASH)),a&&(n=vp(a),n)?(this.logger.verbose("001671",this.correlationId),[n,a]):[null,""]}async handleResponse(e,t,n,a){if(!e.state)throw ut(T2);const{authority:l,azureCloudOptions:c,extraQueryParameters:h,account:f}=t;if(e.ear_jwe){const y=await Ke(Fo,Tc,this.logger,this.performanceClient,t.correlationId)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,l,c,h,f);return Ke(X2,M2,this.logger,this.performanceClient,t.correlationId)(t,e,EA.acquireTokenRedirect,this.config,y,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}const g=await Ke(this.createAuthCodeClient.bind(this),Nl,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:a,requestAuthority:t.authority});return Ke(ch,sh,this.logger,this.performanceClient,t.correlationId)(t,e,n,EA.acquireTokenRedirect,this.config,g,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async initiateAuthRequest(e){if(this.logger.verbose("0yaw2e",this.correlationId),e){this.logger.infoPii("1luf83",this.correlationId);const t={apiId:EA.acquireTokenRedirect,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},n=this.config.auth.onRedirectNavigate;if(typeof n=="function")if(this.logger.verbose("1nehvl",this.correlationId),n(e)!==!1){this.logger.verbose("1a0jxh",this.correlationId),await this.navigationClient.navigateExternal(e,t);return}else{this.logger.verbose("09k5h5",this.correlationId);return}else{this.logger.verbose("0klwf7",this.correlationId),await this.navigationClient.navigateExternal(e,t);return}}else throw this.logger.info("0rlh4e",this.correlationId),ut(F2)}async logout(e){this.logger.verbose("1rkurh",this.correlationId);const t=this.initializeLogoutRequest(e),n=Ti(EA.logout,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{this.eventHandler.emitEvent(Rt.LOGOUT_START,Mt.Redirect,e),await K2(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,t.account);const a={apiId:EA.logout,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},s=await Ke(this.createAuthCodeClient.bind(this),Nl,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:e&&e.authority,requestExtraQueryParameters:e?.extraQueryParameters,account:e&&e.account||void 0});if(s.authority.protocolMode===Fi.OIDC)try{s.authority.endSessionEndpoint}catch{if(t.account?.homeAccountId){this.eventHandler.emitEvent(Rt.LOGOUT_SUCCESS,Mt.Redirect,t);return}}const l=s.getLogoutUri(t);t.account?.homeAccountId&&this.eventHandler.emitEvent(Rt.LOGOUT_SUCCESS,Mt.Redirect,t);const c=this.config.auth.onRedirectNavigate;if(typeof c=="function")if(c(l)!==!1){this.logger.verbose("06v57e",this.correlationId),this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,bl.SIGNOUT),await this.navigationClient.navigateExternal(l,a);return}else this.browserStorage.setInteractionInProgress(!1),this.logger.verbose("0xqes1",this.correlationId);else{this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,bl.SIGNOUT),await this.navigationClient.navigateExternal(l,a);return}}catch(a){throw a instanceof en&&(a.setCorrelationId(this.correlationId),n.cacheFailedRequest(a)),this.eventHandler.emitEvent(Rt.LOGOUT_FAILURE,Mt.Redirect,null,a),this.eventHandler.emitEvent(Rt.LOGOUT_END,Mt.Redirect),a}this.eventHandler.emitEvent(Rt.LOGOUT_END,Mt.Redirect)}getRedirectStartPage(e){const t=e||window.location.href;return QA.getAbsoluteUrl(t,xl())}}async function xL(A,e,t,n){if(!A)throw t.info("1l7hyp",n),ut(F2);return as(IL,sQ,t,e,n)(A)}async function SL(A,e,t,n,a){const s=W2();if(!s.contentDocument)throw"No document associated with iframe!";return(await Y2(s.contentDocument,A,e,t,n,a)).submit(),s}async function UL(A,e,t,n,a){const s=W2();if(!s.contentDocument)throw"No document associated with iframe!";return(await q2(s.contentDocument,A,e,t,n,a)).submit(),s}function IL(A){const e=W2();return e.src=A,e}function W2(){const A=document.createElement("iframe");return A.className="msalSilentIframe",A.style.visibility="hidden",A.style.position="absolute",A.style.width=A.style.height="0",A.style.border="0",A.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),A.setAttribute("allow","local-network-access *"),document.body.appendChild(A),A}class FL extends bh{constructor(e,t,n,a,s,l,c,h,f,g,y){super(e,t,n,a,s,l,h,g,y),this.apiId=c,this.nativeStorage=f}async acquireToken(e){!e.loginHint&&!e.sid&&(!e.account||!e.account.username)&&this.logger.warning("1kl318",this.correlationId);const t={...e};t.prompt?t.prompt!==Ii.NONE&&t.prompt!==Ii.NO_SESSION&&(this.logger.warning("0bmctg",this.correlationId),t.prompt=Ii.NONE):t.prompt=Ii.NONE;const n=await Ke(l0,s0,this.logger,this.performanceClient,this.correlationId)(t,Mt.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);return n.platformBroker=Jf(this.config,this.logger,this.correlationId,this.platformAuthProvider,n.authenticationScheme),f4(n.authority),this.config.system.protocolMode===Fi.EAR?this.executeEarFlow(n):this.executeCodeFlow(n)}async executeCodeFlow(e){let t;const n=Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{return t=await Ke(this.createAuthCodeClient.bind(this),Nl,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:n,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),await Ke(this.silentTokenHelper.bind(this),HC,this.logger,this.performanceClient,e.correlationId)(t,e)}catch(a){if(a instanceof en&&(a.setCorrelationId(this.correlationId),n.cacheFailedRequest(a)),!t||!(a instanceof en)||a.errorCode!==va.INVALID_GRANT_ERROR)throw a;return this.performanceClient.addFields({retryError:a.errorCode},this.correlationId),await Ke(this.silentTokenHelper.bind(this),HC,this.logger,this.performanceClient,this.correlationId)(t,e)}}async executeEarFlow(e){const{correlationId:t,authority:n,azureCloudOptions:a,extraQueryParameters:s,account:l}=e,c=await Ke(Fo,Tc,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,a,s,l),h=await Ke(R2,P2,this.logger,this.performanceClient,t)(),f=await Ke(Pc,Dc,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),g={...e,earJwk:h,codeChallenge:f.challenge};await Ke(UL,Xm,this.logger,this.performanceClient,t)(this.config,c,g,this.logger,this.performanceClient);const y=this.config.auth.OIDCOptions.responseMode,C=await Ke(th,Sp,this.logger,this.performanceClient,t)(this.config.system.iframeBridgeTimeout,this.logger,this.browserCrypto,e),v=as(Qf,Nf,this.logger,this.performanceClient,t)(C,y,this.logger,this.correlationId);if(!v.ear_jwe&&v.code){const I=await Ke(this.createAuthCodeClient.bind(this),Nl,this.logger,this.performanceClient,t)({serverTelemetryManager:Ti(this.apiId,this.config.auth.clientId,t,this.browserStorage,this.logger),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:c});return Ke(ch,sh,this.logger,this.performanceClient,t)(g,v,f.verifier,this.apiId,this.config,I,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}else return Ke(X2,M2,this.logger,this.performanceClient,t)(g,v,this.apiId,this.config,c,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}logout(){return Promise.reject(ut(_2))}async silentTokenHelper(e,t){const n=t.correlationId,a=await Ke(Pc,Dc,this.logger,this.performanceClient,n)(this.performanceClient,this.logger,n),s={...t,codeChallenge:a.challenge};if(t.httpMethod===rh.POST)await Ke(SL,Xm,this.logger,this.performanceClient,n)(this.config,e.authority,s,this.logger,this.performanceClient);else{const f=await Ke(V2,C2,this.logger,this.performanceClient,n)(this.config,e.authority,s,this.logger,this.performanceClient);await Ke(xL,Xm,this.logger,this.performanceClient,n)(f,this.performanceClient,this.logger,n)}const l=this.config.auth.OIDCOptions.responseMode,c=await Ke(th,Sp,this.logger,this.performanceClient,n)(this.config.system.iframeBridgeTimeout,this.logger,this.browserCrypto,t),h=as(Qf,Nf,this.logger,this.performanceClient,n)(c,l,this.logger,this.correlationId);return Ke(ch,sh,this.logger,this.performanceClient,n)(t,h,a.verifier,this.apiId,this.config,e,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}class TL extends bh{async acquireToken(e){const t=await Ke(G2,D2,this.logger,this.performanceClient,e.correlationId)(e,this.config,this.performanceClient,this.logger,this.correlationId),n={...e,...t};e.redirectUri&&(n.redirectUri=Up(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId));const a=Ti(EA.acquireTokenSilent_silentFlow,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),s=await this.createRefreshTokenClient({serverTelemetryManager:a,authorityUrl:n.authority,azureCloudOptions:n.azureCloudOptions,account:n.account});return Ke(s.acquireTokenByRefreshToken.bind(s),rQ,this.logger,this.performanceClient,e.correlationId)(n,EA.acquireTokenSilent_silentFlow).catch(l=>{throw l.setCorrelationId(this.correlationId),a.cacheFailedRequest(l),l})}logout(){return Promise.reject(ut(_2))}async createRefreshTokenClient(e){const t=await Ke(this.getClientConfiguration.bind(this),a0,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:e.serverTelemetryManager,requestAuthority:e.authorityUrl,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return new L_(t,this.performanceClient)}}class _L extends Vx{constructor(e,t){super(e,t),this.includeRedirectUri=!1}}class NL extends bh{constructor(e,t,n,a,s,l,c,h,f,g){super(e,t,n,a,s,l,h,f,g),this.apiId=c}async acquireToken(e){if(!e.code)throw ut(dN);const t=await Ke(l0,s0,this.logger,this.performanceClient,this.correlationId)(e,Mt.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId),n=Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{const a={...t,code:e.code},s=await Ke(this.getClientConfiguration.bind(this),a0,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account}),l=new _L(s,this.performanceClient);this.logger.verbose("1uic5e",this.correlationId);const c=new v4(l,this.browserStorage,a,this.logger,this.performanceClient);return await Ke(c.handleCodeResponseFromServer.bind(c),Hx,this.logger,this.performanceClient,this.correlationId)({code:e.code,msgraph_host:e.msGraphHost,cloud_graph_host_name:e.cloudGraphHostName,cloud_instance_host_name:e.cloudInstanceHostName},t,this.apiId,!1)}catch(a){throw a instanceof en&&(a.setCorrelationId(this.correlationId),n.cacheFailedRequest(a)),a}}logout(){return Promise.reject(ut(_2))}}function QL(A,e,t,n){const a=window.msal?.clientIds||[],s=a.length,l=a.filter(c=>c===A).length;l>1&&t.warning("1e88vg",n),e.add({msalInstanceCount:s,sameClientIdInstanceCount:l})}function wg(A,e,t){try{H2(A)}catch(n){throw e.end({success:!1},n,t),n}}class Z2{constructor(e){this.operatingContext=e,this.isBrowserEnvironment=this.operatingContext.isBrowserEnvironment(),this.config=e.getConfig(),this.initialized=!1,this.logger=this.operatingContext.getLogger(),this.networkClient=this.config.system.networkClient,this.navigationClient=this.config.system.navigationClient,this.redirectResponse=new Map,this.hybridAuthCodeResponses=new Map,this.performanceClient=this.config.telemetry.client,this.browserCrypto=this.isBrowserEnvironment?new _o(this.logger,this.performanceClient):yp,this.eventHandler=new WQ(this.logger),this.browserStorage=this.isBrowserEnvironment?new ow(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler,N_(this.config.auth)):zQ(this.config.auth.clientId,this.logger,this.performanceClient,this.eventHandler);const t={cacheLocation:xa.MemoryStorage,cacheRetentionDays:5};this.nativeInternalStorage=new ow(this.config.auth.clientId,t,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler),this.activeSilentTokenRequests=new Map,this.trackPageVisibility=this.trackPageVisibility.bind(this),this.trackPageVisibilityWithMeasurement=this.trackPageVisibilityWithMeasurement.bind(this)}static async createController(e,t){const n=new Z2(e);return await n.initialize(t),n}trackPageVisibility(e){e&&(this.logger.info("16v6hv",e),this.performanceClient.incrementFields({visibilityChangeCount:1},e))}async initialize(e){const t=this.getRequestCorrelationId(e);if(this.logger.trace("1f7joy",t),this.initialized){this.logger.info("061m5x",t);return}if(!this.isBrowserEnvironment){this.logger.info("19fvpi",t),this.initialized=!0,this.eventHandler.emitEvent(Rt.INITIALIZE_END);return}const n=e?.correlationId||this.getRequestCorrelationId(),a=this.config.system.allowPlatformBroker,s=this.performanceClient.startMeasurement(LQ,n);if(this.eventHandler.emitEvent(Rt.INITIALIZE_START),this.logMultipleInstances(s,n),await Ke(this.browserStorage.initialize.bind(this.browserStorage),aQ,this.logger,this.performanceClient,n)(n),a)try{this.platformAuthProvider=await yL(this.logger,this.performanceClient,n,this.config.system.nativeBrokerHandshakeTimeout)}catch(l){this.logger.verbose(l,n)}this.config.cache.cacheLocation===xa.LocalStorage&&this.eventHandler.subscribeCrossTab(),!this.config.system.navigatePopups&&await this.preGeneratePkceCodes(n),this.initialized=!0,this.eventHandler.emitEvent(Rt.INITIALIZE_END),s.end({allowPlatformBroker:a,success:!0})}async handleRedirectPromise(e){if(this.logger.verbose("02l8bm",""),h4(this.initialized),this.isBrowserEnvironment){const t=e?.hash||"";let n=this.redirectResponse.get(t);return typeof n>"u"?(n=this.handleRedirectPromiseInternal(e),this.redirectResponse.set(t,n),this.logger.verbose("1wn9kp","")):this.logger.verbose("0w0gm3",""),n}return this.logger.verbose("12xi63",""),null}async handleRedirectPromiseInternal(e){if(!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("0le6uv",""),null;if(this.browserStorage.getInteractionInProgress()?.type===bl.SIGNOUT)return this.logger.verbose("1ywcv2",""),this.browserStorage.setInteractionInProgress(!1),Promise.resolve(null);const n=this.getAllAccounts(),a=this.browserStorage.getCachedNativeRequest(),s=a&&this.platformAuthProvider&&!e?.hash;let l;this.eventHandler.emitEvent(Rt.HANDLE_REDIRECT_START,Mt.Redirect);let c;try{if(s&&this.platformAuthProvider){const h=a?.correlationId||"";l=this.performanceClient.startMeasurement(Jm,h),this.logger.trace("12v7is",h);const f=new Ap(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,EA.handleRedirectPromise,this.performanceClient,this.platformAuthProvider,a.accountId,this.nativeInternalStorage,a.correlationId);c=Ke(f.handleRedirectPromise.bind(f),gQ,this.logger,this.performanceClient,l.event.correlationId)(this.performanceClient,l.event.correlationId)}else{const[h,f]=this.browserStorage.getCachedRequest(""),g=h.correlationId;l=this.performanceClient.startMeasurement(Jm,g),this.logger.trace("0znzs5",g);const y=this.createRedirectClient(g);c=Ke(y.handleRedirectPromise.bind(y),dQ,this.logger,this.performanceClient,l.event.correlationId)(h,f,l,e)}}catch(h){throw this.browserStorage.resetRequestCache(""),h}return c.then(h=>(h?(this.browserStorage.resetRequestCache(h.correlationId),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_SUCCESS,Mt.Redirect,h),this.logger.verbose("0ui8f5",h.correlationId),n.length{this.browserStorage.resetRequestCache(l.event.correlationId);const f=h;throw this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Redirect,null,f),this.eventHandler.emitEvent(Rt.HANDLE_REDIRECT_END,Mt.Redirect),l.end({success:!1},f),h})}async acquireTokenRedirect(e){const t=this.getRequestCorrelationId(e);this.logger.verbose("0os66p",t);const n=this.performanceClient.startMeasurement(NQ,t);n.add({scenarioId:e.scenarioId});const a=this.config.auth.onRedirectNavigate;this.config.auth.onRedirectNavigate=s=>{const l=typeof a=="function"?a(s):void 0;return n.add({navigateCallbackResult:l!==!1}),n.event=n.end({success:!0},void 0,e.account)||n.event,l};try{RC(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,bl.SIGNIN),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Redirect,e);let s;return this.platformAuthProvider&&this.canUsePlatformBroker(e)?s=new Ap(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,EA.acquireTokenRedirect,this.performanceClient,this.platformAuthProvider,this.getNativeAccountId(e),this.nativeInternalStorage,t).acquireTokenRedirect(e,n).catch(c=>{if(c instanceof Hs&&Ju(c))return this.platformAuthProvider=void 0,this.createRedirectClient(t).acquireToken(e);if(c instanceof os)return this.logger.verbose("1ipyz4",t),this.createRedirectClient(t).acquireToken(e);throw c}):s=this.createRedirectClient(t).acquireToken(e),await s}catch(s){throw this.browserStorage.resetRequestCache(t),n.event.status===2?this.performanceClient.startMeasurement(Jm,t).end({success:!1},s,e.account):n.end({success:!1},s,e.account),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Redirect,null,s),s}}acquireTokenPopup(e){const t=this.getRequestCorrelationId(e),n=this.performanceClient.startMeasurement(_Q,t);n.add({scenarioId:e.scenarioId});try{this.logger.verbose("0ch87b",t),wg(this.initialized,n,e.account),this.browserStorage.setInteractionInProgress(!0,bl.SIGNIN,e.overrideInteractionInProgress,t)}catch(c){return Promise.reject(c)}const a=this.getAllAccounts();this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Popup,e);let s;const l=this.getPreGeneratedPkceCodes(t);return this.canUsePlatformBroker(e)?s=this.acquireTokenNative({...e,correlationId:t},EA.acquireTokenPopup).then(c=>(n.end({success:!0,isNativeBroker:!0},void 0,c.account),c)).catch(c=>{if(c instanceof Hs&&Ju(c))return this.platformAuthProvider=void 0,this.createPopupClient(t).acquireToken(e,l);if(c instanceof os)return this.logger.verbose("0yy5fw",t),this.createPopupClient(t).acquireToken(e,l);throw c}):s=this.createPopupClient(t).acquireToken(e,l),s.then(c=>{const h=a.length(this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Popup,null,c),n.end({success:!1},c,e.account),Promise.reject(c))).finally(async()=>{this.browserStorage.setInteractionInProgress(!1),this.config.system.navigatePopups||await this.preGeneratePkceCodes(t)})}trackPageVisibilityWithMeasurement(){const e=this.ssoSilentMeasurement||this.acquireTokenByCodeAsyncMeasurement;e&&e.increment({visibilityChangeCount:1})}async ssoSilent(e){const t=this.getRequestCorrelationId(e),n={...e,prompt:e.prompt,correlationId:t};this.ssoSilentMeasurement=this.performanceClient.startMeasurement(QQ,t),this.ssoSilentMeasurement?.add({scenarioId:e.scenarioId}),wg(this.initialized,this.ssoSilentMeasurement,e.account),this.ssoSilentMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement);const a=this.getAllAccounts();this.logger.verbose("0w1b45",t),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Silent,n);let s;return this.canUsePlatformBroker(n)?s=this.acquireTokenNative(n,EA.ssoSilent).catch(l=>{if(l instanceof Hs&&Ju(l))return this.platformAuthProvider=void 0,this.createSilentIframeClient(n.correlationId).acquireToken(n);throw l}):s=this.createSilentIframeClient(n.correlationId).acquireToken(n),s.then(l=>{const c=a.length{throw this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Silent,null,l),this.ssoSilentMeasurement?.end({success:!1},l,e.account),l}).finally(()=>{document.removeEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement)})}async acquireTokenByCode(e){const t=this.getRequestCorrelationId(e);this.logger.trace("0ch6ga",t);const n=this.performanceClient.startMeasurement(TQ,t);wg(this.initialized,n),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Silent,e),n.add({scenarioId:e.scenarioId});try{if(e.code&&e.nativeAccountId)throw ut(pN);if(e.code){const a=e.code;let s=this.hybridAuthCodeResponses.get(a);return s?(this.logger.verbose("0qgp28",t),n.discard()):(this.logger.verbose("06eh73",t),s=this.acquireTokenByCodeAsync({...e,correlationId:t}).then(l=>(this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_SUCCESS,Mt.Silent,l),this.hybridAuthCodeResponses.delete(a),n.end({success:!0,isNativeBroker:l.fromPlatformBroker,accessTokenSize:l.accessToken.length,idTokenSize:l.idToken.length},void 0,l.account),l)).catch(l=>{throw this.hybridAuthCodeResponses.delete(a),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Silent,null,l),n.end({success:!1},l),l}),this.hybridAuthCodeResponses.set(a,s)),await s}else if(e.nativeAccountId)if(this.canUsePlatformBroker(e,e.nativeAccountId)){const a=await this.acquireTokenNative({...e,correlationId:t},EA.acquireTokenByCode,e.nativeAccountId).catch(s=>{throw s instanceof Hs&&Ju(s)&&(this.platformAuthProvider=void 0),s});return n.end({success:!0},void 0,a.account),a}else throw ut(mN);else throw ut(gN)}catch(a){throw this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Silent,null,a),n.end({success:!1},a),a}}async acquireTokenByCodeAsync(e){const t=this.getRequestCorrelationId(e);return this.logger.trace("10d9hy",t),this.acquireTokenByCodeAsyncMeasurement=this.performanceClient.startMeasurement(fQ,t),this.acquireTokenByCodeAsyncMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement),await this.createSilentAuthCodeClient(t).acquireToken(e).then(s=>(this.acquireTokenByCodeAsyncMeasurement?.end({success:!0,fromCache:s.fromCache,isNativeBroker:s.fromPlatformBroker}),s)).catch(s=>{throw this.acquireTokenByCodeAsyncMeasurement?.end({success:!1},s),s}).finally(()=>{document.removeEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement)})}async acquireTokenFromCache(e,t){switch(t){case ri.Default:case ri.AccessToken:case ri.AccessTokenAndRefreshToken:const n=this.createSilentCacheClient(e.correlationId);return Ke(n.acquireToken.bind(n),eQ,this.logger,this.performanceClient,e.correlationId)(e);default:throw tt(Ic)}}async acquireTokenByRefreshToken(e,t){switch(t){case ri.Default:case ri.AccessTokenAndRefreshToken:case ri.RefreshToken:case ri.RefreshTokenAndNetwork:const n=this.createSilentRefreshClient(e.correlationId);return Ke(n.acquireToken.bind(n),nQ,this.logger,this.performanceClient,e.correlationId)(e);default:throw tt(Ic)}}async acquireTokenBySilentIframe(e){const t=this.createSilentIframeClient(e.correlationId);return Ke(t.acquireToken.bind(t),tQ,this.logger,this.performanceClient,e.correlationId)(e)}async logoutRedirect(e){const t=this.getRequestCorrelationId(e);return RC(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,bl.SIGNOUT),this.createRedirectClient(t).logout(e)}logoutPopup(e){try{const t=this.getRequestCorrelationId(e);return H2(this.initialized),this.browserStorage.setInteractionInProgress(!0,bl.SIGNOUT),this.createPopupClient(t).logout(e).finally(()=>{this.browserStorage.setInteractionInProgress(!1)})}catch(t){return Promise.reject(t)}}async clearCache(e){if(!this.isBrowserEnvironment)return;const t=this.getRequestCorrelationId(e);return this.createSilentCacheClient(t).logout(e)}getAllAccounts(e){return VQ(this.logger,this.browserStorage,this.isBrowserEnvironment,this.getRequestCorrelationId(),e)}getAccount(e){return qQ(e,this.logger,this.browserStorage,this.getRequestCorrelationId())}setActiveAccount(e){YQ(e,this.browserStorage,this.getRequestCorrelationId())}getActiveAccount(){return XQ(this.browserStorage,this.getRequestCorrelationId())}async hydrateCache(e,t){this.logger.verbose("16jycr",e.correlationId);const n=LT(e.account,e.cloudGraphHostName,e.msGraphHost);return await this.browserStorage.setAccount(n,e.correlationId,Fc(e.idTokenClaims),EA.hydrateCache),e.fromPlatformBroker?(this.logger.verbose("1fxyu8",e.correlationId),this.nativeInternalStorage.hydrateCache(e,t)):this.browserStorage.hydrateCache(e,t)}async acquireTokenNative(e,t,n,a){const s=this.getRequestCorrelationId(e);if(this.logger.trace("0b9y3p",s),!this.platformAuthProvider)throw ut(n4);return new Ap(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,t,this.performanceClient,this.platformAuthProvider,n||this.getNativeAccountId(e),this.nativeInternalStorage,s).acquireToken(e,a)}canUsePlatformBroker(e,t){const n=this.getRequestCorrelationId(e);if(this.logger.trace("1n9lbl",n),!this.platformAuthProvider)return this.logger.trace("0vnu11",n),!1;if(!Jf(this.config,this.logger,n,this.platformAuthProvider,e.authenticationScheme))return this.logger.trace("1m4bzf",n),!1;if(e.prompt)switch(e.prompt){case Ii.NONE:case Ii.CONSENT:case Ii.LOGIN:this.logger.trace("0vdv8e",n);break;default:return this.logger.trace("0pdzw6",n),!1}return!t&&!this.getNativeAccountId(e)?(this.logger.trace("16lbtk",n),!1):!0}getNativeAccountId(e){const t=e.account||this.getAccount({loginHint:e.loginHint,sid:e.sid})||this.getActiveAccount();return t&&t.nativeAccountId||""}createPopupClient(e){return new CL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider)}createRedirectClient(e){return new EL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider)}createSilentIframeClient(e){return new FL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,EA.ssoSilent,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider)}createSilentCacheClient(e){return new y4(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,e,this.platformAuthProvider)}createSilentRefreshClient(e){return new TL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,e,this.platformAuthProvider)}createSilentAuthCodeClient(e){return new NL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,EA.acquireTokenByCode,this.performanceClient,e,this.platformAuthProvider)}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){return u4(),this.performanceClient.addPerformanceCallback(e)}removePerformanceCallback(e){return this.performanceClient.removePerformanceCallback(e)}getLogger(){return this.logger}setLogger(e){this.logger=e}initializeWrapperLibrary(e,t){this.browserStorage.setWrapperMetadata(e,t)}setNavigationClient(e){this.navigationClient=e}getConfiguration(){return this.config}getPerformanceClient(){return this.performanceClient}isBrowserEnv(){return this.isBrowserEnvironment}getRequestCorrelationId(e){return e?.correlationId?e.correlationId:this.isBrowserEnvironment?Hc():""}async loginRedirect(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("0lz9hf",t),this.acquireTokenRedirect({correlationId:t,...e||FC})}loginPopup(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("0qw7v5",t),this.acquireTokenPopup({correlationId:t,...e||FC})}async acquireTokenSilent(e){const t=this.getRequestCorrelationId(e),n=this.performanceClient.startMeasurement(FQ,t);n.add({cacheLookupPolicy:e.cacheLookupPolicy,scenarioId:e.scenarioId}),wg(this.initialized,n,e.account),this.logger.verbose("0x1c4s",t);const a=e.account||this.getActiveAccount();if(!a)throw ut(lN);return this.acquireTokenSilentDeduped(e,a,t).then(s=>(n.end({success:!0,fromCache:s.fromCache,isNativeBroker:s.fromPlatformBroker,accessTokenSize:s.accessToken.length,idTokenSize:s.idToken.length},void 0,s.account),{...s,state:e.state,correlationId:t})).catch(s=>{throw s instanceof en&&s.setCorrelationId(t),n.end({success:!1},s,a),s})}async acquireTokenSilentDeduped(e,t,n){const a=t0(this.config.auth.clientId,{...e,authority:e.authority||this.config.auth.authority},t.homeAccountId),s=JSON.stringify(a),l=this.activeSilentTokenRequests.get(s);if(typeof l>"u"){this.logger.verbose("0fcjbk",n),this.performanceClient.addFields({deduped:!1},n);const c=Ke(this.acquireTokenSilentAsync.bind(this),WN,this.logger,this.performanceClient,n)({...e,correlationId:n},t);return this.activeSilentTokenRequests.set(s,c),c.finally(()=>{this.activeSilentTokenRequests.delete(s)})}else return this.logger.verbose("1yq7nb",n),this.performanceClient.addFields({deduped:!0},n),l}async acquireTokenSilentAsync(e,t){const n=()=>this.trackPageVisibility(e.correlationId);this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Silent,e),e.correlationId&&this.performanceClient.incrementFields({visibilityChangeCount:0},e.correlationId),document.addEventListener("visibilitychange",n);const a=await Ke(ZQ,iQ,this.logger,this.performanceClient,e.correlationId)(e,t,this.config,this.performanceClient,this.logger),s=e.cacheLookupPolicy||ri.Default;return this.acquireTokenSilentNoIframe(a,s).catch(async c=>{if(LL(c,s))if(this.activeIframeRequest)if(s!==ri.Skip){const[f,g]=this.activeIframeRequest;this.logger.verbose("1w8fso",a.correlationId);const y=this.performanceClient.startMeasurement(AQ,a.correlationId);y.add({awaitIframeCorrelationId:g});const C=await f;if(y.end({success:C}),C)return this.logger.verbose("0ywzzi",a.correlationId),this.acquireTokenSilentNoIframe(a,s);throw this.logger.info("17y14q",a.correlationId),c}else return this.logger.warning("1bd4p8",a.correlationId),Ke(this.acquireTokenBySilentIframe.bind(this),kC,this.logger,this.performanceClient,a.correlationId)(a);else{let f;return this.activeIframeRequest=[new Promise(g=>{f=g}),a.correlationId],this.logger.verbose("0rh08z",a.correlationId),Ke(this.acquireTokenBySilentIframe.bind(this),kC,this.logger,this.performanceClient,a.correlationId)(a).then(g=>(f(!0),g)).catch(g=>{throw f(!1),g}).finally(()=>{this.activeIframeRequest=void 0})}else throw c}).then(c=>(this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_SUCCESS,Mt.Silent,c),e.correlationId&&this.performanceClient.addFields({fromCache:c.fromCache,isNativeBroker:c.fromPlatformBroker},e.correlationId),c)).catch(c=>{throw this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Silent,null,c),c}).finally(()=>{document.removeEventListener("visibilitychange",n)})}async acquireTokenSilentNoIframe(e,t){return Jf(this.config,this.logger,e.correlationId,this.platformAuthProvider,e.authenticationScheme)&&e.account.nativeAccountId?(this.logger.verbose("0sczo4",e.correlationId),this.acquireTokenNative(e,EA.acquireTokenSilent_silentFlow,e.account.nativeAccountId,t).catch(async n=>{throw n instanceof Hs&&Ju(n)?(this.logger.verbose("07rkmb",e.correlationId),this.platformAuthProvider=void 0,tt(Ic)):n})):(this.logger.verbose("0ox81t",e.correlationId),t===ri.AccessToken&&this.logger.verbose("0fvwxe",e.correlationId),Ke(this.acquireTokenFromCache.bind(this),XN,this.logger,this.performanceClient,e.correlationId)(e,t).catch(n=>{if(t===ri.AccessToken)throw n;return this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_NETWORK_START,Mt.Silent,e),Ke(this.acquireTokenByRefreshToken.bind(this),JN,this.logger,this.performanceClient,e.correlationId)(e,t)}))}async preGeneratePkceCodes(e){return this.logger.verbose("1x6uj6",e),this.pkceCode=await Ke(Pc,Dc,this.logger,this.performanceClient,e)(this.performanceClient,this.logger,e),Promise.resolve()}getPreGeneratedPkceCodes(e){const t=this.pkceCode?{...this.pkceCode}:void 0;return this.pkceCode=void 0,t?this.logger.verbose("12js1o",e):this.logger.verbose("1oe9ci",e),this.performanceClient.addFields({usePreGeneratedPkce:!!t},e),t}logMultipleInstances(e,t){const n=this.config.auth.clientId;if(!window)return;window.msal=window.msal||{},window.msal.clientIds=window.msal.clientIds||[],window.msal.clientIds.length>0&&this.logger.verbose("1qtz3l",t),window.msal.clientIds.push(n),QL(n,e,this.logger,t)}}function LL(A,e){const t=!(A instanceof os&&A.subError!==B2),n=A.errorCode===va.INVALID_GRANT_ERROR||A.errorCode===Ic,a=t&&n||A.errorCode===tw||A.errorCode===Ox,s=J_.includes(e);return a&&s}class $2{static loggerCallback(e,t){switch(e){case vn.Error:console.error(t);return;case vn.Info:console.info(t);return;case vn.Verbose:console.debug(t);return;case vn.Warning:console.warn(t);return;default:console.log(t);return}}constructor(e){this.browserEnvironment=typeof window<"u",this.config=vL(e,this.browserEnvironment);let t;try{t=window[xa.SessionStorage]}catch{}const n=t?.getItem(RQ),a=t?.getItem(kQ)?.toLowerCase(),s=a==="true"?!0:a==="false"?!1:void 0,l={...this.config.system.loggerOptions},c=n&&Object.keys(vn).includes(n)?vn[n]:void 0;c&&(l.loggerCallback=$2.loggerCallback,l.logLevel=c),s!==void 0&&(l.piiLoggingEnabled=s),this.logger=new Dl(l,GQ,Mc),this.available=!1}getConfig(){return this.config}getLogger(){return this.logger}isAvailable(){return this.available}isBrowserEnvironment(){return this.browserEnvironment}}class wh extends $2{getModuleName(){return wh.MODULE_NAME}getId(){return wh.ID}async initialize(e){return this.available=typeof window<"u",this.available}}wh.MODULE_NAME="";wh.ID="StandardOperatingContext";class OL{constructor(e,t){this.controller=t||new Z2(new wh(e))}async initialize(e){return this.controller.initialize(e)}async acquireTokenPopup(e){return this.controller.acquireTokenPopup(e)}acquireTokenRedirect(e){return this.controller.acquireTokenRedirect(e)}acquireTokenSilent(e){return this.controller.acquireTokenSilent(e)}acquireTokenByCode(e){return this.controller.acquireTokenByCode(e)}addEventCallback(e,t){return this.controller.addEventCallback(e,t)}removeEventCallback(e){return this.controller.removeEventCallback(e)}addPerformanceCallback(e){return this.controller.addPerformanceCallback(e)}removePerformanceCallback(e){return this.controller.removePerformanceCallback(e)}getAccount(e){return this.controller.getAccount(e)}getAllAccounts(e){return this.controller.getAllAccounts(e)}handleRedirectPromise(e){return this.controller.handleRedirectPromise(e)}loginPopup(e){return this.controller.loginPopup(e)}loginRedirect(e){return this.controller.loginRedirect(e)}logoutRedirect(e){return this.controller.logoutRedirect(e)}logoutPopup(e){return this.controller.logoutPopup(e)}ssoSilent(e){return this.controller.ssoSilent(e)}getLogger(){return this.controller.getLogger()}setLogger(e){this.controller.setLogger(e)}setActiveAccount(e){this.controller.setActiveAccount(e)}getActiveAccount(){return this.controller.getActiveAccount()}initializeWrapperLibrary(e,t){return this.controller.initializeWrapperLibrary(e,t)}setNavigationClient(e){this.controller.setNavigationClient(e)}getConfiguration(){return this.controller.getConfiguration()}async hydrateCache(e,t){return this.controller.hydrateCache(e,t)}clearCache(e){return this.controller.clearCache(e)}}const RL={initialize:()=>Promise.reject(wr(ni)),acquireTokenPopup:()=>Promise.reject(wr(ni)),acquireTokenRedirect:()=>Promise.reject(wr(ni)),acquireTokenSilent:()=>Promise.reject(wr(ni)),acquireTokenByCode:()=>Promise.reject(wr(ni)),getAllAccounts:()=>[],getAccount:()=>null,handleRedirectPromise:()=>Promise.reject(wr(ni)),loginPopup:()=>Promise.reject(wr(ni)),loginRedirect:()=>Promise.reject(wr(ni)),logoutRedirect:()=>Promise.reject(wr(ni)),logoutPopup:()=>Promise.reject(wr(ni)),ssoSilent:()=>Promise.reject(wr(ni)),addEventCallback:()=>null,removeEventCallback:()=>{},addPerformanceCallback:()=>"",removePerformanceCallback:()=>!1,getLogger:()=>{throw wr(ni)},setLogger:()=>{},setActiveAccount:()=>{},getActiveAccount:()=>null,initializeWrapperLibrary:()=>{},setNavigationClient:()=>{},getConfiguration:()=>{throw wr(ni)},hydrateCache:()=>Promise.reject(wr(ni)),clearCache:()=>Promise.reject(wr(ni))};class kL{static getInteractionStatusFromEvent(e,t){switch(e.eventType){case Rt.ACQUIRE_TOKEN_START:if(e.interactionType===Mt.Redirect||e.interactionType===Mt.Popup)return Fr.AcquireToken;break;case Rt.HANDLE_REDIRECT_START:return Fr.HandleRedirect;case Rt.LOGOUT_START:return Fr.Logout;case Rt.LOGOUT_END:if(t&&t!==Fr.Logout)break;return Fr.None;case Rt.HANDLE_REDIRECT_END:if(t&&t!==Fr.HandleRedirect)break;return Fr.None;case Rt.ACQUIRE_TOKEN_SUCCESS:case Rt.ACQUIRE_TOKEN_FAILURE:case Rt.RESTORE_FROM_BFCACHE:if(e.interactionType===Mt.Redirect||e.interactionType===Mt.Popup){if(t&&t!==Fr.AcquireToken)break;return Fr.None}break}return null}}const HL="modulepreload",DL=function(A){return"/lux-studio/"+A},JC={},Wm=function(e,t,n){let a=Promise.resolve();if(t&&t.length>0){let h=function(f){return Promise.all(f.map(g=>Promise.resolve(g).then(y=>({status:"fulfilled",value:y}),y=>({status:"rejected",reason:y}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");a=h(t.map(f=>{if(f=DL(f),f in JC)return;JC[f]=!0;const g=f.endsWith(".css"),y=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${y}`))return;const C=document.createElement("link");if(C.rel=g?"stylesheet":HL,g||(C.as="script"),C.crossOrigin="",C.href=f,c&&C.setAttribute("nonce",c),document.head.appendChild(C),g)return new Promise((v,I)=>{C.addEventListener("load",v),C.addEventListener("error",()=>I(new Error(`Unable to preload CSS for ${f}`)))})}))}function s(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return a.then(l=>{for(const c of l||[])c.status==="rejected"&&s(c.reason);return e().catch(s)})};const ML={instance:RL,inProgress:Fr.None,accounts:[],logger:new Dl({})},ev=ae.createContext(ML);ev.Consumer;function WC(A,e){if(A.length!==e.length)return!1;const t=[...e];return A.every(n=>{const a=t.shift();return!n||!a?!1:n.homeAccountId===a.homeAccountId&&n.localAccountId===a.localAccountId&&n.username===a.username})}const PL="@azure/msal-react",ZC="5.0.3";const _p={UNBLOCK_INPROGRESS:"UNBLOCK_INPROGRESS",EVENT:"EVENT"},jL=(A,e)=>{const{type:t,payload:n}=e;let a=A.inProgress;switch(t){case _p.UNBLOCK_INPROGRESS:A.inProgress===Fr.Startup&&(a=Fr.None,n.logger.info("MsalProvider - handleRedirectPromise resolved, setting inProgress to 'none'",""));break;case _p.EVENT:const l=n.message,c=kL.getInteractionStatusFromEvent(l,A.inProgress);c&&(n.logger.info(`MsalProvider - '${l.eventType}' results in setting inProgress from '${A.inProgress}' to '${c}'`,""),a=c);break;default:throw new Error(`Unknown action type: ${t}`)}if(a===Fr.Startup)return A;const s=n.instance.getAllAccounts();return a!==A.inProgress&&!WC(s,A.accounts)?{...A,inProgress:a,accounts:s}:a!==A.inProgress?{...A,inProgress:a}:WC(s,A.accounts)?A:{...A,accounts:s}};function KL({instance:A,children:e}){ae.useEffect(()=>{A.initializeWrapperLibrary(q_.React,ZC)},[A]);const t=ae.useMemo(()=>A.getLogger().clone(PL,ZC),[A]),[n,a]=ae.useReducer(jL,void 0,()=>({inProgress:Fr.Startup,accounts:[]}));ae.useEffect(()=>{const l=A.addEventCallback(c=>{a({payload:{instance:A,logger:t,message:c},type:_p.EVENT})});return t.verbose(`MsalProvider - Registered event callback with id: '${l}'`,""),A.initialize().then(()=>{A.handleRedirectPromise().catch(()=>{}).finally(()=>{a({payload:{instance:A,logger:t},type:_p.UNBLOCK_INPROGRESS})})}).catch(()=>{}),()=>{l&&(t.verbose(`MsalProvider - Removing event callback '${l}'`,""),A.removeEventCallback(l))}},[A,t]);const s={instance:A,inProgress:n.inProgress,accounts:n.accounts,logger:t};return ai.createElement(ev.Provider,{value:s},e)}const E4=()=>ae.useContext(ev);function GL(A,e){return A.length>0}function zL(A){const{accounts:e,inProgress:t}=E4();return ae.useMemo(()=>t===Fr.Startup?!1:GL(e),[e,t,A])}const VL={auth:{clientId:"9079054c-9620-4757-a256-23413042f1ef",authority:"https://login.microsoftonline.com/e519c2e6-bc6d-4fdf-8d9c-923c2f002385",redirectUri:"https://ai-sandbox.oliver.solutions/lux-studio/",postLogoutRedirectUri:"https://ai-sandbox.oliver.solutions/lux-studio/"},cache:{cacheLocation:"localStorage",storeAuthStateInCookie:!1}},qL={scopes:["User.Read"]},x4=ae.createContext(null),tv=()=>{const A=ae.useContext(x4);if(!A)throw new Error("useAuth must be used within an AuthProvider");return A},YL=({children:A})=>{const{instance:e,accounts:t,inProgress:n}=E4(),a=zL(),[s,l]=ae.useState(null),[c,h]=ae.useState(!0);ae.useEffect(()=>{e.handleRedirectPromise().then(C=>{C&&console.log("Redirect login successful")}).catch(C=>{console.error("Redirect error:",C)})},[e]),ae.useEffect(()=>{if(n===Fr.None){if(t.length>0){const C=t[0];l({id:C.localAccountId,name:C.name||C.username,email:C.username})}else l(null);h(!1)}},[t,n]);const f=async()=>{try{await e.loginRedirect(qL)}catch(C){throw console.error("Login failed:",C),C}},g=async()=>{try{await e.logoutRedirect({postLogoutRedirectUri:window.location.origin})}catch(C){throw console.error("Logout failed:",C),C}},y={user:s,isAuthenticated:a,isLoading:c||n!==Fr.None,login:f,logout:g};return b.jsx(x4.Provider,{value:y,children:A})};const XL=A=>A.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),JL=A=>A.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),$C=A=>{const e=JL(A);return e.charAt(0).toUpperCase()+e.slice(1)},S4=(...A)=>A.filter((e,t,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===t).join(" ").trim(),WL=A=>{for(const e in A)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var ZL={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const $L=ae.forwardRef(({color:A="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:n,className:a="",children:s,iconNode:l,...c},h)=>ae.createElement("svg",{ref:h,...ZL,width:e,height:e,stroke:A,strokeWidth:n?Number(t)*24/Number(e):t,className:S4("lucide",a),...!s&&!WL(c)&&{"aria-hidden":"true"},...c},[...l.map(([f,g])=>ae.createElement(f,g)),...Array.isArray(s)?s:[s]]));const Wt=(A,e)=>{const t=ae.forwardRef(({className:n,...a},s)=>ae.createElement($L,{ref:s,iconNode:e,className:S4(`lucide-${XL($C(A))}`,`lucide-${A}`,n),...a}));return t.displayName=$C(A),t};const e6=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],t6=Wt("arrow-left",e6);const A6=[["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"}]],n6=Wt("camera",A6);const r6=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],So=Wt("check",r6);const i6=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],a6=Wt("chevron-right",i6);const s6=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],o6=Wt("chevron-left",s6);const l6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],c6=Wt("circle-alert",l6);const u6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],eb=Wt("circle-question-mark",u6);const h6=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],f6=Wt("clock",h6);const d6=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],g6=Wt("copy",d6);const p6=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Ec=Wt("download",p6);const m6=[["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:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],w6=Wt("file-down",m6);const v6=[["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"}]],xc=Wt("folder-open",v6);const y6=[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],B6=Wt("folder-plus",y6);const C6=[["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"}]],b6=Wt("grid-3x3",C6);const E6=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],x6=Wt("grip-vertical",E6);const S6=[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19 3 3v-5.5",key:"9ldu5r"}],["path",{d:"m17 22 3-3",key:"1nkfve"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]],U6=Wt("image-down",S6);const I6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],_c=Wt("image",I6);const F6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],tb=Wt("info",F6);const T6=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Zm=Wt("layers",T6);const _6=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],N6=Wt("list",_6);const Q6=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ss=Wt("loader-circle",Q6);const L6=[["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"}]],O6=Wt("log-out",L6);const R6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],k6=Wt("message-square",R6);const H6=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],D6=Wt("pause",H6);const M6=[["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"}]],U4=Wt("pen",M6);const P6=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],j6=Wt("play",P6);const K6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Wf=Wt("plus",K6);const G6=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Np=Wt("refresh-cw",G6);const z6=[["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"}]],V6=Wt("scissors",z6);const q6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Y6=Wt("search",q6);const X6=[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]],J6=Wt("skip-back",X6);const W6=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],Z6=Wt("skip-forward",W6);const $6=[["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M12 21v-9",key:"17s77i"}],["path",{d:"M12 8V3",key:"13r4qs"}],["path",{d:"M17 16h4",key:"h1uq16"}],["path",{d:"M19 12V3",key:"o1uvq1"}],["path",{d:"M19 21v-5",key:"qua636"}],["path",{d:"M3 14h4",key:"bcjad9"}],["path",{d:"M5 10V3",key:"cb8scm"}],["path",{d:"M5 21v-7",key:"1w1uti"}]],eO=Wt("sliders-vertical",$6);const tO=[["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"}]],lw=Wt("sparkles",tO);const AO=[["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"}]],nO=Wt("square-check-big",AO);const rO=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],iO=Wt("square",rO);const aO=[["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"}]],Lf=Wt("trash-2",aO);const sO=[["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"}]],oO=Wt("triangle-alert",sO);const lO=[["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"}]],cO=Wt("upload",lO);const uO=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],Io=Wt("video",uO);const hO=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],I4=Wt("volume-2",hO);const fO=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],F4=Wt("volume-x",fO);const dO=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],gO=Wt("wand-sparkles",dO);const pO=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ds=Wt("x",pO),mO=({activeTab:A,onTabChange:e,activeProjectId:t})=>{const n=[{id:"projects",label:"Projects",icon:xc,requiresProject:!1},{id:"image",label:"Image Gen",icon:_c,requiresProject:!0},{id:"video",label:"Video Gen",icon:Io,requiresProject:!0}];return b.jsx("div",{className:"flex items-center gap-6",children:n.map(a=>{const s=a.icon,l=A===a.id,c=a.requiresProject&&!t;return b.jsxs("button",{onClick:()=>!c&&e(a.id),disabled:c,title:c?"Select a project first":a.label,className:`relative flex items-center gap-2 px-1 py-2 font-medium transition-all ${c?"text-slate-600 cursor-not-allowed":l?"text-cinema-gold":"text-slate-400 hover:text-slate-200"}`,children:[b.jsx(s,{className:"w-4 h-4"}),b.jsx("span",{children:a.label}),b.jsx("span",{className:`absolute bottom-0 left-0 right-0 h-0.5 bg-cinema-gold transition-all ${l?"opacity-100":"opacity-0"}`})]},a.id)})})};var Ab;(function(A){A.STRING="string",A.NUMBER="number",A.INTEGER="integer",A.BOOLEAN="boolean",A.ARRAY="array",A.OBJECT="object"})(Ab||(Ab={}));var nb;(function(A){A.LANGUAGE_UNSPECIFIED="language_unspecified",A.PYTHON="python"})(nb||(nb={}));var rb;(function(A){A.OUTCOME_UNSPECIFIED="outcome_unspecified",A.OUTCOME_OK="outcome_ok",A.OUTCOME_FAILED="outcome_failed",A.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(rb||(rb={}));const ib=["user","model","function","system"];var ab;(function(A){A.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",A.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",A.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",A.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",A.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",A.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(ab||(ab={}));var sb;(function(A){A.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",A.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",A.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",A.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",A.BLOCK_NONE="BLOCK_NONE"})(sb||(sb={}));var ob;(function(A){A.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",A.NEGLIGIBLE="NEGLIGIBLE",A.LOW="LOW",A.MEDIUM="MEDIUM",A.HIGH="HIGH"})(ob||(ob={}));var lb;(function(A){A.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",A.SAFETY="SAFETY",A.OTHER="OTHER"})(lb||(lb={}));var Of;(function(A){A.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",A.STOP="STOP",A.MAX_TOKENS="MAX_TOKENS",A.SAFETY="SAFETY",A.RECITATION="RECITATION",A.LANGUAGE="LANGUAGE",A.BLOCKLIST="BLOCKLIST",A.PROHIBITED_CONTENT="PROHIBITED_CONTENT",A.SPII="SPII",A.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",A.OTHER="OTHER"})(Of||(Of={}));var cb;(function(A){A.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",A.RETRIEVAL_QUERY="RETRIEVAL_QUERY",A.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",A.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",A.CLASSIFICATION="CLASSIFICATION",A.CLUSTERING="CLUSTERING"})(cb||(cb={}));var ub;(function(A){A.MODE_UNSPECIFIED="MODE_UNSPECIFIED",A.AUTO="AUTO",A.ANY="ANY",A.NONE="NONE"})(ub||(ub={}));var hb;(function(A){A.MODE_UNSPECIFIED="MODE_UNSPECIFIED",A.MODE_DYNAMIC="MODE_DYNAMIC"})(hb||(hb={}));class Vr extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class Mu extends Vr{constructor(e,t){super(e),this.response=t}}class T4 extends Vr{constructor(e,t,n,a){super(e),this.status=t,this.statusText=n,this.errorDetails=a}}class Ql extends Vr{}class _4 extends Vr{}const wO="https://generativelanguage.googleapis.com",vO="v1beta",yO="0.24.1",BO="genai-js";var jc;(function(A){A.GENERATE_CONTENT="generateContent",A.STREAM_GENERATE_CONTENT="streamGenerateContent",A.COUNT_TOKENS="countTokens",A.EMBED_CONTENT="embedContent",A.BATCH_EMBED_CONTENTS="batchEmbedContents"})(jc||(jc={}));class CO{constructor(e,t,n,a,s){this.model=e,this.task=t,this.apiKey=n,this.stream=a,this.requestOptions=s}toString(){var e,t;const n=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||vO;let s=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||wO}/${n}/${this.model}:${this.task}`;return this.stream&&(s+="?alt=sse"),s}}function bO(A){const e=[];return A?.apiClient&&e.push(A.apiClient),e.push(`${BO}/${yO}`),e.join(" ")}async function EO(A){var e;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",bO(A.requestOptions)),t.append("x-goog-api-key",A.apiKey);let n=(e=A.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(a){throw new Ql(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${a.message}`)}for(const[a,s]of n.entries()){if(a==="x-goog-api-key")throw new Ql(`Cannot set reserved header name ${a}`);if(a==="x-goog-api-client")throw new Ql(`Header name ${a} can only be set using the apiClient field`);t.append(a,s)}}return t}async function xO(A,e,t,n,a,s){const l=new CO(A,e,t,n,s);return{url:l.toString(),fetchOptions:Object.assign(Object.assign({},FO(s)),{method:"POST",headers:await EO(l),body:a})}}async function fd(A,e,t,n,a,s={},l=fetch){const{url:c,fetchOptions:h}=await xO(A,e,t,n,a,s);return SO(c,h,l)}async function SO(A,e,t=fetch){let n;try{n=await t(A,e)}catch(a){UO(a,A)}return n.ok||await IO(n,A),n}function UO(A,e){let t=A;throw t.name==="AbortError"?(t=new _4(`Request aborted when fetching ${e.toString()}: ${A.message}`),t.stack=A.stack):A instanceof T4||A instanceof Ql||(t=new Vr(`Error fetching from ${e.toString()}: ${A.message}`),t.stack=A.stack),t}async function IO(A,e){let t="",n;try{const a=await A.json();t=a.error.message,a.error.details&&(t+=` ${JSON.stringify(a.error.details)}`,n=a.error.details)}catch{}throw new T4(`Error fetching from ${e.toString()}: [${A.status} ${A.statusText}] ${t}`,A.status,A.statusText,n)}function FO(A){const e={};if(A?.signal!==void 0||A?.timeout>=0){const t=new AbortController;A?.timeout>=0&&setTimeout(()=>t.abort(),A.timeout),A?.signal&&A.signal.addEventListener("abort",()=>{t.abort()}),e.signal=t.signal}return e}function Av(A){return A.text=()=>{if(A.candidates&&A.candidates.length>0){if(A.candidates.length>1&&console.warn(`This response had ${A.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),np(A.candidates[0]))throw new Mu(`${yl(A)}`,A);return TO(A)}else if(A.promptFeedback)throw new Mu(`Text not available. ${yl(A)}`,A);return""},A.functionCall=()=>{if(A.candidates&&A.candidates.length>0){if(A.candidates.length>1&&console.warn(`This response had ${A.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),np(A.candidates[0]))throw new Mu(`${yl(A)}`,A);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),fb(A)[0]}else if(A.promptFeedback)throw new Mu(`Function call not available. ${yl(A)}`,A)},A.functionCalls=()=>{if(A.candidates&&A.candidates.length>0){if(A.candidates.length>1&&console.warn(`This response had ${A.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),np(A.candidates[0]))throw new Mu(`${yl(A)}`,A);return fb(A)}else if(A.promptFeedback)throw new Mu(`Function call not available. ${yl(A)}`,A)},A}function TO(A){var e,t,n,a;const s=[];if(!((t=(e=A.candidates)===null||e===void 0?void 0:e[0].content)===null||t===void 0)&&t.parts)for(const l of(a=(n=A.candidates)===null||n===void 0?void 0:n[0].content)===null||a===void 0?void 0:a.parts)l.text&&s.push(l.text),l.executableCode&&s.push("\n```"+l.executableCode.language+` -`+l.executableCode.code+"\n```\n"),l.codeExecutionResult&&s.push("\n```\n"+l.codeExecutionResult.output+"\n```\n");return s.length>0?s.join(""):""}function fb(A){var e,t,n,a;const s=[];if(!((t=(e=A.candidates)===null||e===void 0?void 0:e[0].content)===null||t===void 0)&&t.parts)for(const l of(a=(n=A.candidates)===null||n===void 0?void 0:n[0].content)===null||a===void 0?void 0:a.parts)l.functionCall&&s.push(l.functionCall);if(s.length>0)return s}const _O=[Of.RECITATION,Of.SAFETY,Of.LANGUAGE];function np(A){return!!A.finishReason&&_O.includes(A.finishReason)}function yl(A){var e,t,n;let a="";if((!A.candidates||A.candidates.length===0)&&A.promptFeedback)a+="Response was blocked",!((e=A.promptFeedback)===null||e===void 0)&&e.blockReason&&(a+=` due to ${A.promptFeedback.blockReason}`),!((t=A.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(a+=`: ${A.promptFeedback.blockReasonMessage}`);else if(!((n=A.candidates)===null||n===void 0)&&n[0]){const s=A.candidates[0];np(s)&&(a+=`Candidate was blocked due to ${s.finishReason}`,s.finishMessage&&(a+=`: ${s.finishMessage}`))}return a}function Zf(A){return this instanceof Zf?(this.v=A,this):new Zf(A)}function NO(A,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(A,e||[]),a,s=[];return a={},l("next"),l("throw"),l("return"),a[Symbol.asyncIterator]=function(){return this},a;function l(C){n[C]&&(a[C]=function(v){return new Promise(function(I,x){s.push([C,v,I,x])>1||c(C,v)})})}function c(C,v){try{h(n[C](v))}catch(I){y(s[0][3],I)}}function h(C){C.value instanceof Zf?Promise.resolve(C.value.v).then(f,g):y(s[0][2],C)}function f(C){c("next",C)}function g(C){c("throw",C)}function y(C,v){C(v),s.shift(),s.length&&c(s[0][0],s[0][1])}}const db=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function QO(A){const e=A.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),t=RO(e),[n,a]=t.tee();return{stream:OO(n),response:LO(a)}}async function LO(A){const e=[],t=A.getReader();for(;;){const{done:n,value:a}=await t.read();if(n)return Av(kO(e));e.push(a)}}function OO(A){return NO(this,arguments,function*(){const t=A.getReader();for(;;){const{value:n,done:a}=yield Zf(t.read());if(a)break;yield yield Zf(Av(n))}})}function RO(A){const e=A.getReader();return new ReadableStream({start(n){let a="";return s();function s(){return e.read().then(({value:l,done:c})=>{if(c){if(a.trim()){n.error(new Vr("Failed to parse stream"));return}n.close();return}a+=l;let h=a.match(db),f;for(;h;){try{f=JSON.parse(h[1])}catch{n.error(new Vr(`Error parsing JSON response: "${h[1]}"`));return}n.enqueue(f),a=a.substring(h[0].length),h=a.match(db)}return s()}).catch(l=>{let c=l;throw c.stack=l.stack,c.name==="AbortError"?c=new _4("Request aborted when reading from the stream"):c=new Vr("Error reading from the stream"),c})}}})}function kO(A){const e=A[A.length-1],t={promptFeedback:e?.promptFeedback};for(const n of A){if(n.candidates){let a=0;for(const s of n.candidates)if(t.candidates||(t.candidates=[]),t.candidates[a]||(t.candidates[a]={index:a}),t.candidates[a].citationMetadata=s.citationMetadata,t.candidates[a].groundingMetadata=s.groundingMetadata,t.candidates[a].finishReason=s.finishReason,t.candidates[a].finishMessage=s.finishMessage,t.candidates[a].safetyRatings=s.safetyRatings,s.content&&s.content.parts){t.candidates[a].content||(t.candidates[a].content={role:s.content.role||"user",parts:[]});const l={};for(const c of s.content.parts)c.text&&(l.text=c.text),c.functionCall&&(l.functionCall=c.functionCall),c.executableCode&&(l.executableCode=c.executableCode),c.codeExecutionResult&&(l.codeExecutionResult=c.codeExecutionResult),Object.keys(l).length===0&&(l.text=""),t.candidates[a].content.parts.push(l)}a++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function N4(A,e,t,n){const a=await fd(e,jc.STREAM_GENERATE_CONTENT,A,!0,JSON.stringify(t),n);return QO(a)}async function Q4(A,e,t,n){const s=await(await fd(e,jc.GENERATE_CONTENT,A,!1,JSON.stringify(t),n)).json();return{response:Av(s)}}function L4(A){if(A!=null){if(typeof A=="string")return{role:"system",parts:[{text:A}]};if(A.text)return{role:"system",parts:[A]};if(A.parts)return A.role?A:{role:"system",parts:A.parts}}}function $f(A){let e=[];if(typeof A=="string")e=[{text:A}];else for(const t of A)typeof t=="string"?e.push({text:t}):e.push(t);return HO(e)}function HO(A){const e={role:"user",parts:[]},t={role:"function",parts:[]};let n=!1,a=!1;for(const s of A)"functionResponse"in s?(t.parts.push(s),a=!0):(e.parts.push(s),n=!0);if(n&&a)throw new Vr("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!n&&!a)throw new Vr("No content is provided for sending chat message.");return n?e:t}function DO(A,e){var t;let n={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(t=e?.cachedContent)===null||t===void 0?void 0:t.name,contents:[]};const a=A.generateContentRequest!=null;if(A.contents){if(a)throw new Ql("CountTokensRequest must have one of contents or generateContentRequest, not both.");n.contents=A.contents}else if(a)n=Object.assign(Object.assign({},n),A.generateContentRequest);else{const s=$f(A);n.contents=[s]}return{generateContentRequest:n}}function gb(A){let e;return A.contents?e=A:e={contents:[$f(A)]},A.systemInstruction&&(e.systemInstruction=L4(A.systemInstruction)),e}function MO(A){return typeof A=="string"||Array.isArray(A)?{content:$f(A)}:A}const pb=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],PO={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function jO(A){let e=!1;for(const t of A){const{role:n,parts:a}=t;if(!e&&n!=="user")throw new Vr(`First content should be with role 'user', got ${n}`);if(!ib.includes(n))throw new Vr(`Each item should include role field. Got ${n} but valid roles are: ${JSON.stringify(ib)}`);if(!Array.isArray(a))throw new Vr("Content should have 'parts' property with an array of Parts");if(a.length===0)throw new Vr("Each Content should have at least one part");const s={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const c of a)for(const h of pb)h in c&&(s[h]+=1);const l=PO[n];for(const c of pb)if(!l.includes(c)&&s[c]>0)throw new Vr(`Content with role '${n}' can't contain '${c}' part`);e=!0}}function mb(A){var e;if(A.candidates===void 0||A.candidates.length===0)return!1;const t=(e=A.candidates[0])===null||e===void 0?void 0:e.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(const n of t.parts)if(n===void 0||Object.keys(n).length===0||n.text!==void 0&&n.text==="")return!1;return!0}const wb="SILENT_ERROR";class KO{constructor(e,t,n,a={}){this.model=t,this.params=n,this._requestOptions=a,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&(jO(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){var n,a,s,l,c,h;await this._sendPromise;const f=$f(e),g={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(a=this.params)===null||a===void 0?void 0:a.generationConfig,tools:(s=this.params)===null||s===void 0?void 0:s.tools,toolConfig:(l=this.params)===null||l===void 0?void 0:l.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(h=this.params)===null||h===void 0?void 0:h.cachedContent,contents:[...this._history,f]},y=Object.assign(Object.assign({},this._requestOptions),t);let C;return this._sendPromise=this._sendPromise.then(()=>Q4(this._apiKey,this.model,g,y)).then(v=>{var I;if(mb(v.response)){this._history.push(f);const x=Object.assign({parts:[],role:"model"},(I=v.response.candidates)===null||I===void 0?void 0:I[0].content);this._history.push(x)}else{const x=yl(v.response);x&&console.warn(`sendMessage() was unsuccessful. ${x}. Inspect response object for details.`)}C=v}).catch(v=>{throw this._sendPromise=Promise.resolve(),v}),await this._sendPromise,C}async sendMessageStream(e,t={}){var n,a,s,l,c,h;await this._sendPromise;const f=$f(e),g={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(a=this.params)===null||a===void 0?void 0:a.generationConfig,tools:(s=this.params)===null||s===void 0?void 0:s.tools,toolConfig:(l=this.params)===null||l===void 0?void 0:l.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(h=this.params)===null||h===void 0?void 0:h.cachedContent,contents:[...this._history,f]},y=Object.assign(Object.assign({},this._requestOptions),t),C=N4(this._apiKey,this.model,g,y);return this._sendPromise=this._sendPromise.then(()=>C).catch(v=>{throw new Error(wb)}).then(v=>v.response).then(v=>{if(mb(v)){this._history.push(f);const I=Object.assign({},v.candidates[0].content);I.role||(I.role="model"),this._history.push(I)}else{const I=yl(v);I&&console.warn(`sendMessageStream() was unsuccessful. ${I}. Inspect response object for details.`)}}).catch(v=>{v.message!==wb&&console.error(v)}),C}}async function GO(A,e,t,n){return(await fd(e,jc.COUNT_TOKENS,A,!1,JSON.stringify(t),n)).json()}async function zO(A,e,t,n){return(await fd(e,jc.EMBED_CONTENT,A,!1,JSON.stringify(t),n)).json()}async function VO(A,e,t,n){const a=t.requests.map(l=>Object.assign(Object.assign({},l),{model:e}));return(await fd(e,jc.BATCH_EMBED_CONTENTS,A,!1,JSON.stringify({requests:a}),n)).json()}class vb{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=L4(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){var n;const a=gb(e),s=Object.assign(Object.assign({},this._requestOptions),t);return Q4(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},a),s)}async generateContentStream(e,t={}){var n;const a=gb(e),s=Object.assign(Object.assign({},this._requestOptions),t);return N4(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},a),s)}startChat(e){var t;return new KO(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(t=this.cachedContent)===null||t===void 0?void 0:t.name},e),this._requestOptions)}async countTokens(e,t={}){const n=DO(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),a=Object.assign(Object.assign({},this._requestOptions),t);return GO(this.apiKey,this.model,n,a)}async embedContent(e,t={}){const n=MO(e),a=Object.assign(Object.assign({},this._requestOptions),t);return zO(this.apiKey,this.model,n,a)}async batchEmbedContents(e,t={}){const n=Object.assign(Object.assign({},this._requestOptions),t);return VO(this.apiKey,this.model,e,n)}}class O4{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new Vr("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new vb(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new Ql("Cached content must contain a `name` field.");if(!e.model)throw new Ql("Cached content must contain a `model` field.");const a=["model","systemInstruction"];for(const l of a)if(t?.[l]&&e[l]&&t?.[l]!==e[l]){if(l==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,h=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(c===h)continue}throw new Ql(`Different value for "${l}" specified in modelParams (${t[l]}) and cachedContent (${e[l]})`)}const s=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new vb(this.apiKey,s,n)}}const qO="CinemaStudioPro",YO=3,XO={projects:{keyPath:"id",indexes:["name","updatedAt","userId"]},items:{keyPath:"id",indexes:["projectId","type","createdAt"]},storyboards:{keyPath:"id",indexes:["projectId","updatedAt"]}},JO=()=>{const[A,e]=ae.useState(null),[t,n]=ae.useState(!1),[a,s]=ae.useState(null);ae.useEffect(()=>(new Promise((x,_)=>{const T=indexedDB.open(qO,YO);T.onerror=()=>{_(new Error("Failed to open database"))},T.onsuccess=k=>{x(k.target.result)},T.onupgradeneeded=k=>{const z=k.target.result,H=k.target.transaction;Object.entries(XO).forEach(([re,le])=>{let ce;z.objectStoreNames.contains(re)?ce=H.objectStore(re):ce=z.createObjectStore(re,{keyPath:le.keyPath}),le.indexes.forEach($=>{ce.indexNames.contains($)||ce.createIndex($,$,{unique:!1})})})}}).then(x=>{e(x),n(!0)}).catch(x=>{s(x.message),console.error("IndexedDB initialization failed:",x)}),()=>{A&&A.close()}),[]);const l=ae.useCallback((I,x)=>new Promise((_,T)=>{if(!A){T(new Error("Database not initialized"));return}const H=A.transaction(I,"readwrite").objectStore(I).add(x);H.onsuccess=()=>_(x),H.onerror=()=>T(new Error(`Failed to add to ${I}`))}),[A]),c=ae.useCallback((I,x)=>new Promise((_,T)=>{if(!A){T(new Error("Database not initialized"));return}const H=A.transaction(I,"readwrite").objectStore(I).put(x);H.onsuccess=()=>_(x),H.onerror=()=>T(new Error(`Failed to update ${I}`))}),[A]),h=ae.useCallback((I,x)=>new Promise((_,T)=>{if(!A){T(new Error("Database not initialized"));return}const H=A.transaction(I,"readonly").objectStore(I).get(x);H.onsuccess=()=>_(H.result),H.onerror=()=>T(new Error(`Failed to get from ${I}`))}),[A]),f=ae.useCallback(I=>new Promise((x,_)=>{if(!A){_(new Error("Database not initialized"));return}const z=A.transaction(I,"readonly").objectStore(I).getAll();z.onsuccess=()=>x(z.result||[]),z.onerror=()=>_(new Error(`Failed to get all from ${I}`))}),[A]),g=ae.useCallback((I,x,_)=>new Promise((T,k)=>{if(!A){k(new Error("Database not initialized"));return}const le=A.transaction(I,"readonly").objectStore(I).index(x).getAll(_);le.onsuccess=()=>T(le.result||[]),le.onerror=()=>k(new Error(`Failed to query ${I} by ${x}`))}),[A]),y=ae.useCallback((I,x)=>new Promise((_,T)=>{if(!A){T(new Error("Database not initialized"));return}const H=A.transaction(I,"readwrite").objectStore(I).delete(x);H.onsuccess=()=>_(!0),H.onerror=()=>T(new Error(`Failed to delete from ${I}`))}),[A]),C=ae.useCallback(I=>new Promise((x,_)=>{if(!A){_(new Error("Database not initialized"));return}const z=A.transaction(I,"readwrite").objectStore(I).clear();z.onsuccess=()=>x(!0),z.onerror=()=>_(new Error(`Failed to clear ${I}`))}),[A]),v=ae.useCallback(I=>new Promise((x,_)=>{if(!A){_(new Error("Database not initialized"));return}const z=A.transaction(I,"readonly").objectStore(I).count();z.onsuccess=()=>x(z.result),z.onerror=()=>_(new Error(`Failed to count ${I}`))}),[A]);return{isReady:t,error:a,add:l,put:c,get:h,getAll:f,getByIndex:g,remove:y,clear:C,count:v}},nv=()=>{const{isReady:A,error:e,add:t,put:n,get:a,getAll:s,getByIndex:l,remove:c}=JO(),{user:h}=tv(),f=h?.id||"local",[g,y]=ae.useState([]),[C,v]=ae.useState(!0),[I,x]=ae.useState(null),_=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,N=>{const G=Math.random()*16|0;return(N==="x"?G:G&3|8).toString(16)});ae.useEffect(()=>{A&&T()},[A]);const T=async()=>{v(!0);try{const N=await s("projects"),G=[];for(const he of N)if(he.userId)he.userId===f&&G.push(he);else{const Ne={...he,userId:f};await n("projects",Ne),G.push(Ne)}const W=G.sort((he,Ne)=>Ne.updatedAt-he.updatedAt);y(W),x(null)}catch(N){x(N.message),console.error("Failed to load projects:",N)}finally{v(!1)}},k=ae.useCallback(async N=>{if(!N?.trim())throw new Error("Project name is required");const G={id:_(),userId:f,name:N.trim(),createdAt:Date.now(),updatedAt:Date.now()};try{return await t("projects",G),y(W=>[G,...W]),G}catch(W){throw x(W.message),W}},[t]),z=ae.useCallback(async N=>{try{const G=await l("items","projectId",N);for(const W of G)await c("items",W.id);return await c("projects",N),y(W=>W.filter(he=>he.id!==N)),!0}catch(G){throw x(G.message),G}},[l,c]),H=ae.useCallback(async(N,G)=>{if(!G?.trim())throw new Error("Project name is required");try{const W=await a("projects",N);if(!W)throw new Error("Project not found");const he={...W,name:G.trim(),updatedAt:Date.now()};return await n("projects",he),y(Ne=>Ne.map(P=>P.id===N?he:P).sort((P,S)=>S.updatedAt-P.updatedAt)),he}catch(W){throw x(W.message),W}},[a,n]),re=ae.useCallback(async(N,G)=>{const W={id:_(),projectId:N,type:G.type,prompt:G.prompt,settings:G.settings||{},referenceImages:G.referenceImages||[],thumbnail:G.thumbnail||null,data:G.data,mimeType:G.mimeType||"image/png",createdAt:Date.now()};try{await t("items",W);const he=await a("projects",N);return he&&(await n("projects",{...he,updatedAt:Date.now()}),y(Ne=>Ne.map(P=>P.id===N?{...P,updatedAt:Date.now()}:P).sort((P,S)=>S.updatedAt-P.updatedAt))),W}catch(he){throw x(he.message),he}},[t,a,n]),le=ae.useCallback(async(N,G)=>{try{await c("items",G);const W=await a("projects",N);return W&&await n("projects",{...W,updatedAt:Date.now()}),!0}catch(W){throw x(W.message),W}},[a,n,c]),ce=ae.useCallback(async N=>{try{return(await l("items","projectId",N)).sort((W,he)=>he.createdAt-W.createdAt)}catch(G){throw x(G.message),G}},[l]),$=ae.useCallback(async N=>{try{const G=await a("projects",N);if(!G)throw new Error("Project not found");const W=await ce(N);return{...G,items:W}}catch(G){throw x(G.message),G}},[a,ce]),Y=ae.useCallback(async N=>{try{const G=await $(N);return{version:1,exportedAt:Date.now(),project:G}}catch(G){throw x(G.message),G}},[$]),de=ae.useCallback(async(N,G,W=[])=>{if(!G?.trim())throw new Error("Storyboard name is required");const he=W.map((P,S)=>({imageId:P,order:S,annotation:""})),Ne={id:_(),projectId:N,name:G.trim(),frames:he,createdAt:Date.now(),updatedAt:Date.now()};try{return await t("storyboards",Ne),Ne}catch(P){throw x(P.message),P}},[t]),R=ae.useCallback(async N=>{try{return(await l("storyboards","projectId",N)).sort((W,he)=>he.updatedAt-W.updatedAt)}catch(G){throw x(G.message),G}},[l]),V=ae.useCallback(async N=>{try{return await a("storyboards",N)}catch(G){throw x(G.message),G}},[a]),ne=ae.useCallback(async(N,G)=>{try{const W=await a("storyboards",N);if(!W)throw new Error("Storyboard not found");const he={...W,...G,updatedAt:Date.now()};return await n("storyboards",he),he}catch(W){throw x(W.message),W}},[a,n]),Ae=ae.useCallback(async N=>{try{return await c("storyboards",N),!0}catch(G){throw x(G.message),G}},[c]),Ce=ae.useCallback(async N=>{try{const{project:G}=N,W={...G,id:_(),userId:f,name:`${G.name} (imported)`,createdAt:Date.now(),updatedAt:Date.now()};if(await t("projects",W),G.items)for(const he of G.items)await t("items",{...he,id:_(),projectId:W.id,createdAt:Date.now()});return await T(),W}catch(G){throw x(G.message),G}},[t,T]);return{projects:g,isLoading:C,isReady:A,error:I||e,createProject:k,deleteProject:z,renameProject:H,addItemToProject:re,removeItemFromProject:le,getProjectItems:ce,getProjectWithItems:$,exportProject:Y,importProject:Ce,refreshProjects:T,createStoryboard:de,getStoryboards:R,getStoryboard:V,updateStoryboard:ne,deleteStoryboard:Ae}},Sc=A=>`/lux-studio/api/${A}`,WO=({activeProjectId:A,editData:e,onEditLoaded:t})=>{const{addItemToProject:n,getProjectWithItems:a,isReady:s}=nv(),l=[{value:"Arri Alexa 35",display:"Arri Alexa 35",sensorFormat:"Super 35",tooltip:"The Hollywood Standard. Best for natural skin tones and a classic cinematic 'blockbuster' feel.",tags:"Narrative / Drama",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Laowa Probe"],physics:"ArriRaw sensor readout, high dynamic range, natural noise floor, thick color science"},{value:"Sony Venice 2",display:"Sony Venice 2",sensorFormat:"Full Frame",tooltip:"The Low-Light King. Excellent for night scenes, clean shadows, and a modern aesthetic.",tags:"Commercial / Night",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Arri Signature","Laowa Probe"],physics:"Dual ISO digital sensor, clean shadows, modern color science, high frequency detail"},{value:"Red V-Raptor",display:"Red V-Raptor",sensorFormat:"Full Frame",tooltip:"Hyper-Real Action. Perfect for high-speed motion, sports, and razor-sharp detail.",tags:"Action / Sports",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Arri Signature","Laowa Probe"],physics:"RedCode RAW 8K, clinical sharpness, high shutter angle clarity, hyper-realistic texture"},{value:"Arriflex 416",display:"Arriflex 416",sensorFormat:"Super 16 (Film)",tooltip:"Gritty & Nostalgic. High grain, soft focus, and vibrant, messy colors. The 'Indie' look.",tags:"Vintage / Music Video",compatibleLenses:["Zeiss Super Speed","Laowa Probe"],physics:"Super 16mm film gate, heavy grain structure, soft optical resolution, vibrant chemical color"},{value:"Arricam LT",display:"Arricam LT",sensorFormat:"35mm (Film)",tooltip:"The Golden Age. Fine grain, organic texture, and rich colors. The classic movie look before digital.",tags:"Period Piece / Premium",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Laowa Probe"],physics:"35mm motion picture film stock, organic grain structure, halation on highlights, photochemical dynamic range"},{value:"Fujifilm GFX 100",display:"Fujifilm GFX 100",sensorFormat:"Medium Format",tooltip:"The Studio Master. Massive resolution and depth. Unbeatable for print-quality stills.",tags:"Product / Fashion",compatibleLenses:["Fujinon GF","Arri Signature","Laowa Probe"],physics:"Medium format digital sensor, zero circle of confusion, extreme resolution, pore-level detail"},{value:"Phantom Flex4K",display:"Phantom Flex4K",sensorFormat:"Super 35",tooltip:"The Time Machine. 1000fps slow motion.",tags:"High-Speed / Sports",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Laowa Probe","Angénieux Optimo"],physics:"High-speed global shutter sensor, frozen fluid dynamics, zero motion blur, deep saturation, specialized for 1000fps playback"},{value:"Blackmagic URSA Cine 12K",display:"URSA Cine 12K",sensorFormat:"Full Frame",tooltip:"Resolution Monster. Infinite reframing capability.",tags:"Future-Proof / VFX",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Arri Signature","Laowa Probe","Canon TS-E","Angénieux Optimo"],physics:"12K RGB sensor, extreme resolution, zero aliasing, distinct non-bayer pattern texture, analytics-grade sharpness"}],c=[{value:"Panavision C-Series",display:"Panavision C-Series",compatibleFormats:["Super 35","35mm"],tooltip:"Classic Widescreen. Horizontal blue flares, oval bokeh. The sci-fi blockbuster look.",keywords:"Flares, Oval Bokeh",physics:"anamorphic optics, characteristic oval bokeh, horizontal blue lens flares, slight barrel distortion"},{value:"Cooke S7/i",display:"Cooke S7/i",compatibleFormats:["Full Frame","Super 35","35mm"],tooltip:"The 'Cooke Look.' Warm, gentle, and incredibly flattering. Gold standard for portraits.",keywords:"Warmth, Face Focus",physics:"Cooke speed panchrio look, warm color rendering, gentle focus falloff, flattering face compression"},{value:"Canon K-35",display:"Canon K-35",compatibleFormats:["Full Frame","Super 35","35mm"],tooltip:"Dreamy & Retro. Low contrast, glowing highlights. 1970s/80s vibe.",keywords:"Glow, Retro",physics:"vintage aspherical elements, glowing highlights, low contrast, rainbow flaring, soft sharpness"},{value:"Arri Signature",display:"Arri Signature",compatibleFormats:["Large Format","Full Frame"],tooltip:"Modern Perfection. Ultra-clean, no distortion, pure reality. The invisible lens.",keywords:"Clean, Realistic",physics:"telecentric optical design, zero breathing, ultra-flat field, modern rendering, pure black levels"},{value:"Zeiss Super Speed",display:"Zeiss Super Speed",compatibleFormats:["Super 16 ONLY"],tooltip:"The 16mm Classic. Sharp but textured. Designed specifically for the smaller 16mm film frame.",keywords:"Triangular Bokeh, Grit",physics:"vintage high-speed glass, triangular bokeh at wide apertures, chromatic aberration, gritty texture"},{value:"Fujinon GF",display:"Fujinon GF",compatibleFormats:["Medium Format ONLY"],tooltip:"Studio Glass. Clinically sharp, specifically designed for the massive GFX sensor.",keywords:"Clinical Sharpness",physics:"modern medium format optics, clinical edge-to-edge sharpness, zero distortion, high micro-contrast"},{value:"Laowa Probe",display:"Laowa Probe",compatibleFormats:["All Formats"],tooltip:"Insect-Eye View. Extreme close-ups of small objects/textures.",keywords:"Macro",physics:"macro bug-eye perspective, extreme depth of field, tubular lens construction, surreal wide-angle macro"},{value:"Helios 44-2",display:"Helios 44-2 (Vintage)",compatibleFormats:["Full Frame","Super 35","35mm"],tooltip:"Swirly Bokeh. The cult classic.",keywords:"Swirly Bokeh, Vintage",physics:"Vintage Soviet glass, characteristic swirly bokeh at edges, low contrast flaring, soft center focus, dreamlike aberrations"},{value:"Canon TS-E",display:"Canon Tilt-Shift",compatibleFormats:["Full Frame","Medium Format"],tooltip:"Miniature Effect. Selective focus control.",keywords:"Tilt-Shift, Miniature",physics:"Tilted focal plane, miniature faking effect, selective focus slice, corrected perspective lines, architectural rigidity"},{value:"Angénieux Optimo",display:"Angénieux Optimo",compatibleFormats:["Super 35","Full Frame"],tooltip:"The Hollywood Zoom. Perfect versatility.",keywords:"Cinema Zoom",physics:"Cinema zoom optics, warm organic contrast, breathing-free focus pulls, uniform field illumination"}],h=[{value:"Portrait Studio",lighting:"Rembrandt lighting, softbox diffusion, 3-point setup",defaultCamera:"Arri Alexa 35",defaultLens:"Cooke S7/i",focusType:"stylistic"},{value:"Product (Crisp)",lighting:"Infinity curve, bright diffuse lighting, shadowless, high key",defaultCamera:"Fujifilm GFX 100",defaultLens:"Fujinon GF",focusType:"realism"},{value:"Food Photography",lighting:"Natural window light simulation, back-lighting for steam/texture, warm reflector fill, medium depth of field, focus on texture",defaultCamera:"Sony Venice 2",defaultLens:"Cooke S7/i",focusType:"stylistic"},{value:"Golden Hour (Outdoor)",lighting:"Sun low on horizon, warm orange glow, long dramatic shadows, volumetric backlight, magic hour atmosphere, cinematic depth",defaultCamera:"Arricam LT",defaultLens:"Cooke S7/i",focusType:"stylistic",example:"A vintage Lancia Stratos rally car drifting sideways on a dirt track, kicking up a massive wall of dust that glows incandescent gold in the backlight, creating a dramatic silhouette against the sunset."},{value:"Blue Hour (City)",lighting:"Twilight, deep blue ambient sky light contrasting with warm practical street lamps, moody, atmospheric, balanced exposure",defaultCamera:"Sony Venice 2",defaultLens:"Arri Signature",focusType:"stylistic"},{value:"Neon Cyberpunk",lighting:"Harsh neon signage, mixed color temp, wet reflections",defaultCamera:"Red V-Raptor",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Nostalgic Memory",lighting:"Hazy atmosphere, overexposed highlights, light leaks, warm color grade, sentimental mood, soft focus throughout",defaultCamera:"Arriflex 416",defaultLens:"Zeiss Super Speed",focusType:"stylistic"},{value:"Corporate Headshot",lighting:"Clean white background, high-key lighting, professional balanced fill, sharp focus on eyes, moderate depth of field",defaultCamera:"Fuji GFX 100",defaultLens:"Cooke S7/i",focusType:"realism"},{value:"Macro: Luxury Jewelry",lighting:"Sparkling point-source lighting, black velvet background, high contrast reflection control, focus stacking simulation for complete sharpness",defaultCamera:"Fuji GFX 100",defaultLens:"Macro / Probe Lens",focusType:"realism"},{value:"Macro: Nature Details",lighting:"Diffused natural sunlight, shallow depth of field, vibrant greens, morning dew, microscopic texture",defaultCamera:"Arri Alexa 35",defaultLens:"Macro / Probe Lens",focusType:"stylistic"},{value:"Wildlife / Safari",lighting:"Telephoto compression, frozen motion, golden hour backlight, natural habitat, separation from background",defaultCamera:"Red V-Raptor",defaultLens:"Cooke S7/i",focusType:"stylistic"},{value:"Sports Action",lighting:"High shutter speed, frozen particles/sweat, stadium floodlights, dynamic composition, sharp subject focus",defaultCamera:"Red V-Raptor",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Street Photography",lighting:"Candid moment, natural available light, messy urban background, hyperfocal distance, deep depth of field, everything in focus",defaultCamera:"Arriflex 416",defaultLens:"Canon K-35",focusType:"realism"},{value:"Architecture",lighting:"Balanced mixed lighting, straight lines, airy atmosphere",defaultCamera:"Fujifilm GFX 100",defaultLens:"Fujinon GF",focusType:"realism"},{value:"Fashion Editorial",lighting:"Avant-garde lighting, colored gels, stark shadows, high fashion pose, studio backdrop, stylized depth",defaultCamera:"Sony Venice 2",defaultLens:"Canon K-35",focusType:"stylistic"},{value:"Cinematic Horror",lighting:"Underexposed, single harsh source (flashlight), heavy shadows",defaultCamera:"Arricam LT",defaultLens:"Canon K-35",focusType:"stylistic"},{value:"Docu / Realism",lighting:"Natural window key light, negative fill, messy authentic background",defaultCamera:"Arri Alexa 35",defaultLens:"Arri Signature",focusType:"realism"},{value:"Symmetrical Whimsy",lighting:"Even soft lighting, centered symmetrical composition, muted earth tones with subtle color accents, overcast natural light, deadpan framing, tactile real-world textures",defaultCamera:"Arricam LT",defaultLens:"Arri Signature",focusType:"realism"},{value:"IMAX Scale Epic",lighting:"Naturalistic practical lighting, cool color temperature, high contrast, immense sense of scale, deep depth of field",defaultCamera:"Arri Alexa 35",defaultLens:"Arri Signature",focusType:"realism"},{value:"Clinical Thriller",lighting:"Low-key chiaroscuro, controlled shadows, sickly green/yellow color grade, precise stabilized motion",defaultCamera:"Red V-Raptor",defaultLens:"Arri Signature",focusType:"stylistic"},{value:"Brutalist Atmosphere",lighting:"Single source silhouette, atmospheric haze, monochromatic orange/sepia tones, stark geometry, visual silence",defaultCamera:"Arri Alexa 35",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Technicolor Dream",lighting:"Artificial studio lighting, high saturation, vibrant pinks and cyans, glossy plastic textures, high-key brightness",defaultCamera:"Arri Alexa 35",defaultLens:"Cooke S7/i",focusType:"stylistic"},{value:"Obsessive Symmetry",lighting:"One-point perspective, deep focus, wide angle distortion, cold practical lighting, clinical perfection",defaultCamera:"Arricam LT",defaultLens:"Arri Signature",focusType:"realism"},{value:"Hong Kong Nostalgia",lighting:"Step-printing effect, motion blur, neon-soaked humidity, intimate handheld, rain-slicked textures",defaultCamera:"Arriflex 416",defaultLens:"Zeiss Super Speed",focusType:"stylistic"},{value:"Industrial Haze",lighting:"Volumetric lighting, visible shafts of light (god rays), atmospheric smoke, high-density industrial detail",defaultCamera:"Arri Alexa 35",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Gothic Fantasy",lighting:"German Expressionist lighting, high contrast long shadows, twisted geometry, desaturated palette",defaultCamera:"Arri Alexa 35",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"LED Volume (Virtual Production)",lighting:"Interactive environmental lighting, soft ambient wrap from LED panels, perfect reflection matching, zero green spill",defaultCamera:"Arri Alexa 35",defaultLens:"Arri Signature",focusType:"realism"},{value:"Automotive: Showroom",lighting:"Massive softbox ceiling, continuous highlight lines along bodywork, negative fill to shape curves, pure white infinity cove",defaultCamera:"Sony Venice 2",defaultLens:"Arri Signature",focusType:"realism",example:"A silver concept car parked on a pure white infinity curve, continuous highlight lines tracing the aerodynamic bodywork."},{value:"Knolling / Flat Lay",lighting:"Overhead soft diffuse light, shadowless cavity, high-key evenness, precise grid alignment",defaultCamera:"Fujifilm GFX 100",defaultLens:"Fujinon GF",focusType:"realism"},{value:"Conflict Photography",lighting:"Harsh midday sun, atmospheric dust and smoke, high contrast, documentary style reality, blown highlights, raw and unpolished",defaultCamera:"Arriflex 416",defaultLens:"Zeiss Super Speed",focusType:"realism"},{value:"NYC Street Editorial",lighting:"Natural city canyon light, bounce board fill for face, sharp modern contrast, motion blur in background, high-resolution gloss",defaultCamera:"Sony Venice 2",defaultLens:"Arri Signature",focusType:"stylistic"},{value:"Underground Rave / Flash",lighting:"Direct on-camera flash with slow shutter drag (rear-curtain sync), light trails, laser rim lighting, sweaty atmosphere, darkness crushing the background",defaultCamera:"Red V-Raptor",defaultLens:"Helios 44-2",focusType:"stylistic"},{value:"Architectural Digest Interior",lighting:"North-facing window soft light, large diffusion frames, negative fill for contrast, texture-raking angle, perfectly balanced exposure",defaultCamera:"Fujifilm GFX 100",defaultLens:"Canon TS-E",focusType:"realism"},{value:"90s Grunge Editorial",lighting:"Hard direct flash, dirty green/yellow color cast, vignetting, unretouched skin texture, claustrophobic framing",defaultCamera:"Arriflex 416",defaultLens:"Canon K-35",focusType:"stylistic"},{value:"Cassette Futurism (Retro Sci-Fi)",lighting:"Flickering CRT monitor glow, harsh overhead fluorescent strips, brutalist shadows, beige and grey color palette, industrial haze",defaultCamera:"Arriflex 416",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Tech Commercial (Macro)",lighting:"Slow moving light sweep (motion control), brushed metal reflections, dramatic rim lighting in a black void, sub-surface scattering on materials",defaultCamera:"Arri Alexa 35",defaultLens:"Laowa Probe",focusType:"realism"},{value:"Surreal Infrared",lighting:"Full spectrum daylight, false color infrared shift (foliage turns pink/white), deep blue skies, high contrast, dreamlike atmosphere",defaultCamera:"Arricam LT",defaultLens:"Canon K-35",focusType:"stylistic"},{value:"Spaghetti Western",lighting:"Harsh high-noon sun, heat haze distortion, sweaty skin texture, extreme close-up on eyes, deep depth of field",defaultCamera:"Arricam LT",defaultLens:"Angénieux Optimo",focusType:"stylistic"},{value:"Automotive: Process Trailer",lighting:"Dynamic passing street lights, rhythmic shadow movement, wet road reflections, motion blur on background only",defaultCamera:"Arri Alexa 35",defaultLens:"Angénieux Optimo",focusType:"stylistic",example:"A black sports car speeding through a tunnel, dynamic motion blur on the tunnel lights, sharp focus on the car badge."},{value:"Product (Liquid/Splash)",lighting:"High-speed strobe lighting, frozen droplets, backlit fluid translucency, crystal clear refraction",defaultCamera:"Phantom Flex4K",defaultLens:"Laowa Probe",focusType:"stylistic",example:"A strawberry dropping into milk, creating a perfect crown splash, frozen in mid-air with high-speed strobe lighting."},{value:"VFX / Green Screen",lighting:"Raw chromakey plate, perfectly flat shadowless green background, distinct rim light for separation, zero color spill, high-fidelity capture",defaultCamera:"Blackmagic URSA Cine 12K",defaultLens:"Arri Signature",focusType:"realism",example:"A raw chromakey plate of a superhero in a landing pose, completely isolated against a flat, pure digital green background, sharp focus, ready for compositing."},{value:"Custom",lighting:null,defaultCamera:null,defaultLens:null,focusType:"stylistic"}],f=["16:9","4:3","3:4","1:1","9:16"],[g,y]=ae.useState("Golden Hour (Outdoor)"),[C,v]=ae.useState(""),[I,x]=ae.useState(""),[_,T]=ae.useState("16:9"),[k,z]=ae.useState(""),[H,re]=ae.useState(""),[le,ce]=ae.useState(!1),[$,Y]=ae.useState(!1),[de,R]=ae.useState(""),[V,ne]=ae.useState(null),[Ae,Ce]=ae.useState(c),[N,G]=ae.useState(.3),[W,he]=ae.useState(null),[Ne,P]=ae.useState(!1),[S,Q]=ae.useState(""),[K,Z]=ae.useState([]),[se,ue]=ae.useState("2K"),[be,oe]=ae.useState([]),[ve,He]=ae.useState(!1);ae.useEffect(()=>{const Be=h.find(Ve=>Ve.value===g);Be&&Be.defaultCamera&&(v(Be.defaultCamera),x(Be.defaultLens))},[g]),ae.useEffect(()=>{const Be=h.find(Ve=>Ve.value===g);Be&&(v(Be.defaultCamera||l[0].value),x(Be.defaultLens||c[0].value))},[]),ae.useEffect(()=>{const Be=l.find(Ve=>Ve.value===C);if(Be&&Be.compatibleLenses){const Ve=c.filter(lt=>Be.compatibleLenses.includes(lt.value));Ce(Ve),!Be.compatibleLenses.includes(I)&&Ve.length>0&&x(Ve[0].value)}else Ce(c)},[C]),ae.useEffect(()=>{if(e){if(e.prompt){const Be=e.prompt.replace(/^Uploaded:\s*/i,"");z(Be)}if(e.imageData){let Be=e.imageData,Ve="image/png";if(e.imageData.startsWith("data:")){const lt=e.imageData.match(/^data:([^;]+);base64,(.+)$/);lt&&(Ve=lt[1],Be=lt[2])}he({data:Be,mime_type:Ve})}t&&t()}},[e,t]),ae.useEffect(()=>{(async()=>{if(!A||!s){oe([]);return}try{const Ve=await a(A);if(Ve&&Ve.items){const lt=Ve.items.filter(it=>it.type==="image");oe(lt)}}catch(Ve){console.error("Failed to load project images:",Ve)}})()},[A,s,a]);const Xe=Be=>{K.length>=14||K.some(Ve=>Ve.projectItemId===Be.id)||(Z(Ve=>[...Ve,{data:Be.data,mime_type:Be.mimeType,name:Be.prompt?.substring(0,20)||"Project Image",projectItemId:Be.id}]),He(!1))},$e=Be=>({"16:9":"A cinematic 16:9 horizontal composition featuring","4:3":"A classic 4:3 format composition featuring","3:4":"A 3:4 portrait format composition featuring","1:1":"A square 1:1 format composition featuring","9:16":"A 9:16 portrait format composition featuring"})[Be]||"",nt=Be=>({Architecture:"Strictly AVOID: messy, dirt, grime, imperfections, motion blur, handheld, shaky","Product (Crisp)":"Strictly AVOID: messy, dirt, grime, imperfections, motion blur, handheld, shaky","Corporate Headshot":"Strictly AVOID: shadow over eyes, silhouette, dark, moody, gritty, high contrast","Portrait Studio":"Strictly AVOID: shadow over eyes, silhouette, dark, moody, gritty, high contrast","Cinematic Horror":"Strictly AVOID: bright, cheerful, clean, pristine, high-key, sunshine","Nostalgic Memory":"Strictly AVOID: bright, cheerful, clean, pristine, high-key, sunshine"})[Be]||"",X=Be=>({"Neon Cyberpunk":"Hovering vehicle, rain, neon lights","Golden Hour (Outdoor)":"Vintage convertible, dust kicking up, lens flare","Cinematic Horror":"Distressed clothing, expressions of terror, flashlight beams cutting through fog, unseen threat in shadows","Corporate Headshot":"Business professional attire, confident posture, subtle smile, perfectly groomed","Portrait Studio":"Professional studio setup, controlled lighting, posed subject","Fashion Editorial":"High fashion couture, avant-garde styling, dramatic poses, editorial expression","Street Photography":"Authentic street fashion, candid moments, urban environment, real people","Blue Hour (City)":"Urban nightlife fashion, city lights reflecting, atmospheric fog, metropolitan energy","Wildlife / Safari":"Natural habitat, majestic animals, golden savanna light, environmental storytelling","Symmetrical Whimsy":"Perfectly centered vintage car, pastel luggage on roof, quirkily dressed driver","IMAX Scale Epic":"Lone rover traversing massive alien glacier, tiny against the landscape","Clinical Thriller":"Sterile hospital corridor, flickering fluorescent light, solitary figure","Brutalist Atmosphere":"Concrete monolith, lone figure dwarfed by structure, dust particles","Technicolor Dream":"Plastic fantastic furniture, bubble machines, candy-colored wardrobe","Obsessive Symmetry":"Identical twins in matching outfits, geometric patterns, perfect alignment","Hong Kong Nostalgia":"Taxi in heavy rain, neon lights reflecting on wet glass, lonely passenger","Industrial Haze":"Factory interior, steam pipes, worker silhouette against machinery","Gothic Fantasy":"Twisted architecture, dramatic cape, fog machine atmosphere"})[Be]||"",We=Be=>({"Arri Alexa 35":"ArriRaw sensor data, pleasing noise floor, high dynamic range, natural skin micro-texture","Sony Venice 2":"Clean digital sensor, zero noise, high-frequency detail, modern sharpness","Red V-Raptor":"8K RedCode RAW, clinical detail, hyper-sharp edges, high shutter angle crispness","Arriflex 416":"Kodak Vision3 500T film stock, heavy film grain, halation, soft organic edges, chemical color process","Arricam LT":"Kodak Vision3 50D film stock, fine grain, organic resolution, rich photochemical colors","Fujifilm GFX 100":"100 Megapixel medium format sensor, pore-level skin detail, textile fiber detail, print quality resolution","Phantom Flex4K":"High-speed sensor readout, frozen temporal resolution, saturated color depth, zero motion blur artifacts","Blackmagic URSA Cine 12K":"12K RGB pattern, infinite reframing capability, zero aliasing, analytics-grade edge definition"})[Be]||"",Tt=()=>{if(!k.trim()){R("Please enter a scene description");return}const Ve=h.find(rA=>rA.value===g)?.lighting||"",lt=We(C),it=$e(_),ct=Ve?`, ${Ve}`:"",rt=`${it} ${k}${ct}, ${lt}, shot on ${C}, ${I}, cinematic composition, aspect ratio ${_}`;re(rt),R("")},Fe=async()=>{if(!k.trim()){R("Please enter a scene description");return}const Be="AIzaSyDs7EKdC9NLM5UqWlGUqeQO96TmSA-kos8";console.log("API Key status:","Present"),ce(!0),R("");try{console.log("Initializing Gemini AI...");const Ve=new O4(Be),lt=["gemini-2.5-flash","gemini-2.5-pro","gemini-2.0-flash-exp","gemini-2.0-flash","gemini-2.0-flash-001","gemini-1.5-pro-latest","gemini-1.5-flash-latest","gemini-1.5-flash","gemini-1.5-pro","gemini-pro"];let it=null,ct=null;for(const eA of lt)try{console.log(`Trying model: ${eA}`),it=Ve.getGenerativeModel({model:eA}),console.log(`Successfully initialized model: ${eA}`);break}catch(mt){console.log(`Model ${eA} not available, trying next...`),ct=mt}if(!it)throw ct||new Error("No Gemini models available");const rt=h.find(eA=>eA.value===g),rA=l.find(eA=>eA.value===C),zt=c.find(eA=>eA.value===I),St=$e(_),_t=nt(g),Vt=X(g),bt=We(C),fA=k.split(" ").length,It=rA?.physics||"",Nt=zt?.physics||"",Zt=rt?.lighting||"";console.log("=== PROMPT GENERATION DEBUG ==="),console.log("Application:",g),console.log("Lighting Style:",Zt),console.log("Camera:",C),console.log("Lens:",I),console.log("Aspect Ratio:",_),console.log("Scene:",k),console.log("================================");const pe=Math.round(N*100);let Le;N<=.2?Le=`LITERAL MODE (${pe}%): Use the user's scene description almost verbatim. Only reformat for prompt structure. Do NOT add subjects, objects, or narrative elements not explicitly mentioned. Keep it minimal and faithful to the input.`:N<=.5?Le=`CONSERVATIVE MODE (${pe}%): Preserve the exact subject matter from the input. You may add sensory atmosphere (air quality, light quality, material textures) but do NOT add new people, objects, or story elements. Enhance what's there, don't invent.`:N<=.8?Le=`CREATIVE MODE (${pe}%): Expand the scene with environmental context and secondary details. Add mood-setting elements, background activity, and atmospheric touches. You may introduce minor supporting elements that complement the main subject. Make the scene feel lived-in and rich.`:Le=`INVENTIVE MODE (${pe}%): Full creative license. Invent dramatic moments, narrative tension, and unexpected compelling details. Add story-driven elements, emotional subtext, and cinematic intrigue. Transform a simple description into a visually striking scene with depth and meaning. Be bold.`;const at=`You are an expert Cinematographer creating image prompts. +`+u.stack}}var Se=Object.prototype.hasOwnProperty,Ye=A.unstable_scheduleCallback,Ze=A.unstable_cancelCallback,At=A.unstable_shouldYield,st=A.unstable_requestPaint,ht=A.unstable_now,Ut=A.unstable_getCurrentPriorityLevel,Be=A.unstable_ImmediatePriority,Ve=A.unstable_UserBlockingPriority,lt=A.unstable_NormalPriority,it=A.unstable_LowPriority,ct=A.unstable_IdlePriority,rt=A.log,rA=A.unstable_setDisableYieldValue,zt=null,St=null;function _t(r){if(typeof rt=="function"&&rA(r),St&&typeof St.setStrictMode=="function")try{St.setStrictMode(zt,r)}catch{}}var Vt=Math.clz32?Math.clz32:It,bt=Math.log,fA=Math.LN2;function It(r){return r>>>=0,r===0?32:31-(bt(r)/fA|0)|0}var Nt=256,Zt=262144,pe=4194304;function Le(r){var i=r&42;if(i!==0)return i;switch(r&-r){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 r&261888;case 262144:case 524288:case 1048576:case 2097152:return r&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return r&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return r}}function at(r,i,o){var u=r.pendingLanes;if(u===0)return 0;var p=0,w=r.suspendedLanes,F=r.pingedLanes;r=r.warmLanes;var j=u&134217727;return j!==0?(u=j&~w,u!==0?p=Le(u):(F&=j,F!==0?p=Le(F):o||(o=j&~r,o!==0&&(p=Le(o))))):(j=u&~w,j!==0?p=Le(j):F!==0?p=Le(F):o||(o=u&~r,o!==0&&(p=Le(o)))),p===0?0:i!==0&&i!==p&&(i&w)===0&&(w=p&-p,o=i&-i,w>=o||w===32&&(o&4194048)!==0)?i:p}function jt(r,i){return(r.pendingLanes&~(r.suspendedLanes&~r.pingedLanes)&i)===0}function $t(r,i){switch(r){case 1:case 2:case 4:case 8:case 64:return i+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 i+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 xA(){var r=pe;return pe<<=1,(pe&62914560)===0&&(pe=4194304),r}function eA(r){for(var i=[],o=0;31>o;o++)i.push(r);return i}function mt(r,i){r.pendingLanes|=i,i!==268435456&&(r.suspendedLanes=0,r.pingedLanes=0,r.warmLanes=0)}function FA(r,i,o,u,p,w){var F=r.pendingLanes;r.pendingLanes=o,r.suspendedLanes=0,r.pingedLanes=0,r.warmLanes=0,r.expiredLanes&=o,r.entangledLanes&=o,r.errorRecoveryDisabledLanes&=o,r.shellSuspendCounter=0;var j=r.entanglements,fe=r.expirationTimes,Qe=r.hiddenUpdates;for(o=F&~o;0"u")return null;try{return r.activeElement||r.body}catch{return r.body}}var kn=/[\n"\\]/g;function Sn(r){return r.replace(kn,function(i){return"\\"+i.charCodeAt(0).toString(16)+" "})}function Qo(r,i,o,u,p,w,F,j){r.name="",F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"?r.type=F:r.removeAttribute("type"),i!=null?F==="number"?(i===0&&r.value===""||r.value!=i)&&(r.value=""+BA(i)):r.value!==""+BA(i)&&(r.value=""+BA(i)):F!=="submit"&&F!=="reset"||r.removeAttribute("value"),i!=null?ql(r,F,BA(i)):o!=null?ql(r,F,BA(o)):u!=null&&r.removeAttribute("value"),p==null&&w!=null&&(r.defaultChecked=!!w),p!=null&&(r.checked=p&&typeof p!="function"&&typeof p!="symbol"),j!=null&&typeof j!="function"&&typeof j!="symbol"&&typeof j!="boolean"?r.name=""+BA(j):r.removeAttribute("name")}function Xc(r,i,o,u,p,w,F,j){if(w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"&&(r.type=w),i!=null||o!=null){if(!(w!=="submit"&&w!=="reset"||i!=null)){ps(r);return}o=o!=null?""+BA(o):"",i=i!=null?""+BA(i):o,j||i===r.value||(r.value=i),r.defaultValue=i}u=u??p,u=typeof u!="function"&&typeof u!="symbol"&&!!u,r.checked=j?r.checked:!!u,r.defaultChecked=!!u,F!=null&&typeof F!="function"&&typeof F!="symbol"&&typeof F!="boolean"&&(r.name=F),ps(r)}function ql(r,i,o){i==="number"&&Br(r.ownerDocument)===r||r.defaultValue===""+o||(r.defaultValue=""+o)}function Cr(r,i,o,u){if(r=r.options,i){i={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$l=!1;if($n)try{var Js={};Object.defineProperty(Js,"passive",{get:function(){$l=!0}}),window.addEventListener("test",Js,Js),window.removeEventListener("test",Js,Js)}catch{$l=!1}var Zr=null,Ws=null,Aa=null;function tu(){if(Aa)return Aa;var r,i=Ws,o=i.length,u,p="value"in Zr?Zr.value:Zr.textContent,w=p.length;for(r=0;r=ji),qn=" ",ws=!1;function vs(r,i){switch(r){case"keyup":return ko.indexOf(i.keyCode)!==-1;case"keydown":return i.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ho(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var ia=!1;function br(r,i){switch(r){case"compositionend":return Ho(i);case"keypress":return i.which!==32?null:(ws=!0,qn);case"textInput":return r=i.data,r===qn&&ws?null:r;default:return null}}function Da(r,i){if(ia)return r==="compositionend"||!ra&&vs(r,i)?(r=tu(),Aa=Ws=Zr=null,ia=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(i.ctrlKey||i.altKey||i.metaKey)||i.ctrlKey&&i.altKey){if(i.char&&1=i)return{node:o,offset:i-r};r=u}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=jo(o)}}function Ka(r,i){return r&&i?r===i?!0:r&&r.nodeType===3?!1:i&&i.nodeType===3?Ka(r,i.parentNode):"contains"in r?r.contains(i):r.compareDocumentPosition?!!(r.compareDocumentPosition(i)&16):!1:!1}function Ga(r){r=r!=null&&r.ownerDocument!=null&&r.ownerDocument.defaultView!=null?r.ownerDocument.defaultView:window;for(var i=Br(r.document);i instanceof r.HTMLIFrameElement;){try{var o=typeof i.contentWindow.location.href=="string"}catch{o=!1}if(o)r=i.contentWindow;else break;i=Br(r.document)}return i}function ca(r){var i=r&&r.nodeName&&r.nodeName.toLowerCase();return i&&(i==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||i==="textarea"||r.contentEditable==="true")}var to=$n&&"documentMode"in document&&11>=document.documentMode,ei=null,za=null,ur=null,ui=!1;function CA(r,i,o){var u=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;ui||ei==null||ei!==Br(u)||(u=ei,"selectionStart"in u&&ca(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),ur&&ja(ur,u)||(ur=u,u=Wd(za,"onSelect"),0>=F,p-=F,mi=1<<32-Vt(i)+p|o<AA?(uA=xt,xt=null):uA=xt.sibling;var IA=Oe(xe,xt,_e[AA],Ge);if(IA===null){xt===null&&(xt=uA);break}r&&xt&&IA.alternate===null&&i(xe,xt),we=w(IA,we,AA),UA===null?Ot=IA:UA.sibling=IA,UA=IA,xt=uA}if(AA===_e.length)return o(xe,xt),sA&&Ai(xe,AA),Ot;if(xt===null){for(;AA<_e.length;AA++)xt=ze(xe,_e[AA],Ge),xt!==null&&(we=w(xt,we,AA),UA===null?Ot=xt:UA.sibling=xt,UA=xt);return sA&&Ai(xe,AA),Ot}for(xt=u(xt);AA<_e.length;AA++)uA=Re(xt,xe,AA,_e[AA],Ge),uA!==null&&(r&&uA.alternate!==null&&xt.delete(uA.key===null?AA:uA.key),we=w(uA,we,AA),UA===null?Ot=uA:UA.sibling=uA,UA=uA);return r&&xt.forEach(function(hl){return i(xe,hl)}),sA&&Ai(xe,AA),Ot}function Dt(xe,we,_e,Ge){if(_e==null)throw Error(n(151));for(var Ot=null,UA=null,xt=we,AA=we=0,uA=null,IA=_e.next();xt!==null&&!IA.done;AA++,IA=_e.next()){xt.index>AA?(uA=xt,xt=null):uA=xt.sibling;var hl=Oe(xe,xt,IA.value,Ge);if(hl===null){xt===null&&(xt=uA);break}r&&xt&&hl.alternate===null&&i(xe,xt),we=w(hl,we,AA),UA===null?Ot=hl:UA.sibling=hl,UA=hl,xt=uA}if(IA.done)return o(xe,xt),sA&&Ai(xe,AA),Ot;if(xt===null){for(;!IA.done;AA++,IA=_e.next())IA=ze(xe,IA.value,Ge),IA!==null&&(we=w(IA,we,AA),UA===null?Ot=IA:UA.sibling=IA,UA=IA);return sA&&Ai(xe,AA),Ot}for(xt=u(xt);!IA.done;AA++,IA=_e.next())IA=Re(xt,xe,AA,IA.value,Ge),IA!==null&&(r&&IA.alternate!==null&&xt.delete(IA.key===null?AA:IA.key),we=w(IA,we,AA),UA===null?Ot=IA:UA.sibling=IA,UA=IA);return r&&xt.forEach(function(aI){return i(xe,aI)}),sA&&Ai(xe,AA),Ot}function YA(xe,we,_e,Ge){if(typeof _e=="object"&&_e!==null&&_e.type===x&&_e.key===null&&(_e=_e.props.children),typeof _e=="object"&&_e!==null){switch(_e.$$typeof){case v:e:{for(var Ot=_e.key;we!==null;){if(we.key===Ot){if(Ot=_e.type,Ot===x){if(we.tag===7){o(xe,we.sibling),Ge=p(we,_e.props.children),Ge.return=xe,xe=Ge;break e}}else if(we.elementType===Ot||typeof Ot=="object"&&Ot!==null&&Ot.$$typeof===$&&Ie(Ot)===we.type){o(xe,we.sibling),Ge=p(we,_e.props),Kt(Ge,_e),Ge.return=xe,xe=Ge;break e}o(xe,we);break}else i(xe,we);we=we.sibling}_e.type===x?(Ge=Bs(_e.props.children,xe.mode,Ge,_e.key),Ge.return=xe,xe=Ge):(Ge=Go(_e.type,_e.key,_e.props,null,xe.mode,Ge),Kt(Ge,_e),Ge.return=xe,xe=Ge)}return F(xe);case I:e:{for(Ot=_e.key;we!==null;){if(we.key===Ot)if(we.tag===4&&we.stateNode.containerInfo===_e.containerInfo&&we.stateNode.implementation===_e.implementation){o(xe,we.sibling),Ge=p(we,_e.children||[]),Ge.return=xe,xe=Ge;break e}else{o(xe,we);break}else i(xe,we);we=we.sibling}Ge=zo(_e,xe.mode,Ge),Ge.return=xe,xe=Ge}return F(xe);case $:return _e=Ie(_e),YA(xe,we,_e,Ge)}if(Ce(_e))return yt(xe,we,_e,Ge);if(V(_e)){if(Ot=V(_e),typeof Ot!="function")throw Error(n(150));return _e=Ot.call(_e),Dt(xe,we,_e,Ge)}if(typeof _e.then=="function")return YA(xe,we,dt(_e),Ge);if(_e.$$typeof===z)return YA(xe,we,gu(xe,_e),Ge);wt(xe,_e)}return typeof _e=="string"&&_e!==""||typeof _e=="number"||typeof _e=="bigint"?(_e=""+_e,we!==null&&we.tag===6?(o(xe,we.sibling),Ge=p(we,_e),Ge.return=xe,xe=Ge):(o(xe,we),Ge=cc(_e,xe.mode,Ge),Ge.return=xe,xe=Ge),F(xe)):o(xe,we)}return function(xe,we,_e,Ge){try{Bt=0;var Ot=YA(xe,we,_e,Ge);return qe=null,Ot}catch(xt){if(xt===me||xt===ee)throw xt;var UA=fr(29,xt,null,xe.mode);return UA.lanes=Ge,UA.return=xe,UA}finally{}}}var WA=aA(!0),Yt=aA(!1),gt=!1;function ot(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function on(r,i){r=r.updateQueue,i.updateQueue===r&&(i.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,callbacks:null})}function Ht(r){return{lane:r,tag:0,payload:null,callback:null,next:null}}function tA(r,i,o){var u=r.updateQueue;if(u===null)return null;if(u=u.shared,(NA&2)!==0){var p=u.pending;return p===null?i.next=i:(i.next=p.next,p.next=i),u.pending=i,i=hr(r),oc(r,null,o),i}return sc(r,u,i,o),hr(r)}function TA(r,i,o){if(i=i.updateQueue,i!==null&&(i=i.shared,(o&4194048)!==0)){var u=i.lanes;u&=r.pendingLanes,o|=u,i.lanes=o,tn(r,o)}}function Dn(r,i){var o=r.updateQueue,u=r.alternate;if(u!==null&&(u=u.updateQueue,o===u)){var p=null,w=null;if(o=o.firstBaseUpdate,o!==null){do{var F={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};w===null?p=w=F:w=w.next=F,o=o.next}while(o!==null);w===null?p=w=i:w=w.next=i}else p=w=i;o={baseState:u.baseState,firstBaseUpdate:p,lastBaseUpdate:w,shared:u.shared,callbacks:u.callbacks},r.updateQueue=o;return}r=o.lastBaseUpdate,r===null?o.firstBaseUpdate=i:r.next=i,o.lastBaseUpdate=i}var ar=!1;function zA(){if(ar){var r=m;if(r!==null)throw r}}function In(r,i,o,u){ar=!1;var p=r.updateQueue;gt=!1;var w=p.firstBaseUpdate,F=p.lastBaseUpdate,j=p.shared.pending;if(j!==null){p.shared.pending=null;var fe=j,Qe=fe.next;fe.next=null,F===null?w=Qe:F.next=Qe,F=fe;var Me=r.alternate;Me!==null&&(Me=Me.updateQueue,j=Me.lastBaseUpdate,j!==F&&(j===null?Me.firstBaseUpdate=Qe:j.next=Qe,Me.lastBaseUpdate=fe))}if(w!==null){var ze=p.baseState;F=0,Me=Qe=fe=null,j=w;do{var Oe=j.lane&-536870913,Re=Oe!==j.lane;if(Re?(cA&Oe)===Oe:(u&Oe)===Oe){Oe!==0&&Oe===d&&(ar=!0),Me!==null&&(Me=Me.next={lane:0,tag:j.tag,payload:j.payload,callback:null,next:null});e:{var yt=r,Dt=j;Oe=i;var YA=o;switch(Dt.tag){case 1:if(yt=Dt.payload,typeof yt=="function"){ze=yt.call(YA,ze,Oe);break e}ze=yt;break e;case 3:yt.flags=yt.flags&-65537|128;case 0:if(yt=Dt.payload,Oe=typeof yt=="function"?yt.call(YA,ze,Oe):yt,Oe==null)break e;ze=y({},ze,Oe);break e;case 2:gt=!0}}Oe=j.callback,Oe!==null&&(r.flags|=64,Re&&(r.flags|=8192),Re=p.callbacks,Re===null?p.callbacks=[Oe]:Re.push(Oe))}else Re={lane:Oe,tag:j.tag,payload:j.payload,callback:j.callback,next:null},Me===null?(Qe=Me=Re,fe=ze):Me=Me.next=Re,F|=Oe;if(j=j.next,j===null){if(j=p.shared.pending,j===null)break;Re=j,j=Re.next,Re.next=null,p.lastBaseUpdate=Re,p.shared.pending=null}}while(!0);Me===null&&(fe=ze),p.baseState=fe,p.firstBaseUpdate=Qe,p.lastBaseUpdate=Me,w===null&&(p.shared.lanes=0),Al|=F,r.lanes=F,r.memoizedState=ze}}function dr(r,i){if(typeof r!="function")throw Error(n(191,r));r.call(i)}function Fn(r,i){var o=r.callbacks;if(o!==null)for(r.callbacks=null,r=0;rw?w:8;var F=N.T,j={};N.T=j,O0(r,!1,i,o);try{var fe=p(),Qe=N.S;if(Qe!==null&&Qe(j,fe),fe!==null&&typeof fe=="object"&&typeof fe.then=="function"){var Me=O(fe,u);Kh(r,i,Me,Xi(r))}else Kh(r,i,u,Xi(r))}catch(ze){Kh(r,i,{then:function(){},status:"rejected",reason:ze},Xi())}finally{G.p=w,F!==null&&j.types!==null&&(F.types=j.types),N.T=F}}function t3(){}function Q0(r,i,o,u){if(r.tag!==5)throw Error(n(476));var p=Rv(r).queue;Ov(r,p,i,W,o===null?t3:function(){return kv(r),o(u)})}function Rv(r){var i=r.memoizedState;if(i!==null)return i;i={memoizedState:W,baseState:W,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:fa,lastRenderedState:W},next:null};var o={};return i.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:fa,lastRenderedState:o},next:null},r.memoizedState=i,r=r.alternate,r!==null&&(r.memoizedState=i),i}function kv(r){var i=Rv(r);i.next===null&&(i=r.alternate.memoizedState),Kh(r,i.next.queue,{},Xi())}function L0(){return ir(sf)}function Hv(){return gn().memoizedState}function Dv(){return gn().memoizedState}function A3(r){for(var i=r.return;i!==null;){switch(i.tag){case 24:case 3:var o=Xi();r=Ht(o);var u=tA(i,r,o);u!==null&&(xi(u,i,o),TA(u,i,o)),i={cache:Xo()},r.payload=i;return}i=i.return}}function n3(r,i,o){var u=Xi();o={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Nd(r)?Pv(i,o):(o=au(r,i,o,u),o!==null&&(xi(o,r,u),jv(o,i,u)))}function Mv(r,i,o){var u=Xi();Kh(r,i,o,u)}function Kh(r,i,o,u){var p={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Nd(r))Pv(i,p);else{var w=r.alternate;if(r.lanes===0&&(w===null||w.lanes===0)&&(w=i.lastRenderedReducer,w!==null))try{var F=i.lastRenderedState,j=w(F,o);if(p.hasEagerState=!0,p.eagerState=j,tr(j,F))return sc(r,i,p,0),ZA===null&&ac(),!1}catch{}finally{}if(o=au(r,i,p,u),o!==null)return xi(o,r,u),jv(o,i,u),!0}return!1}function O0(r,i,o,u){if(u={lane:2,revertLane:fm(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Nd(r)){if(i)throw Error(n(479))}else i=au(r,o,u,2),i!==null&&xi(i,r,2)}function Nd(r){var i=r.alternate;return r===Qt||i!==null&&i===Qt}function Pv(r,i){yi=kr=!0;var o=r.pending;o===null?i.next=i:(i.next=o.next,o.next=i),r.pending=i}function jv(r,i,o){if((o&4194048)!==0){var u=i.lanes;u&=r.pendingLanes,o|=u,i.lanes=o,tn(r,o)}}var Gh={readContext:ir,use:Jo,useCallback:VA,useContext:VA,useEffect:VA,useImperativeHandle:VA,useLayoutEffect:VA,useInsertionEffect:VA,useMemo:VA,useReducer:VA,useRef:VA,useState:VA,useDebugValue:VA,useDeferredValue:VA,useTransition:VA,useSyncExternalStore:VA,useId:VA,useHostTransitionStatus:VA,useFormState:VA,useActionState:VA,useOptimistic:VA,useMemoCache:VA,useCacheRefresh:VA};Gh.useEffectEvent=VA;var Kv={readContext:ir,use:Jo,useCallback:function(r,i){return Yn().memoizedState=[r,i===void 0?null:i],r},useContext:ir,useEffect:Sv,useImperativeHandle:function(r,i,o){o=o!=null?o.concat([r]):null,Zo(4194308,4,Tv.bind(null,i,r),o)},useLayoutEffect:function(r,i){return Zo(4194308,4,r,i)},useInsertionEffect:function(r,i){Zo(4,2,r,i)},useMemo:function(r,i){var o=Yn();i=i===void 0?null:i;var u=r();if(Sr){_t(!0);try{r()}finally{_t(!1)}}return o.memoizedState=[u,i],u},useReducer:function(r,i,o){var u=Yn();if(o!==void 0){var p=o(i);if(Sr){_t(!0);try{o(i)}finally{_t(!1)}}}else p=i;return u.memoizedState=u.baseState=p,r={pending:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:p},u.queue=r,r=r.dispatch=n3.bind(null,Qt,r),[u.memoizedState,r]},useRef:function(r){var i=Yn();return r={current:r},i.memoizedState=r},useState:function(r){r=_s(r);var i=r.queue,o=Mv.bind(null,Qt,i);return i.dispatch=o,[r.memoizedState,o]},useDebugValue:_0,useDeferredValue:function(r,i){var o=Yn();return N0(o,r,i)},useTransition:function(){var r=_s(!1);return r=Ov.bind(null,Qt,r.queue,!0,!1),Yn().memoizedState=r,[!1,r]},useSyncExternalStore:function(r,i,o){var u=Qt,p=Yn();if(sA){if(o===void 0)throw Error(n(407));o=o()}else{if(o=i(),ZA===null)throw Error(n(349));(cA&127)!==0||Xa(u,i,o)}p.memoizedState=o;var w={value:o,getSnapshot:i};return p.queue=w,Sv(Mh.bind(null,u,w,r),[r]),u.flags|=2048,co(9,{destroy:void 0},Dh.bind(null,u,w,o,i),null),o},useId:function(){var r=Yn(),i=ZA.identifierPrefix;if(sA){var o=wi,u=mi;o=(u&~(1<<32-Vt(u)-1)).toString(32)+o,i="_"+i+"R_"+o,o=Nn++,0<\/script>",w=w.removeChild(w.firstChild);break;case"select":w=typeof u.is=="string"?F.createElement("select",{is:u.is}):F.createElement("select"),u.multiple?w.multiple=!0:u.size&&(w.size=u.size);break;default:w=typeof u.is=="string"?F.createElement(p,{is:u.is}):F.createElement(p)}}w[RA]=i,w[an]=u;e:for(F=i.child;F!==null;){if(F.tag===5||F.tag===6)w.appendChild(F.stateNode);else if(F.tag!==4&&F.tag!==27&&F.child!==null){F.child.return=F,F=F.child;continue}if(F===i)break e;for(;F.sibling===null;){if(F.return===null||F.return===i)break e;F=F.return}F.sibling.return=F.return,F=F.sibling}i.stateNode=w;e:switch(Ir(w,p,u),p){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&ho(i)}}return un(i),X0(i,i.type,r===null?null:r.memoizedProps,i.pendingProps,o),null;case 6:if(r&&i.stateNode!=null)r.memoizedProps!==u&&ho(i);else{if(typeof u!="string"&&i.stateNode===null)throw Error(n(166));if(r=se.current,rr(i)){if(r=i.stateNode,o=i.memoizedProps,u=null,p=nr,p!==null)switch(p.tag){case 27:case 5:u=p.memoizedProps}r[RA]=i,r=!!(r.nodeValue===o||u!==null&&u.suppressHydrationWarning===!0||oB(r.nodeValue,o)),r||bs(i,!0)}else r=Zd(r).createTextNode(u),r[RA]=i,i.stateNode=r}return un(i),null;case 31:if(o=i.memoizedState,r===null||r.memoizedState!==null){if(u=rr(i),o!==null){if(r===null){if(!u)throw Error(n(318));if(r=i.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(n(557));r[RA]=i}else ao(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;un(i),r=!1}else o=Lh(),r!==null&&r.memoizedState!==null&&(r.memoizedState.hydrationErrors=o),r=!0;if(!r)return i.flags&256?(kA(i),i):(kA(i),null);if((i.flags&128)!==0)throw Error(n(558))}return un(i),null;case 13:if(u=i.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(p=rr(i),u!==null&&u.dehydrated!==null){if(r===null){if(!p)throw Error(n(318));if(p=i.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(n(317));p[RA]=i}else ao(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;un(i),p=!1}else p=Lh(),r!==null&&r.memoizedState!==null&&(r.memoizedState.hydrationErrors=p),p=!0;if(!p)return i.flags&256?(kA(i),i):(kA(i),null)}return kA(i),(i.flags&128)!==0?(i.lanes=o,i):(o=u!==null,r=r!==null&&r.memoizedState!==null,o&&(u=i.child,p=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(p=u.alternate.memoizedState.cachePool.pool),w=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(w=u.memoizedState.cachePool.pool),w!==p&&(u.flags|=2048)),o!==r&&o&&(i.child.flags|=8192),kd(i,i.updateQueue),un(i),null);case 4:return oe(),r===null&&mm(i.stateNode.containerInfo),un(i),null;case 10:return vi(i.type),un(i),null;case 19:if(S(pA),u=i.memoizedState,u===null)return un(i),null;if(p=(i.flags&128)!==0,w=u.rendering,w===null)if(p)Vh(u,!1);else{if(Qn!==0||r!==null&&(r.flags&128)!==0)for(r=i.child;r!==null;){if(w=gr(r),w!==null){for(i.flags|=128,Vh(u,!1),r=w.updateQueue,i.updateQueue=r,kd(i,r),i.subtreeFlags=0,r=o,o=i.child;o!==null;)lc(o,r),o=o.sibling;return Q(pA,pA.current&1|2),sA&&Ai(i,u.treeForkCount),i.child}r=r.sibling}u.tail!==null&&ht()>jd&&(i.flags|=128,p=!0,Vh(u,!1),i.lanes=4194304)}else{if(!p)if(r=gr(w),r!==null){if(i.flags|=128,p=!0,r=r.updateQueue,i.updateQueue=r,kd(i,r),Vh(u,!0),u.tail===null&&u.tailMode==="hidden"&&!w.alternate&&!sA)return un(i),null}else 2*ht()-u.renderingStartTime>jd&&o!==536870912&&(i.flags|=128,p=!0,Vh(u,!1),i.lanes=4194304);u.isBackwards?(w.sibling=i.child,i.child=w):(r=u.last,r!==null?r.sibling=w:i.child=w,u.last=w)}return u.tail!==null?(r=u.tail,u.rendering=r,u.tail=r.sibling,u.renderingStartTime=ht(),r.sibling=null,o=pA.current,Q(pA,p?o&1|2:o&1),sA&&Ai(i,u.treeForkCount),r):(un(i),null);case 22:case 23:return kA(i),Mn(),u=i.memoizedState!==null,r!==null?r.memoizedState!==null!==u&&(i.flags|=8192):u&&(i.flags|=8192),u?(o&536870912)!==0&&(i.flags&128)===0&&(un(i),i.subtreeFlags&6&&(i.flags|=8192)):un(i),o=i.updateQueue,o!==null&&kd(i,o.retryQueue),o=null,r!==null&&r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),u=null,i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(u=i.memoizedState.cachePool.pool),u!==o&&(i.flags|=2048),r!==null&&S(M),null;case 24:return o=null,r!==null&&(o=r.memoizedState.cache),i.memoizedState.cache!==o&&(i.flags|=2048),vi(En),un(i),null;case 25:return null;case 30:return null}throw Error(n(156,i.tag))}function o3(r,i){switch(hu(i),i.tag){case 1:return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 3:return vi(En),oe(),r=i.flags,(r&65536)!==0&&(r&128)===0?(i.flags=r&-65537|128,i):null;case 26:case 27:case 5:return He(i),null;case 31:if(i.memoizedState!==null){if(kA(i),i.alternate===null)throw Error(n(340));ao()}return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 13:if(kA(i),r=i.memoizedState,r!==null&&r.dehydrated!==null){if(i.alternate===null)throw Error(n(340));ao()}return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 19:return S(pA),null;case 4:return oe(),null;case 10:return vi(i.type),null;case 22:case 23:return kA(i),Mn(),r!==null&&S(M),r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 24:return vi(En),null;case 25:return null;default:return null}}function fy(r,i){switch(hu(i),i.tag){case 3:vi(En),oe();break;case 26:case 27:case 5:He(i);break;case 4:oe();break;case 31:i.memoizedState!==null&&kA(i);break;case 13:kA(i);break;case 19:S(pA);break;case 10:vi(i.type);break;case 22:case 23:kA(i),Mn(),r!==null&&S(M);break;case 24:vi(En)}}function qh(r,i){try{var o=i.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var p=u.next;o=p;do{if((o.tag&r)===r){u=void 0;var w=o.create,F=o.inst;u=w(),F.destroy=u}o=o.next}while(o!==p)}}catch(j){DA(i,i.return,j)}}function el(r,i,o){try{var u=i.updateQueue,p=u!==null?u.lastEffect:null;if(p!==null){var w=p.next;u=w;do{if((u.tag&r)===r){var F=u.inst,j=F.destroy;if(j!==void 0){F.destroy=void 0,p=i;var fe=o,Qe=j;try{Qe()}catch(Me){DA(p,fe,Me)}}}u=u.next}while(u!==w)}}catch(Me){DA(i,i.return,Me)}}function dy(r){var i=r.updateQueue;if(i!==null){var o=r.stateNode;try{Fn(i,o)}catch(u){DA(r,r.return,u)}}}function gy(r,i,o){o.props=pc(r.type,r.memoizedProps),o.state=r.memoizedState;try{o.componentWillUnmount()}catch(u){DA(r,i,u)}}function Yh(r,i){try{var o=r.ref;if(o!==null){switch(r.tag){case 26:case 27:case 5:var u=r.stateNode;break;case 30:u=r.stateNode;break;default:u=r.stateNode}typeof o=="function"?r.refCleanup=o(u):o.current=u}}catch(p){DA(r,i,p)}}function Ns(r,i){var o=r.ref,u=r.refCleanup;if(o!==null)if(typeof u=="function")try{u()}catch(p){DA(r,i,p)}finally{r.refCleanup=null,r=r.alternate,r!=null&&(r.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(p){DA(r,i,p)}else o.current=null}function py(r){var i=r.type,o=r.memoizedProps,u=r.stateNode;try{e:switch(i){case"button":case"input":case"select":case"textarea":o.autoFocus&&u.focus();break e;case"img":o.src?u.src=o.src:o.srcSet&&(u.srcset=o.srcSet)}}catch(p){DA(r,r.return,p)}}function J0(r,i,o){try{var u=r.stateNode;T3(u,r.type,o,i),u[an]=i}catch(p){DA(r,r.return,p)}}function my(r){return r.tag===5||r.tag===3||r.tag===26||r.tag===27&&sl(r.type)||r.tag===4}function W0(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||my(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.tag===27&&sl(r.type)||r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Z0(r,i,o){var u=r.tag;if(u===5||u===6)r=r.stateNode,i?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(r,i):(i=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,i.appendChild(r),o=o._reactRootContainer,o!=null||i.onclick!==null||(i.onclick=Mi));else if(u!==4&&(u===27&&sl(r.type)&&(o=r.stateNode,i=null),r=r.child,r!==null))for(Z0(r,i,o),r=r.sibling;r!==null;)Z0(r,i,o),r=r.sibling}function Hd(r,i,o){var u=r.tag;if(u===5||u===6)r=r.stateNode,i?o.insertBefore(r,i):o.appendChild(r);else if(u!==4&&(u===27&&sl(r.type)&&(o=r.stateNode),r=r.child,r!==null))for(Hd(r,i,o),r=r.sibling;r!==null;)Hd(r,i,o),r=r.sibling}function wy(r){var i=r.stateNode,o=r.memoizedProps;try{for(var u=r.type,p=i.attributes;p.length;)i.removeAttributeNode(p[0]);Ir(i,u,o),i[RA]=r,i[an]=o}catch(w){DA(r,r.return,w)}}var fo=!1,Jn=!1,$0=!1,vy=typeof WeakSet=="function"?WeakSet:Set,pr=null;function l3(r,i){if(r=r.containerInfo,ym=ig,r=Ga(r),ca(r)){if("selectionStart"in r)var o={start:r.selectionStart,end:r.selectionEnd};else e:{o=(o=r.ownerDocument)&&o.defaultView||window;var u=o.getSelection&&o.getSelection();if(u&&u.rangeCount!==0){o=u.anchorNode;var p=u.anchorOffset,w=u.focusNode;u=u.focusOffset;try{o.nodeType,w.nodeType}catch{o=null;break e}var F=0,j=-1,fe=-1,Qe=0,Me=0,ze=r,Oe=null;t:for(;;){for(var Re;ze!==o||p!==0&&ze.nodeType!==3||(j=F+p),ze!==w||u!==0&&ze.nodeType!==3||(fe=F+u),ze.nodeType===3&&(F+=ze.nodeValue.length),(Re=ze.firstChild)!==null;)Oe=ze,ze=Re;for(;;){if(ze===r)break t;if(Oe===o&&++Qe===p&&(j=F),Oe===w&&++Me===u&&(fe=F),(Re=ze.nextSibling)!==null)break;ze=Oe,Oe=ze.parentNode}ze=Re}o=j===-1||fe===-1?null:{start:j,end:fe}}else o=null}o=o||{start:0,end:0}}else o=null;for(Bm={focusedElem:r,selectionRange:o},ig=!1,pr=i;pr!==null;)if(i=pr,r=i.child,(i.subtreeFlags&1028)!==0&&r!==null)r.return=i,pr=r;else for(;pr!==null;){switch(i=pr,w=i.alternate,r=i.flags,i.tag){case 0:if((r&4)!==0&&(r=i.updateQueue,r=r!==null?r.events:null,r!==null))for(o=0;o title"))),Ir(w,u,o),w[RA]=r,yn(w),u=w;break e;case"link":var F=xB("link","href",p).get(u+(o.href||""));if(F){for(var j=0;jYA&&(F=YA,YA=Dt,Dt=F);var xe=Ko(j,Dt),we=Ko(j,YA);if(xe&&we&&(Re.rangeCount!==1||Re.anchorNode!==xe.node||Re.anchorOffset!==xe.offset||Re.focusNode!==we.node||Re.focusOffset!==we.offset)){var _e=ze.createRange();_e.setStart(xe.node,xe.offset),Re.removeAllRanges(),Dt>YA?(Re.addRange(_e),Re.extend(we.node,we.offset)):(_e.setEnd(we.node,we.offset),Re.addRange(_e))}}}}for(ze=[],Re=j;Re=Re.parentNode;)Re.nodeType===1&&ze.push({element:Re,left:Re.scrollLeft,top:Re.scrollTop});for(typeof j.focus=="function"&&j.focus(),j=0;jo?32:o,N.T=null,o=am,am=null;var w=rl,F=vo;if(sr=0,Tu=rl=null,vo=0,(NA&6)!==0)throw Error(n(331));var j=NA;if(NA|=4,Ty(w.current),Uy(w,w.current,F,o),NA=j,ef(0,!1),St&&typeof St.onPostCommitFiberRoot=="function")try{St.onPostCommitFiberRoot(zt,w)}catch{}return!0}finally{G.p=p,N.T=u,Yy(r,i)}}function Jy(r,i,o){i=di(o,i),i=D0(r.stateNode,i,2),r=tA(r,i,2),r!==null&&(mt(r,2),Qs(r))}function DA(r,i,o){if(r.tag===3)Jy(r,r,o);else for(;i!==null;){if(i.tag===3){Jy(i,r,o);break}else if(i.tag===1){var u=i.stateNode;if(typeof i.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(nl===null||!nl.has(u))){r=di(o,r),o=Wv(2),u=tA(i,o,2),u!==null&&(Zv(o,u,i,r),mt(u,2),Qs(u));break}}i=i.return}}function cm(r,i,o){var u=r.pingCache;if(u===null){u=r.pingCache=new h3;var p=new Set;u.set(i,p)}else p=u.get(i),p===void 0&&(p=new Set,u.set(i,p));p.has(o)||(Am=!0,p.add(o),r=m3.bind(null,r,i,o),i.then(r,r))}function m3(r,i,o){var u=r.pingCache;u!==null&&u.delete(i),r.pingedLanes|=r.suspendedLanes&o,r.warmLanes&=~o,ZA===r&&(cA&o)===o&&(Qn===4||Qn===3&&(cA&62914560)===cA&&300>ht()-Pd?(NA&2)===0&&_u(r,0):nm|=o,Fu===cA&&(Fu=0)),Qs(r)}function Wy(r,i){i===0&&(i=xA()),r=Va(r,i),r!==null&&(mt(r,i),Qs(r))}function w3(r){var i=r.memoizedState,o=0;i!==null&&(o=i.retryLane),Wy(r,o)}function v3(r,i){var o=0;switch(r.tag){case 31:case 13:var u=r.stateNode,p=r.memoizedState;p!==null&&(o=p.retryLane);break;case 19:u=r.stateNode;break;case 22:u=r.stateNode._retryCache;break;default:throw Error(n(314))}u!==null&&u.delete(i),Wy(r,o)}function y3(r,i){return Ye(r,i)}var Yd=null,Qu=null,um=!1,Xd=!1,hm=!1,al=0;function Qs(r){r!==Qu&&r.next===null&&(Qu===null?Yd=Qu=r:Qu=Qu.next=r),Xd=!0,um||(um=!0,C3())}function ef(r,i){if(!hm&&Xd){hm=!0;do for(var o=!1,u=Yd;u!==null;){if(r!==0){var p=u.pendingLanes;if(p===0)var w=0;else{var F=u.suspendedLanes,j=u.pingedLanes;w=(1<<31-Vt(42|r)+1)-1,w&=p&~(F&~j),w=w&201326741?w&201326741|1:w?w|2:0}w!==0&&(o=!0,tB(u,w))}else w=cA,w=at(u,u===ZA?w:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(w&3)===0||jt(u,w)||(o=!0,tB(u,w));u=u.next}while(o);hm=!1}}function B3(){Zy()}function Zy(){Xd=um=!1;var r=0;al!==0&&N3()&&(r=al);for(var i=ht(),o=null,u=Yd;u!==null;){var p=u.next,w=$y(u,i);w===0?(u.next=null,o===null?Yd=p:o.next=p,p===null&&(Qu=o)):(o=u,(r!==0||(w&3)!==0)&&(Xd=!0)),u=p}sr!==0&&sr!==5||ef(r),al!==0&&(al=0)}function $y(r,i){for(var o=r.suspendedLanes,u=r.pingedLanes,p=r.expirationTimes,w=r.pendingLanes&-62914561;0j)break;var Me=fe.transferSize,ze=fe.initiatorType;Me&&lB(ze)&&(fe=fe.responseEnd,F+=Me*(fe"u"?null:document;function BB(r,i,o){var u=Lu;if(u&&typeof i=="string"&&i){var p=Sn(i);p='link[rel="'+r+'"][href="'+p+'"]',typeof o=="string"&&(p+='[crossorigin="'+o+'"]'),yB.has(p)||(yB.add(p),r={rel:r,crossOrigin:o,href:i},u.querySelector(p)===null&&(i=u.createElement("link"),Ir(i,"link",r),yn(i),u.head.appendChild(i)))}}function P3(r){yo.D(r),BB("dns-prefetch",r,null)}function j3(r,i){yo.C(r,i),BB("preconnect",r,i)}function K3(r,i,o){yo.L(r,i,o);var u=Lu;if(u&&r&&i){var p='link[rel="preload"][as="'+Sn(i)+'"]';i==="image"&&o&&o.imageSrcSet?(p+='[imagesrcset="'+Sn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(p+='[imagesizes="'+Sn(o.imageSizes)+'"]')):p+='[href="'+Sn(r)+'"]';var w=p;switch(i){case"style":w=Ou(r);break;case"script":w=Ru(r)}pa.has(w)||(r=y({rel:"preload",href:i==="image"&&o&&o.imageSrcSet?void 0:r,as:i},o),pa.set(w,r),u.querySelector(p)!==null||i==="style"&&u.querySelector(rf(w))||i==="script"&&u.querySelector(af(w))||(i=u.createElement("link"),Ir(i,"link",r),yn(i),u.head.appendChild(i)))}}function G3(r,i){yo.m(r,i);var o=Lu;if(o&&r){var u=i&&typeof i.as=="string"?i.as:"script",p='link[rel="modulepreload"][as="'+Sn(u)+'"][href="'+Sn(r)+'"]',w=p;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":w=Ru(r)}if(!pa.has(w)&&(r=y({rel:"modulepreload",href:r},i),pa.set(w,r),o.querySelector(p)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(af(w)))return}u=o.createElement("link"),Ir(u,"link",r),yn(u),o.head.appendChild(u)}}}function z3(r,i,o){yo.S(r,i,o);var u=Lu;if(u&&r){var p=ea(u).hoistableStyles,w=Ou(r);i=i||"default";var F=p.get(w);if(!F){var j={loading:0,preload:null};if(F=u.querySelector(rf(w)))j.loading=5;else{r=y({rel:"stylesheet",href:r,"data-precedence":i},o),(o=pa.get(w))&&Im(r,o);var fe=F=u.createElement("link");yn(fe),Ir(fe,"link",r),fe._p=new Promise(function(Qe,Me){fe.onload=Qe,fe.onerror=Me}),fe.addEventListener("load",function(){j.loading|=1}),fe.addEventListener("error",function(){j.loading|=2}),j.loading|=4,eg(F,i,u)}F={type:"stylesheet",instance:F,count:1,state:j},p.set(w,F)}}}function V3(r,i){yo.X(r,i);var o=Lu;if(o&&r){var u=ea(o).hoistableScripts,p=Ru(r),w=u.get(p);w||(w=o.querySelector(af(p)),w||(r=y({src:r,async:!0},i),(i=pa.get(p))&&Fm(r,i),w=o.createElement("script"),yn(w),Ir(w,"link",r),o.head.appendChild(w)),w={type:"script",instance:w,count:1,state:null},u.set(p,w))}}function q3(r,i){yo.M(r,i);var o=Lu;if(o&&r){var u=ea(o).hoistableScripts,p=Ru(r),w=u.get(p);w||(w=o.querySelector(af(p)),w||(r=y({src:r,async:!0,type:"module"},i),(i=pa.get(p))&&Fm(r,i),w=o.createElement("script"),yn(w),Ir(w,"link",r),o.head.appendChild(w)),w={type:"script",instance:w,count:1,state:null},u.set(p,w))}}function CB(r,i,o,u){var p=(p=se.current)?$d(p):null;if(!p)throw Error(n(446));switch(r){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(i=Ou(o.href),o=ea(p).hoistableStyles,u=o.get(i),u||(u={type:"style",instance:null,count:0,state:null},o.set(i,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){r=Ou(o.href);var w=ea(p).hoistableStyles,F=w.get(r);if(F||(p=p.ownerDocument||p,F={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},w.set(r,F),(w=p.querySelector(rf(r)))&&!w._p&&(F.instance=w,F.state.loading=5),pa.has(r)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},pa.set(r,o),w||Y3(p,r,o,F.state))),i&&u===null)throw Error(n(528,""));return F}if(i&&u!==null)throw Error(n(529,""));return null;case"script":return i=o.async,o=o.src,typeof o=="string"&&i&&typeof i!="function"&&typeof i!="symbol"?(i=Ru(o),o=ea(p).hoistableScripts,u=o.get(i),u||(u={type:"script",instance:null,count:0,state:null},o.set(i,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(n(444,r))}}function Ou(r){return'href="'+Sn(r)+'"'}function rf(r){return'link[rel="stylesheet"]['+r+"]"}function bB(r){return y({},r,{"data-precedence":r.precedence,precedence:null})}function Y3(r,i,o,u){r.querySelector('link[rel="preload"][as="style"]['+i+"]")?u.loading=1:(i=r.createElement("link"),u.preload=i,i.addEventListener("load",function(){return u.loading|=1}),i.addEventListener("error",function(){return u.loading|=2}),Ir(i,"link",o),yn(i),r.head.appendChild(i))}function Ru(r){return'[src="'+Sn(r)+'"]'}function af(r){return"script[async]"+r}function EB(r,i,o){if(i.count++,i.instance===null)switch(i.type){case"style":var u=r.querySelector('style[data-href~="'+Sn(o.href)+'"]');if(u)return i.instance=u,yn(u),u;var p=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return u=(r.ownerDocument||r).createElement("style"),yn(u),Ir(u,"style",p),eg(u,o.precedence,r),i.instance=u;case"stylesheet":p=Ou(o.href);var w=r.querySelector(rf(p));if(w)return i.state.loading|=4,i.instance=w,yn(w),w;u=bB(o),(p=pa.get(p))&&Im(u,p),w=(r.ownerDocument||r).createElement("link"),yn(w);var F=w;return F._p=new Promise(function(j,fe){F.onload=j,F.onerror=fe}),Ir(w,"link",u),i.state.loading|=4,eg(w,o.precedence,r),i.instance=w;case"script":return w=Ru(o.src),(p=r.querySelector(af(w)))?(i.instance=p,yn(p),p):(u=o,(p=pa.get(w))&&(u=y({},o),Fm(u,p)),r=r.ownerDocument||r,p=r.createElement("script"),yn(p),Ir(p,"link",u),r.head.appendChild(p),i.instance=p);case"void":return null;default:throw Error(n(443,i.type))}else i.type==="stylesheet"&&(i.state.loading&4)===0&&(u=i.instance,i.state.loading|=4,eg(u,o.precedence,r));return i.instance}function eg(r,i,o){for(var u=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=u.length?u[u.length-1]:null,w=p,F=0;F title"):null)}function X3(r,i,o){if(o===1||i.itemProp!=null)return!1;switch(r){case"meta":case"title":return!0;case"style":if(typeof i.precedence!="string"||typeof i.href!="string"||i.href==="")break;return!0;case"link":if(typeof i.rel!="string"||typeof i.href!="string"||i.href===""||i.onLoad||i.onError)break;switch(i.rel){case"stylesheet":return r=i.disabled,typeof i.precedence=="string"&&r==null;default:return!0}case"script":if(i.async&&typeof i.async!="function"&&typeof i.async!="symbol"&&!i.onLoad&&!i.onError&&i.src&&typeof i.src=="string")return!0}return!1}function UB(r){return!(r.type==="stylesheet"&&(r.state.loading&3)===0)}function J3(r,i,o,u){if(o.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var p=Ou(u.href),w=i.querySelector(rf(p));if(w){i=w._p,i!==null&&typeof i=="object"&&typeof i.then=="function"&&(r.count++,r=Ag.bind(r),i.then(r,r)),o.state.loading|=4,o.instance=w,yn(w);return}w=i.ownerDocument||i,u=bB(u),(p=pa.get(p))&&Im(u,p),w=w.createElement("link"),yn(w);var F=w;F._p=new Promise(function(j,fe){F.onload=j,F.onerror=fe}),Ir(w,"link",u),o.instance=w}r.stylesheets===null&&(r.stylesheets=new Map),r.stylesheets.set(o,i),(i=o.state.preload)&&(o.state.loading&3)===0&&(r.count++,o=Ag.bind(r),i.addEventListener("load",o),i.addEventListener("error",o))}}var Tm=0;function W3(r,i){return r.stylesheets&&r.count===0&&rg(r,r.stylesheets),0Tm?50:800)+i);return r.unsuspend=o,function(){r.unsuspend=null,clearTimeout(u),clearTimeout(p)}}:null}function Ag(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)rg(this,this.stylesheets);else if(this.unsuspend){var r=this.unsuspend;this.unsuspend=null,r()}}}var ng=null;function rg(r,i){r.stylesheets=null,r.unsuspend!==null&&(r.count++,ng=new Map,i.forEach(Z3,r),ng=null,Ag.call(r))}function Z3(r,i){if(!(i.state.loading&4)){var o=ng.get(r);if(o)var u=o.get(null);else{o=new Map,ng.set(r,o);for(var p=r.querySelectorAll("link[data-precedence],style[data-precedence]"),w=0;w"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(A)}catch(e){console.error(e)}}return A(),Dm.exports=dI(),Dm.exports}var pI=gI();const mI="msal.js.common",XE="https://login.microsoftonline.com/common/",wI="login.microsoftonline.com",JE="common",vI="adfs",yI="dstsv2",BI=`${XE}discovery/instance?api-version=1.1&authorization_endpoint=`,WB=".ciamlogin.com",CI=".onmicrosoft.com",z1="|",WE="openid",ZE="profile",Jw="offline_access",bI="email",Ww="S256",EI="application/x-www-form-urlencoded;charset=utf-8",ff="Not Available",V1="/",ZB="http://169.254.169.254/metadata/instance/compute/location",xI="2020-06-01",SI=2e3,UI="TryAutoDetect",II="login.microsoft.com",FI=["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],$B=240,TI="invalid_instance",eC=200,_I=400,tC=400,NI=499,QI=500,LI=599,rh={GET:"GET",POST:"POST"},yh=[WE,ZE,Jw],AC=[...yh,bI],si={CONTENT_TYPE:"Content-Type",CONTENT_LENGTH:"Content-Length",RETRY_AFTER:"Retry-After",CCS_HEADER:"X-AnchorMailbox",WWWAuthenticate:"WWW-Authenticate",AuthenticationInfo:"Authentication-Info",X_MS_REQUEST_ID:"x-ms-request-id",X_MS_HTTP_VERSION:"x-ms-httpver"},nC={ACTIVE_ACCOUNT_FILTERS:"active-account-filters"},_l={COMMON:"common",ORGANIZATIONS:"organizations",CONSUMERS:"consumers"},hg={ACCESS_TOKEN:"access_token",XMS_CC:"xms_cc"},Ii={LOGIN:"login",SELECT_ACCOUNT:"select_account",CONSENT:"consent",NONE:"none",NO_SESSION:"no_session"},Zw={CODE:"code",IDTOKEN_TOKEN_REFRESHTOKEN:"id_token token refresh_token"},$w={QUERY:"query",FRAGMENT:"fragment"},$E={AUTHORIZATION_CODE_GRANT:"authorization_code",REFRESH_TOKEN_GRANT:"refresh_token"},OI="MSSTS",RI="ADFS",ex="Generic",tx="-",q1=".",_r={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},e2="appmetadata",kI="client_info",gp="1",Y1="authority-metadata",HI=3600*24,es={CONFIG:"config",CACHE:"cache",NETWORK:"network",HARDCODED_VALUES:"hardcoded_values"},rC=5,DI=330,MI=50,Ax="server-telemetry",iC="|",Hu=",",PI="1",jI="0",KI="unknown_error",MA={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},GI=60,zI=3600,nx="throttling",VI="retry-after, h429",qI="invalid_grant",YI="client_mismatch",Du={FAILED_AUTO_DETECTION:"1",INTERNAL_CACHE:"2",ENVIRONMENT_VARIABLE:"3",IMDS:"4"},Km={CONFIGURED_NO_AUTO_DETECTION:"2",AUTO_DETECTION_REQUESTED_SUCCESSFUL:"4",AUTO_DETECTION_REQUESTED_FAILED:"5"},yc={NOT_APPLICABLE:"0",FORCE_REFRESH_OR_CLAIMS:"1",NO_CACHED_ACCESS_TOKEN:"2",CACHED_ACCESS_TOKEN_EXPIRED:"3",PROACTIVELY_REFRESHED:"4"},XI={Pop:"pop"},rx=300;const Oc="client_id",ix="redirect_uri",JI="response_type",WI="response_mode",ZI="grant_type",$I="claims",eF="scope",tF="refresh_token",AF="state",nF="nonce",rF="prompt",iF="code",aF="code_challenge",sF="code_challenge_method",oF="code_verifier",lF="client-request-id",cF="x-client-SKU",uF="x-client-VER",hF="x-client-OS",fF="x-client-CPU",dF="x-client-current-telemetry",gF="x-client-last-telemetry",pF="x-ms-lib-capability",mF="x-app-name",wF="x-app-ver",vF="post_logout_redirect_uri",yF="id_token_hint",BF="client_secret",CF="client_assertion",bF="client_assertion_type",ax="token_type",sx="req_cnf",aC="return_spa_code",EF="nativebroker",xF="logout_hint",SF="sid",UF="login_hint",IF="domain_hint",FF="x-client-xtra-sku",pp="brk_client_id",mp="brk_redirect_uri",X1="instance_aware",TF="ear_jwk",_F="ear_jwe_crypto";function t2(A){return`See https://aka.ms/msal.js.errors#${A} for details`}class en extends Error{constructor(e,t,n){const a=t||(e?t2(e):""),s=a?`${e}: ${a}`:e;super(s),Object.setPrototypeOf(this,en.prototype),this.errorCode=e||"",this.errorMessage=a||"",this.subError=n||"",this.name="AuthError"}setCorrelationId(e){this.correlationId=e}}function J1(A,e){return new en(A,e||t2(A))}class A2 extends en{constructor(e){super(e),this.name="ClientConfigurationError",Object.setPrototypeOf(this,A2.prototype)}}function An(A){return new A2(A)}class Ea{static isEmptyObj(e){if(e)try{const t=JSON.parse(e);return Object.keys(t).length===0}catch{}return!0}static startsWith(e,t){return e.indexOf(t)===0}static endsWith(e,t){return e.length>=t.length&&e.lastIndexOf(t)===e.length-t.length}static queryStringToObject(e){const t={},n=e.split("&"),a=s=>decodeURIComponent(s.replace(/\+/g," "));return n.forEach(s=>{if(s.trim()){const[l,c]=s.split(/=(.+)/g,2);l&&c&&(t[a(l)]=a(c))}}),t}static trimArrayEntries(e){return e.map(t=>t.trim())}static removeEmptyStringsFromArray(e){return e.filter(t=>!!t)}static jsonParseHelper(e){try{return JSON.parse(e)}catch{return null}}static matchPattern(e,t){return new RegExp(e.replace(/\\/g,"\\\\").replace(/\*/g,"[^ ]*").replace(/\?/g,"\\?")).test(t)}}class n2 extends en{constructor(e,t){super(e,t),this.name="ClientAuthError",Object.setPrototypeOf(this,n2.prototype)}}function tt(A,e){return new n2(A,e)}const NF="redirect_uri_empty",QF="authority_uri_insecure",fg="url_parse_error",LF="empty_url_error",OF="empty_input_scopes_error",ox="invalid_claims",RF="token_request_empty",kF="logout_request_empty",lx="pkce_params_missing",cx="invalid_cloud_discovery_metadata",HF="invalid_authority_metadata",DF="untrusted_authority",r2="missing_ssh_jwk",MF="missing_ssh_kid",PF="cannot_set_OIDCOptions",jF="cannot_allow_platform_broker",KF="authority_mismatch",GF="invalid_request_method_for_EAR";const ux="client_info_decoding_error",zF="client_info_empty_error",hx="token_parsing_error",VF="null_or_empty_token",pl="endpoints_resolution_error",qF="network_error",YF="openid_config_error",XF="hash_not_deserialized",Vf="invalid_state",JF="state_mismatch",sC="state_not_found",WF="nonce_mismatch",fx="auth_time_not_found",ZF="max_age_transpired",$F="multiple_matching_appMetadata",eT="request_cannot_be_made",tT="cannot_remove_empty_scope",AT="cannot_append_scopeset",oC="empty_input_scopeset",dx="no_account_in_silent_request",nT="invalid_cache_record",gx="invalid_cache_environment",lC="no_account_found",px="no_crypto_object",Ic="token_refresh_required",rT="token_claims_cnf_required_for_signedjwt",iT="authorization_code_missing_from_server_response",aT="binding_key_not_removed",sT="end_session_endpoint_not_supported",mx="key_id_missing",iA="method_not_implemented";class qr{constructor(e){const t=e?Ea.trimArrayEntries([...e]):[],n=t?Ea.removeEmptyStringsFromArray(t):[];if(!n||!n.length)throw An(OF);this.scopes=new Set,n.forEach(a=>this.scopes.add(a))}static fromString(e){const n=(e||"").split(" ");return new qr(n)}static createSearchScopes(e){const t=e&&e.length>0?e:[...yh],n=new qr(t);return n.containsOnlyOIDCScopes()?n.removeScope(Jw):n.removeOIDCScopes(),n}containsScope(e){const t=this.printScopesLowerCase().split(" "),n=new qr(t);return e?n.scopes.has(e.toLowerCase()):!1}containsScopeSet(e){return!e||e.scopes.size<=0?!1:this.scopes.size>=e.scopes.size&&e.asArray().every(t=>this.containsScope(t))}containsOnlyOIDCScopes(){let e=0;return AC.forEach(t=>{this.containsScope(t)&&(e+=1)}),this.scopes.size===e}appendScope(e){e&&this.scopes.add(e.trim())}appendScopes(e){try{e.forEach(t=>this.appendScope(t))}catch{throw tt(AT)}}removeScope(e){if(!e)throw tt(tT);this.scopes.delete(e.trim())}removeOIDCScopes(){AC.forEach(e=>{this.scopes.delete(e)})}unionScopeSets(e){if(!e)throw tt(oC);const t=new Set;return e.scopes.forEach(n=>t.add(n.toLowerCase())),this.scopes.forEach(n=>t.add(n.toLowerCase())),t}intersectingScopeSets(e){if(!e)throw tt(oC);e.containsOnlyOIDCScopes()||e.removeOIDCScopes();const t=this.unionScopeSets(e),n=e.getScopeCount(),a=this.getScopeCount();return t.sizee.push(t)),e}printScopes(){return this.scopes?this.asArray().join(" "):""}printScopesLowerCase(){return this.printScopes().toLowerCase()}}function Wp(A,e,t){if(!e)return;const n=A.get(Oc);n&&A.has(pp)&&t?.addFields({embeddedClientId:n,embeddedRedirectUri:A.get(ix)},e)}function i2(A,e){A.set(JI,e)}function oT(A,e){A.set(WI,e||$w.QUERY)}function lT(A){A.set(EF,"1")}function a2(A,e,t=!0,n=yh){t&&!n.includes("openid")&&!e.includes("openid")&&n.push("openid");const a=t?[...e||[],...n]:e||[],s=new qr(a);A.set(eF,s.printScopes())}function s2(A,e){A.set(Oc,e)}function o2(A,e){A.set(ix,e)}function cT(A,e){A.set(vF,e)}function uT(A,e){A.set(yF,e)}function hT(A,e){A.set(IF,e)}function dg(A,e){A.set(UF,e)}function wp(A,e){A.set(si.CCS_HEADER,`UPN:${e}`)}function _f(A,e){A.set(si.CCS_HEADER,`Oid:${e.uid}@${e.utid}`)}function cC(A,e){A.set(SF,e)}function l2(A,e,t){const n=wT(e,t);try{JSON.parse(n)}catch{throw An(ox)}A.set($I,n)}function c2(A,e){A.set(lF,e)}function u2(A,e){A.set(cF,e.sku),A.set(uF,e.version),e.os&&A.set(hF,e.os),e.cpu&&A.set(fF,e.cpu)}function h2(A,e){e?.appName&&A.set(mF,e.appName),e?.appVersion&&A.set(wF,e.appVersion)}function fT(A,e){A.set(rF,e)}function wx(A,e){e&&A.set(AF,e)}function dT(A,e){A.set(nF,e)}function f2(A,e,t){if(e&&t)A.set(aF,e),A.set(sF,t);else throw An(lx)}function gT(A,e){A.set(iF,e)}function pT(A,e){A.set(tF,e)}function mT(A,e){A.set(oF,e)}function vx(A,e){A.set(BF,e)}function yx(A,e){e&&A.set(CF,e)}function Bx(A,e){e&&A.set(bF,e)}function Cx(A,e){A.set(ZI,e)}function d2(A){A.set(kI,"1")}function bx(A){A.has(X1)||A.set(X1,"true")}function Ps(A,e){Object.entries(e).forEach(([t,n])=>{!A.has(t)&&n&&A.set(t,n)})}function wT(A,e){let t;if(!A)t={};else try{t=JSON.parse(A)}catch{throw An(ox)}return e&&e.length>0&&(t.hasOwnProperty(hg.ACCESS_TOKEN)||(t[hg.ACCESS_TOKEN]={}),t[hg.ACCESS_TOKEN][hg.XMS_CC]={values:e}),JSON.stringify(t)}function g2(A,e){e&&(A.set(ax,MA.POP),A.set(sx,e))}function Ex(A,e){e&&(A.set(ax,MA.SSH),A.set(sx,e))}function xx(A,e){A.set(dF,e.generateCurrentRequestHeaderValue()),A.set(gF,e.generateLastRequestHeaderValue())}function Sx(A){A.set(pF,VI)}function vT(A,e){A.set(xF,e)}function Zp(A,e,t){A.has(pp)||A.set(pp,e),A.has(mp)||A.set(mp,t)}function yT(A,e){A.set(TF,encodeURIComponent(e)),A.set(_F,"eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0")}function uC(A){if(!A)return A;let e=A.toLowerCase();return Ea.endsWith(e,"?")?e=e.slice(0,-1):Ea.endsWith(e,"?/")&&(e=e.slice(0,-2)),Ea.endsWith(e,"/")||(e+="/"),e}function Ux(A){return A.startsWith("#/")?A.substring(2):A.startsWith("#")||A.startsWith("?")?A.substring(1):A}function vp(A){if(!A||A.indexOf("=")<0)return null;try{const e=Ux(A),t=Object.fromEntries(new URLSearchParams(e));if(t.code||t.ear_jwe||t.error||t.error_description||t.state)return t}catch{throw tt(XF)}return null}function qf(A){const e=new Array;return A.forEach((t,n)=>{e.push(`${n}=${encodeURIComponent(t)}`)}),e.join("&")}function hC(A){if(!A)return A;const e=A.split("#")[0];try{const t=new URL(e),n=t.origin+t.pathname+t.search;return uC(n)}catch{return uC(e)}}const yp={createNewGuid:()=>{throw tt(iA)},base64Decode:()=>{throw tt(iA)},base64Encode:()=>{throw tt(iA)},base64UrlEncode:()=>{throw tt(iA)},encodeKid:()=>{throw tt(iA)},async getPublicKeyThumbprint(){throw tt(iA)},async removeTokenBindingKey(){throw tt(iA)},async clearKeystore(){throw tt(iA)},async signJwt(){throw tt(iA)},async hashString(){throw tt(iA)}};var vn;(function(A){A[A.Error=0]="Error",A[A.Warning=1]="Warning",A[A.Info=2]="Info",A[A.Verbose=3]="Verbose",A[A.Trace=4]="Trace"})(vn||(vn={}));const BT=50,CT=500,Cc=new Map;function bT(A,e){Cc.delete(A),Cc.set(A,e)}function ET(A,e){const t=Date.now();let n=Cc.get(A);if(n)bT(A,n);else if(n={logs:[],firstEventTime:t},Cc.set(A,n),Cc.size>BT){const a=Cc.keys().next().value;a&&Cc.delete(a)}n.logs.push({...e,milliseconds:t-n.firstEventTime}),n.logs.length>CT&&n.logs.shift()}function xT(A){if(A.length!==6)return!1;for(let e=0;e="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"))return!1}return!0}let Ml=class W1{constructor(e,t,n){this.level=vn.Info;const a=()=>{},s=e||W1.createDefaultLoggerOptions();this.localCallback=s.loggerCallback||a,this.piiLoggingEnabled=s.piiLoggingEnabled||!1,this.level=typeof s.logLevel=="number"?s.logLevel:vn.Info,this.packageName=t||"",this.packageVersion=n||""}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:vn.Info}}clone(e,t){return new W1({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level},e,t)}logMessage(e,t){const n=t.correlationId;if(xT(e)){const h={hash:e,level:t.logLevel,containsPii:t.containsPii||!1,milliseconds:0};ET(n,h)}if(t.logLevel>this.level||!this.piiLoggingEnabled&&t.containsPii)return;const c=`${`[${new Date().toUTCString()}] : [${n}]`} : ${this.packageName}@${this.packageVersion} : ${vn[t.logLevel]} - ${e}`;this.executeCallback(t.logLevel,c,t.containsPii||!1)}executeCallback(e,t,n){this.localCallback&&this.localCallback(e,t,n)}error(e,t){this.logMessage(e,{logLevel:vn.Error,containsPii:!1,correlationId:t})}errorPii(e,t){this.logMessage(e,{logLevel:vn.Error,containsPii:!0,correlationId:t})}warning(e,t){this.logMessage(e,{logLevel:vn.Warning,containsPii:!1,correlationId:t})}warningPii(e,t){this.logMessage(e,{logLevel:vn.Warning,containsPii:!0,correlationId:t})}info(e,t){this.logMessage(e,{logLevel:vn.Info,containsPii:!1,correlationId:t})}infoPii(e,t){this.logMessage(e,{logLevel:vn.Info,containsPii:!0,correlationId:t})}verbose(e,t){this.logMessage(e,{logLevel:vn.Verbose,containsPii:!1,correlationId:t})}verbosePii(e,t){this.logMessage(e,{logLevel:vn.Verbose,containsPii:!0,correlationId:t})}trace(e,t){this.logMessage(e,{logLevel:vn.Trace,containsPii:!1,correlationId:t})}tracePii(e,t){this.logMessage(e,{logLevel:vn.Trace,containsPii:!0,correlationId:t})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}};const $p="@azure/msal-common",ld="16.0.3";const p2={None:"none"};function fC(A,e){return!!A&&!!e&&A===e.split(".")[1]}function Bh(A,e,t,n){if(n){const{oid:a,sub:s,tid:l,name:c,tfp:h,acr:f,preferred_username:g,upn:y,login_hint:C}=n,v=l||h||f||"";return{tenantId:v,localAccountId:a||s||"",name:c,username:g||y||"",loginHint:C,isHomeTenant:fC(v,A)}}else return{tenantId:t,localAccountId:e,username:"",isHomeTenant:fC(t,A)}}function m2(A,e,t,n){let a=A;if(e){const{isHomeTenant:s,...l}=e;a={...A,...l}}if(t){const{isHomeTenant:s,...l}=Bh(A.homeAccountId,A.localAccountId,A.tenantId,t);return a={...a,...l,idTokenClaims:t,idToken:n},a}return a}function Uo(A,e){const t=ST(A);try{const n=e(t);return JSON.parse(n)}catch{throw tt(hx)}}function Fc(A){if(!A.signin_state)return!1;const e=["kmsi","dvc_dmjd"];return A.signin_state.some(t=>e.includes(t.trim().toLowerCase()))}function ST(A){if(!A)throw tt(VF);const t=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(A);if(!t||t.length<4)throw tt(hx);return t[2]}function Ix(A,e){if(e===0||Date.now()-3e5>A+e)throw tt(ZF)}class QA{get urlString(){return this._urlString}constructor(e){if(this._urlString=e,!this._urlString)throw An(LF);e.includes("#")||(this._urlString=QA.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return Ea.endsWith(t,"?")?t=t.slice(0,-1):Ea.endsWith(t,"?/")&&(t=t.slice(0,-2)),Ea.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch{throw An(fg)}if(!e.HostNameAndPort||!e.PathSegments)throw An(fg);if(!e.Protocol||e.Protocol.toLowerCase()!=="https:")throw An(QF)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return QA.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),n=t.PathSegments;return e&&n.length!==0&&(n[0]===_l.COMMON||n[0]===_l.ORGANIZATIONS)&&(n[0]=e),QA.constructAuthorityUriFromObject(t)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw An(fg);const n={Protocol:t[1],HostNameAndPort:t[4],AbsolutePath:t[5],QueryString:t[7]};let a=n.AbsolutePath.split("/");return a=a.filter(s=>s&&s.length>0),n.PathSegments=a,n.QueryString&&n.QueryString.endsWith("/")&&(n.QueryString=n.QueryString.substring(0,n.QueryString.length-1)),n}static getDomainFromUrl(e){const t=RegExp("^([^:/?#]+://)?([^/?#]*)"),n=e.match(t);if(!n)throw An(fg);return n[2]}static getAbsoluteUrl(e,t){if(e[0]===V1){const a=new QA(t).getUrlComponents();return a.Protocol+"//"+a.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e){return new QA(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"))}}const UT=[{host:"login.microsoftonline.com"},{host:"login.chinacloudapi.cn",issuerHost:"login.partner.microsoftonline.cn"},{host:"login.microsoftonline.us"},{host:"login.sovcloud-identity.fr"},{host:"login.sovcloud-identity.de"},{host:"login.sovcloud-identity.sg"}];function IT(A,e){return{token_endpoint:`https://${A}/{tenantid}/oauth2/v2.0/token`,jwks_uri:`https://${A}/{tenantid}/discovery/v2.0/keys`,issuer:`https://${e}/{tenantid}/v2.0`,authorization_endpoint:`https://${A}/{tenantid}/oauth2/v2.0/authorize`,end_session_endpoint:`https://${A}/{tenantid}/oauth2/v2.0/logout`}}const FT=UT.reduce((A,{host:e,issuerHost:t})=>(A[e]=IT(e,t||e),A),{}),Fx={endpointMetadata:FT,instanceDiscoveryMetadata:{metadata:[{preferred_network:"login.microsoftonline.com",preferred_cache:"login.windows.net",aliases:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"]},{preferred_network:"login.partner.microsoftonline.cn",preferred_cache:"login.partner.microsoftonline.cn",aliases:["login.partner.microsoftonline.cn","login.chinacloudapi.cn"]},{preferred_network:"login.microsoftonline.de",preferred_cache:"login.microsoftonline.de",aliases:["login.microsoftonline.de"]},{preferred_network:"login.microsoftonline.us",preferred_cache:"login.microsoftonline.us",aliases:["login.microsoftonline.us","login.usgovcloudapi.net"]},{preferred_network:"login-us.microsoftonline.com",preferred_cache:"login-us.microsoftonline.com",aliases:["login-us.microsoftonline.com"]}]}},dC=Fx.endpointMetadata,w2=Fx.instanceDiscoveryMetadata,Tx=new Set;w2.metadata.forEach(A=>{A.aliases.forEach(e=>{Tx.add(e)})});function TT(A,e,t){let n;const a=A.canonicalAuthority;if(a){const s=new QA(a).getUrlComponents().HostNameAndPort;n=gC(e,t,s,A.cloudDiscoveryMetadata?.metadata)||gC(e,t,s,w2.metadata)||A.knownAuthorities}return n||[]}function gC(A,e,t,n,a){if(A.trace("1bmquz",e),t&&n){const s=Bp(n,t);if(s)return A.trace("1fotbt",e),s.aliases;A.trace("14avvj",e)}return null}function _T(A){return Bp(w2.metadata,A)}function Bp(A,e){for(let t=0;t[t.tenantId,t])),dataBoundary:A.dataBoundary}}function QT(A,e,t){let n;e.authorityType===rs.Adfs?n=RI:e.protocolMode===Fi.OIDC?n=ex:n=OI;let a,s;A.clientInfo&&t&&(a=Cp(A.clientInfo,t),a.xms_tdbr&&(s=a.xms_tdbr==="EU"?"EU":"None"));const l=A.environment||e&&e.getPreferredCache();if(!l)throw tt(gx);const c=A.idTokenClaims?.preferred_username||A.idTokenClaims?.upn,h=A.idTokenClaims?.emails?A.idTokenClaims.emails[0]:null,f=c||h||"",g=A.idTokenClaims?.login_hint,y=a?.utid||v2(A.idTokenClaims)||"",C=a?.uid||A.idTokenClaims?.oid||A.idTokenClaims?.sub||"";let v;return A.tenantProfiles?v=A.tenantProfiles:v=[Bh(A.homeAccountId,C,y,A.idTokenClaims)],{homeAccountId:A.homeAccountId,environment:l,realm:y,localAccountId:C,username:f,authorityType:n,loginHint:g,clientInfo:A.clientInfo,name:A.idTokenClaims?.name||"",lastModificationTime:void 0,lastModificationApp:void 0,cloudGraphHostName:A.cloudGraphHostName,msGraphHost:A.msGraphHost,nativeAccountId:A.nativeAccountId,tenantProfiles:v,dataBoundary:s}}function LT(A,e,t){const n=Array.from(A.tenantProfiles?.values()||[]);return n.length===0&&A.tenantId&&A.localAccountId&&n.push(Bh(A.homeAccountId,A.localAccountId,A.tenantId,A.idTokenClaims)),{authorityType:A.authorityType||ex,homeAccountId:A.homeAccountId,localAccountId:A.localAccountId,nativeAccountId:A.nativeAccountId,realm:A.tenantId,environment:A.environment,username:A.username,loginHint:A.loginHint,name:A.name,cloudGraphHostName:e,msGraphHost:t,tenantProfiles:n,dataBoundary:A.dataBoundary}}function _x(A,e,t,n,a,s){if(!(e===rs.Adfs||e===rs.Dsts)){if(A)try{const l=Cp(A,n.base64Decode);if(l.uid&&l.utid)return`${l.uid}.${l.utid}`}catch{}t.warning("1ub6wv",a)}return s?.sub||""}function OT(A){return A?A.hasOwnProperty("homeAccountId")&&A.hasOwnProperty("environment")&&A.hasOwnProperty("realm")&&A.hasOwnProperty("localAccountId")&&A.hasOwnProperty("username")&&A.hasOwnProperty("authorityType"):!1}class ew{constructor(e,t,n,a,s){this.clientId=e,this.cryptoImpl=t,this.commonLogger=n.clone($p,ld),this.staticAuthorityOptions=s,this.performanceClient=a}getAllAccounts(e={},t){return this.buildTenantProfiles(this.getAccountsFilteredBy(e,t),t,e)}getAccountInfoFilteredBy(e,t){const n=this.getAllAccounts(e,t);return n.length>1?n.sort(s=>s.idTokenClaims?-1:1)[0]:n.length===1?n[0]:null}getBaseAccountInfo(e,t){const n=this.getAccountsFilteredBy(e,t);return n.length>0?Rc(n[0]):null}buildTenantProfiles(e,t,n){return e.flatMap(a=>this.getTenantProfilesFromAccountEntity(a,t,n?.tenantId,n))}getTenantedAccountInfoByFilter(e,t,n,a,s){let l=null,c;if(s&&!this.tenantProfileMatchesFilter(n,s))return null;const h=this.getIdToken(e,a,t,n.tenantId);return h&&(c=Uo(h.secret,this.cryptoImpl.base64Decode),!this.idTokenClaimsMatchTenantProfileFilter(c,s))?null:(l=m2(e,n,c,h?.secret),l)}getTenantProfilesFromAccountEntity(e,t,n,a){const s=Rc(e);let l=s.tenantProfiles||new Map;const c=this.getTokenKeys();if(n){const f=l.get(n);if(f)l=new Map([[n,f]]);else return[]}const h=[];return l.forEach(f=>{const g=this.getTenantedAccountInfoByFilter(s,c,f,t,a);g&&h.push(g)}),h}tenantProfileMatchesFilter(e,t){return!(t.localAccountId&&!this.matchLocalAccountIdFromTenantProfile(e,t.localAccountId)||t.name&&e.name!==t.name||t.isHomeTenant!==void 0&&e.isHomeTenant!==t.isHomeTenant)}idTokenClaimsMatchTenantProfileFilter(e,t){return!(t&&(t.localAccountId&&!this.matchLocalAccountIdFromTokenClaims(e,t.localAccountId)||t.loginHint&&!this.matchLoginHintFromTokenClaims(e,t.loginHint)||t.username&&!this.matchUsername(e.preferred_username,t.username)||t.name&&!this.matchName(e,t.name)||t.sid&&!this.matchSid(e,t.sid)))}async saveCacheRecord(e,t,n,a,s){if(!e)throw tt(nT);try{e.account&&await this.setAccount(e.account,t,n,a),e.idToken&&s?.idToken!==!1&&await this.setIdTokenCredential(e.idToken,t,n),e.accessToken&&s?.accessToken!==!1&&await this.saveAccessToken(e.accessToken,t,n),e.refreshToken&&s?.refreshToken!==!1&&await this.setRefreshTokenCredential(e.refreshToken,t,n),e.appMetadata&&this.setAppMetadata(e.appMetadata,t)}catch(l){throw this.commonLogger?.error("0j476p",t),l instanceof en?l:$1(l)}}async saveAccessToken(e,t,n){const a={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType},s=this.getTokenKeys(),l=qr.fromString(e.target);s.accessToken.forEach(c=>{if(!this.accessTokenKeyMatchesFilter(c,a,!1))return;const h=this.getAccessTokenCredential(c,t);h&&this.credentialMatchesFilter(h,a,t)&&qr.fromString(h.target).intersectingScopeSets(l)&&this.removeAccessToken(c,t)}),await this.setAccessTokenCredential(e,t,n)}getAccountsFilteredBy(e,t){const n=this.getAccountKeys(),a=[];return n.forEach(s=>{const l=this.getAccount(s,t);if(!l||e.homeAccountId&&!this.matchHomeAccountId(l,e.homeAccountId)||e.username&&!this.matchUsername(l.username,e.username)||e.environment&&!this.matchEnvironment(l,e.environment,t)||e.realm&&!this.matchRealm(l,e.realm)||e.nativeAccountId&&!this.matchNativeAccountId(l,e.nativeAccountId)||e.authorityType&&!this.matchAuthorityType(l,e.authorityType))return;const c={localAccountId:e?.localAccountId,name:e?.name},h=l.tenantProfiles?.filter(f=>this.tenantProfileMatchesFilter(f,c));h&&h.length===0||a.push(l)}),a}credentialMatchesFilter(e,t,n){return!(t.clientId&&!this.matchClientId(e,t.clientId)||t.userAssertionHash&&!this.matchUserAssertionHash(e,t.userAssertionHash)||typeof t.homeAccountId=="string"&&!this.matchHomeAccountId(e,t.homeAccountId)||t.environment&&!this.matchEnvironment(e,t.environment,n)||t.realm&&!this.matchRealm(e,t.realm)||t.credentialType&&!this.matchCredentialType(e,t.credentialType)||t.familyId&&!this.matchFamilyId(e,t.familyId)||t.target&&!this.matchTarget(e,t.target)||e.credentialType===_r.ACCESS_TOKEN_WITH_AUTH_SCHEME&&(t.tokenType&&!this.matchTokenType(e,t.tokenType)||t.tokenType===MA.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId)))}getAppMetadataFilteredBy(e,t){const n=this.getKeys(),a={};return n.forEach(s=>{if(!this.isAppMetadata(s))return;const l=this.getAppMetadata(s,t);l&&(e.environment&&!this.matchEnvironment(l,e.environment,t)||e.clientId&&!this.matchClientId(l,e.clientId)||(a[s]=l))}),a}getAuthorityMetadataByAlias(e,t){const n=this.getAuthorityMetadataKeys();let a=null;return n.forEach(s=>{if(!this.isAuthorityMetadata(s)||s.indexOf(this.clientId)===-1)return;const l=this.getAuthorityMetadata(s,t);l&&l.aliases.indexOf(e)!==-1&&(a=l)}),a}removeAllAccounts(e){this.getAllAccounts({},e).forEach(n=>{this.removeAccount(n,e)})}removeAccount(e,t){this.removeAccountContext(e,t);const n=this.getAccountKeys(),a=s=>s.includes(e.homeAccountId)&&s.includes(e.environment);n.filter(a).forEach(s=>{this.removeItem(s,t),this.performanceClient.incrementFields({accountsRemoved:1},t)})}removeAccountContext(e,t){const n=this.getTokenKeys(),a=s=>s.includes(e.homeAccountId)&&s.includes(e.environment);n.idToken.filter(a).forEach(s=>{this.removeIdToken(s,t)}),n.accessToken.filter(a).forEach(s=>{this.removeAccessToken(s,t)}),n.refreshToken.filter(a).forEach(s=>{this.removeRefreshToken(s,t)})}removeAccessToken(e,t){const n=this.getAccessTokenCredential(e,t);if(n&&(this.removeItem(e,t),this.performanceClient.incrementFields({accessTokensRemoved:1},t),n.credentialType.toLowerCase()===_r.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()&&n.tokenType===MA.POP)){const s=n.keyId;s&&this.cryptoImpl.removeTokenBindingKey(s,t).catch(()=>{this.commonLogger.error("0cx291",t),this.performanceClient?.incrementFields({removeTokenBindingKeyFailure:1},t)})}}removeAppMetadata(e){return this.getKeys().forEach(n=>{this.isAppMetadata(n)&&this.removeItem(n,e)}),!0}getIdToken(e,t,n,a){this.commonLogger.trace("1drz22",t);const s={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:_r.ID_TOKEN,clientId:this.clientId,realm:a},l=this.getIdTokensByFilter(s,t,n),c=l.size;if(c<1)return this.commonLogger.info("1atvtd",t),null;if(c>1){let h=l;if(!a){const f=new Map;l.forEach((y,C)=>{y.realm===e.tenantId&&f.set(C,y)});const g=f.size;if(g<1)return this.commonLogger.info("0ooalx",t),l.values().next().value;if(g===1)return this.commonLogger.info("1eq2vc",t),f.values().next().value;h=f}return this.commonLogger.info("1ws328",t),h.forEach((f,g)=>{this.removeIdToken(g,t)}),this.performanceClient.addFields({multiMatchedID:l.size},t),null}return this.commonLogger.info("1sm769",t),l.values().next().value}getIdTokensByFilter(e,t,n){const a=n&&n.idToken||this.getTokenKeys().idToken,s=new Map;return a.forEach(l=>{if(!this.idTokenKeyMatchesFilter(l,{clientId:this.clientId,...e}))return;const c=this.getIdTokenCredential(l,t);c&&this.credentialMatchesFilter(c,e,t)&&s.set(l,c)}),s}idTokenKeyMatchesFilter(e,t){const n=e.toLowerCase();return!(t.clientId&&n.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&n.indexOf(t.homeAccountId.toLowerCase())===-1)}removeIdToken(e,t){this.removeItem(e,t)}removeRefreshToken(e,t){this.removeItem(e,t)}getAccessToken(e,t,n,a){const s=t.correlationId;this.commonLogger.trace("1t7hz1",s);const l=qr.createSearchScopes(t.scopes),c=t.authenticationScheme||MA.BEARER,h=c.toLowerCase()!==MA.BEARER.toLowerCase()?_r.ACCESS_TOKEN_WITH_AUTH_SCHEME:_r.ACCESS_TOKEN,f={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:h,clientId:this.clientId,realm:a||e.tenantId,target:l,tokenType:c,keyId:t.sshKid},g=n&&n.accessToken||this.getTokenKeys().accessToken,y=[];g.forEach(v=>{if(this.accessTokenKeyMatchesFilter(v,f,!0)){const I=this.getAccessTokenCredential(v,s);I&&this.credentialMatchesFilter(I,f,s)&&y.push(I)}});const C=y.length;return C<1?(this.commonLogger.info("1nckna",s),null):C>1?(this.commonLogger.info("1wkfwp",s),y.forEach(v=>{this.removeAccessToken(this.generateCredentialKey(v),s)}),this.performanceClient.addFields({multiMatchedAT:y.length},s),null):(this.commonLogger.info("06yt98",s),y[0])}accessTokenKeyMatchesFilter(e,t,n){const a=e.toLowerCase();if(t.clientId&&a.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&a.indexOf(t.homeAccountId.toLowerCase())===-1||t.realm&&a.indexOf(t.realm.toLowerCase())===-1)return!1;if(t.target){const s=t.target.asArray();for(let l=0;l{if(!this.accessTokenKeyMatchesFilter(s,e,!0))return;const l=this.getAccessTokenCredential(s,t);l&&this.credentialMatchesFilter(l,e,t)&&a.push(l)}),a}getRefreshToken(e,t,n,a){this.commonLogger.trace("0x53vi",n);const s=t?gp:void 0,l={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:_r.REFRESH_TOKEN,clientId:this.clientId,familyId:s},c=a&&a.refreshToken||this.getTokenKeys().refreshToken,h=[];c.forEach(g=>{if(this.refreshTokenKeyMatchesFilter(g,l)){const y=this.getRefreshTokenCredential(g,n);y&&this.credentialMatchesFilter(y,l,n)&&h.push(y)}});const f=h.length;return f<1?(this.commonLogger.info("0dlw11",n),null):(f>1&&this.performanceClient.addFields({multiMatchedRT:f},n),this.commonLogger.info("0wcnep",n),h[0])}refreshTokenKeyMatchesFilter(e,t){const n=e.toLowerCase();return!(t.familyId&&n.indexOf(t.familyId.toLowerCase())===-1||!t.familyId&&t.clientId&&n.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&n.indexOf(t.homeAccountId.toLowerCase())===-1)}readAppMetadataFromCache(e,t){const n={environment:e,clientId:this.clientId},a=this.getAppMetadataFilteredBy(n,t),s=Object.keys(a).map(c=>a[c]),l=s.length;if(l<1)return null;if(l>1)throw tt($F);return s[0]}isAppMetadataFOCI(e,t){const n=this.readAppMetadataFromCache(e,t);return!!(n&&n.familyId===gp)}matchHomeAccountId(e,t){return typeof e.homeAccountId=="string"&&t===e.homeAccountId}matchLocalAccountIdFromTokenClaims(e,t){const n=e.oid||e.sub;return t===n}matchLocalAccountIdFromTenantProfile(e,t){return e.localAccountId===t}matchName(e,t){return t.toLowerCase()===e.name?.toLowerCase()}matchUsername(e,t){return!!(e&&typeof e=="string"&&t?.toLowerCase()===e.toLowerCase())}matchUserAssertionHash(e,t){return!!(e.userAssertionHash&&t===e.userAssertionHash)}matchEnvironment(e,t,n){if(this.staticAuthorityOptions){const s=TT(this.staticAuthorityOptions,this.commonLogger,n);if(s.includes(t)&&s.includes(e.environment))return!0}const a=this.getAuthorityMetadataByAlias(t,n);return!!(a&&a.aliases.indexOf(e.environment)>-1)}matchCredentialType(e,t){return e.credentialType&&t.toLowerCase()===e.credentialType.toLowerCase()}matchClientId(e,t){return!!(e.clientId&&t===e.clientId)}matchFamilyId(e,t){return!!(e.familyId&&t===e.familyId)}matchRealm(e,t){return e.realm?.toLowerCase()===t.toLowerCase()}matchNativeAccountId(e,t){return!!(e.nativeAccountId&&t===e.nativeAccountId)}matchLoginHintFromTokenClaims(e,t){return e.login_hint===t||e.preferred_username===t||e.upn===t}matchSid(e,t){return e.sid===t}matchAuthorityType(e,t){return!!(e.authorityType&&t.toLowerCase()===e.authorityType.toLowerCase())}matchTarget(e,t){return e.credentialType!==_r.ACCESS_TOKEN&&e.credentialType!==_r.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target?!1:qr.fromString(e.target).containsScopeSet(t)}matchTokenType(e,t){return!!(e.tokenType&&e.tokenType===t)}matchKeyId(e,t){return!!(e.keyId&&e.keyId===t)}isAppMetadata(e){return e.indexOf(e2)!==-1}isAuthorityMetadata(e){return e.indexOf(Y1)!==-1}generateAuthorityMetadataCacheKey(e){return`${Y1}-${this.clientId}-${e}`}static toObject(e,t){for(const n in t)e[n]=t[n];return e}}class RT extends ew{async setAccount(){throw tt(iA)}getAccount(){throw tt(iA)}async setIdTokenCredential(){throw tt(iA)}getIdTokenCredential(){throw tt(iA)}async setAccessTokenCredential(){throw tt(iA)}getAccessTokenCredential(){throw tt(iA)}async setRefreshTokenCredential(){throw tt(iA)}getRefreshTokenCredential(){throw tt(iA)}setAppMetadata(){throw tt(iA)}getAppMetadata(){throw tt(iA)}setServerTelemetry(){throw tt(iA)}getServerTelemetry(){throw tt(iA)}setAuthorityMetadata(){throw tt(iA)}getAuthorityMetadata(){throw tt(iA)}getAuthorityMetadataKeys(){throw tt(iA)}setThrottlingCache(){throw tt(iA)}getThrottlingCache(){throw tt(iA)}removeItem(){throw tt(iA)}getKeys(){throw tt(iA)}getAccountKeys(){throw tt(iA)}getTokenKeys(){throw tt(iA)}generateCredentialKey(){throw tt(iA)}generateAccountKey(){throw tt(iA)}}const kT={InProgress:1};class Nx{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:kT.InProgress,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""}}}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}incrementFields(){}cacheEventByCorrelationId(){}}const Qx={tokenRenewalOffsetSeconds:rx,preventCorsPreflight:!1},HT={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:vn.Info,correlationId:""},DT={async sendGetRequestAsync(){throw tt(iA)},async sendPostRequestAsync(){throw tt(iA)}},MT={sku:mI,version:ld,cpu:"",os:""},PT={clientSecret:"",clientAssertion:void 0},jT={azureCloudInstance:p2.None,tenant:`${JE}`},KT={application:{appName:"",appVersion:""}};function y2({authOptions:A,systemOptions:e,loggerOptions:t,storageInterface:n,networkInterface:a,cryptoInterface:s,clientCredentials:l,libraryInfo:c,telemetry:h,serverTelemetryManager:f,persistencePlugin:g,serializableCache:y}){const C={...HT,...t};return{authOptions:GT(A),systemOptions:{...Qx,...e},loggerOptions:C,storageInterface:n||new RT(A.clientId,yp,new Ml(C),new Nx),networkInterface:a||DT,cryptoInterface:s||yp,clientCredentials:l||PT,libraryInfo:{...MT,...c},telemetry:{...KT,...h},serverTelemetryManager:f||null,persistencePlugin:g||null,serializableCache:y||null}}function GT(A){return{clientCapabilities:[],azureCloudOptions:jT,instanceAware:!1,...A}}function Lx(A){return A.authOptions.authority.options.protocolMode===Fi.OIDC}class zc extends en{constructor(e,t,n,a,s){super(e,t,n),this.name="ServerError",this.errorNo=a,this.status=s,Object.setPrototypeOf(this,zc.prototype)}}const tw="no_tokens_found",zT="native_account_unavailable",Ox="refresh_token_expired",Rx="ux_not_allowed",VT="interaction_required",qT="consent_required",YT="login_required",B2="bad_token";const pC=[VT,qT,YT,B2,Rx],XT=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token","ux_not_allowed"];class os extends en{constructor(e,t,n,a,s,l,c,h){super(e,t,n),Object.setPrototypeOf(this,os.prototype),this.timestamp=a||"",this.traceId=s||"",this.correlationId=l||"",this.claims=c||"",this.name="InteractionRequiredAuthError",this.errorNo=h}}function kx(A,e,t){const n=!!A&&pC.indexOf(A)>-1,a=!!t&&XT.indexOf(t)>-1,s=!!e&&pC.some(l=>e.indexOf(l)>-1);return n||s||a}function bp(A,e){return new os(A,e)}function JT(A,e,t){const n=WT(A,t);return e?`${n}${z1}${e}`:n}function WT(A,e){if(!A)throw tt(px);const t={id:A.createNewGuid()};e&&(t.meta=e);const n=JSON.stringify(t);return A.base64Encode(n)}function cd(A,e){if(!A)throw tt(px);if(!e)throw tt(Vf);try{const t=e.split(z1),n=t[0],a=t.length>1?t.slice(1).join(z1):"",s=A(n),l=JSON.parse(s);return{userRequestState:a||"",libraryState:l}}catch{throw tt(Vf)}}function ls(){return Math.round(new Date().getTime()/1e3)}function mC(A){return A.getTime()/1e3}function Zg(A){return A?new Date(Number(A)*1e3):new Date}function Ep(A,e){const t=Number(A)||0;return ls()+e>t}function wC(A,e){const t=Number(A)+e*24*60*60*1e3;return Date.now()>t}function ZT(A){return Number(A)>ls()}const $T="networkClientSendPostRequestAsync",e_="refreshTokenClientExecutePostToTokenEndpoint",t_="authorizationCodeClientExecutePostToTokenEndpoint",A_="refreshTokenClientExecuteTokenRequest",n_="refreshTokenClientAcquireToken",Gm="refreshTokenClientAcquireTokenWithCachedRefreshToken",r_="refreshTokenClientCreateTokenRequestBody",i_="silentFlowClientGenerateResultFromCacheRecord",C2="getAuthCodeUrl",Hx="handleCodeResponseFromServer",a_="authClientExecuteTokenRequest",s_="authClientCreateTokenRequestBody",o_="updateTokenEndpointAuthority",ud="popTokenGenerateCnf",b2="handleServerTokenResponse",l_="authorityResolveEndpointsAsync",c_="authorityGetCloudDiscoveryMetadataFromNetwork",u_="authorityUpdateCloudDiscoveryMetadata",h_="authorityGetEndpointMetadataFromNetwork",f_="authorityUpdateEndpointMetadata",vC="authorityUpdateMetadataWithRegionalInformation",d_="regionDiscoveryDetectRegion",yC="regionDiscoveryGetRegionFromIMDS",g_="regionDiscoveryGetCurrentVersion",p_="cacheManagerGetRefreshToken",m_="setUserData";const as=(A,e,t,n,a)=>(...s)=>{t.trace("1plfzx",a);const l=n.startMeasurement(e,a);if(a){const c=e+"CallCount";n.incrementFields({[c]:1},a)}try{const c=A(...s);return l.end({success:!0}),t.trace("1g8n6a",a),c}catch(c){t.trace("0cfd8i",a);try{t.trace(JSON.stringify(c),a)}catch{t.trace("00dty7",a)}throw l.end({success:!1},c),c}},Ke=(A,e,t,n,a)=>(...s)=>{t.trace("1plfzx",a);const l=n.startMeasurement(e,a);if(a){const c=e+"CallCount";n.incrementFields({[c]:1},a)}return A(...s).then(c=>(t.trace("1g8n6a",a),l.end({success:!0}),c)).catch(c=>{t.trace("0cfd8i",a);try{t.trace(JSON.stringify(c),a)}catch{t.trace("00dty7",a)}throw l.end({success:!1},c),c})};const w_={SW:"sw"};class mh{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){const n=await Ke(this.generateKid.bind(this),ud,t,this.performanceClient,e.correlationId)(e),a=this.cryptoUtils.base64UrlEncode(JSON.stringify(n));return{kid:n.kid,reqCnfString:a}}async generateKid(e){return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:w_.SW}}async signPopToken(e,t,n){return this.signPayload(e,t,n)}async signPayload(e,t,n,a){const{resourceRequestMethod:s,resourceRequestUri:l,shrClaims:c,shrNonce:h,shrOptions:f}=n,y=(l?new QA(l):void 0)?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:ls(),m:s?.toUpperCase(),u:y?.HostNameAndPort,nonce:h||this.cryptoUtils.createNewGuid(),p:y?.AbsolutePath,q:y?.QueryString?[[],y.QueryString]:void 0,client_claims:c||void 0,...a},t,f,n.correlationId)}}class v_{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}function E2(A,e,t,n,a){return{credentialType:_r.ID_TOKEN,homeAccountId:A,environment:e,clientId:n,secret:t,realm:a,lastUpdatedAt:Date.now().toString()}}function x2(A,e,t,n,a,s,l,c,h,f,g,y,C){const v={homeAccountId:A,credentialType:_r.ACCESS_TOKEN,secret:t,cachedAt:ls().toString(),expiresOn:l.toString(),extendedExpiresOn:c.toString(),environment:e,clientId:n,realm:a,target:s,tokenType:g||MA.BEARER,lastUpdatedAt:Date.now().toString()};if(y&&(v.userAssertionHash=y),f&&(v.refreshOn=f.toString()),v.tokenType?.toLowerCase()!==MA.BEARER.toLowerCase())switch(v.credentialType=_r.ACCESS_TOKEN_WITH_AUTH_SCHEME,v.tokenType){case MA.POP:const I=Uo(t,h);if(!I?.cnf?.kid)throw tt(rT);v.keyId=I.cnf.kid;break;case MA.SSH:v.keyId=C}return v}function y_(A,e,t,n,a,s,l){const c={credentialType:_r.REFRESH_TOKEN,homeAccountId:A,environment:e,clientId:n,secret:t,lastUpdatedAt:Date.now().toString()};return s&&(c.userAssertionHash=s),a&&(c.familyId=a),l&&(c.expiresOn=l.toString()),c}function e0(A){return A.hasOwnProperty("homeAccountId")&&A.hasOwnProperty("environment")&&A.hasOwnProperty("credentialType")&&A.hasOwnProperty("clientId")&&A.hasOwnProperty("secret")}function BC(A){return A?e0(A)&&A.hasOwnProperty("realm")&&A.hasOwnProperty("target")&&(A.credentialType===_r.ACCESS_TOKEN||A.credentialType===_r.ACCESS_TOKEN_WITH_AUTH_SCHEME):!1}function B_(A){return A?e0(A)&&A.hasOwnProperty("realm")&&A.credentialType===_r.ID_TOKEN:!1}function CC(A){return A?e0(A)&&A.credentialType===_r.REFRESH_TOKEN:!1}function C_(A,e){const t=A.indexOf(Ax)===0;let n=!0;return e&&(n=e.hasOwnProperty("failedRequests")&&e.hasOwnProperty("errors")&&e.hasOwnProperty("cacheHits")),t&&n}function b_(A,e){let t=!1;A&&(t=A.indexOf(nx)===0);let n=!0;return e&&(n=e.hasOwnProperty("throttleTime")),t&&n}function E_({environment:A,clientId:e}){return[e2,A,e].join(tx).toLowerCase()}function x_(A,e){return e?A.indexOf(e2)===0&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("environment"):!1}function S_(A,e){return e?A.indexOf(Y1)===0&&e.hasOwnProperty("aliases")&&e.hasOwnProperty("preferred_cache")&&e.hasOwnProperty("preferred_network")&&e.hasOwnProperty("canonical_authority")&&e.hasOwnProperty("authorization_endpoint")&&e.hasOwnProperty("token_endpoint")&&e.hasOwnProperty("issuer")&&e.hasOwnProperty("aliasesFromNetwork")&&e.hasOwnProperty("endpointsFromNetwork")&&e.hasOwnProperty("expiresAt")&&e.hasOwnProperty("jwks_uri"):!1}function bC(){return ls()+HI}function gg(A,e,t){A.authorization_endpoint=e.authorization_endpoint,A.token_endpoint=e.token_endpoint,A.end_session_endpoint=e.end_session_endpoint,A.issuer=e.issuer,A.endpointsFromNetwork=t,A.jwks_uri=e.jwks_uri}function zm(A,e,t){A.aliases=e.aliases,A.preferred_cache=e.preferred_cache,A.preferred_network=e.preferred_network,A.aliasesFromNetwork=t}function EC(A){return A.expiresAt<=ls()}class kc{constructor(e,t,n,a,s,l,c){this.clientId=e,this.cacheStorage=t,this.cryptoObj=n,this.logger=a,this.performanceClient=s,this.serializableCache=l,this.persistencePlugin=c}validateTokenResponse(e,t,n){if(e.error||e.error_description||e.suberror){const a=`Error(s): ${e.error_codes||ff} - Timestamp: ${e.timestamp||ff} - Description: ${e.error_description||ff} - Correlation ID: ${e.correlation_id||ff} - Trace ID: ${e.trace_id||ff}`,s=e.error_codes?.length?e.error_codes[0]:void 0,l=new zc(e.error,a,e.suberror,s,e.status);if(n&&e.status&&e.status>=QI&&e.status<=LI){this.logger.warning("16ks7j",t);return}else if(n&&e.status&&e.status>=_I&&e.status<=NI){this.logger.warning("0g61x3",t);return}throw kx(e.error,e.error_description,e.suberror)?new os(e.error,e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.correlation_id||"",e.claims||"",s):l}}async handleServerTokenResponse(e,t,n,a,s,l,c,h,f,g){let y;if(e.id_token){if(y=Uo(e.id_token||"",this.cryptoObj.base64Decode),l&&l.nonce&&y.nonce!==l.nonce)throw tt(WF);if(a.maxAge||a.maxAge===0){const x=y.auth_time;if(!x)throw tt(fx);Ix(x,a.maxAge)}}this.homeAccountIdentifier=_x(e.client_info||"",t.authorityType,this.logger,this.cryptoObj,a.correlationId,y);let C;l&&l.state&&(C=cd(this.cryptoObj.base64Decode,l.state)),e.key_id=e.key_id||a.sshKid||void 0;const v=this.generateCacheRecord(e,t,n,a,y,c,l);let I;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("0jbz5k",a.correlationId),I=new v_(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(I)),h&&!f&&v.account&&this.cacheStorage.getAllAccounts({homeAccountId:v.account.homeAccountId,environment:v.account.environment},a.correlationId).length<1)return this.logger.warning("1gmt66",a.correlationId),this.performanceClient?.addFields({acntLoggedOut:!0},a.correlationId),await kc.generateAuthenticationResult(this.cryptoObj,t,v,!1,a,this.performanceClient,y,C,void 0,g);await this.cacheStorage.saveCacheRecord(v,a.correlationId,Fc(y||{}),s,a.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&I&&(this.logger.verbose("1bh17u",a.correlationId),await this.persistencePlugin.afterCacheAccess(I))}return kc.generateAuthenticationResult(this.cryptoObj,t,v,!1,a,this.performanceClient,y,C,e,g)}generateCacheRecord(e,t,n,a,s,l,c){const h=t.getPreferredCache();if(!h)throw tt(gx);const f=v2(s);let g,y;e.id_token&&s&&(g=E2(this.homeAccountIdentifier,h,e.id_token,this.clientId,f||""),y=Dx(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,a.correlationId,s,e.client_info,h,f,c,void 0,this.logger));let C=null;if(e.access_token){const x=e.scope?qr.fromString(e.scope):new qr(a.scopes||[]),_=(typeof e.expires_in=="string"?parseInt(e.expires_in,10):e.expires_in)||0,T=(typeof e.ext_expires_in=="string"?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,k=(typeof e.refresh_in=="string"?parseInt(e.refresh_in,10):e.refresh_in)||void 0,z=n+_,H=z+T,re=k&&k>0?n+k:void 0;C=x2(this.homeAccountIdentifier,h,e.access_token,this.clientId,f||t.tenant||"",x.printScopes(),z,H,this.cryptoObj.base64Decode,re,e.token_type,l,e.key_id)}let v=null;if(e.refresh_token){let x;if(e.refresh_token_expires_in){const _=typeof e.refresh_token_expires_in=="string"?parseInt(e.refresh_token_expires_in,10):e.refresh_token_expires_in;x=n+_,this.performanceClient?.addFields({ntwkRtExpiresOnSeconds:x},a.correlationId)}v=y_(this.homeAccountIdentifier,h,e.refresh_token,this.clientId,e.foci,l,x)}let I=null;return e.foci&&(I={clientId:this.clientId,environment:h,familyId:e.foci}),{account:y,idToken:g,accessToken:C,refreshToken:v,appMetadata:I}}static async generateAuthenticationResult(e,t,n,a,s,l,c,h,f,g){let y="",C=[],v=null,I,x,_="";if(n.accessToken){if(n.accessToken.tokenType===MA.POP&&!s.popKid){const H=new mh(e,l),{secret:re,keyId:le}=n.accessToken;if(!le)throw tt(mx);y=await H.signPopToken(re,le,s)}else y=n.accessToken.secret;C=qr.fromString(n.accessToken.target).asArray(),v=Zg(n.accessToken.expiresOn),I=Zg(n.accessToken.extendedExpiresOn),n.accessToken.refreshOn&&(x=Zg(n.accessToken.refreshOn))}n.appMetadata&&(_=n.appMetadata.familyId===gp?gp:"");const T=c?.oid||c?.sub||"",k=c?.tid||"";f?.spa_accountid&&n.account&&(n.account.nativeAccountId=f?.spa_accountid);const z=n.account?m2(Rc(n.account),void 0,c,n.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:T,tenantId:k,scopes:C,account:z,idToken:n?.idToken?.secret||"",idTokenClaims:c||{},accessToken:y,fromCache:a,expiresOn:v,extExpiresOn:I,refreshOn:x,correlationId:s.correlationId,requestId:g||"",familyId:_,tokenType:n.accessToken?.tokenType||"",state:h?h.userRequestState:"",cloudGraphHostName:n.account?.cloudGraphHostName||"",msGraphHost:n.account?.msGraphHost||"",code:f?.spa_code,fromPlatformBroker:!1}}}function Dx(A,e,t,n,a,s,l,c,h,f,g,y){y?.verbose("09jz0t",a);const v=A.getAccountKeys().find(k=>k.startsWith(t));let I=null;v&&(I=A.getAccount(v,a));const x=I||QT({homeAccountId:t,idTokenClaims:s,clientInfo:l,environment:c,cloudGraphHostName:f?.cloud_graph_host_name,msGraphHost:f?.msgraph_host,nativeAccountId:g},e,n),_=x.tenantProfiles||[],T=h||x.realm;if(T&&!_.find(k=>k.tenantId===T)){const k=Bh(t,x.localAccountId,T,s);_.push(k)}return x.tenantProfiles=_,x}const is={HOME_ACCOUNT_ID:"home_account_id",UPN:"UPN"};async function Mx(A,e,t){return typeof A=="string"?A:A({clientId:e,tokenEndpoint:t})}function t0(A,e,t){return{clientId:A,authority:e.authority,scopes:e.scopes,homeAccountIdentifier:t,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid,embeddedClientId:e.embeddedClientId||e.extraParameters?.clientId}}class ks{static generateThrottlingStorageKey(e){return`${nx}.${JSON.stringify(e)}`}static preProcess(e,t,n){const a=ks.generateThrottlingStorageKey(t),s=e.getThrottlingCache(a,n);if(s){if(s.throttleTime=500&&e.status<600}static checkResponseForRetryAfter(e){return e.headers?e.headers.hasOwnProperty(si.RETRY_AFTER)&&(e.status<200||e.status>=300):!1}static calculateThrottleTime(e){const t=e<=0?0:e,n=Date.now()/1e3;return Math.floor(Math.min(n+(t||GI),n+zI)*1e3)}static removeThrottle(e,t,n,a){const s=t0(t,n,a),l=this.generateThrottlingStorageKey(s);e.removeItem(l,n.correlationId)}}class A0 extends en{constructor(e,t,n){super(e.errorCode,e.errorMessage,e.subError),Object.setPrototypeOf(this,A0.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=n}}function Cf(A,e,t,n){return A.errorMessage=`${A.errorMessage}, additionalErrorInfo: error.name:${n?.name}, error.message:${n?.message}`,new A0(A,e,t)}function Px(A,e,t){const n={};if(n[si.CONTENT_TYPE]=EI,!e&&t)switch(t.type){case is.HOME_ACCOUNT_ID:try{const a=ah(t.credential);n[si.CCS_HEADER]=`Oid:${a.uid}@${a.utid}`}catch{A.verbose("1qhtee","")}break;case is.UPN:n[si.CCS_HEADER]=`UPN: ${t.credential}`;break}return n}function jx(A,e,t,n){const a=new Map;return A.embeddedClientId&&Zp(a,e,t),A.extraQueryParameters&&Ps(a,A.extraQueryParameters),c2(a,A.correlationId),Wp(a,A.correlationId,n),qf(a)}async function Kx(A,e,t,n,a,s,l,c,h,f){const g=await U_(n,A,{body:e,headers:t},a,s,l,c,h);return f&&g.status<500&&g.status!==429&&f.clearTelemetryCache(),g}async function U_(A,e,t,n,a,s,l,c){ks.preProcess(a,A,n);let h;try{h=await Ke(s.sendPostRequestAsync.bind(s),$T,l,c,n)(e,t);const f=h.headers||{};c?.addFields({refreshTokenSize:h.body.refresh_token?.length||0,httpVerToken:f[si.X_MS_HTTP_VERSION]||"",requestId:f[si.X_MS_REQUEST_ID]||""},n)}catch(f){if(f instanceof A0){const g=f.responseHeaders;throw g&&c?.addFields({httpVerToken:g[si.X_MS_HTTP_VERSION]||"",requestId:g[si.X_MS_REQUEST_ID]||"",contentTypeHeader:g[si.CONTENT_TYPE]||void 0,contentLengthHeader:g[si.CONTENT_LENGTH]||void 0,httpStatus:f.httpStatus},n),f.error}throw f instanceof en?f:tt(qF)}return ks.postProcess(a,A,h,n),h}function I_(A){return A.hasOwnProperty("authorization_endpoint")&&A.hasOwnProperty("token_endpoint")&&A.hasOwnProperty("issuer")&&A.hasOwnProperty("jwks_uri")}function F_(A){return A.hasOwnProperty("tenant_discovery_endpoint")&&A.hasOwnProperty("metadata")}function T_(A){return A.hasOwnProperty("error")&&A.hasOwnProperty("error_description")}class n0{constructor(e,t,n,a){this.networkInterface=e,this.logger=t,this.performanceClient=n,this.correlationId=a}async detectRegion(e,t){let n=e;if(n)t.region_source=Du.ENVIRONMENT_VARIABLE;else{const a=n0.IMDS_OPTIONS;try{const s=await Ke(this.getRegionFromIMDS.bind(this),yC,this.logger,this.performanceClient,this.correlationId)(xI,a);if(s.status===eC&&(n=s.body,t.region_source=Du.IMDS),s.status===tC){const l=await Ke(this.getCurrentVersion.bind(this),g_,this.logger,this.performanceClient,this.correlationId)(a);if(!l)return t.region_source=Du.FAILED_AUTO_DETECTION,null;const c=await Ke(this.getRegionFromIMDS.bind(this),yC,this.logger,this.performanceClient,this.correlationId)(l,a);c.status===eC&&(n=c.body,t.region_source=Du.IMDS)}}catch{return t.region_source=Du.FAILED_AUTO_DETECTION,null}}return n||(t.region_source=Du.FAILED_AUTO_DETECTION),n||null}async getRegionFromIMDS(e,t){return this.networkInterface.sendGetRequestAsync(`${ZB}?api-version=${e}&format=text`,t,SI)}async getCurrentVersion(e){try{const t=await this.networkInterface.sendGetRequestAsync(`${ZB}?format=json`,e);return t.status===tC&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch{return null}}}n0.IMDS_OPTIONS={headers:{Metadata:"true"}};class Si{constructor(e,t,n,a,s,l,c,h){this.canonicalAuthority=e,this._canonicalAuthority.validateAsUri(),this.networkInterface=t,this.cacheManager=n,this.authorityOptions=a,this.regionDiscoveryMetadata={region_used:void 0,region_source:void 0,region_outcome:void 0},this.logger=s,this.performanceClient=c,this.correlationId=l,this.managedIdentity=h||!1,this.regionDiscovery=new n0(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(WB))return rs.Ciam;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case vI:return rs.Adfs;case yI:return rs.Dsts}return rs.Default}get authorityType(){return this.getAuthorityType(this.canonicalAuthorityUrlComponents)}get protocolMode(){return this.authorityOptions.protocolMode}get options(){return this.authorityOptions}get canonicalAuthority(){return this._canonicalAuthority.urlString}set canonicalAuthority(e){this._canonicalAuthority=new QA(e),this._canonicalAuthority.validateAsUri(),this._canonicalAuthorityUrlComponents=null}get canonicalAuthorityUrlComponents(){return this._canonicalAuthorityUrlComponents||(this._canonicalAuthorityUrlComponents=this._canonicalAuthority.getUrlComponents()),this._canonicalAuthorityUrlComponents}get hostnameAndPort(){return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase()}get tenant(){return this.canonicalAuthorityUrlComponents.PathSegments[0]}get authorizationEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.authorization_endpoint);throw tt(pl)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw tt(pl)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw tt(pl)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw tt(sT);return this.replacePath(this.metadata.end_session_endpoint)}else throw tt(pl)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw tt(pl)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw tt(pl)}canReplaceTenant(e){return e.PathSegments.length===1&&!Si.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===rs.Default&&this.protocolMode!==Fi.OIDC}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const a=new QA(this.metadata.canonical_authority).getUrlComponents(),s=a.PathSegments;return this.canonicalAuthorityUrlComponents.PathSegments.forEach((c,h)=>{let f=s[h];if(h===0&&this.canReplaceTenant(a)){const g=new QA(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];f!==g&&(this.logger.verbose("1q3g2x",this.correlationId),f=g)}c!==f&&(t=t.replace(`/${f}/`,`/${c}/`))}),this.replaceTenant(t)}get defaultOpenIdConfigurationEndpoint(){const e=this.hostnameAndPort;return this.canonicalAuthority.endsWith("v2.0/")||this.authorityType===rs.Adfs||this.protocolMode===Fi.OIDC&&!this.isAliasOfKnownMicrosoftAuthority(e)?`${this.canonicalAuthority}.well-known/openid-configuration`:`${this.canonicalAuthority}v2.0/.well-known/openid-configuration`}discoveryComplete(){return!!this.metadata}async resolveEndpointsAsync(){const e=this.getCurrentMetadataEntity(),t=await Ke(this.updateCloudDiscoveryMetadata.bind(this),u_,this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const n=await Ke(this.updateEndpointMetadata.bind(this),f_,this.logger,this.performanceClient,this.correlationId)(e);this.updateCachedMetadata(e,t,{source:n}),this.performanceClient?.addFields({cloudDiscoverySource:t,authorityEndpointSource:n},this.correlationId)}getCurrentMetadataEntity(){let e=this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort,this.correlationId);return e||(e={aliases:[],preferred_cache:this.hostnameAndPort,preferred_network:this.hostnameAndPort,canonical_authority:this.canonicalAuthority,authorization_endpoint:"",token_endpoint:"",end_session_endpoint:"",issuer:"",aliasesFromNetwork:!1,endpointsFromNetwork:!1,expiresAt:bC(),jwks_uri:""}),e}updateCachedMetadata(e,t,n){t!==es.CACHE&&n?.source!==es.CACHE&&(e.expiresAt=bC(),e.canonical_authority=this.canonicalAuthority);const a=this.cacheManager.generateAuthorityMetadataCacheKey(e.preferred_cache,this.correlationId);this.cacheManager.setAuthorityMetadata(a,e,this.correlationId),this.metadata=e}async updateEndpointMetadata(e){const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===es.HARDCODED_VALUES&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){const a=await Ke(this.updateMetadataWithRegionalInformation.bind(this),vC,this.logger,this.performanceClient,this.correlationId)(t.metadata);gg(e,a,!1),e.canonical_authority=this.canonicalAuthority}return t.source}let n=await Ke(this.getEndpointMetadataFromNetwork.bind(this),h_,this.logger,this.performanceClient,this.correlationId)();if(n)return this.authorityOptions.azureRegionConfiguration?.azureRegion&&(n=await Ke(this.updateMetadataWithRegionalInformation.bind(this),vC,this.logger,this.performanceClient,this.correlationId)(n)),gg(e,n,!0),es.NETWORK;throw tt(YF,this.defaultOpenIdConfigurationEndpoint)}updateEndpointMetadataFromLocalSources(e){this.logger.verbose("1fi0kc",this.correlationId);const t=this.getEndpointMetadataFromConfig();if(t)return this.logger.verbose("06t0uj",this.correlationId),gg(e,t,!1),{source:es.CONFIG};this.logger.verbose("151k0p",this.correlationId);const n=this.getEndpointMetadataFromHardcodedValues();if(n)return gg(e,n,!1),{source:es.HARDCODED_VALUES,metadata:n};this.logger.verbose("1imop5",this.correlationId);const a=EC(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!a?(this.logger.verbose("16uq31",""),{source:es.CACHE}):(a&&this.logger.verbose("0uoibc",""),null)}isAuthoritySameType(e){return new QA(e.canonical_authority).getUrlComponents().PathSegments.length===this.canonicalAuthorityUrlComponents.PathSegments.length}getEndpointMetadataFromConfig(){if(this.authorityOptions.authorityMetadata)try{return JSON.parse(this.authorityOptions.authorityMetadata)}catch{throw An(HF)}return null}async getEndpointMetadataFromNetwork(){const e={},t=this.defaultOpenIdConfigurationEndpoint;this.logger.verbose("1y65x6",this.correlationId);try{const n=await this.networkInterface.sendGetRequestAsync(t,e);return I_(n.body)?n.body:(this.logger.verbose("1koyv8",this.correlationId),null)}catch{return this.logger.verbose("0a9wik",this.correlationId),null}}getEndpointMetadataFromHardcodedValues(){return this.hostnameAndPort in dC?dC[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if(t!==UI)return this.regionDiscoveryMetadata.region_outcome=Km.CONFIGURED_NO_AUTO_DETECTION,this.regionDiscoveryMetadata.region_used=t,Si.replaceWithRegionalInformation(e,t);const n=await Ke(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),d_,this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(n)return this.regionDiscoveryMetadata.region_outcome=Km.AUTO_DETECTION_REQUESTED_SUCCESSFUL,this.regionDiscoveryMetadata.region_used=n,Si.replaceWithRegionalInformation(e,n);this.regionDiscoveryMetadata.region_outcome=Km.AUTO_DETECTION_REQUESTED_FAILED}return e}async updateCloudDiscoveryMetadata(e){const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const n=await Ke(this.getCloudDiscoveryMetadataFromNetwork.bind(this),c_,this.logger,this.performanceClient,this.correlationId)();if(n)return zm(e,n,!0),es.NETWORK;throw An(DF)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("0jhlgt",this.correlationId),this.logger.verbosePii("1fy7uz",this.correlationId),this.logger.verbosePii("08zabj",this.correlationId),this.logger.verbosePii("1o1kv3",this.correlationId);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("1nakio",this.correlationId),zm(e,t,!1),es.CONFIG;this.logger.verbose("1x74aj",this.correlationId);const n=_T(this.hostnameAndPort);if(n)return this.logger.verbose("0by47c",this.correlationId),zm(e,n,!1),es.HARDCODED_VALUES;this.logger.verbose("0r2fzy",this.correlationId);const a=EC(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!a?(this.logger.verbose("1uffgh",""),es.CACHE):(a&&this.logger.verbose("0uoibc",""),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===rs.Ciam)return this.logger.verbose("04y84h",this.correlationId),Si.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);if(this.authorityOptions.cloudDiscoveryMetadata){this.logger.verbose("0gszr3",this.correlationId);try{this.logger.verbose("1iifkx",this.correlationId);const e=JSON.parse(this.authorityOptions.cloudDiscoveryMetadata),t=Bp(e.metadata,this.hostnameAndPort);if(this.logger.verbose("0q67e3",""),t)return this.logger.verbose("0hzfao",this.correlationId),t;this.logger.verbose("1ajz3u",this.correlationId)}catch{throw this.logger.verbose("1wq5tu",this.correlationId),An(cx)}}return this.isInKnownAuthorities()?(this.logger.verbose("0mt9al",this.correlationId),Si.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){const e=`${BI}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let n=null;try{const a=await this.networkInterface.sendGetRequestAsync(e,t);let s,l;if(F_(a.body))s=a.body,l=s.metadata,this.logger.verbosePii("1vglyt",this.correlationId);else if(T_(a.body)){if(this.logger.warning("062uto",this.correlationId),s=a.body,s.error===TI)return this.logger.error("1x90tm",this.correlationId),null;this.logger.warning("0wchdm",this.correlationId),this.logger.warning("1s5mpv",this.correlationId),this.logger.warning("1yhqpw",this.correlationId),l=[]}else return this.logger.error("0768g0",this.correlationId),null;this.logger.verbose("1lrobr",this.correlationId),n=Bp(l,this.hostnameAndPort)}catch(a){return a instanceof en?this.logger.error("0vwhc7",this.correlationId):this.logger.error("0s2z41",this.correlationId),null}return n||(this.logger.warning("0jp28q",this.correlationId),this.logger.verbose("130sd8",this.correlationId),n=Si.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),n}isInKnownAuthorities(){return this.authorityOptions.knownAuthorities.filter(t=>t&&QA.getDomainFromUrl(t).toLowerCase()===this.hostnameAndPort).length>0}static generateAuthority(e,t){let n;if(t&&t.azureCloudInstance!==p2.None){const a=t.tenant?t.tenant:JE;n=`${t.azureCloudInstance}/${a}/`}return n||e}static createCloudDiscoveryMetadataFromHost(e){return{preferred_network:e,preferred_cache:e,aliases:[e]}}getPreferredCache(){if(this.managedIdentity)return wI;if(this.discoveryComplete())return this.metadata.preferred_cache;throw tt(pl)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return Tx.has(e)}static isPublicCloudAuthority(e){return FI.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,n){const a=new QA(e);a.validateAsUri();const s=a.getUrlComponents();let l=`${t}.${s.HostNameAndPort}`;this.isPublicCloudAuthority(s.HostNameAndPort)&&(l=`${t}.${II}`);const c=QA.constructAuthorityUriFromObject({...a.getUrlComponents(),HostNameAndPort:l}).urlString;return n?`${c}?${n}`:c}static replaceWithRegionalInformation(e,t){const n={...e};return n.authorization_endpoint=Si.buildRegionalAuthorityString(n.authorization_endpoint,t),n.token_endpoint=Si.buildRegionalAuthorityString(n.token_endpoint,t),n.end_session_endpoint&&(n.end_session_endpoint=Si.buildRegionalAuthorityString(n.end_session_endpoint,t)),n}static transformCIAMAuthority(e){let t=e;const a=new QA(e).getUrlComponents();if(a.PathSegments.length===0&&a.HostNameAndPort.endsWith(WB)){const s=a.HostNameAndPort.split(".")[0];t=`${t}${s}${CI}`}return t}}Si.reservedTenantDomains=new Set(["{tenant}","{tenantid}",_l.COMMON,_l.CONSUMERS,_l.ORGANIZATIONS]);function __(A){const n=new QA(A).getUrlComponents().PathSegments.slice(-1)[0]?.toLowerCase();switch(n){case _l.COMMON:case _l.ORGANIZATIONS:case _l.CONSUMERS:return;default:return n}}function Gx(A){return A.endsWith(V1)?A:`${A}${V1}`}function N_(A){const e=A.cloudDiscoveryMetadata;let t;if(e)try{t=JSON.parse(e)}catch{throw An(cx)}return{canonicalAuthority:A.authority?Gx(A.authority):void 0,knownAuthorities:A.knownAuthorities,cloudDiscoveryMetadata:t}}async function zx(A,e,t,n,a,s,l){const c=Si.transformCIAMAuthority(Gx(A)),h=new Si(c,e,t,n,a,s,l);try{return await Ke(h.resolveEndpointsAsync.bind(h),l_,a,l,s)(),h}catch{throw tt(pl)}}class Vx{constructor(e,t){this.includeRedirectUri=!0,this.config=y2(e),this.logger=new Ml(this.config.loggerOptions,$p,ld),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async acquireToken(e,t,n){if(!e.code)throw tt(eT);n&&n.cloud_instance_host_name&&await Ke(this.updateTokenEndpointAuthority.bind(this),o_,this.logger,this.performanceClient,e.correlationId)(n.cloud_instance_host_name,e.correlationId);const a=ls(),s=await Ke(this.executeTokenRequest.bind(this),a_,this.logger,this.performanceClient,e.correlationId)(this.authority,e,this.serverTelemetryManager),l=s.headers?.[si.X_MS_REQUEST_ID],c=new kc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.performanceClient,this.config.serializableCache,this.config.persistencePlugin);return c.validateTokenResponse(s.body,e.correlationId),Ke(c.handleServerTokenResponse.bind(c),b2,this.logger,this.performanceClient,e.correlationId)(s.body,this.authority,a,e,t,n,void 0,void 0,void 0,l)}getLogoutUri(e){if(!e)throw An(kF);const t=this.createLogoutUrlQueryString(e);return QA.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t,n){const a=jx(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri,this.performanceClient),s=QA.appendQueryString(e.tokenEndpoint,a),l=await Ke(this.createTokenRequestBody.bind(this),s_,this.logger,this.performanceClient,t.correlationId)(t);let c;if(t.clientInfo)try{const g=Cp(t.clientInfo,this.cryptoUtils.base64Decode);c={credential:`${g.uid}${q1}${g.utid}`,type:is.HOME_ACCOUNT_ID}}catch{this.logger.verbose("0wznt3",t.correlationId)}const h=Px(this.logger,this.config.systemOptions.preventCorsPreflight,c||t.ccsCredential),f=t0(this.config.authOptions.clientId,t);return Ke(Kx,t_,this.logger,this.performanceClient,t.correlationId)(s,l,h,f,t.correlationId,this.cacheManager,this.networkClient,this.logger,this.performanceClient,n)}async createTokenRequestBody(e){const t=new Map;if(s2(t,e.embeddedClientId||e.extraParameters?.[Oc]||this.config.authOptions.clientId),this.includeRedirectUri)o2(t,e.redirectUri);else if(!e.redirectUri)throw An(NF);if(a2(t,e.scopes,!0,this.oidcDefaultScopes),gT(t,e.code),u2(t,this.config.libraryInfo),h2(t,this.config.telemetry.application),Sx(t),this.serverTelemetryManager&&!Lx(this.config)&&xx(t,this.serverTelemetryManager),e.codeVerifier&&mT(t,e.codeVerifier),this.config.clientCredentials.clientSecret&&vx(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const a=this.config.clientCredentials.clientAssertion;yx(t,await Mx(a.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),Bx(t,a.assertionType)}if(Cx(t,$E.AUTHORIZATION_CODE_GRANT),d2(t),e.authenticationScheme===MA.POP){const a=new mh(this.cryptoUtils,this.performanceClient);let s;e.popKid?s=this.cryptoUtils.encodeKid(e.popKid):s=(await Ke(a.generateCnf.bind(a),ud,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString,g2(t,s)}else if(e.authenticationScheme===MA.SSH)if(e.sshJwk)Ex(t,e.sshJwk);else throw An(r2);(!Ea.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&l2(t,e.claims,this.config.authOptions.clientCapabilities);let n;if(e.clientInfo)try{const a=Cp(e.clientInfo,this.cryptoUtils.base64Decode);n={credential:`${a.uid}${q1}${a.utid}`,type:is.HOME_ACCOUNT_ID}}catch{this.logger.verbose("0wznt3",e.correlationId)}else n=e.ccsCredential;if(this.config.systemOptions.preventCorsPreflight&&n)switch(n.type){case is.HOME_ACCOUNT_ID:try{const a=ah(n.credential);_f(t,a)}catch{this.logger.verbose("1qhtee",e.correlationId)}break;case is.UPN:wp(t,n.credential);break}return e.embeddedClientId&&Zp(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.extraParameters&&Ps(t,e.extraParameters),e.enableSpaAuthorizationCode&&(!e.extraParameters||!e.extraParameters[aC])&&Ps(t,{[aC]:"1"}),Wp(t,e.correlationId,this.performanceClient),qf(t)}createLogoutUrlQueryString(e){const t=new Map;return e.postLogoutRedirectUri&&cT(t,e.postLogoutRedirectUri),e.correlationId&&c2(t,e.correlationId),e.idTokenHint&&uT(t,e.idTokenHint),e.state&&wx(t,e.state),e.logoutHint&&vT(t,e.logoutHint),e.extraQueryParameters&&Ps(t,e.extraQueryParameters),this.config.authOptions.instanceAware&&bx(t),qf(t)}async updateTokenEndpointAuthority(e,t){const n=`https://${e}/${this.authority.tenant}/`,a=await zx(n,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=a}}const Q_=300;class L_{constructor(e,t){this.config=y2(e),this.logger=new Ml(this.config.loggerOptions,$p,ld),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}async acquireToken(e,t){const n=ls(),a=await Ke(this.executeTokenRequest.bind(this),A_,this.logger,this.performanceClient,e.correlationId)(e,this.authority),s=a.headers?.[si.X_MS_REQUEST_ID],l=new kc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.performanceClient,this.config.serializableCache,this.config.persistencePlugin);return l.validateTokenResponse(a.body,e.correlationId),Ke(l.handleServerTokenResponse.bind(l),b2,this.logger,this.performanceClient,e.correlationId)(a.body,this.authority,n,e,t,void 0,void 0,!0,e.forceCache,s)}async acquireTokenByRefreshToken(e,t){if(!e)throw An(RF);if(!e.account)throw tt(dx);if(this.cacheManager.isAppMetadataFOCI(e.account.environment,e.correlationId))try{return await Ke(this.acquireTokenWithCachedRefreshToken.bind(this),Gm,this.logger,this.performanceClient,e.correlationId)(e,!0,t)}catch(a){const s=a instanceof os&&a.errorCode===tw,l=a instanceof zc&&a.errorCode===qI&&a.subError===YI;if(s||l)return Ke(this.acquireTokenWithCachedRefreshToken.bind(this),Gm,this.logger,this.performanceClient,e.correlationId)(e,!1,t);throw a}return Ke(this.acquireTokenWithCachedRefreshToken.bind(this),Gm,this.logger,this.performanceClient,e.correlationId)(e,!1,t)}async acquireTokenWithCachedRefreshToken(e,t,n){const a=as(this.cacheManager.getRefreshToken.bind(this.cacheManager),p_,this.logger,this.performanceClient,e.correlationId)(e.account,t,e.correlationId,void 0);if(!a)throw bp(tw);if(a.expiresOn){const l=e.refreshTokenExpirationOffsetSeconds||Q_;if(this.performanceClient?.addFields({cacheRtExpiresOnSeconds:Number(a.expiresOn),rtOffsetSeconds:l},e.correlationId),Ep(a.expiresOn,l))throw bp(Ox)}const s={...e,refreshToken:a.secret,authenticationScheme:e.authenticationScheme||MA.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:is.HOME_ACCOUNT_ID}};try{return await Ke(this.acquireToken.bind(this),n_,this.logger,this.performanceClient,e.correlationId)(s,n)}catch(l){if(l instanceof os&&l.subError===B2){this.logger.verbose("1pg3ap",e.correlationId);const c=this.cacheManager.generateCredentialKey(a);this.cacheManager.removeRefreshToken(c,e.correlationId)}throw l}}async executeTokenRequest(e,t){const n=jx(e,this.config.authOptions.clientId,this.config.authOptions.redirectUri,this.performanceClient),a=QA.appendQueryString(t.tokenEndpoint,n),s=await Ke(this.createTokenRequestBody.bind(this),r_,this.logger,this.performanceClient,e.correlationId)(e),l=Px(this.logger,this.config.systemOptions.preventCorsPreflight,e.ccsCredential),c=t0(this.config.authOptions.clientId,e);return Ke(Kx,e_,this.logger,this.performanceClient,e.correlationId)(a,s,l,c,e.correlationId,this.cacheManager,this.networkClient,this.logger,this.performanceClient,this.serverTelemetryManager)}async createTokenRequestBody(e){const t=new Map;if(s2(t,e.embeddedClientId||e.extraParameters?.[Oc]||this.config.authOptions.clientId),e.redirectUri&&o2(t,e.redirectUri),a2(t,e.scopes,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),Cx(t,$E.REFRESH_TOKEN_GRANT),d2(t),u2(t,this.config.libraryInfo),h2(t,this.config.telemetry.application),Sx(t),this.serverTelemetryManager&&!Lx(this.config)&&xx(t,this.serverTelemetryManager),pT(t,e.refreshToken),this.config.clientCredentials.clientSecret&&vx(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const n=this.config.clientCredentials.clientAssertion;yx(t,await Mx(n.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),Bx(t,n.assertionType)}if(e.authenticationScheme===MA.POP){const n=new mh(this.cryptoUtils,this.performanceClient);let a;e.popKid?a=this.cryptoUtils.encodeKid(e.popKid):a=(await Ke(n.generateCnf.bind(n),ud,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString,g2(t,a)}else if(e.authenticationScheme===MA.SSH)if(e.sshJwk)Ex(t,e.sshJwk);else throw An(r2);if((!Ea.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&l2(t,e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case is.HOME_ACCOUNT_ID:try{const n=ah(e.ccsCredential.credential);_f(t,n)}catch{this.logger.verbose("1qhtee",e.correlationId)}break;case is.UPN:wp(t,e.ccsCredential.credential);break}return e.embeddedClientId&&Zp(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.extraParameters&&Ps(t,{...e.extraParameters}),Wp(t,e.correlationId,this.performanceClient),qf(t)}}class O_{constructor(e,t){this.config=y2(e),this.logger=new Ml(this.config.loggerOptions,$p,ld),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}async acquireCachedToken(e){let t=yc.NOT_APPLICABLE;if(e.forceRefresh||!Ea.isEmptyObj(e.claims))throw this.setCacheOutcome(yc.FORCE_REFRESH_OR_CLAIMS,e.correlationId),tt(Ic);if(!e.account)throw tt(dx);const n=e.account.tenantId||__(e.authority),a=this.cacheManager.getTokenKeys(),s=this.cacheManager.getAccessToken(e.account,e,a,n);if(s){if(ZT(s.cachedAt)||Ep(s.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(yc.CACHED_ACCESS_TOKEN_EXPIRED,e.correlationId),tt(Ic);s.refreshOn&&Ep(s.refreshOn,0)&&(t=yc.PROACTIVELY_REFRESHED)}else throw this.setCacheOutcome(yc.NO_CACHED_ACCESS_TOKEN,e.correlationId),tt(Ic);const l=e.authority||this.authority.getPreferredCache(),c={account:this.cacheManager.getAccount(this.cacheManager.generateAccountKey(e.account),e.correlationId),accessToken:s,idToken:this.cacheManager.getIdToken(e.account,e.correlationId,a,n),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(l,e.correlationId)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await Ke(this.generateResultFromCacheRecord.bind(this),i_,this.logger,this.performanceClient,e.correlationId)(c,e),t]}setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==yc.NOT_APPLICABLE&&this.logger.info("09ingz",t)}async generateResultFromCacheRecord(e,t){let n;if(e.idToken&&(n=Uo(e.idToken.secret,this.config.cryptoInterface.base64Decode)),t.maxAge||t.maxAge===0){const a=n?.auth_time;if(!a)throw tt(fx);Ix(a,t.maxAge)}return kc.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,this.performanceClient,n)}}const R_={sendGetRequestAsync:()=>Promise.reject(tt(iA)),sendPostRequestAsync:()=>Promise.reject(tt(iA))};function k_(A,e,t,n){const a=e.correlationId,s=new Map;s2(s,e.embeddedClientId||e.extraQueryParameters?.[Oc]||A.clientId);const l=[...e.scopes||[],...e.extraScopesToConsent||[]];if(a2(s,l,!0,A.authority.options.OIDCOptions?.defaultScopes),o2(s,e.redirectUri),c2(s,a),oT(s,e.responseMode),d2(s),e.prompt&&(fT(s,e.prompt),n?.addFields({prompt:e.prompt},a)),e.domainHint&&(hT(s,e.domainHint),n?.addFields({domainHintFromRequest:!0},a)),e.prompt!==Ii.SELECT_ACCOUNT)if(e.sid&&e.prompt===Ii.NONE)t.verbose("1tvqyx",e.correlationId),cC(s,e.sid),n?.addFields({sidFromRequest:!0},a);else if(e.account){const c=M_(e.account);let h=P_(e.account);if(h&&e.domainHint&&(t.warning("0wkg3v",e.correlationId),h=null),h){t.verbose("1eyfsw",e.correlationId),dg(s,h),n?.addFields({loginHintFromClaim:!0},a);try{const f=ah(e.account.homeAccountId);_f(s,f)}catch{t.verbose("12ugck",e.correlationId)}}else if(c&&e.prompt===Ii.NONE){t.verbose("1rmd8s",e.correlationId),cC(s,c),n?.addFields({sidFromClaim:!0},a);try{const f=ah(e.account.homeAccountId);_f(s,f)}catch{t.verbose("12ugck",e.correlationId)}}else if(e.loginHint)t.verbose("0y3007",e.correlationId),dg(s,e.loginHint),wp(s,e.loginHint),n?.addFields({loginHintFromRequest:!0},a);else if(e.account.username){t.verbose("02f507",e.correlationId),dg(s,e.account.username),n?.addFields({loginHintFromUpn:!0},a);try{const f=ah(e.account.homeAccountId);_f(s,f)}catch{t.verbose("12ugck",e.correlationId)}}}else e.loginHint&&(t.verbose("0g01ey",e.correlationId),dg(s,e.loginHint),wp(s,e.loginHint),n?.addFields({loginHintFromRequest:!0},a));else t.verbose("169k9v",e.correlationId);return e.nonce&&dT(s,e.nonce),e.state&&wx(s,e.state),(e.claims||A.clientCapabilities&&A.clientCapabilities.length>0)&&l2(s,e.claims,A.clientCapabilities),e.embeddedClientId&&Zp(s,A.clientId,A.redirectUri),A.instanceAware&&(!e.extraQueryParameters||!Object.keys(e.extraQueryParameters).includes(X1))&&bx(s),s}function S2(A,e){const t=qf(e);return QA.appendQueryString(A.authorizationEndpoint,t)}function H_(A,e){if(qx(A,e),!A.code)throw tt(iT);return A}function qx(A,e){if(!A.state||!e)throw A.state?tt(sC,"Cached State"):tt(sC,"Server State");let t,n;try{t=decodeURIComponent(A.state)}catch{throw tt(Vf,A.state)}try{n=decodeURIComponent(e)}catch{throw tt(Vf,A.state)}if(t!==n)throw tt(JF);if(A.error||A.error_description||A.suberror){const a=D_(A);throw kx(A.error,A.error_description,A.suberror)?new os(A.error||"",A.error_description,A.suberror,A.timestamp||"",A.trace_id||"",A.correlation_id||"",A.claims||"",a):new zc(A.error||"",A.error_description,A.suberror,a)}}function D_(A){const e="code=",t=A.error_uri?.lastIndexOf(e);return t&&t>=0?A.error_uri?.substring(t+e.length):void 0}function M_(A){return A.idTokenClaims?.sid||null}function P_(A){return A.loginHint||A.idTokenClaims?.login_hint||null}const Aw="unexpected_error";const xC=",",Yx="|";function j_(A){const{skus:e,libraryName:t,libraryVersion:n,extensionName:a,extensionVersion:s}=A,l=new Map([[0,[t,n]],[2,[a,s]]]);let c=[];if(e?.length){if(c=e.split(xC),c.length<4)return e}else c=Array.from({length:4},()=>Yx);return l.forEach((h,f)=>{h.length===2&&h[0]?.length&&h[1]?.length&&K_({skuArr:c,index:f,skuName:h[0],skuVersion:h[1]})}),c.join(xC)}function K_(A){const{skuArr:e,index:t,skuName:n,skuVersion:a}=A;t>=e.length||(e[t]=[n,a].join(Yx))}class Yf{constructor(e,t){this.cacheOutcome=yc.NOT_APPLICABLE,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||"",this.wrapperVer=e.wrapperVer||"",this.telemetryCacheKey=Ax+tx+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${Hu}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],n=this.getNativeBrokerErrorCode();n?.length&&t.push(`broker_error=${n}`);const a=t.join(Hu),s=this.getRegionDiscoveryFields(),l=[e,s].join(Hu);return[rC,l,a].join(iC)}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=Yf.maxErrorsToSend(e),n=e.failedRequests.slice(0,2*t).join(Hu),a=e.errors.slice(0,t).join(Hu),s=e.errors.length,l=t=MI&&(t.failedRequests.shift(),t.failedRequests.shift(),t.errors.shift()),t.failedRequests.push(this.apiId,this.correlationId),e instanceof Error&&e&&e.toString()?e instanceof en?e.subError?t.errors.push(e.subError):e.errorCode?t.errors.push(e.errorCode):t.errors.push(e.toString()):t.errors.push(e.toString()):t.errors.push(KI),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId),e.cacheHits}getLastRequests(){const e={failedRequests:[],errors:[],cacheHits:0};return this.cacheManager.getServerTelemetry(this.telemetryCacheKey,this.correlationId)||e}clearTelemetryCache(){const e=this.getLastRequests(),t=Yf.maxErrorsToSend(e),n=e.errors.length;if(t===n)this.cacheManager.removeItem(this.telemetryCacheKey,this.correlationId);else{const a={failedRequests:e.failedRequests.slice(t*2),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,a,this.correlationId)}}static maxErrorsToSend(e){let t,n=0,a=0;const s=e.errors.length;for(t=0;ttypeof A=="number"&&A in IC?IC[A]:"unknown";var Mt;(function(A){A.Redirect="redirect",A.Popup="popup",A.Silent="silent",A.None="none"})(Mt||(Mt={}));const Fr={Startup:"startup",Logout:"logout",AcquireToken:"acquireToken",HandleRedirect:"handleRedirect",None:"none"},FC={scopes:yh},Xx="jwk",q_={React:"@azure/msal-react"},nw="msal.db",Y_=1,X_=`${nw}.keys`,ri={Default:0,AccessToken:1,AccessTokenAndRefreshToken:2,RefreshToken:3,RefreshTokenAndNetwork:4,Skip:5},J_=[ri.Default,ri.Skip,ri.RefreshTokenAndNetwork];function mg(A){return encodeURIComponent(Xf(A).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"))}function kl(A){return Jx(A).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Xf(A){return Jx(new TextEncoder().encode(A))}function Jx(A){const e=Array.from(A,t=>String.fromCodePoint(t)).join("");return btoa(e)}const Wx="pkce_not_created",Zx="ear_jwk_empty",W_="ear_jwe_empty",TC="crypto_nonexistent",F2="empty_navigate_uri",Z_="hash_empty_error",T2="no_state_in_hash",$_="hash_does_not_contain_known_properties",$x="unable_to_parse_state",eN="state_interaction_type_mismatch",tN="interaction_in_progress",AN="interaction_in_progress_cancelled",nN="popup_window_error",rN="empty_window_error",rw="user_cancelled",iN="redirect_bridge_empty_response",aN="redirect_in_iframe",sN="block_iframe_reload",oN="block_nested_popups",_2="silent_logout_unsupported",lN="no_account_error",cN="no_token_request_cache_error",uN="unable_to_parse_token_request_cache_error",e4="non_browser_environment",gf="database_not_open",iw="no_network_connectivity",hN="post_request_failed",fN="get_request_failed",_C="failed_to_parse_response",t4="crypto_key_not_found",dN="auth_code_required",gN="auth_code_or_nativeAccountId_required",pN="spa_code_and_nativeAccountId_present",A4="database_unavailable",mN="unable_to_acquire_token_from_native_platform",wN="native_handshake_timeout",vN="native_extension_not_installed",n4="native_connection_not_established",$g="uninitialized_public_client_application",yN="native_prompt_not_supported",BN="invalid_base64_string",CN="invalid_pop_token_request",bN="failed_to_build_headers",EN="failed_to_parse_headers",Vm="failed_to_decrypt_ear_response",xp="timed_out",xN="empty_response";function Zi(A){return new TextDecoder().decode(Nl(A))}function Nl(A){let e=A.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw ut(BN)}const t=atob(e);return Uint8Array.from(t,n=>n.codePointAt(0)||0)}const SN="RSASSA-PKCS1-v1_5",Ch="AES-GCM",r4="HKDF",N2="SHA-256",UN=2048,IN=new Uint8Array([1,0,1]),NC="0123456789abcdef",QC=new Uint32Array(1),Q2="raw",i4="encrypt",L2="decrypt",FN="deriveKey",TN="crypto_subtle_undefined",O2={name:SN,hash:N2,modulusLength:UN,publicExponent:IN};function _N(A){if(!window)throw ut(e4);if(!window.crypto)throw ut(TC);if(!A&&!window.crypto.subtle)throw ut(TC,TN)}async function a4(A){const t=new TextEncoder().encode(A);return window.crypto.subtle.digest(N2,t)}function NN(A){return window.crypto.getRandomValues(A)}function qm(){return window.crypto.getRandomValues(QC),QC[0]}function Hc(){const A=Date.now(),e=qm()*1024+(qm()&1023),t=new Uint8Array(16),n=Math.trunc(e/2**30),a=e&2**30-1,s=qm();t[0]=A/2**40,t[1]=A/2**32,t[2]=A/2**24,t[3]=A/2**16,t[4]=A/2**8,t[5]=A,t[6]=112|n>>>8,t[7]=n,t[8]=128|a>>>24,t[9]=a>>>16,t[10]=a>>>8,t[11]=a,t[12]=s>>>24,t[13]=s>>>16,t[14]=s>>>8,t[15]=s;let l="";for(let c=0;c>>4),l+=NC.charAt(t[c]&15),(c===3||c===5||c===7||c===9)&&(l+="-");return l}async function QN(A,e){return window.crypto.subtle.generateKey(O2,A,e)}async function Ym(A){return window.crypto.subtle.exportKey(Xx,A)}async function LN(A,e,t){return window.crypto.subtle.importKey(Xx,A,O2,e,t)}async function ON(A,e){return window.crypto.subtle.sign(O2,A,e)}async function R2(){const A=await s4(),t={alg:"dir",kty:"oct",k:kl(new Uint8Array(A))};return Xf(JSON.stringify(t))}async function RN(A){const e=Zi(A),n=JSON.parse(e).k,a=Nl(n);return window.crypto.subtle.importKey(Q2,a,Ch,!1,[L2])}async function kN(A,e){const t=e.split(".");if(t.length!==5)throw ut(Vm,"jwe_length");const n=await RN(A).catch(()=>{throw ut(Vm,"import_key")});try{const a=new TextEncoder().encode(t[0]),s=Nl(t[2]),l=Nl(t[3]),c=Nl(t[4]),h=c.byteLength*8,f=new Uint8Array(l.length+c.length);f.set(l),f.set(c,l.length);const g=await window.crypto.subtle.decrypt({name:Ch,iv:s,tagLength:h,additionalData:a},n,f);return new TextDecoder().decode(g)}catch{throw ut(Vm,"decrypt")}}async function s4(){const A=await window.crypto.subtle.generateKey({name:Ch,length:256},!0,[i4,L2]);return window.crypto.subtle.exportKey(Q2,A)}async function LC(A){return window.crypto.subtle.importKey(Q2,A,r4,!1,[FN])}async function o4(A,e,t){return window.crypto.subtle.deriveKey({name:r4,salt:e,hash:N2,info:new TextEncoder().encode(t)},A,{name:Ch,length:256},!1,[i4,L2])}async function HN(A,e,t){const n=new TextEncoder().encode(e),a=window.crypto.getRandomValues(new Uint8Array(16)),s=await o4(A,a,t),l=await window.crypto.subtle.encrypt({name:Ch,iv:new Uint8Array(12)},s,n);return{data:kl(new Uint8Array(l)),nonce:kl(a)}}async function OC(A,e,t,n){const a=Nl(n),s=await o4(A,Nl(e),t),l=await window.crypto.subtle.decrypt({name:Ch,iv:new Uint8Array(12)},s,a);return new TextDecoder().decode(l)}async function DN(A){const e=await a4(A),t=new Uint8Array(e);return kl(t)}class k2 extends en{constructor(e,t){super(e,t),this.name="BrowserConfigurationAuthError",Object.setPrototypeOf(this,k2.prototype)}}function wr(A){return new k2(A,r0(A))}const l4="storage_not_supported",ni="stubbed_public_client_application_called",MN="in_mem_redirect_unavailable";function PN(){const A=window.location.hash,e=window.location.search;let t=!1,n=!1,a="",s;if(A&&A.length>1){const g=A.charAt(0)==="#"?A.substring(1):A,y=new URLSearchParams(g);y.has("state")&&(t=!0,a=g,s=y)}if(e&&e.length>1){const g=e.charAt(0)==="?"?e.substring(1):e,y=new URLSearchParams(g);y.has("state")&&(n=!0,a=g,s=y)}if(t&&n){const g=e.charAt(0)==="?"?e.substring(1):e,y=A.charAt(0)==="#"?A.substring(1):A;a=`${g}${y}`,s=new URLSearchParams(a)}if(!a||!s)throw ut(xN);const l=s.get("state");if(!l)throw ut(T2);const{libraryState:c}=cd(Zi,l),{id:h,meta:f}=c;if(!h||!f)throw ut($x,"missing_library_state");return{params:s,payload:a,urlHash:A,urlQuery:e,hasResponseInHash:t,hasResponseInQuery:n,libraryState:{id:h,meta:f}}}function c4(A){A.location.hash="",typeof A.history.replaceState=="function"&&A.history.replaceState(null,"",`${A.location.origin}${A.location.pathname}${A.location.search}`)}function jN(A){const e=A.split("#");e.shift(),window.location.hash=e.length>0?e.join("#"):""}function i0(){return window.parent!==window}function KN(){if(i0())return!1;try{const{libraryState:A}=PN(),{meta:e}=A;return e.interactionType===Mt.Popup}catch{return!1}}let El=null;function GN(A,e){El&&(A.verbose("18y01k",e),clearTimeout(El.timeoutId),El.channel.close(),El.reject(ut(AN)),El=null)}async function th(A,e,t,n){return new Promise((a,s)=>{e.verbose("1rf6em",n.correlationId);const{libraryState:l}=cd(t.base64Decode,n.state||""),c=new BroadcastChannel(l.id);let h;const f=window.setTimeout(()=>{El=null,c.close(),s(ut(xp,"redirect_bridge_timeout"))},A);El={timeoutId:f,channel:c,reject:s},c.onmessage=g=>{h=g.data.payload,El=null,clearTimeout(f),c.close(),h?a(h):s(ut(iN))}})}function xl(){return typeof window<"u"&&window.location?window.location.href.split("?")[0].split("#")[0]:""}function zN(){const e=new QA(window.location.href).getUrlComponents();return`${e.Protocol}//${e.HostNameAndPort}/`}function VN(){if(vp(window.location.hash)&&i0())throw ut(sN)}function qN(A){if(i0()&&!A)throw ut(aN)}function YN(){if(KN())throw ut(oN)}function u4(){if(typeof window>"u")throw ut(e4)}function h4(A){if(!A)throw ut($g)}function H2(A){u4(),VN(),YN(),h4(A)}function RC(A,e){if(H2(A),qN(e.system.allowRedirectInIframe),e.cache.cacheLocation===xa.MemoryStorage)throw wr(MN)}function f4(A){const e=document.createElement("link");e.rel="preconnect",e.href=new URL(A).origin,e.crossOrigin="anonymous",document.head.appendChild(e),window.setTimeout(()=>{try{document.head.removeChild(e)}catch{}},1e4)}function aw(){return Hc()}const XN="acquireTokenFromCache",JN="acquireTokenByRefreshToken",WN="acquireTokenSilentAsync",ZN="cryptoOptsGetPublicKeyThumbprint",$N="cryptoOptsSignJwt",eQ="silentCacheClientAcquireToken",tQ="silentIframeClientAcquireToken",AQ="awaitConcurrentIframe",nQ="silentRefreshClientAcquireToken",Tc="standardInteractionClientGetDiscoveredAuthority",d4="nativeInteractionClientAcquireToken",rQ="refreshTokenClientAcquireTokenByRefreshToken",kC="acquireTokenBySilentIframe",D2="initializeBaseRequest",iQ="initializeSilentRequest",aQ="initializeCache",HC="silentIframeClientTokenHelper",Xm="silentHandlerInitiateAuthRequest",Sp="silentHandlerMonitorIframeForHash",sQ="silentHandlerLoadFrameSync",Ql="standardInteractionClientCreateAuthCodeClient",a0="standardInteractionClientGetClientConfiguration",s0="standardInteractionClientInitializeAuthorizationRequest",oQ="silentFlowClientAcquireCachedToken",lQ="getStandardParams",cQ="handleCodeResponse",M2="handleResponseEar",g4="handleResponsePlatformBroker",sh="handleResponseCode",uQ="authClientAcquireToken",Nf="deserializeResponse",hQ="authorityFactoryCreateDiscoveredInstance",fQ="acquireTokenByCodeAsync",dQ="handleRedirectPromise",gQ="handleNativeRedirectPromise",pQ="nativeMessageHandlerHandshake",mQ="importExistingCache",Dc="generatePkceCodes",wQ="generateCodeVerifier",vQ="generateCodeChallengeFromVerifier",yQ="sha256Digest",BQ="getRandomValues",DC="generateHKDF",CQ="generateBaseKey",bQ="base64Decode",EQ="urlEncodeArr",xQ="encrypt",MC="decrypt",P2="generateEarKey",SQ="decryptEarResponse";class UQ{constructor(){this.dbName=nw,this.version=Y_,this.tableName=X_,this.dbOpen=!1}async open(){return new Promise((e,t)=>{const n=window.indexedDB.open(this.dbName,this.version);n.addEventListener("upgradeneeded",a=>{a.target.result.createObjectStore(this.tableName)}),n.addEventListener("success",a=>{const s=a;this.db=s.target.result,this.dbOpen=!0,e()}),n.addEventListener("error",()=>t(ut(A4)))})}closeConnection(){const e=this.db;e&&this.dbOpen&&(e.close(),this.dbOpen=!1)}async validateDbIsOpen(){if(!this.dbOpen)return this.open()}async getItem(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(ut(gf));const l=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).get(e);l.addEventListener("success",c=>{const h=c;this.closeConnection(),t(h.target.result)}),l.addEventListener("error",c=>{this.closeConnection(),n(c)})})}async setItem(e,t){return await this.validateDbIsOpen(),new Promise((n,a)=>{if(!this.db)return a(ut(gf));const c=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).put(t,e);c.addEventListener("success",()=>{this.closeConnection(),n()}),c.addEventListener("error",h=>{this.closeConnection(),a(h)})})}async removeItem(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(ut(gf));const l=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).delete(e);l.addEventListener("success",()=>{this.closeConnection(),t()}),l.addEventListener("error",c=>{this.closeConnection(),n(c)})})}async getKeys(){return await this.validateDbIsOpen(),new Promise((e,t)=>{if(!this.db)return t(ut(gf));const s=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).getAllKeys();s.addEventListener("success",l=>{const c=l;this.closeConnection(),e(c.target.result)}),s.addEventListener("error",l=>{this.closeConnection(),t(l)})})}async containsKey(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(ut(gf));const l=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).count(e);l.addEventListener("success",c=>{const h=c;this.closeConnection(),t(h.target.result===1)}),l.addEventListener("error",c=>{this.closeConnection(),n(c)})})}async deleteDatabase(){return this.db&&this.dbOpen&&this.closeConnection(),new Promise((e,t)=>{const n=window.indexedDB.deleteDatabase(nw),a=setTimeout(()=>t(!1),200);n.addEventListener("success",()=>(clearTimeout(a),e(!0))),n.addEventListener("blocked",()=>(clearTimeout(a),e(!0))),n.addEventListener("error",()=>(clearTimeout(a),t(!1)))})}}class o0{constructor(){this.cache=new Map}async initialize(){}getItem(e){return this.cache.get(e)||null}getUserData(e){return this.getItem(e)}setItem(e,t){this.cache.set(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){this.cache.delete(e)}getKeys(){const e=[];return this.cache.forEach((t,n)=>{e.push(n)}),e}containsKey(e){return this.cache.has(e)}clear(){this.cache.clear()}decryptData(){return Promise.resolve(null)}}class IQ{constructor(e){this.inMemoryCache=new o0,this.indexedDBCache=new UQ,this.logger=e}handleDatabaseAccessError(e,t){if(e instanceof hd&&e.errorCode===A4)this.logger.error("1wx7zz",t);else throw e}async getItem(e,t){const n=this.inMemoryCache.getItem(e);if(!n)try{return this.logger.verbose("0naxpl",t),await this.indexedDBCache.getItem(e)}catch(a){this.handleDatabaseAccessError(a,t)}return n}async setItem(e,t,n){this.inMemoryCache.setItem(e,t);try{await this.indexedDBCache.setItem(e,t)}catch(a){this.handleDatabaseAccessError(a,n)}}async removeItem(e,t){this.inMemoryCache.removeItem(e);try{await this.indexedDBCache.removeItem(e)}catch(n){this.handleDatabaseAccessError(n,t)}}async getKeys(e){const t=this.inMemoryCache.getKeys();if(t.length===0)try{return this.logger.verbose("1iqrbq",e),await this.indexedDBCache.getKeys()}catch(n){this.handleDatabaseAccessError(n,e)}return t}async containsKey(e,t){const n=this.inMemoryCache.containsKey(e);if(!n)try{return this.logger.verbose("03zl2j",t),await this.indexedDBCache.containsKey(e)}catch(a){this.handleDatabaseAccessError(a,t)}return n}clearInMemory(e){this.logger.verbose("03r21p",e),this.inMemoryCache.clear(),this.logger.verbose("0uksk1",e)}async clearPersistent(e){try{this.logger.verbose("0rdqut",e);const t=await this.indexedDBCache.deleteDatabase();return t&&this.logger.verbose("149ouc",e),t}catch(t){return this.handleDatabaseAccessError(t,e),!1}}}class _o{constructor(e,t,n){this.logger=e,_N(n??!1),this.cache=new IQ(this.logger),this.performanceClient=t}createNewGuid(){return Hc()}base64Encode(e){return Xf(e)}base64Decode(e){return Zi(e)}base64UrlEncode(e){return mg(e)}encodeKid(e){return this.base64UrlEncode(JSON.stringify({kid:e}))}async getPublicKeyThumbprint(e){const t=this.performanceClient?.startMeasurement(ZN,e.correlationId),n=await QN(_o.EXTRACTABLE,_o.POP_KEY_USAGES),a=await Ym(n.publicKey),s={e:a.e,kty:a.kty,n:a.n},l=PC(s),c=await this.hashString(l),h=await Ym(n.privateKey),f=await LN(h,!1,["sign"]);return await this.cache.setItem(c,{privateKey:f,publicKey:n.publicKey,requestMethod:e.resourceRequestMethod,requestUri:e.resourceRequestUri},e.correlationId),t&&t.end({success:!0}),c}async removeTokenBindingKey(e,t){if(await this.cache.removeItem(e,t),await this.cache.containsKey(e,t))throw tt(aT)}async clearKeystore(e){this.cache.clearInMemory(e);try{return await this.cache.clearPersistent(e),!0}catch(t){return t instanceof Error?this.logger.error("1owpn8",e):this.logger.error("0yrmwo",e),!1}}async signJwt(e,t,n,a){const s=this.performanceClient?.startMeasurement($N,a),l=await this.cache.getItem(t,a||"");if(!l)throw ut(t4);const c=await Ym(l.publicKey),h=PC(c),f=mg(JSON.stringify({kid:t})),g=I2.getShrHeaderString({...n?.header,alg:c.alg,kid:f}),y=mg(g);e.cnf={jwk:JSON.parse(h)};const C=mg(JSON.stringify(e)),v=`${y}.${C}`,x=new TextEncoder().encode(v),_=await ON(l.privateKey,x),T=kl(new Uint8Array(_)),k=`${v}.${T}`;return s&&s.end({success:!0}),k}async hashString(e){return DN(e)}}_o.POP_KEY_USAGES=["sign","verify"];_o.EXTRACTABLE=!0;function PC(A){return JSON.stringify(A,Object.keys(A).sort())}const FQ="acquireTokenSilent",TQ="acquireTokenByCode",_Q="acquireTokenPopup",NQ="acquireTokenPreRedirect",Jm="acquireTokenRedirect",QQ="ssoSilent",LQ="initializeClientApplication",OQ="localStorageUpdated";const Nr="msal",j2="browser",jC="|",Kr=2,ep=2,RQ=`${Nr}.${j2}.log.level`,kQ=`${Nr}.${j2}.log.pii`,HQ=`${Nr}.${j2}.platform.auth.dom`,KC=`${Nr}.version`,GC="account.keys",zC="token.keys";function oh(A=ep){return A<1?`${Nr}.${GC}`:`${Nr}.${A}.${GC}`}function lh(A,e=Kr){return e<1?`${Nr}.${zC}.${A}`:`${Nr}.${e}.${zC}.${A}`}const DQ=1440*60*1e3,sw={Lax:"Lax",None:"None"};class p4{initialize(){return Promise.resolve()}getItem(e){const t=`${encodeURIComponent(e)}`,n=document.cookie.split(";");for(let a=0;a{const a=decodeURIComponent(n).trim().split("=");t.push(a[0])}),t}containsKey(e){return this.getKeys().includes(e)}decryptData(){return Promise.resolve(null)}}function MQ(A){const e=new Date;return new Date(e.getTime()+A*DQ).toUTCString()}function vl(A,e){const t=A.getItem(oh(e));return t?JSON.parse(t):[]}function ns(A,e,t){const n=e.getItem(lh(A,t));if(n){const a=JSON.parse(n);if(a&&a.hasOwnProperty("idToken")&&a.hasOwnProperty("accessToken")&&a.hasOwnProperty("refreshToken"))return a}return{idToken:[],accessToken:[],refreshToken:[]}}function tp(A){return A.hasOwnProperty("id")&&A.hasOwnProperty("nonce")&&A.hasOwnProperty("data")}const VC="msal.cache.encryption",PQ="msal.broadcast.cache";class jQ{constructor(e,t,n){if(!window.localStorage)throw wr(l4);this.memoryStorage=new o0,this.initialized=!1,this.clientId=e,this.logger=t,this.performanceClient=n,this.broadcast=new BroadcastChannel(PQ)}async initialize(e){const t=new p4,n=t.getItem(VC);let a={key:"",id:""};if(n)try{a=JSON.parse(n)}catch{}if(a.key&&a.id){const s=as(Nl,bQ,this.logger,this.performanceClient,e)(a.key);this.encryptionCookie={id:a.id,key:await Ke(LC,DC,this.logger,this.performanceClient,e)(s)}}else{const s=Hc(),l=await Ke(s4,CQ,this.logger,this.performanceClient,e)(),c=as(kl,EQ,this.logger,this.performanceClient,e)(new Uint8Array(l));this.encryptionCookie={id:s,key:await Ke(LC,DC,this.logger,this.performanceClient,e)(l)};const h={id:s,key:c};t.setItem(VC,JSON.stringify(h),0,!0,sw.None)}await Ke(this.importExistingCache.bind(this),mQ,this.logger,this.performanceClient,e)(e),this.broadcast.addEventListener("message",s=>{this.updateCache(s,e)}),this.initialized=!0}getItem(e){return window.localStorage.getItem(e)}getUserData(e){if(!this.initialized)throw ut($g);return this.memoryStorage.getItem(e)}async decryptData(e,t,n){if(!this.initialized||!this.encryptionCookie)throw ut($g);if(t.id!==this.encryptionCookie.id)return this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},n),null;const a=await Ke(OC,MC,this.logger,this.performanceClient,n)(this.encryptionCookie.key,t.nonce,this.getContext(e),t.data);if(!a)return null;try{return{...JSON.parse(a),lastUpdatedAt:t.lastUpdatedAt}}catch{return this.performanceClient.incrementFields({encryptedCacheCorruptionCount:1},n),null}}setItem(e,t){window.localStorage.setItem(e,t)}async setUserData(e,t,n,a,s){if(!this.initialized||!this.encryptionCookie)throw ut($g);if(s)this.setItem(e,t);else{const{data:l,nonce:c}=await Ke(HN,xQ,this.logger,this.performanceClient,n)(this.encryptionCookie.key,t,this.getContext(e)),h={id:this.encryptionCookie.id,nonce:c,data:l,lastUpdatedAt:a};this.setItem(e,JSON.stringify(h))}this.memoryStorage.setItem(e,t),this.broadcast.postMessage({key:e,value:t,context:this.getContext(e)})}removeItem(e){this.memoryStorage.containsKey(e)&&(this.memoryStorage.removeItem(e),this.broadcast.postMessage({key:e,value:null,context:this.getContext(e)})),window.localStorage.removeItem(e)}getKeys(){return Object.keys(window.localStorage)}containsKey(e){return window.localStorage.hasOwnProperty(e)}clear(){this.memoryStorage.clear(),vl(this).forEach(n=>this.removeItem(n));const t=ns(this.clientId,this);t.idToken.forEach(n=>this.removeItem(n)),t.accessToken.forEach(n=>this.removeItem(n)),t.refreshToken.forEach(n=>this.removeItem(n)),this.getKeys().forEach(n=>{(n.startsWith(Nr)||n.indexOf(this.clientId)!==-1)&&this.removeItem(n)})}async importExistingCache(e){if(!this.encryptionCookie)return;let t=vl(this);t=await this.importArray(t,e),t.length?this.setItem(oh(),JSON.stringify(t)):this.removeItem(oh());const n=ns(this.clientId,this);n.idToken=await this.importArray(n.idToken,e),n.accessToken=await this.importArray(n.accessToken,e),n.refreshToken=await this.importArray(n.refreshToken,e),n.idToken.length||n.accessToken.length||n.refreshToken.length?this.setItem(lh(this.clientId),JSON.stringify(n)):this.removeItem(lh(this.clientId))}async getItemFromEncryptedCache(e,t){if(!this.encryptionCookie)return null;const n=this.getItem(e);if(!n)return null;let a;try{a=JSON.parse(n)}catch{return null}return tp(a)?a.id!==this.encryptionCookie.id?(this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},t),null):(this.performanceClient.incrementFields({encryptedCacheCount:1},t),Ke(OC,MC,this.logger,this.performanceClient,t)(this.encryptionCookie.key,a.nonce,this.getContext(e),a.data)):(this.performanceClient.incrementFields({unencryptedCacheCount:1},t),n)}async importArray(e,t){const n=[],a=[];return e.forEach(s=>{const l=this.getItemFromEncryptedCache(s,t).then(c=>{c?(this.memoryStorage.setItem(s,c),n.push(s)):this.removeItem(s)});a.push(l)}),await Promise.all(a),n}getContext(e){let t="";return e.includes(this.clientId)&&(t=this.clientId),t}updateCache(e,t){this.logger.trace("17cxcm",t);const n=this.performanceClient.startMeasurement(OQ);n.add({isBackground:!0});const{key:a,value:s,context:l}=e.data;if(!a){this.logger.error("0e10qr",t),n.end({success:!1,errorCode:"noKey"});return}if(l&&l!==this.clientId){this.logger.trace("04rtdy",t),n.end({success:!1,errorCode:"contextMismatch"});return}s?(this.memoryStorage.setItem(a,s),this.logger.verbose("1vzsgt",t)):(this.memoryStorage.removeItem(a),this.logger.verbose("04ypih",t)),n.end({success:!0})}}class KQ{constructor(){if(!window.sessionStorage)throw wr(l4)}async initialize(){}getItem(e){return window.sessionStorage.getItem(e)}getUserData(e){return this.getItem(e)}setItem(e,t){window.sessionStorage.setItem(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){window.sessionStorage.removeItem(e)}getKeys(){return Object.keys(window.sessionStorage)}containsKey(e){return window.sessionStorage.hasOwnProperty(e)}decryptData(){return Promise.resolve(null)}}const Rt={INITIALIZE_START:"msal:initializeStart",INITIALIZE_END:"msal:initializeEnd",ACTIVE_ACCOUNT_CHANGED:"msal:activeAccountChanged",LOGIN_SUCCESS:"msal:loginSuccess",ACQUIRE_TOKEN_START:"msal:acquireTokenStart",BROKERED_REQUEST_START:"msal:brokeredRequestStart",ACQUIRE_TOKEN_SUCCESS:"msal:acquireTokenSuccess",BROKERED_REQUEST_SUCCESS:"msal:brokeredRequestSuccess",ACQUIRE_TOKEN_FAILURE:"msal:acquireTokenFailure",BROKERED_REQUEST_FAILURE:"msal:brokeredRequestFailure",ACQUIRE_TOKEN_NETWORK_START:"msal:acquireTokenFromNetworkStart",HANDLE_REDIRECT_START:"msal:handleRedirectStart",HANDLE_REDIRECT_END:"msal:handleRedirectEnd",POPUP_OPENED:"msal:popupOpened",LOGOUT_START:"msal:logoutStart",LOGOUT_SUCCESS:"msal:logoutSuccess",LOGOUT_FAILURE:"msal:logoutFailure",LOGOUT_END:"msal:logoutEnd",RESTORE_FROM_BFCACHE:"msal:restoreFromBFCache",BROKER_CONNECTION_ESTABLISHED:"msal:brokerConnectionEstablished"};const GQ="@azure/msal-browser",Mc="5.1.0";function fl(A,e){const t=A.indexOf(e);t>-1&&A.splice(t,1)}class ow extends ew{constructor(e,t,n,a,s,l,c){super(e,n,a,s,c),this.cacheConfig=t,this.logger=a,this.internalStorage=new o0,this.browserStorage=qC(e,t.cacheLocation,a,s),this.temporaryCacheStorage=qC(e,xa.SessionStorage,a,s),this.cookieStorage=new p4,this.eventHandler=l}async initialize(e){this.performanceClient.addFields({cacheLocation:this.cacheConfig.cacheLocation,cacheRetentionDays:this.cacheConfig.cacheRetentionDays},e),await this.browserStorage.initialize(e),await this.migrateExistingCache(e),this.trackVersionChanges(e)}async migrateExistingCache(e){let t=vl(this.browserStorage),n=ns(this.clientId,this.browserStorage);this.performanceClient.addFields({preMigrateAcntCount:t.length,preMigrateATCount:n.accessToken.length,preMigrateITCount:n.idToken.length,preMigrateRTCount:n.refreshToken.length},e);for(let s=0;sh.includes(l)).forEach(h=>{this.browserStorage.removeItem(h),fl(c.idToken,h)}),[...c.accessToken].filter(h=>h.includes(l)).forEach(h=>{this.browserStorage.removeItem(h),fl(c.accessToken,h)}),[...c.refreshToken].filter(h=>h.includes(l)).forEach(h=>{this.browserStorage.removeItem(h),fl(c.refreshToken,h)}),this.setTokenKeys(c,a,n)}this.performanceClient.incrementFields({expiredAcntRemovedCount:1},a),this.browserStorage.removeItem(e)}getKMSIValues(){const e={},t=this.getTokenKeys().idToken;for(const n of t){const a=this.browserStorage.getUserData(n);if(a){const s=JSON.parse(a),l=Uo(s.secret,Zi);l&&(e[s.homeAccountId]=Fc(l))}}return e}async migrateIdTokens(e,t,n){const a=ns(this.clientId,this.browserStorage,e);if(a.idToken.length===0)return;const s=ns(this.clientId,this.browserStorage,Kr),l=vl(this.browserStorage),c=vl(this.browserStorage,t);for(const h of[...a.idToken]){this.performanceClient.incrementFields({oldITCount:1},n);const f=await this.updateOldEntry(h,n);if(!f){fl(a.idToken,h);continue}const g=l.find(k=>k.includes(f.homeAccountId)),y=c.find(k=>k.includes(f.homeAccountId));let C=null;if(g)C=this.getAccount(g,n);else if(y){const k=this.browserStorage.getItem(y),z=this.validateAndParseJson(k||"");C=z&&tp(z)?await this.browserStorage.decryptData(y,z,n):z}if(!C){this.performanceClient.incrementFields({skipITMigrateCount:1},n);continue}const v=Uo(f.secret,Zi),I=this.generateCredentialKey(f),x=this.getIdTokenCredential(I,n),_=Object.keys(v).includes("signin_state"),T=x&&Object.keys(Uo(x.secret,Zi)||{}).includes("signin_state");if(!x||f.lastUpdatedAt>x.lastUpdatedAt&&(_||!T)){const k=C.tenantProfiles||[],z=v2(v)||C.realm;if(z&&!k.find(le=>le.tenantId===z)){const le=Bh(C.homeAccountId,C.localAccountId,z,v);k.push(le)}C.tenantProfiles=k;const H=this.generateAccountKey(Rc(C)),re=Fc(v);await this.setUserData(H,JSON.stringify(C),n,C.lastUpdatedAt,re),l.includes(H)||l.push(H),await this.setUserData(I,JSON.stringify(f),n,f.lastUpdatedAt,re),this.performanceClient.incrementFields({migratedITCount:1},n),s.idToken.push(I)}}this.setTokenKeys(a,n,e),this.setTokenKeys(s,n),this.setAccountKeys(l,n)}async migrateAccessTokens(e,t,n){const a=ns(this.clientId,this.browserStorage,e);if(a.accessToken.length===0)return;const s=ns(this.clientId,this.browserStorage,Kr);for(const l of[...a.accessToken]){this.performanceClient.incrementFields({oldATCount:1},n);const c=await this.updateOldEntry(l,n);if(!c){fl(a.accessToken,l);continue}if(!(c.homeAccountId in t)){this.performanceClient.incrementFields({skipATMigrateCount:1},n);continue}const h=this.generateCredentialKey(c),f=t[c.homeAccountId];if(!s.accessToken.includes(h))await this.setUserData(h,JSON.stringify(c),n,c.lastUpdatedAt,f),this.performanceClient.incrementFields({migratedATCount:1},n),s.accessToken.push(h);else{const g=this.getAccessTokenCredential(h,n);(!g||c.lastUpdatedAt>g.lastUpdatedAt)&&(await this.setUserData(h,JSON.stringify(c),n,c.lastUpdatedAt,f),this.performanceClient.incrementFields({migratedATCount:1},n))}}this.setTokenKeys(a,n,e),this.setTokenKeys(s,n)}async migrateRefreshTokens(e,t,n){const a=ns(this.clientId,this.browserStorage,e);if(a.refreshToken.length===0)return;const s=ns(this.clientId,this.browserStorage,Kr);for(const l of[...a.refreshToken]){this.performanceClient.incrementFields({oldRTCount:1},n);const c=await this.updateOldEntry(l,n);if(!c){fl(a.refreshToken,l);continue}if(!(c.homeAccountId in t)){this.performanceClient.incrementFields({skipRTMigrateCount:1},n);continue}const h=this.generateCredentialKey(c),f=t[c.homeAccountId];if(!s.refreshToken.includes(h))await this.setUserData(h,JSON.stringify(c),n,c.lastUpdatedAt,f),this.performanceClient.incrementFields({migratedRTCount:1},n),s.refreshToken.push(h);else{const g=this.getRefreshTokenCredential(h,n);(!g||c.lastUpdatedAt>g.lastUpdatedAt)&&(await this.setUserData(h,JSON.stringify(c),n,c.lastUpdatedAt,f),this.performanceClient.incrementFields({migratedRTCount:1},n))}}this.setTokenKeys(a,n,e),this.setTokenKeys(s,n)}trackVersionChanges(e){const t=this.browserStorage.getItem(KC);t&&(this.logger.info("1wuc87",e),this.performanceClient.addFields({previousLibraryVersion:t},e)),t!==Mc&&this.setItem(KC,Mc,e)}validateAndParseJson(e){if(!e)return null;try{const t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}setItem(e,t,n){const a=new Array(Kr+1).fill(0),s=[],l=20;for(let c=0;c<=l;c++)try{if(this.browserStorage.setItem(e,t),c>0)for(let h=0;h<=Kr;h++){const f=a.slice(0,h).reduce((y,C)=>y+C,0);if(f>=c)break;const g=c>f+a[h]?f+a[h]:c;c>f&&a[h]>0&&this.removeAccessTokenKeys(s.slice(f,g),n,h)}break}catch(h){const f=$1(h);if(f.errorCode===Z1&&c0)for(let g=0;g<=Kr;g++){const y=l.slice(0,g).reduce((v,I)=>v+I,0);if(y>=f)break;const C=f>y+l[g]?y+l[g]:f;f>y&&l[g]>0&&this.removeAccessTokenKeys(c.slice(y,C),n,g)}break}catch(g){const y=$1(g);if(y.errorCode===Z1&&f-1?(n.splice(a,1),this.setAccountKeys(n,t)):this.logger.trace("1dytu2",t)}removeAccount(e,t){const n=this.getActiveAccount(t);n?.homeAccountId===e.homeAccountId&&n?.environment===e.environment&&this.setActiveAccount(null,t),super.removeAccount(e,t),this.removeAccountKeyFromMap(this.generateAccountKey(e),t),this.browserStorage.getKeys().forEach(a=>{a.includes(e.homeAccountId)&&a.includes(e.environment)&&this.browserStorage.removeItem(a)})}removeIdToken(e,t){super.removeIdToken(e,t);const n=this.getTokenKeys(),a=n.idToken.indexOf(e);a>-1&&(this.logger.info("05udv9",t),n.idToken.splice(a,1),this.setTokenKeys(n,t))}removeAccessToken(e,t,n=!0){super.removeAccessToken(e,t),n&&this.removeAccessTokenKeys([e],t)}removeAccessTokenKeys(e,t,n=Kr){this.logger.trace("17o18n",t);const a=this.getTokenKeys(n);let s=0;if(e.forEach(l=>{const c=a.accessToken.indexOf(l);c>-1&&(a.accessToken.splice(c,1),s++)}),s>0){this.logger.info("15i5d5",t),this.setTokenKeys(a,t,n);return}}removeRefreshToken(e,t){super.removeRefreshToken(e,t);const n=this.getTokenKeys(),a=n.refreshToken.indexOf(e);a>-1&&(this.logger.info("1f4fq3",t),n.refreshToken.splice(a,1),this.setTokenKeys(n,t))}getTokenKeys(e=Kr){return ns(this.clientId,this.browserStorage,e)}setTokenKeys(e,t,n=Kr){if(e.idToken.length===0&&e.accessToken.length===0&&e.refreshToken.length===0){this.removeItem(lh(this.clientId,n));return}else this.setItem(lh(this.clientId,n),JSON.stringify(e),t)}getIdTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("1jukz6",t),this.removeIdToken(e,t),null;const a=this.validateAndParseJson(n);return!a||!B_(a)?(this.logger.trace("1jukz6",t),null):(this.logger.trace("01ju66",t),a)}async setIdTokenCredential(e,t,n){this.logger.trace("13hjll",t);const a=this.generateCredentialKey(e),s=Date.now().toString();e.lastUpdatedAt=s,await this.setUserData(a,JSON.stringify(e),t,s,n);const l=this.getTokenKeys();l.idToken.indexOf(a)===-1&&(this.logger.info("07jy92",t),l.idToken.push(a),this.setTokenKeys(l,t))}getAccessTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("0bqvx8",t),this.removeAccessTokenKeys([e],t),null;const a=this.validateAndParseJson(n);return!a||!BC(a)?(this.logger.trace("0bqvx8",t),null):(this.logger.trace("1o81rl",t),a)}async setAccessTokenCredential(e,t,n){this.logger.trace("1pondb",t);const a=this.generateCredentialKey(e),s=Date.now().toString();e.lastUpdatedAt=s,await this.setUserData(a,JSON.stringify(e),t,s,n);const l=this.getTokenKeys(),c=l.accessToken.indexOf(a);c!==-1&&l.accessToken.splice(c,1),this.logger.trace("1onhey",t),l.accessToken.push(a),this.setTokenKeys(l,t)}getRefreshTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("0jlizt",t),this.removeRefreshToken(e,t),null;const a=this.validateAndParseJson(n);return!a||!CC(a)?(this.logger.trace("0jlizt",t),null):(this.logger.trace("0nokxi",t),a)}async setRefreshTokenCredential(e,t,n){this.logger.trace("0tcg8d",t);const a=this.generateCredentialKey(e),s=Date.now().toString();e.lastUpdatedAt=s,await this.setUserData(a,JSON.stringify(e),t,s,n);const l=this.getTokenKeys();l.refreshToken.indexOf(a)===-1&&(this.logger.info("0eckjs",t),l.refreshToken.push(a),this.setTokenKeys(l,t))}getAppMetadata(e,t){const n=this.browserStorage.getItem(e);if(!n)return this.logger.trace("1q101h",t),null;const a=this.validateAndParseJson(n);return!a||!x_(e,a)?(this.logger.trace("1q101h",t),null):(this.logger.trace("19pvg2",t),a)}setAppMetadata(e,t){this.logger.trace("0cyma6",t);const n=E_(e);this.setItem(n,JSON.stringify(e),t)}getServerTelemetry(e,t){const n=this.browserStorage.getItem(e);if(!n)return this.logger.trace("0jk19c",t),null;const a=this.validateAndParseJson(n);return!a||!C_(e,a)?(this.logger.trace("0jk19c",t),null):(this.logger.trace("12jguk",t),a)}setServerTelemetry(e,t,n){this.logger.trace("1poh61",n),this.setItem(e,JSON.stringify(t),n)}getAuthorityMetadata(e,t){const n=this.internalStorage.getItem(e);if(!n)return this.logger.trace("1r39oe",t),null;const a=this.validateAndParseJson(n);return a&&S_(e,a)?(this.logger.trace("1ohvk3",t),a):null}getAuthorityMetadataKeys(){return this.internalStorage.getKeys().filter(t=>this.isAuthorityMetadata(t))}setWrapperMetadata(e,t){this.internalStorage.setItem(pg.WRAPPER_SKU,e),this.internalStorage.setItem(pg.WRAPPER_VER,t)}getWrapperMetadata(){const e=this.internalStorage.getItem(pg.WRAPPER_SKU)||"",t=this.internalStorage.getItem(pg.WRAPPER_VER)||"";return[e,t]}setAuthorityMetadata(e,t,n){this.logger.trace("07w8n2",n),this.internalStorage.setItem(e,JSON.stringify(t))}getActiveAccount(e){const t=this.generateCacheKey(nC.ACTIVE_ACCOUNT_FILTERS),n=this.browserStorage.getItem(t);if(!n)return this.logger.trace("08gw0e",e),null;const a=this.validateAndParseJson(n);return a?(this.logger.trace("1t3ch7",e),this.getAccountInfoFilteredBy({homeAccountId:a.homeAccountId,localAccountId:a.localAccountId,tenantId:a.tenantId},e)):(this.logger.trace("0me1up",e),null)}setActiveAccount(e,t){const n=this.generateCacheKey(nC.ACTIVE_ACCOUNT_FILTERS);if(e){this.logger.verbose("0rsj80",t);const a={homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,tenantId:e.tenantId};this.setItem(n,JSON.stringify(a),t)}else this.logger.verbose("1bp5z5",t),this.browserStorage.removeItem(n);this.eventHandler.emitEvent(Rt.ACTIVE_ACCOUNT_CHANGED)}getThrottlingCache(e,t){const n=this.browserStorage.getItem(e);if(!n)return this.logger.trace("1h4wa6",t),null;const a=this.validateAndParseJson(n);return!a||!b_(e,a)?(this.logger.trace("1h4wa6",t),null):(this.logger.trace("0of6n8",t),a)}setThrottlingCache(e,t,n){this.logger.trace("0wfgh6",n),this.setItem(e,JSON.stringify(t),n)}getTemporaryCache(e,t,n){const a=n?this.generateCacheKey(e):e,s=this.temporaryCacheStorage.getItem(a);if(!s){if(this.cacheConfig.cacheLocation===xa.LocalStorage){const l=this.browserStorage.getItem(a);if(l)return this.logger.trace("1yt61y",t),l}return this.logger.trace("1qhy81",t),null}return s}setTemporaryCache(e,t,n){const a=n?this.generateCacheKey(e):e;this.temporaryCacheStorage.setItem(a,t)}removeItem(e){this.browserStorage.removeItem(e)}removeTemporaryItem(e){this.temporaryCacheStorage.removeItem(e)}getKeys(){return this.browserStorage.getKeys()}clear(e){this.removeAllAccounts(e),this.removeAppMetadata(e),this.temporaryCacheStorage.getKeys().forEach(t=>{(t.indexOf(Nr)!==-1||t.indexOf(this.clientId)!==-1)&&this.removeTemporaryItem(t)}),this.browserStorage.getKeys().forEach(t=>{(t.indexOf(Nr)!==-1||t.indexOf(this.clientId)!==-1)&&this.browserStorage.removeItem(t)}),this.internalStorage.clear()}generateCacheKey(e){return Ea.startsWith(e,Nr)?e:`${Nr}.${this.clientId}.${e}`}generateCredentialKey(e){const t=e.credentialType===_r.REFRESH_TOKEN&&e.familyId||e.clientId,n=e.tokenType&&e.tokenType.toLowerCase()!==MA.BEARER.toLowerCase()?e.tokenType.toLowerCase():"";return[`${Nr}.${Kr}`,e.homeAccountId,e.environment,e.credentialType,t,e.realm||"",e.target||"",n].join(jC).toLowerCase()}generateAccountKey(e){const t=e.homeAccountId.split(".")[1];return[`${Nr}.${ep}`,e.homeAccountId,e.environment,t||e.tenantId||""].join(jC).toLowerCase()}resetRequestCache(e){this.logger.trace("0h0ynu",e),this.removeTemporaryItem(this.generateCacheKey(Wn.REQUEST_PARAMS)),this.removeTemporaryItem(this.generateCacheKey(Wn.VERIFIER)),this.removeTemporaryItem(this.generateCacheKey(Wn.ORIGIN_URI)),this.removeTemporaryItem(this.generateCacheKey(Wn.URL_HASH)),this.removeTemporaryItem(this.generateCacheKey(Wn.NATIVE_REQUEST)),this.setInteractionInProgress(!1,void 0)}cacheAuthorizeRequest(e,t,n){this.logger.trace("1tzef5",t);const a=Xf(JSON.stringify(e));if(this.setTemporaryCache(Wn.REQUEST_PARAMS,a,!0),n){const s=Xf(n);this.setTemporaryCache(Wn.VERIFIER,s,!0)}}getCachedRequest(e){this.logger.trace("0uen20",e);const t=this.getTemporaryCache(Wn.REQUEST_PARAMS,e,!0);if(!t)throw ut(cN);const n=this.getTemporaryCache(Wn.VERIFIER,e,!0);let a,s="";try{a=JSON.parse(Zi(t)),n&&(s=Zi(n))}catch{throw this.logger.errorPii("0ewsey",e),this.logger.error("0tvdic",e),ut(uN)}return[a,s]}getCachedNativeRequest(){this.logger.trace("1yxcdm","");const e=this.getTemporaryCache(Wn.NATIVE_REQUEST,"",!0);if(!e)return this.logger.trace("0mnxd4",""),null;const t=this.validateAndParseJson(e);return t||(this.logger.error("0rrkip",""),null)}isInteractionInProgress(e){const t=this.getInteractionInProgress()?.clientId;return e?t===this.clientId:!!t}getInteractionInProgress(){const e=`${Nr}.${Wn.INTERACTION_STATUS_KEY}`,t=this.getTemporaryCache(e,"",!1);try{return t?JSON.parse(t):null}catch{return this.logger.error("0jjyys",""),this.removeTemporaryItem(e),this.resetRequestCache(""),c4(window),null}}setInteractionInProgress(e,t=bl.SIGNIN,n=!1,a=""){const s=`${Nr}.${Wn.INTERACTION_STATUS_KEY}`;if(e){if(this.getInteractionInProgress())if(n)this.logger.warning("1pmscr",a),GN(this.logger,a),this.removeTemporaryItem(s);else throw ut(tN);this.setTemporaryCache(s,JSON.stringify({clientId:this.clientId,type:t}),!1)}else!e&&this.getInteractionInProgress()?.clientId===this.clientId&&this.removeTemporaryItem(s)}async hydrateCache(e,t){const n=E2(e.account.homeAccountId,e.account.environment,e.idToken,this.clientId,e.tenantId),a=x2(e.account.homeAccountId,e.account.environment,e.accessToken,this.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?mC(e.expiresOn):0,e.extExpiresOn?mC(e.extExpiresOn):0,Zi,void 0,e.tokenType,void 0,t.sshKid),s={idToken:n,accessToken:a};return this.saveCacheRecord(s,e.correlationId,Fc(Uo(e.idToken,Zi)),EA.hydrateCache)}async saveCacheRecord(e,t,n,a,s){try{await super.saveCacheRecord(e,t,n,a,s)}catch(l){if(l instanceof ih&&this.performanceClient&&t)try{const c=this.getTokenKeys();this.performanceClient.addFields({cacheRtCount:c.refreshToken.length,cacheIdCount:c.idToken.length,cacheAtCount:c.accessToken.length},t)}catch{}throw l}}}function qC(A,e,t,n){try{switch(e){case xa.LocalStorage:return new jQ(A,t,n);case xa.SessionStorage:return new KQ;case xa.MemoryStorage:default:break}}catch(a){t.error(a,"")}return new o0}const zQ=(A,e,t,n)=>{const a={cacheLocation:xa.MemoryStorage,cacheRetentionDays:5};return new ow(A,a,yp,e,t,n)};function VQ(A,e,t,n,a){return A.verbose("1yd030",n),t?e.getAllAccounts(a,n):[]}function qQ(A,e,t,n){if(e.trace("0u7b90",n),Object.keys(A).length===0)return e.warning("1kz0cu",n),null;const a=t.getAccountInfoFilteredBy(A,n);return a?(e.verbose("0btgll",n),a):(e.verbose("0ltaj5",n),null)}function YQ(A,e,t){e.setActiveAccount(A,t)}function XQ(A,e){return A.getActiveAccount(e)}const JQ="msal.broadcast.event";class WQ{constructor(e){this.eventCallbacks=new Map,this.logger=e||new Ml({}),typeof BroadcastChannel<"u"&&(this.broadcastChannel=new BroadcastChannel(JQ)),this.invokeCrossTabCallbacks=this.invokeCrossTabCallbacks.bind(this)}addEventCallback(e,t,n){if(typeof window<"u"){const a=n||aw();return this.eventCallbacks.has(a)?(this.logger.error("1578i0",""),null):(this.eventCallbacks.set(a,[e,t||[]]),this.logger.verbose("1cnec4",""),a)}return null}removeEventCallback(e){this.eventCallbacks.delete(e),this.logger.verbose("12zotd","")}emitEvent(e,t,n,a){const s={eventType:e,interactionType:t||null,payload:n||null,error:a||null,timestamp:Date.now()};switch(e){case Rt.LOGIN_SUCCESS:case Rt.LOGOUT_SUCCESS:case Rt.ACTIVE_ACCOUNT_CHANGED:this.broadcastChannel?.postMessage(s)}this.invokeCallbacks(s)}invokeCallbacks(e){this.eventCallbacks.forEach(([t,n],a)=>{(n.length===0||n.includes(e.eventType))&&(this.logger.verbose("15jpwk",""),t.apply(null,[e]))})}invokeCrossTabCallbacks(e){const t=e.data;this.invokeCallbacks(t)}subscribeCrossTab(){this.broadcastChannel?.addEventListener("message",this.invokeCrossTabCallbacks)}unsubscribeCrossTab(){this.broadcastChannel?.removeEventListener("message",this.invokeCrossTabCallbacks)}}class m4{constructor(e,t,n,a,s,l,c,h,f){this.config=e,this.browserStorage=t,this.browserCrypto=n,this.networkClient=this.config.system.networkClient,this.eventHandler=s,this.navigationClient=l,this.platformAuthProvider=f,this.correlationId=h,this.logger=a.clone(va.MSAL_SKU,Mc),this.performanceClient=c}}function Up(A,e,t,n){t.verbose("0bd1la",n);const a=A||e||"";return QA.getAbsoluteUrl(a,xl())}function Ti(A,e,t,n,a,s){a.verbose("1p12tq",t);const l={clientId:e,correlationId:t,apiId:A,forceRefresh:!1,wrapperSKU:n.getWrapperMetadata()[0],wrapperVer:n.getWrapperMetadata()[1]};return new Yf(l,n)}async function Fo(A,e,t,n,a,s,l,c,h){const f=c&&c.hasOwnProperty("instance_aware")?c.instance_aware:void 0,g={protocolMode:A.system.protocolMode,OIDCOptions:A.auth.OIDCOptions,knownAuthorities:A.auth.knownAuthorities,cloudDiscoveryMetadata:A.auth.cloudDiscoveryMetadata,authorityMetadata:A.auth.authorityMetadata},y=s||A.auth.authority,C=f?.length?f==="true":A.auth.instanceAware,v=h&&C?A.auth.authority.replace(QA.getDomainFromUrl(y),h.environment):y,I=Si.generateAuthority(v,l||A.auth.azureCloudOptions),x=await Ke(zx,hQ,a,t,e)(I,A.system.networkClient,n,g,a,e,t);if(h&&!x.isAlias(h.environment))throw An(KF);return x}async function K2(A,e,t,n,a){if(a)try{A.removeAccount(a,n),t.verbose("0s4z6h",n)}catch{t.error("0mgg1d",n)}else try{t.verbose("0zj631",n),A.clear(n),await e.clearKeystore(n)}catch{t.error("12ih0c",n)}}async function G2(A,e,t,n,a){const s=A.authority||e.auth.authority,l=[...A&&A.scopes||[]],c={...A,correlationId:A.correlationId,authority:s,scopes:l};if(!c.authenticationScheme)c.authenticationScheme=MA.BEARER,n.verbose("1l4fwv",a);else{if(c.authenticationScheme===MA.SSH){if(!A.sshJwk)throw An(r2);if(!A.sshKid)throw An(MF)}n.verbose("1ecmns",a)}return c}async function ZQ(A,e,t,n,a){const s=await Ke(G2,D2,a,n,A.correlationId)(A,t,n,a,A.correlationId);return{...A,...s,account:e,forceRefresh:A.forceRefresh||!1}}function w4(A,e){let t;const n=A.httpMethod;if(e===Fi.EAR){if(n&&n!==rh.POST)throw An(GF);t=rh.POST}else t=n||rh.GET;return t}class bh extends m4{initializeLogoutRequest(e){this.logger.verbose("0546u4",this.correlationId);const t={correlationId:this.correlationId,...e};if(e)if(e.logoutHint)this.logger.verbose("12k4l4",this.correlationId);else if(e.account){const n=this.getLogoutHintFromIdTokenClaims(e.account);n&&(this.logger.verbose("0st5di",this.correlationId),t.logoutHint=n)}else this.logger.verbose("0pdtc3",this.correlationId);else this.logger.verbose("07ndze",this.correlationId);return!e||e.postLogoutRedirectUri!==null?e&&e.postLogoutRedirectUri?(this.logger.verbose("1vamm6",t.correlationId),t.postLogoutRedirectUri=QA.getAbsoluteUrl(e.postLogoutRedirectUri,xl())):this.config.auth.postLogoutRedirectUri===null?this.logger.verbose("15m5g7",t.correlationId):this.config.auth.postLogoutRedirectUri?(this.logger.verbose("1f4xlz",t.correlationId),t.postLogoutRedirectUri=QA.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri,xl())):(this.logger.verbose("17s5rf",t.correlationId),t.postLogoutRedirectUri=QA.getAbsoluteUrl(xl(),xl())):this.logger.verbose("0ljv63",t.correlationId),t}getLogoutHintFromIdTokenClaims(e){const t=e.idTokenClaims;if(t){if(t.login_hint)return t.login_hint;this.logger.verbose("0mvp54",this.correlationId)}else this.logger.verbose("1e7bdp",this.correlationId);return null}async createAuthCodeClient(e){const t=await Ke(this.getClientConfiguration.bind(this),a0,this.logger,this.performanceClient,this.correlationId)(e);return new Vx(t,this.performanceClient)}async getClientConfiguration(e){const{serverTelemetryManager:t,requestAuthority:n,requestAzureCloudOptions:a,requestExtraQueryParameters:s,account:l}=e,c=e.authority||await Ke(Fo,Tc,this.logger,this.performanceClient,this.correlationId)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,a,s,l),h=this.config.system.loggerOptions;return{authOptions:{clientId:this.config.auth.clientId,authority:c,clientCapabilities:this.config.auth.clientCapabilities,redirectUri:this.config.auth.redirectUri},systemOptions:{tokenRenewalOffsetSeconds:this.config.system.tokenRenewalOffsetSeconds,preventCorsPreflight:!0},loggerOptions:{loggerCallback:h.loggerCallback,piiLoggingEnabled:h.piiLoggingEnabled,logLevel:h.logLevel,correlationId:this.correlationId},cryptoInterface:this.browserCrypto,networkInterface:this.networkClient,storageInterface:this.browserStorage,serverTelemetryManager:t,libraryInfo:{sku:va.MSAL_SKU,version:Mc,cpu:"",os:""},telemetry:this.config.telemetry}}}async function l0(A,e,t,n,a,s,l,c){const h=Up(A.redirectUri,t.auth.redirectUri,s,c),f={interactionType:e},g=JT(n,A&&A.state||"",f),C={...await Ke(G2,D2,s,l,c)({...A,correlationId:c},t,l,s,c),redirectUri:h,state:g,nonce:A.nonce||Hc(),responseMode:t.auth.OIDCOptions.responseMode},v={...C,httpMethod:w4(C,t.system.protocolMode)};if(A.loginHint||A.sid)return v;const I=A.account||a.getActiveAccount(c);return I&&(s.verbose("1eqlb3",c),s.verbosePii("0tf99t",c),v.account=I),v}function $Q(A,e){if(!e)return null;try{return cd(A.base64Decode,e).libraryState.meta}catch{throw tt(Vf)}}function Qf(A,e,t,n){const a=vp(A);if(!a)throw Ux(A)?(t.error("13pl0s",n),t.errorPii("1097vx",n),ut($_)):(t.error("18h0l1",n),ut(Z_));return a}function eL(A,e,t){if(!A.state)throw ut(T2);const n=$Q(e,A.state);if(!n)throw ut($x);if(n.interactionType!==t)throw ut(eN)}class v4{constructor(e,t,n,a,s){this.authModule=e,this.browserStorage=t,this.authCodeRequest=n,this.logger=a,this.performanceClient=s}async handleCodeResponse(e,t,n){let a;try{a=H_(e,t.state)}catch(s){throw s instanceof zc&&s.subError===rw?ut(rw):s}return Ke(this.handleCodeResponseFromServer.bind(this),Hx,this.logger,this.performanceClient,t.correlationId)(a,t,n)}async handleCodeResponseFromServer(e,t,n,a=!0){if(this.logger.trace("0mf2hb",t.correlationId),this.authCodeRequest.code=e.code,a&&(e.nonce=t.nonce||void 0),e.state=t.state,e.client_info)this.authCodeRequest.clientInfo=e.client_info;else{const l=this.createCcsCredentials(t);l&&(this.authCodeRequest.ccsCredential=l)}return await Ke(this.authModule.acquireToken.bind(this.authModule),uQ,this.logger,this.performanceClient,t.correlationId)(this.authCodeRequest,n,e)}createCcsCredentials(e){return e.account?{credential:e.account.homeAccountId,type:is.HOME_ACCOUNT_ID}:e.loginHint?{credential:e.loginHint,type:is.UPN}:null}}const tL="ContentError",AL="PageException",nL="user_switch";const rL="USER_INTERACTION_REQUIRED",iL="USER_CANCEL",aL="NO_NETWORK",sL="PERSISTENT_ERROR",oL="DISABLED",lL="ACCOUNT_UNAVAILABLE",cL="UX_NOT_ALLOWED";const uL=-2147186943;class Hs extends en{constructor(e,t,n){super(e,t||r0(e)),Object.setPrototypeOf(this,Hs.prototype),this.name="NativeAuthError",this.ext=n}}function Ju(A){if(A.ext&&A.ext.status&&(A.ext.status===sL||A.ext.status===oL)||A.ext&&A.ext.error&&A.ext.error===uL)return!0;switch(A.errorCode){case tL:case AL:return!0;default:return!1}}function Ip(A,e,t){if(t&&t.status)switch(t.status){case lL:return bp(zT,r0(A));case rL:return new os(A,e);case iL:return ut(rw);case aL:return ut(iw);case cL:return bp(Rx)}return new Hs(A,e,t)}class y4 extends bh{async acquireToken(e){const t=Ti(EA.acquireTokenSilent_silentFlow,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),n=await Ke(this.getClientConfiguration.bind(this),a0,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,account:e.account}),a=new O_(n,this.performanceClient);this.logger.verbose("0wa871",this.correlationId);try{const l=(await Ke(a.acquireCachedToken.bind(a),oQ,this.logger,this.performanceClient,e.correlationId)(e))[0];return this.performanceClient.addFields({fromCache:!0},e.correlationId),l}catch(s){throw s instanceof hd&&s.errorCode===t4&&this.logger.verbose("06wena",this.correlationId),s}}logout(e){this.logger.verbose("1rkurh",this.correlationId);const t=this.initializeLogoutRequest(e);return K2(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,t.account)}}class Ap extends m4{constructor(e,t,n,a,s,l,c,h,f,g,y,C){super(e,t,n,a,s,l,h,C,f),this.apiId=c,this.accountId=g,this.platformAuthProvider=f,this.nativeStorageManager=y,this.silentCacheClient=new y4(e,this.nativeStorageManager,n,a,s,l,h,C,f);const v=this.platformAuthProvider.getExtensionName();this.skus=Yf.makeExtraSkuString({libraryName:va.MSAL_SKU,libraryVersion:Mc,extensionName:v,extensionVersion:this.platformAuthProvider.getExtensionVersion()})}addRequestSKUs(e){e.extraParameters={...e.extraParameters,[FF]:this.skus}}async acquireToken(e,t){this.logger.trace("03qeos",this.correlationId);const n=this.performanceClient.startMeasurement(d4,e.correlationId),a=ls(),s=Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{const l=await this.initializeNativeRequest(e);try{const h=await this.acquireTokensFromCache(this.accountId,l);return n.end({success:!0,isNativeBroker:!1,fromCache:!0}),h}catch(h){if(t===ri.AccessToken)throw this.logger.info("0eitbc",this.correlationId),h;this.logger.info("0957j1",this.correlationId)}const c=await this.platformAuthProvider.sendMessage(l);return await this.handleNativeResponse(c,l,a).then(h=>(n.end({success:!0,isNativeBroker:!0,requestId:h.requestId}),s.clearNativeBrokerErrorCode(),h)).catch(h=>{throw n.end({success:!1,errorCode:h.errorCode,subErrorCode:h.subError,isNativeBroker:!0}),h})}catch(l){throw l instanceof Hs&&s.setNativeBrokerErrorCode(l.errorCode),l}}createSilentCacheRequest(e,t){return{authority:e.authority,correlationId:this.correlationId,scopes:qr.fromString(e.scope).asArray(),account:t,forceRefresh:!1}}async acquireTokensFromCache(e,t){if(!e)throw this.logger.warning("1ndf3e",this.correlationId),tt(lC);const n=this.browserStorage.getBaseAccountInfo({nativeAccountId:e},t.correlationId);if(!n)throw tt(lC);try{const a=this.createSilentCacheRequest(t,n),s=await this.silentCacheClient.acquireToken(a),l={...n,idTokenClaims:s?.idTokenClaims,idToken:s?.idToken};return{...s,account:l}}catch(a){throw a}}async acquireTokenRedirect(e,t,n){this.logger.trace("0luikq",this.correlationId);const a=await this.initializeNativeRequest(e),s=n?.navigateToLoginRequestUrl??!0;try{await this.platformAuthProvider.sendMessage(a)}catch(h){if(h instanceof Hs&&(Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger).setNativeBrokerErrorCode(h.errorCode),Ju(h)))throw h}this.browserStorage.setTemporaryCache(Wn.NATIVE_REQUEST,JSON.stringify(a),!0);const l={apiId:EA.acquireTokenRedirect,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},c=s?window.location.href:Up(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId);t.end({success:!0}),await this.navigationClient.navigateExternal(c,l)}async handleRedirectPromise(e,t){if(this.logger.trace("1c5lhw",this.correlationId),!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("0le6uv",this.correlationId),null;const n=this.browserStorage.getCachedNativeRequest();if(!n)return this.logger.verbose("0a6zjb",this.correlationId),e&&t&&e?.addFields({errorCode:"no_cached_request"},t),null;const{prompt:a,...s}=n;a&&this.logger.verbose("0ac34v",this.correlationId),this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Wn.NATIVE_REQUEST));const l=ls();try{this.logger.verbose("003x5a",this.correlationId);const c=await this.platformAuthProvider.sendMessage(s),h=await this.handleNativeResponse(c,s,l);return Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger).clearNativeBrokerErrorCode(),h}catch(c){throw c}}logout(){return this.logger.trace("0u2sjm",this.correlationId),Promise.reject("Logout not implemented yet")}async handleNativeResponse(e,t,n){this.logger.trace("1bojln",this.correlationId);const a=Uo(e.id_token,Zi),s=this.createHomeAccountIdentifier(e,a),l=this.browserStorage.getAccountInfoFilteredBy({nativeAccountId:t.accountId},this.correlationId)?.homeAccountId;if(t.extraParameters?.child_client_id&&e.account.id!==t.accountId)this.logger.info("1ub1in",this.correlationId);else if(s!==l&&e.account.id!==t.accountId)throw Ip(nL);const c=await Fo(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,t.authority),h=Dx(this.browserStorage,c,s,Zi,this.correlationId,a,e.client_info,void 0,a.tid,void 0,e.account.id);e.expires_in=Number(e.expires_in);const f=await this.generateAuthenticationResult(e,t,a,h,c.canonicalAuthority,n);return await this.cacheAccount(h,Fc(a)),await this.cacheNativeTokens(e,t,s,a,e.access_token,f.tenantId,n),f}createHomeAccountIdentifier(e,t){return _x(e.client_info||"",rs.Default,this.logger,this.browserCrypto,this.correlationId,t)}generateScopes(e,t){return t?qr.fromString(t):qr.fromString(e)}async generatePopAccessToken(e,t){if(t.tokenType===MA.POP&&t.signPopToken){if(e.shr)return this.logger.trace("0coqhu",this.correlationId),e.shr;const n=new mh(this.browserCrypto,this.performanceClient),a={resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,shrNonce:t.shrNonce,correlationId:this.correlationId};if(!t.keyId)throw tt(mx);return n.signPopToken(e.access_token,t.keyId,a)}else return e.access_token}async generateAuthenticationResult(e,t,n,a,s,l){const c=this.addTelemetryFromNativeResponse(e.properties.MATS),h=this.generateScopes(t.scope,e.scope),f=e.account.properties||{},g=f.UID||n.oid||n.sub||"",y=f.TenantId||n.tid||"",C=m2(Rc(a),void 0,n,e.id_token);C.nativeAccountId!==e.account.id&&(C.nativeAccountId=e.account.id);const v=await this.generatePopAccessToken(e,t),I=t.tokenType===MA.POP?MA.POP:MA.BEARER;return{authority:s,uniqueId:g,tenantId:y,scopes:h.asArray(),account:C,idToken:e.id_token,idTokenClaims:n,accessToken:v,fromCache:c?this.isResponseFromCache(c):!1,expiresOn:Zg(l+e.expires_in),tokenType:I,correlationId:this.correlationId,state:e.state,fromPlatformBroker:!0}}async cacheAccount(e,t){await this.browserStorage.setAccount(e,this.correlationId,t,this.apiId),this.browserStorage.removeAccountContext(Rc(e),this.correlationId)}cacheNativeTokens(e,t,n,a,s,l,c){const h=E2(n,t.authority,e.id_token||"",t.clientId,a.tid||""),f=t.tokenType===MA.POP?$B:(typeof e.expires_in=="string"?parseInt(e.expires_in,10):e.expires_in)||0,g=c+f,y=this.generateScopes(e.scope,t.scope),C=x2(n,t.authority,s,t.clientId,a.tid||l,y.printScopes(),g,0,Zi,void 0,t.tokenType,void 0,t.keyId),v={idToken:h,accessToken:C};return this.nativeStorageManager.saveCacheRecord(v,this.correlationId,Fc(a),this.apiId,t.storeInCache)}getExpiresInValue(e,t){return e===MA.POP?$B:(typeof t=="string"?parseInt(t,10):t)||0}addTelemetryFromNativeResponse(e){const t=this.getMATSFromResponse(e);return t?(this.performanceClient.addFields({extensionId:this.platformAuthProvider.getExtensionId(),extensionVersion:this.platformAuthProvider.getExtensionVersion(),matsBrokerVersion:t.broker_version,matsAccountJoinOnStart:t.account_join_on_start,matsAccountJoinOnEnd:t.account_join_on_end,matsDeviceJoin:t.device_join,matsPromptBehavior:t.prompt_behavior,matsApiErrorCode:t.api_error_code,matsUiVisible:t.ui_visible,matsSilentCode:t.silent_code,matsSilentBiSubCode:t.silent_bi_sub_code,matsSilentMessage:t.silent_message,matsSilentStatus:t.silent_status,matsHttpStatus:t.http_status,matsHttpEventCount:t.http_event_count},this.correlationId),t):null}getMATSFromResponse(e){if(e)try{return JSON.parse(e)}catch{this.logger.error("0b3l57",this.correlationId)}return null}isResponseFromCache(e){return typeof e.is_cached>"u"?(this.logger.verbose("1okqev",this.correlationId),!1):!!e.is_cached}async initializeNativeRequest(e){this.logger.trace("04j6wj",this.correlationId);const t=await this.getCanonicalAuthority(e),{scopes:n,...a}=e,s=new qr(n||[]);s.appendScopes(yh);const l={...a,accountId:this.accountId,clientId:this.config.auth.clientId,authority:t.urlString,scope:s.printScopes(),redirectUri:Up(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId),prompt:this.getPrompt(e.prompt),correlationId:this.correlationId,tokenType:e.authenticationScheme,windowTitleSubstring:document.title,extraParameters:{...e.extraParameters},extendedExpiryToken:!1,keyId:e.popKid};if(l.signPopToken&&e.popKid)throw ut(CN);if(this.handleExtraBrokerParams(l),l.extraParameters=l.extraParameters||{},l.extraParameters.telemetry=ya.MATS_TELEMETRY,e.authenticationScheme===MA.POP){const c={resourceRequestUri:e.resourceRequestUri,resourceRequestMethod:e.resourceRequestMethod,shrClaims:e.shrClaims,shrNonce:e.shrNonce,correlationId:this.correlationId},h=new mh(this.browserCrypto,this.performanceClient);let f;if(l.keyId)f=this.browserCrypto.base64UrlEncode(JSON.stringify({kid:l.keyId})),l.signPopToken=!1;else{const g=await Ke(h.generateCnf.bind(h),ud,this.logger,this.performanceClient,this.correlationId)(c,this.logger);f=g.reqCnfString,l.keyId=g.kid,l.signPopToken=!0}l.reqCnf=f}return this.addRequestSKUs(l),l}async getCanonicalAuthority(e){const t=e.authority||this.config.auth.authority,{azureCloudOptions:n,account:a}=e;a&&await Fo(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,t,n,void 0,a);const s=new QA(t);return s.validateAsUri(),s}getPrompt(e){switch(this.apiId){case EA.ssoSilent:case EA.acquireTokenSilent_silentFlow:return this.logger.trace("1hiwaz",this.correlationId),Ii.NONE}if(!e){this.logger.trace("1qlu04",this.correlationId);return}switch(e){case Ii.NONE:case Ii.CONSENT:case Ii.LOGIN:return this.logger.trace("1ynje4",this.correlationId),e;default:throw this.logger.trace("0nkr6q",this.correlationId),ut(yN)}}handleExtraBrokerParams(e){const t=e.extraParameters&&e.extraParameters.hasOwnProperty(pp)&&e.extraParameters.hasOwnProperty(mp)&&e.extraParameters.hasOwnProperty(Oc);if(!e.embeddedClientId&&!t)return;let n="";const a=e.redirectUri;e.embeddedClientId?(e.redirectUri=this.config.auth.redirectUri,n=e.embeddedClientId):e.extraParameters&&(e.redirectUri=e.extraParameters[mp],n=e.extraParameters[Oc]),e.extraParameters={child_client_id:n,child_redirect_uri:a},this.performanceClient?.addFields({embeddedClientId:n,embeddedRedirectUri:a},e.correlationId)}}async function z2(A,e,t,n,a){const s=k_({...A.auth,authority:e},t,n,a);if(u2(s,{sku:va.MSAL_SKU,version:Mc,os:"",cpu:""}),A.system.protocolMode!==Fi.OIDC&&h2(s,A.telemetry.application),t.platformBroker&&(lT(s),t.authenticationScheme===MA.POP)){const l=new _o(n,a),c=new mh(l,a);let h;t.popKid?h=l.encodeKid(t.popKid):h=(await Ke(c.generateCnf.bind(c),ud,n,a,t.correlationId)(t,n)).reqCnfString,g2(s,h)}return Wp(s,t.correlationId,a),s}async function V2(A,e,t,n,a){if(!t.codeChallenge)throw An(lx);const s=await Ke(z2,lQ,n,a,t.correlationId)(A,e,t,n,a);return i2(s,Zw.CODE),f2(s,t.codeChallenge,Ww),Ps(s,{...t.extraQueryParameters,...t.extraParameters}),S2(e,s)}async function q2(A,e,t,n,a,s){if(!n.earJwk)throw ut(Zx);const l=await z2(e,t,n,a,s);i2(l,Zw.IDTOKEN_TOKEN_REFRESHTOKEN),yT(l,n.earJwk),f2(l,n.codeChallenge,Ww),Ps(l,{...n.extraParameters});const c=new Map;Ps(c,n.extraQueryParameters||{});const h=S2(t,c);return B4(A,h,l)}async function Y2(A,e,t,n,a,s){const l=await z2(e,t,n,a,s);i2(l,Zw.CODE),f2(l,n.codeChallenge,n.codeChallengeMethod||Ww),Ps(l,{...n.extraParameters});const c=new Map;Ps(c,n.extraQueryParameters||{});const h=S2(t,c);return B4(A,h,l)}function B4(A,e,t){const n=A.createElement("form");return n.method="post",n.action=e,t.forEach((a,s)=>{const l=A.createElement("input");l.hidden=!0,l.name=s,l.value=a,n.appendChild(l)}),A.body.appendChild(n),n}async function C4(A,e,t,n,a,s,l,c,h,f){if(c.verbose("11qcow",A.correlationId),!f)throw ut(n4);const g=new _o(c,h),y=new Ap(n,a,g,c,l,n.system.navigationClient,t,h,f,e,s,A.correlationId),{userRequestState:C}=cd(g.base64Decode,A.state);return Ke(y.acquireToken.bind(y),d4,c,h,A.correlationId)({...A,state:C,prompt:void 0})}async function ch(A,e,t,n,a,s,l,c,h,f,g,y){if(ks.removeThrottle(l,a.auth.clientId,A),e.accountId)return Ke(C4,g4,f,g,A.correlationId)(A,e.accountId,n,a,l,c,h,f,g,y);const C={...A,code:e.code||"",codeVerifier:t},v=new v4(s,l,C,f,g);return await Ke(v.handleCodeResponse.bind(v),cQ,f,g,A.correlationId)(e,A,n)}async function X2(A,e,t,n,a,s,l,c,h,f,g){if(ks.removeThrottle(s,n.auth.clientId,A),qx(e,A.state),!e.ear_jwe)throw ut(W_);if(!A.earJwk)throw ut(Zx);const y=JSON.parse(await Ke(kN,SQ,h,f,A.correlationId)(A.earJwk,e.ear_jwe));if(y.accountId)return Ke(C4,g4,h,f,A.correlationId)(A,y.accountId,t,n,s,l,c,h,f,g);const C=new kc(n.auth.clientId,s,new _o(h,f),h,f,null,null);C.validateTokenResponse(y,A.correlationId);const v={code:"",state:A.state,nonce:A.nonce,client_info:y.client_info,cloud_graph_host_name:y.cloud_graph_host_name,cloud_instance_host_name:y.cloud_instance_host_name,cloud_instance_name:y.cloud_instance_name,msgraph_host:y.msgraph_host};return await Ke(C.handleServerTokenResponse.bind(C),b2,h,f,A.correlationId)(y,a,ls(),A,t,v,void 0,void 0,void 0,void 0)}const hL=32;async function Pc(A,e,t){const n=as(fL,wQ,e,A,t)(A,e,t),a=await Ke(dL,vQ,e,A,t)(n,A,e,t);return{verifier:n,challenge:a}}function fL(A,e,t){try{const n=new Uint8Array(hL);return as(NN,BQ,e,A,t)(n),kl(n)}catch{throw ut(Wx)}}async function dL(A,e,t,n){try{const a=await Ke(a4,yQ,t,e,n)(A);return kl(new Uint8Array(a))}catch{throw ut(Wx)}}class Fp{navigateInternal(e,t){return Fp.defaultNavigateWindow(e,t)}navigateExternal(e,t){return Fp.defaultNavigateWindow(e,t)}static defaultNavigateWindow(e,t){return t.noHistory?window.location.replace(e):window.location.assign(e),new Promise((n,a)=>{setTimeout(()=>{a(ut(xp,"failed_to_redirect"))},t.timeout)})}}class gL{async sendGetRequestAsync(e,t){let n,a={},s=0;const l=YC(t);try{n=await fetch(e,{method:UC.GET,headers:l})}catch(c){throw Cf(ut(window.navigator.onLine?fN:iw),void 0,void 0,c)}a=XC(n.headers);try{return s=n.status,{headers:a,body:await n.json(),status:s}}catch(c){throw Cf(ut(_C),s,a,c)}}async sendPostRequestAsync(e,t){const n=t&&t.body||"",a=YC(t);let s,l=0,c={};try{s=await fetch(e,{method:UC.POST,headers:a,body:n})}catch(h){throw Cf(ut(window.navigator.onLine?hN:iw),void 0,void 0,h)}c=XC(s.headers);try{return l=s.status,{headers:c,body:await s.json(),status:l}}catch(h){throw Cf(ut(_C),l,c,h)}}}function YC(A){try{const e=new Headers;if(!(A&&A.headers))return e;const t=A.headers;return Object.entries(t).forEach(([n,a])=>{e.append(n,a)}),e}catch(e){throw Cf(ut(bN),void 0,void 0,e)}}function XC(A){try{const e={};return A.forEach((t,n)=>{e[n]=t}),e}catch{throw ut(EN)}}const pL=6e4,mL=1e4,wL=3e4,b4=2e3;function vL({auth:A,cache:e,system:t,telemetry:n},a){const s={clientId:"",authority:`${XE}`,knownAuthorities:[],cloudDiscoveryMetadata:"",authorityMetadata:"",redirectUri:typeof window<"u"&&window.location?window.location.href.split("?")[0].split("#")[0]:"",postLogoutRedirectUri:"",clientCapabilities:[],OIDCOptions:{responseMode:$w.FRAGMENT,defaultScopes:[WE,ZE,Jw]},azureCloudOptions:{azureCloudInstance:p2.None,tenant:""},instanceAware:!1},l={cacheLocation:xa.SessionStorage,cacheRetentionDays:5},c={loggerCallback:()=>{},logLevel:vn.Info,piiLoggingEnabled:!1},f={...{...Qx,loggerOptions:c,networkClient:a?new gL:R_,navigationClient:new Fp,popupBridgeTimeout:t?.popupBridgeTimeout||pL,iframeBridgeTimeout:t?.iframeBridgeTimeout||mL,redirectNavigationTimeout:wL,allowRedirectInIframe:!1,navigatePopups:!0,allowPlatformBroker:!1,nativeBrokerHandshakeTimeout:t?.nativeBrokerHandshakeTimeout||b4,protocolMode:Fi.AAD},...t,loggerOptions:t?.loggerOptions||c},g={application:{appName:"",appVersion:""},client:new Nx};if(t?.protocolMode!==Fi.OIDC&&A?.OIDCOptions&&new Ml(f.loggerOptions).warning(JSON.stringify(An(PF)),""),t?.protocolMode&&t.protocolMode===Fi.OIDC&&f?.allowPlatformBroker)throw An(jF);return{auth:{...s,...A,OIDCOptions:{...s.OIDCOptions,...A?.OIDCOptions}},cache:{...l,...e},system:f,telemetry:{...g,...n}}}class Tp{constructor(e,t,n,a){this.logger=e,this.handshakeTimeoutMs=t,this.extensionId=a,this.resolvers=new Map,this.handshakeResolvers=new Map,this.messageChannel=new MessageChannel,this.windowListener=this.onWindowMessage.bind(this),this.performanceClient=n,this.handshakeEvent=n.startMeasurement(pQ),this.platformAuthType=ya.PLATFORM_EXTENSION_PROVIDER}async sendMessage(e){this.logger.trace("0on4p2",e.correlationId);const t={method:df.GetToken,request:e},n={channel:ya.CHANNEL_ID,extensionId:this.extensionId,responseId:Hc(),body:t};this.logger.trace("1qadfi",e.correlationId),this.logger.tracePii("1xm533",e.correlationId),this.messageChannel.port1.postMessage(n);const a=await new Promise((l,c)=>{this.resolvers.set(n.responseId,{resolve:l,reject:c})});return this.validatePlatformBrokerResponse(a)}static async createProvider(e,t,n,a){e.trace("15zfnw",a);try{const s=new Tp(e,t,n,ya.PREFERRED_EXTENSION_ID);return await s.sendHandshakeRequest(a),s}catch{const l=new Tp(e,t,n);return await l.sendHandshakeRequest(a),l}}async sendHandshakeRequest(e){this.logger.trace("1dpg9o",e),window.addEventListener("message",this.windowListener,!1);const t={channel:ya.CHANNEL_ID,extensionId:this.extensionId,responseId:Hc(),body:{method:df.HandshakeRequest}};return this.handshakeEvent.add({extensionId:this.extensionId,extensionHandshakeTimeoutMs:this.handshakeTimeoutMs}),this.messageChannel.port1.onmessage=n=>{this.onChannelMessage(n)},window.postMessage(t,window.origin,[this.messageChannel.port2]),new Promise((n,a)=>{this.handshakeResolvers.set(t.responseId,{resolve:n,reject:a}),this.timeoutId=window.setTimeout(()=>{window.removeEventListener("message",this.windowListener,!1),this.messageChannel.port1.close(),this.messageChannel.port2.close(),this.handshakeEvent.end({extensionHandshakeTimedOut:!0,success:!1}),a(ut(wN)),this.handshakeResolvers.delete(t.responseId)},this.handshakeTimeoutMs)})}onWindowMessage(e){const t=aw();if(this.logger.trace("0jpn5u",t),e.source!==window)return;const n=e.data;if(!(!n.channel||n.channel!==ya.CHANNEL_ID)&&!(n.extensionId&&n.extensionId!==this.extensionId)&&n.body.method===df.HandshakeRequest){const a=this.handshakeResolvers.get(n.responseId);if(!a){this.logger.trace("07buhm",t);return}this.logger.verbose(n.extensionId?"0xrkug":"No extension installed",t),clearTimeout(this.timeoutId),this.messageChannel.port1.close(),this.messageChannel.port2.close(),window.removeEventListener("message",this.windowListener,!1),this.handshakeEvent.end({success:!1,extensionInstalled:!1}),a.reject(ut(vN))}}onChannelMessage(e){const t=aw();this.logger.trace("1py8yf",t);const n=e.data,a=this.resolvers.get(n.responseId),s=this.handshakeResolvers.get(n.responseId);try{const l=n.body.method;if(l===df.Response){if(!a)return;const c=n.body.response;if(this.logger.trace("19hpgm",t),this.logger.tracePii("179a24",t),c.status!=="Success")a.reject(Ip(c.code,c.description,c.ext));else if(c.result)c.result.code&&c.result.description?a.reject(Ip(c.result.code,c.result.description,c.result.ext)):a.resolve(c.result);else throw J1(Aw,"Event does not contain result.");this.resolvers.delete(n.responseId)}else if(l===df.HandshakeResponse){if(!s){this.logger.trace("082qnt",t);return}clearTimeout(this.timeoutId),window.removeEventListener("message",this.windowListener,!1),this.extensionId=n.extensionId,this.extensionVersion=n.body.version,this.logger.verbose("0yf5ib",t),this.handshakeEvent.end({extensionInstalled:!0,success:!0}),s.resolve(),this.handshakeResolvers.delete(n.responseId)}}catch(l){this.logger.error("0xf978",t),this.logger.errorPii("04i99o",t),this.logger.errorPii("0xdvsy",t),a?a.reject(l):s&&s.reject(l)}}validatePlatformBrokerResponse(e){if(e.hasOwnProperty("access_token")&&e.hasOwnProperty("id_token")&&e.hasOwnProperty("client_info")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scope")&&e.hasOwnProperty("expires_in"))return e;throw J1(Aw,"Response missing expected properties.")}getExtensionId(){return this.extensionId}getExtensionVersion(){return this.extensionVersion}getExtensionName(){return this.getExtensionId()===ya.PREFERRED_EXTENSION_ID?"chrome":this.getExtensionId()?.length?"unknown":void 0}}class J2{constructor(e,t,n){this.logger=e,this.performanceClient=t,this.correlationId=n,this.platformAuthType=ya.PLATFORM_DOM_PROVIDER}static async createProvider(e,t,n){if(e.trace("12mj4a",n),window.navigator?.platformAuthentication&&(await window.navigator.platformAuthentication.getSupportedContracts(ya.MICROSOFT_ENTRA_BROKERID))?.includes(ya.PLATFORM_DOM_APIS))return e.trace("1h5q1r",n),new J2(e,t,n)}getExtensionId(){return ya.MICROSOFT_ENTRA_BROKERID}getExtensionVersion(){return""}getExtensionName(){return ya.DOM_API_NAME}async sendMessage(e){this.logger.trace("02bcil",e.correlationId);try{const t=this.initializePlatformDOMRequest(e),n=await window.navigator.platformAuthentication.executeGetToken(t);return this.validatePlatformBrokerResponse(n,e.correlationId)}catch(t){throw this.logger.error("11im7g",e.correlationId),t}}initializePlatformDOMRequest(e){this.logger.trace("15d6yv",e.correlationId);const{accountId:t,clientId:n,authority:a,scope:s,redirectUri:l,correlationId:c,state:h,storeInCache:f,embeddedClientId:g,extraParameters:y,...C}=e,v=this.getDOMExtraParams(C);return{accountId:t,brokerId:this.getExtensionId(),authority:a,clientId:n,correlationId:c||this.correlationId,extraParameters:{...y,...v},isSecurityTokenService:!1,redirectUri:l,scope:s,state:h,storeInCache:f,embeddedClientId:g}}validatePlatformBrokerResponse(e,t){if(e.hasOwnProperty("isSuccess")){if(e.hasOwnProperty("accessToken")&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("clientInfo")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scopes")&&e.hasOwnProperty("expiresIn"))return this.logger.trace("0h4vei",t),this.convertToPlatformBrokerResponse(e,t);if(e.hasOwnProperty("error")){const n=e;if(n.isSuccess===!1&&n.error&&n.error.code)throw this.logger.trace("0g92vm",t),Ip(n.error.code,n.error.description,{error:parseInt(n.error.errorCode),protocol_error:n.error.protocolError,status:n.error.status,properties:n.error.properties})}}throw J1(Aw,"Response missing expected properties.")}convertToPlatformBrokerResponse(e,t){return this.logger.trace("14913t",t),{access_token:e.accessToken,id_token:e.idToken,client_info:e.clientInfo,account:e.account,expires_in:e.expiresIn,scope:e.scopes,state:e.state||"",properties:e.properties||{},extendedLifetimeToken:e.extendedLifetimeToken??!1,shr:e.proofOfPossessionPayload}}getDOMExtraParams(e){return{...Object.entries(e).reduce((a,[s,l])=>(a[s]=String(l),a),{})}}}async function yL(A,e,t,n){A.trace("134j0v",t);const a=BL();A.trace("04c81g",t);let s;try{a&&(s=await J2.createProvider(A,e,t)),s||(A.trace("0l3na8",t),s=await Tp.createProvider(A,n||b4,e,t))}catch(l){A.trace("0icbd7",l)}return s}function BL(){let A;try{return A=window[xa.SessionStorage],A?.getItem(HQ)==="true"}catch{return!1}}function Jf(A,e,t,n,a){if(e.trace("0uko3r",t),!A.system.allowPlatformBroker)return e.trace("04hozs",t),!1;if(!n)return e.trace("0kvv1r",t),!1;if(a)switch(a){case MA.BEARER:case MA.POP:return e.trace("18tev1",t),!0;default:return e.trace("1dd2nh",t),!1}return!0}class CL extends bh{constructor(e,t,n,a,s,l,c,h,f,g){super(e,t,n,a,s,l,c,f,g),this.nativeStorage=h,this.eventHandler=s}acquireToken(e,t){let n;try{if(n={popupName:this.generatePopupName(e.scopes||yh,e.authority||this.config.auth.authority),popupWindowAttributes:e.popupWindowAttributes||{},popupWindowParent:e.popupWindowParent??window},this.performanceClient.addFields({isAsyncPopup:!this.config.system.navigatePopups},this.correlationId),this.config.system.navigatePopups){const s={...e,httpMethod:w4(e,this.config.system.protocolMode)};return this.logger.verbose("1f9ok3",this.correlationId),n.popup=this.openSizedPopup("about:blank",n),this.acquireTokenPopupAsync(s,n,t)}else return this.logger.verbose("162h4u",this.correlationId),this.acquireTokenPopupAsync(e,n,t)}catch(a){return Promise.reject(a)}}logout(e){try{this.logger.verbose("068rup",this.correlationId);const t=this.initializeLogoutRequest(e),n={popupName:this.generateLogoutPopupName(t),popupWindowAttributes:e?.popupWindowAttributes||{},popupWindowParent:e?.popupWindowParent??window},a=e&&e.authority,s=e&&e.mainWindowRedirectUri;return this.config.system.navigatePopups?(this.logger.verbose("1a28da",this.correlationId),n.popup=this.openSizedPopup("about:blank",n),this.logoutPopupAsync(t,n,a,s)):(this.logger.verbose("1phd8u",this.correlationId),this.logoutPopupAsync(t,n,a,s))}catch(t){return Promise.reject(t)}}async acquireTokenPopupAsync(e,t,n){this.logger.verbose("1g77pg",this.correlationId);const a=await Ke(l0,s0,this.logger,this.performanceClient,this.correlationId)(e,Mt.Popup,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);t.popup&&f4(a.authority);const s=Jf(this.config,this.logger,this.correlationId,this.platformAuthProvider,e.authenticationScheme);return a.platformBroker=s,this.config.system.protocolMode===Fi.EAR?this.executeEarFlow(a,t,n):this.executeCodeFlow(a,t,n)}async executeCodeFlow(e,t,n){const a=e.correlationId,s=Ti(EA.acquireTokenPopup,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),l=n||await Ke(Pc,Dc,this.logger,this.performanceClient,a)(this.performanceClient,this.logger,a),c={...e,codeChallenge:l.challenge};try{const h=await Ke(this.createAuthCodeClient.bind(this),Ql,this.logger,this.performanceClient,a)({serverTelemetryManager:s,requestAuthority:c.authority,requestAzureCloudOptions:c.azureCloudOptions,requestExtraQueryParameters:c.extraQueryParameters,account:c.account});if(c.httpMethod===rh.POST)return await this.executeCodeFlowWithPost(c,t,h,l.verifier);{const f=await Ke(V2,C2,this.logger,this.performanceClient,a)(this.config,h.authority,c,this.logger,this.performanceClient),g=this.initiateAuthRequest(f,t);this.eventHandler.emitEvent(Rt.POPUP_OPENED,Mt.Popup,{popupWindow:g},null);const y=await th(this.config.system.popupBridgeTimeout,this.logger,this.browserCrypto,e),C=as(Qf,Nf,this.logger,this.performanceClient,this.correlationId)(y,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);return await Ke(ch,sh,this.logger,this.performanceClient,a)(e,C,l.verifier,EA.acquireTokenPopup,this.config,h,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}catch(h){throw t.popup?.close(),h instanceof en&&(h.setCorrelationId(this.correlationId),s.cacheFailedRequest(h)),h}}async executeEarFlow(e,t,n){const{correlationId:a,authority:s,azureCloudOptions:l,extraQueryParameters:c,account:h}=e,f=await Ke(Fo,Tc,this.logger,this.performanceClient,a)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,s,l,c,h),g=await Ke(R2,P2,this.logger,this.performanceClient,a)(),y=n||await Ke(Pc,Dc,this.logger,this.performanceClient,a)(this.performanceClient,this.logger,a),C={...e,earJwk:g,codeChallenge:y.challenge},v=t.popup||this.openPopup("about:blank",t);(await q2(v.document,this.config,f,C,this.logger,this.performanceClient)).submit();const x=await Ke(th,Sp,this.logger,this.performanceClient,a)(this.config.system.popupBridgeTimeout,this.logger,this.browserCrypto,C),_=as(Qf,Nf,this.logger,this.performanceClient,this.correlationId)(x,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);if(!_.ear_jwe&&_.code){const T=await Ke(this.createAuthCodeClient.bind(this),Ql,this.logger,this.performanceClient,a)({serverTelemetryManager:Ti(EA.acquireTokenPopup,this.config.auth.clientId,a,this.browserStorage,this.logger),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:f});return Ke(ch,sh,this.logger,this.performanceClient,a)(C,_,y.verifier,EA.acquireTokenPopup,this.config,T,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}else return Ke(X2,M2,this.logger,this.performanceClient,a)(C,_,EA.acquireTokenPopup,this.config,f,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async executeCodeFlowWithPost(e,t,n,a){const s=e.correlationId,l=await Ke(Fo,Tc,this.logger,this.performanceClient,s)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger),c=t.popup||this.openPopup("about:blank",t);(await Y2(c.document,this.config,l,e,this.logger,this.performanceClient)).submit();const f=await Ke(th,Sp,this.logger,this.performanceClient,s)(this.config.system.popupBridgeTimeout,this.logger,this.browserCrypto,e),g=as(Qf,Nf,this.logger,this.performanceClient,this.correlationId)(f,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);return Ke(ch,sh,this.logger,this.performanceClient,s)(e,g,a,EA.acquireTokenPopup,this.config,n,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async logoutPopupAsync(e,t,n,a){this.logger.verbose("0b7yrk",this.correlationId),this.eventHandler.emitEvent(Rt.LOGOUT_START,Mt.Popup,e);const s=Ti(EA.logoutPopup,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{await K2(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,e.account);const l=await Ke(this.createAuthCodeClient.bind(this),Ql,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:s,requestAuthority:n,account:e.account||void 0});try{l.authority.endSessionEndpoint}catch{if(e.account?.homeAccountId&&e.postLogoutRedirectUri&&l.authority.protocolMode===Fi.OIDC){if(this.eventHandler.emitEvent(Rt.LOGOUT_SUCCESS,Mt.Popup,e),a){const f={apiId:EA.logoutPopup,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},g=QA.getAbsoluteUrl(a,xl());await this.navigationClient.navigateInternal(g,f)}t.popup?.close();return}}const c=l.getLogoutUri(e);this.eventHandler.emitEvent(Rt.LOGOUT_SUCCESS,Mt.Popup,e);const h=this.openPopup(c,t);if(this.eventHandler.emitEvent(Rt.POPUP_OPENED,Mt.Popup,{popupWindow:h},null),await th(this.config.system.popupBridgeTimeout,this.logger,this.browserCrypto,e).catch(()=>{}),a){const f={apiId:EA.logoutPopup,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},g=QA.getAbsoluteUrl(a,xl());this.logger.verbose("0qcur2",this.correlationId),this.logger.verbosePii("0oj7lk",this.correlationId),await this.navigationClient.navigateInternal(g,f)}else this.logger.verbose("03zgcf",this.correlationId)}catch(l){throw t.popup?.close(),l instanceof en&&(l.setCorrelationId(this.correlationId),s.cacheFailedRequest(l)),this.eventHandler.emitEvent(Rt.LOGOUT_FAILURE,Mt.Popup,null,l),this.eventHandler.emitEvent(Rt.LOGOUT_END,Mt.Popup),l}this.eventHandler.emitEvent(Rt.LOGOUT_END,Mt.Popup)}initiateAuthRequest(e,t){if(e)return this.logger.infoPii("1kcr9k",this.correlationId),this.openPopup(e,t);throw this.logger.error("1l7hyp",this.correlationId),ut(F2)}openPopup(e,t){try{let n;if(t.popup?(n=t.popup,this.logger.verbosePii("0cgeo7",this.correlationId),n.location.assign(e)):typeof t.popup>"u"&&(this.logger.verbosePii("0c2awd",this.correlationId),n=this.openSizedPopup(e,t)),!n)throw ut(rN);return n.focus&&n.focus(),this.currentWindow=n,n}catch{throw this.logger.error("0dxfb9",this.correlationId),ut(nN)}}openSizedPopup(e,{popupName:t,popupWindowAttributes:n,popupWindowParent:a}){const s=a.screenLeft?a.screenLeft:a.screenX,l=a.screenTop?a.screenTop:a.screenY,c=a.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,h=a.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;let f=n.popupSize?.width,g=n.popupSize?.height,y=n.popupPosition?.top,C=n.popupPosition?.left;return(!f||f<0||f>c)&&(this.logger.verbose("08vfmo",this.correlationId),f=va.POPUP_WIDTH),(!g||g<0||g>h)&&(this.logger.verbose("09cxa0",this.correlationId),g=va.POPUP_HEIGHT),(!y||y<0||y>h)&&(this.logger.verbose("1qh4wo",this.correlationId),y=Math.max(0,h/2-va.POPUP_HEIGHT/2+l)),(!C||C<0||C>c)&&(this.logger.verbose("1sz3en",this.correlationId),C=Math.max(0,c/2-va.POPUP_WIDTH/2+s)),a.open(e,t,`width=${f}, height=${g}, top=${y}, left=${C}, scrollbars=yes`)}generatePopupName(e,t){return`${va.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${e.join("-")}.${t}.${this.correlationId}`}generateLogoutPopupName(e){const t=e.account&&e.account.homeAccountId;return`${va.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${t}.${this.correlationId}`}}function bL(){if(typeof window>"u"||typeof window.performance>"u"||typeof window.performance.getEntriesByType!="function")return;const A=window.performance.getEntriesByType("navigation");return(A.length?A[0]:void 0)?.type}class EL extends bh{constructor(e,t,n,a,s,l,c,h,f,g){super(e,t,n,a,s,l,c,f,g),this.nativeStorage=h}async acquireToken(e){const t=await Ke(l0,s0,this.logger,this.performanceClient,this.correlationId)(e,Mt.Redirect,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);t.platformBroker=Jf(this.config,this.logger,this.correlationId,this.platformAuthProvider,e.authenticationScheme);const n=s=>{s.persisted&&(this.logger.verbose("0udvtt",this.correlationId),this.browserStorage.resetRequestCache(this.correlationId),this.eventHandler.emitEvent(Rt.RESTORE_FROM_BFCACHE,Mt.Redirect))},a=this.getRedirectStartPage(e.redirectStartPage);this.logger.verbosePii("0zao0a",this.correlationId),this.browserStorage.setTemporaryCache(Wn.ORIGIN_URI,a,!0),window.addEventListener("pageshow",n);try{this.config.system.protocolMode===Fi.EAR?await this.executeEarFlow(t):await this.executeCodeFlow(t)}catch(s){throw s instanceof en&&s.setCorrelationId(this.correlationId),window.removeEventListener("pageshow",n),s}}async executeCodeFlow(e){const t=e.correlationId,n=Ti(EA.acquireTokenRedirect,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),a=await Ke(Pc,Dc,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),s={...e,codeChallenge:a.challenge};this.browserStorage.cacheAuthorizeRequest(s,this.correlationId,a.verifier);try{if(s.httpMethod===rh.POST)return await this.executeCodeFlowWithPost(s);{const l=await Ke(this.createAuthCodeClient.bind(this),Ql,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:s.authority,requestAzureCloudOptions:s.azureCloudOptions,requestExtraQueryParameters:s.extraQueryParameters,account:s.account}),c=await Ke(V2,C2,this.logger,this.performanceClient,e.correlationId)(this.config,l.authority,s,this.logger,this.performanceClient);return await this.initiateAuthRequest(c)}}catch(l){throw l instanceof en&&(l.setCorrelationId(this.correlationId),n.cacheFailedRequest(l)),l}}async executeEarFlow(e){const{correlationId:t,authority:n,azureCloudOptions:a,extraQueryParameters:s,account:l}=e,c=await Ke(Fo,Tc,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,a,s,l),h=await Ke(R2,P2,this.logger,this.performanceClient,t)(),f=await Ke(Pc,Dc,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),g={...e,earJwk:h,codeChallenge:f.challenge};return this.browserStorage.cacheAuthorizeRequest(g,this.correlationId,f.verifier),(await q2(document,this.config,c,g,this.logger,this.performanceClient)).submit(),new Promise((C,v)=>{setTimeout(()=>{v(ut(xp,"failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async executeCodeFlowWithPost(e){const t=e.correlationId,n=await Ke(Fo,Tc,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger);return this.browserStorage.cacheAuthorizeRequest(e,this.correlationId),(await Y2(document,this.config,n,e,this.logger,this.performanceClient)).submit(),new Promise((s,l)=>{setTimeout(()=>{l(ut(xp,"failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async handleRedirectPromise(e,t,n,a){const s=Ti(EA.handleRedirectPromise,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),l=a?.navigateToLoginRequestUrl??!0;try{const[c,h]=this.getRedirectResponse(a?.hash||"");if(!c)return this.logger.info("1qmv0q",this.correlationId),this.browserStorage.resetRequestCache(this.correlationId),bL()!=="back_forward"?n.event.errorCode="no_server_response":this.logger.verbose("1eqegq",this.correlationId),null;const f=this.browserStorage.getTemporaryCache(Wn.ORIGIN_URI,this.correlationId,!0)||"",g=hC(f),y=hC(window.location.href);if(g===y&&l)return this.logger.verbose("11yred",this.correlationId),f.indexOf("#")>-1&&jN(f),await this.handleResponse(c,e,t,s);if(l){if(!i0()||this.config.system.allowRedirectInIframe){this.browserStorage.setTemporaryCache(Wn.URL_HASH,h,!0);const C={apiId:EA.handleRedirectPromise,timeout:this.config.system.redirectNavigationTimeout,noHistory:!0};let v=!0;if(!f||f==="null"){const I=zN();this.browserStorage.setTemporaryCache(Wn.ORIGIN_URI,I,!0),this.logger.warning("1dutq1",this.correlationId),v=await this.navigationClient.navigateInternal(I,C)}else this.logger.verbose("08jpy1",this.correlationId),v=await this.navigationClient.navigateInternal(f,C);if(!v)return await this.handleResponse(c,e,t,s)}}else return this.logger.verbose("0v4sdv",this.correlationId),await this.handleResponse(c,e,t,s);return null}catch(c){throw c instanceof en&&(c.setCorrelationId(this.correlationId),s.cacheFailedRequest(c)),c}}getRedirectResponse(e){this.logger.verbose("1c5i8m",this.correlationId);let t=e;t||(this.config.auth.OIDCOptions.responseMode===$w.QUERY?t=window.location.search:t=window.location.hash);let n=vp(t);if(n){try{eL(n,this.browserCrypto,Mt.Redirect)}catch(s){return s instanceof en&&this.logger.error("0bkq6p",this.correlationId),[null,""]}return c4(window),this.logger.verbose("00uvho",this.correlationId),[n,t]}const a=this.browserStorage.getTemporaryCache(Wn.URL_HASH,this.correlationId,!0);return this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Wn.URL_HASH)),a&&(n=vp(a),n)?(this.logger.verbose("001671",this.correlationId),[n,a]):[null,""]}async handleResponse(e,t,n,a){if(!e.state)throw ut(T2);const{authority:l,azureCloudOptions:c,extraQueryParameters:h,account:f}=t;if(e.ear_jwe){const y=await Ke(Fo,Tc,this.logger,this.performanceClient,t.correlationId)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,l,c,h,f);return Ke(X2,M2,this.logger,this.performanceClient,t.correlationId)(t,e,EA.acquireTokenRedirect,this.config,y,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}const g=await Ke(this.createAuthCodeClient.bind(this),Ql,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:a,requestAuthority:t.authority});return Ke(ch,sh,this.logger,this.performanceClient,t.correlationId)(t,e,n,EA.acquireTokenRedirect,this.config,g,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async initiateAuthRequest(e){if(this.logger.verbose("0yaw2e",this.correlationId),e){this.logger.infoPii("1luf83",this.correlationId);const t={apiId:EA.acquireTokenRedirect,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},n=this.config.auth.onRedirectNavigate;if(typeof n=="function")if(this.logger.verbose("1nehvl",this.correlationId),n(e)!==!1){this.logger.verbose("1a0jxh",this.correlationId),await this.navigationClient.navigateExternal(e,t);return}else{this.logger.verbose("09k5h5",this.correlationId);return}else{this.logger.verbose("0klwf7",this.correlationId),await this.navigationClient.navigateExternal(e,t);return}}else throw this.logger.info("0rlh4e",this.correlationId),ut(F2)}async logout(e){this.logger.verbose("1rkurh",this.correlationId);const t=this.initializeLogoutRequest(e),n=Ti(EA.logout,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{this.eventHandler.emitEvent(Rt.LOGOUT_START,Mt.Redirect,e),await K2(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,t.account);const a={apiId:EA.logout,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},s=await Ke(this.createAuthCodeClient.bind(this),Ql,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:e&&e.authority,requestExtraQueryParameters:e?.extraQueryParameters,account:e&&e.account||void 0});if(s.authority.protocolMode===Fi.OIDC)try{s.authority.endSessionEndpoint}catch{if(t.account?.homeAccountId){this.eventHandler.emitEvent(Rt.LOGOUT_SUCCESS,Mt.Redirect,t);return}}const l=s.getLogoutUri(t);t.account?.homeAccountId&&this.eventHandler.emitEvent(Rt.LOGOUT_SUCCESS,Mt.Redirect,t);const c=this.config.auth.onRedirectNavigate;if(typeof c=="function")if(c(l)!==!1){this.logger.verbose("06v57e",this.correlationId),this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,bl.SIGNOUT),await this.navigationClient.navigateExternal(l,a);return}else this.browserStorage.setInteractionInProgress(!1),this.logger.verbose("0xqes1",this.correlationId);else{this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,bl.SIGNOUT),await this.navigationClient.navigateExternal(l,a);return}}catch(a){throw a instanceof en&&(a.setCorrelationId(this.correlationId),n.cacheFailedRequest(a)),this.eventHandler.emitEvent(Rt.LOGOUT_FAILURE,Mt.Redirect,null,a),this.eventHandler.emitEvent(Rt.LOGOUT_END,Mt.Redirect),a}this.eventHandler.emitEvent(Rt.LOGOUT_END,Mt.Redirect)}getRedirectStartPage(e){const t=e||window.location.href;return QA.getAbsoluteUrl(t,xl())}}async function xL(A,e,t,n){if(!A)throw t.info("1l7hyp",n),ut(F2);return as(IL,sQ,t,e,n)(A)}async function SL(A,e,t,n,a){const s=W2();if(!s.contentDocument)throw"No document associated with iframe!";return(await Y2(s.contentDocument,A,e,t,n,a)).submit(),s}async function UL(A,e,t,n,a){const s=W2();if(!s.contentDocument)throw"No document associated with iframe!";return(await q2(s.contentDocument,A,e,t,n,a)).submit(),s}function IL(A){const e=W2();return e.src=A,e}function W2(){const A=document.createElement("iframe");return A.className="msalSilentIframe",A.style.visibility="hidden",A.style.position="absolute",A.style.width=A.style.height="0",A.style.border="0",A.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),A.setAttribute("allow","local-network-access *"),document.body.appendChild(A),A}class FL extends bh{constructor(e,t,n,a,s,l,c,h,f,g,y){super(e,t,n,a,s,l,h,g,y),this.apiId=c,this.nativeStorage=f}async acquireToken(e){!e.loginHint&&!e.sid&&(!e.account||!e.account.username)&&this.logger.warning("1kl318",this.correlationId);const t={...e};t.prompt?t.prompt!==Ii.NONE&&t.prompt!==Ii.NO_SESSION&&(this.logger.warning("0bmctg",this.correlationId),t.prompt=Ii.NONE):t.prompt=Ii.NONE;const n=await Ke(l0,s0,this.logger,this.performanceClient,this.correlationId)(t,Mt.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);return n.platformBroker=Jf(this.config,this.logger,this.correlationId,this.platformAuthProvider,n.authenticationScheme),f4(n.authority),this.config.system.protocolMode===Fi.EAR?this.executeEarFlow(n):this.executeCodeFlow(n)}async executeCodeFlow(e){let t;const n=Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{return t=await Ke(this.createAuthCodeClient.bind(this),Ql,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:n,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),await Ke(this.silentTokenHelper.bind(this),HC,this.logger,this.performanceClient,e.correlationId)(t,e)}catch(a){if(a instanceof en&&(a.setCorrelationId(this.correlationId),n.cacheFailedRequest(a)),!t||!(a instanceof en)||a.errorCode!==va.INVALID_GRANT_ERROR)throw a;return this.performanceClient.addFields({retryError:a.errorCode},this.correlationId),await Ke(this.silentTokenHelper.bind(this),HC,this.logger,this.performanceClient,this.correlationId)(t,e)}}async executeEarFlow(e){const{correlationId:t,authority:n,azureCloudOptions:a,extraQueryParameters:s,account:l}=e,c=await Ke(Fo,Tc,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,a,s,l),h=await Ke(R2,P2,this.logger,this.performanceClient,t)(),f=await Ke(Pc,Dc,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),g={...e,earJwk:h,codeChallenge:f.challenge};await Ke(UL,Xm,this.logger,this.performanceClient,t)(this.config,c,g,this.logger,this.performanceClient);const y=this.config.auth.OIDCOptions.responseMode,C=await Ke(th,Sp,this.logger,this.performanceClient,t)(this.config.system.iframeBridgeTimeout,this.logger,this.browserCrypto,e),v=as(Qf,Nf,this.logger,this.performanceClient,t)(C,y,this.logger,this.correlationId);if(!v.ear_jwe&&v.code){const I=await Ke(this.createAuthCodeClient.bind(this),Ql,this.logger,this.performanceClient,t)({serverTelemetryManager:Ti(this.apiId,this.config.auth.clientId,t,this.browserStorage,this.logger),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:c});return Ke(ch,sh,this.logger,this.performanceClient,t)(g,v,f.verifier,this.apiId,this.config,I,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}else return Ke(X2,M2,this.logger,this.performanceClient,t)(g,v,this.apiId,this.config,c,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}logout(){return Promise.reject(ut(_2))}async silentTokenHelper(e,t){const n=t.correlationId,a=await Ke(Pc,Dc,this.logger,this.performanceClient,n)(this.performanceClient,this.logger,n),s={...t,codeChallenge:a.challenge};if(t.httpMethod===rh.POST)await Ke(SL,Xm,this.logger,this.performanceClient,n)(this.config,e.authority,s,this.logger,this.performanceClient);else{const f=await Ke(V2,C2,this.logger,this.performanceClient,n)(this.config,e.authority,s,this.logger,this.performanceClient);await Ke(xL,Xm,this.logger,this.performanceClient,n)(f,this.performanceClient,this.logger,n)}const l=this.config.auth.OIDCOptions.responseMode,c=await Ke(th,Sp,this.logger,this.performanceClient,n)(this.config.system.iframeBridgeTimeout,this.logger,this.browserCrypto,t),h=as(Qf,Nf,this.logger,this.performanceClient,n)(c,l,this.logger,this.correlationId);return Ke(ch,sh,this.logger,this.performanceClient,n)(t,h,a.verifier,this.apiId,this.config,e,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}class TL extends bh{async acquireToken(e){const t=await Ke(G2,D2,this.logger,this.performanceClient,e.correlationId)(e,this.config,this.performanceClient,this.logger,this.correlationId),n={...e,...t};e.redirectUri&&(n.redirectUri=Up(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId));const a=Ti(EA.acquireTokenSilent_silentFlow,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger),s=await this.createRefreshTokenClient({serverTelemetryManager:a,authorityUrl:n.authority,azureCloudOptions:n.azureCloudOptions,account:n.account});return Ke(s.acquireTokenByRefreshToken.bind(s),rQ,this.logger,this.performanceClient,e.correlationId)(n,EA.acquireTokenSilent_silentFlow).catch(l=>{throw l.setCorrelationId(this.correlationId),a.cacheFailedRequest(l),l})}logout(){return Promise.reject(ut(_2))}async createRefreshTokenClient(e){const t=await Ke(this.getClientConfiguration.bind(this),a0,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:e.serverTelemetryManager,requestAuthority:e.authorityUrl,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return new L_(t,this.performanceClient)}}class _L extends Vx{constructor(e,t){super(e,t),this.includeRedirectUri=!1}}class NL extends bh{constructor(e,t,n,a,s,l,c,h,f,g){super(e,t,n,a,s,l,h,f,g),this.apiId=c}async acquireToken(e){if(!e.code)throw ut(dN);const t=await Ke(l0,s0,this.logger,this.performanceClient,this.correlationId)(e,Mt.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId),n=Ti(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger);try{const a={...t,code:e.code},s=await Ke(this.getClientConfiguration.bind(this),a0,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account}),l=new _L(s,this.performanceClient);this.logger.verbose("1uic5e",this.correlationId);const c=new v4(l,this.browserStorage,a,this.logger,this.performanceClient);return await Ke(c.handleCodeResponseFromServer.bind(c),Hx,this.logger,this.performanceClient,this.correlationId)({code:e.code,msgraph_host:e.msGraphHost,cloud_graph_host_name:e.cloudGraphHostName,cloud_instance_host_name:e.cloudInstanceHostName},t,this.apiId,!1)}catch(a){throw a instanceof en&&(a.setCorrelationId(this.correlationId),n.cacheFailedRequest(a)),a}}logout(){return Promise.reject(ut(_2))}}function QL(A,e,t,n){const a=window.msal?.clientIds||[],s=a.length,l=a.filter(c=>c===A).length;l>1&&t.warning("1e88vg",n),e.add({msalInstanceCount:s,sameClientIdInstanceCount:l})}function wg(A,e,t){try{H2(A)}catch(n){throw e.end({success:!1},n,t),n}}class Z2{constructor(e){this.operatingContext=e,this.isBrowserEnvironment=this.operatingContext.isBrowserEnvironment(),this.config=e.getConfig(),this.initialized=!1,this.logger=this.operatingContext.getLogger(),this.networkClient=this.config.system.networkClient,this.navigationClient=this.config.system.navigationClient,this.redirectResponse=new Map,this.hybridAuthCodeResponses=new Map,this.performanceClient=this.config.telemetry.client,this.browserCrypto=this.isBrowserEnvironment?new _o(this.logger,this.performanceClient):yp,this.eventHandler=new WQ(this.logger),this.browserStorage=this.isBrowserEnvironment?new ow(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler,N_(this.config.auth)):zQ(this.config.auth.clientId,this.logger,this.performanceClient,this.eventHandler);const t={cacheLocation:xa.MemoryStorage,cacheRetentionDays:5};this.nativeInternalStorage=new ow(this.config.auth.clientId,t,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler),this.activeSilentTokenRequests=new Map,this.trackPageVisibility=this.trackPageVisibility.bind(this),this.trackPageVisibilityWithMeasurement=this.trackPageVisibilityWithMeasurement.bind(this)}static async createController(e,t){const n=new Z2(e);return await n.initialize(t),n}trackPageVisibility(e){e&&(this.logger.info("16v6hv",e),this.performanceClient.incrementFields({visibilityChangeCount:1},e))}async initialize(e){const t=this.getRequestCorrelationId(e);if(this.logger.trace("1f7joy",t),this.initialized){this.logger.info("061m5x",t);return}if(!this.isBrowserEnvironment){this.logger.info("19fvpi",t),this.initialized=!0,this.eventHandler.emitEvent(Rt.INITIALIZE_END);return}const n=e?.correlationId||this.getRequestCorrelationId(),a=this.config.system.allowPlatformBroker,s=this.performanceClient.startMeasurement(LQ,n);if(this.eventHandler.emitEvent(Rt.INITIALIZE_START),this.logMultipleInstances(s,n),await Ke(this.browserStorage.initialize.bind(this.browserStorage),aQ,this.logger,this.performanceClient,n)(n),a)try{this.platformAuthProvider=await yL(this.logger,this.performanceClient,n,this.config.system.nativeBrokerHandshakeTimeout)}catch(l){this.logger.verbose(l,n)}this.config.cache.cacheLocation===xa.LocalStorage&&this.eventHandler.subscribeCrossTab(),!this.config.system.navigatePopups&&await this.preGeneratePkceCodes(n),this.initialized=!0,this.eventHandler.emitEvent(Rt.INITIALIZE_END),s.end({allowPlatformBroker:a,success:!0})}async handleRedirectPromise(e){if(this.logger.verbose("02l8bm",""),h4(this.initialized),this.isBrowserEnvironment){const t=e?.hash||"";let n=this.redirectResponse.get(t);return typeof n>"u"?(n=this.handleRedirectPromiseInternal(e),this.redirectResponse.set(t,n),this.logger.verbose("1wn9kp","")):this.logger.verbose("0w0gm3",""),n}return this.logger.verbose("12xi63",""),null}async handleRedirectPromiseInternal(e){if(!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("0le6uv",""),null;if(this.browserStorage.getInteractionInProgress()?.type===bl.SIGNOUT)return this.logger.verbose("1ywcv2",""),this.browserStorage.setInteractionInProgress(!1),Promise.resolve(null);const n=this.getAllAccounts(),a=this.browserStorage.getCachedNativeRequest(),s=a&&this.platformAuthProvider&&!e?.hash;let l;this.eventHandler.emitEvent(Rt.HANDLE_REDIRECT_START,Mt.Redirect);let c;try{if(s&&this.platformAuthProvider){const h=a?.correlationId||"";l=this.performanceClient.startMeasurement(Jm,h),this.logger.trace("12v7is",h);const f=new Ap(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,EA.handleRedirectPromise,this.performanceClient,this.platformAuthProvider,a.accountId,this.nativeInternalStorage,a.correlationId);c=Ke(f.handleRedirectPromise.bind(f),gQ,this.logger,this.performanceClient,l.event.correlationId)(this.performanceClient,l.event.correlationId)}else{const[h,f]=this.browserStorage.getCachedRequest(""),g=h.correlationId;l=this.performanceClient.startMeasurement(Jm,g),this.logger.trace("0znzs5",g);const y=this.createRedirectClient(g);c=Ke(y.handleRedirectPromise.bind(y),dQ,this.logger,this.performanceClient,l.event.correlationId)(h,f,l,e)}}catch(h){throw this.browserStorage.resetRequestCache(""),h}return c.then(h=>(h?(this.browserStorage.resetRequestCache(h.correlationId),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_SUCCESS,Mt.Redirect,h),this.logger.verbose("0ui8f5",h.correlationId),n.length{this.browserStorage.resetRequestCache(l.event.correlationId);const f=h;throw this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Redirect,null,f),this.eventHandler.emitEvent(Rt.HANDLE_REDIRECT_END,Mt.Redirect),l.end({success:!1},f),h})}async acquireTokenRedirect(e){const t=this.getRequestCorrelationId(e);this.logger.verbose("0os66p",t);const n=this.performanceClient.startMeasurement(NQ,t);n.add({scenarioId:e.scenarioId});const a=this.config.auth.onRedirectNavigate;this.config.auth.onRedirectNavigate=s=>{const l=typeof a=="function"?a(s):void 0;return n.add({navigateCallbackResult:l!==!1}),n.event=n.end({success:!0},void 0,e.account)||n.event,l};try{RC(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,bl.SIGNIN),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Redirect,e);let s;return this.platformAuthProvider&&this.canUsePlatformBroker(e)?s=new Ap(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,EA.acquireTokenRedirect,this.performanceClient,this.platformAuthProvider,this.getNativeAccountId(e),this.nativeInternalStorage,t).acquireTokenRedirect(e,n).catch(c=>{if(c instanceof Hs&&Ju(c))return this.platformAuthProvider=void 0,this.createRedirectClient(t).acquireToken(e);if(c instanceof os)return this.logger.verbose("1ipyz4",t),this.createRedirectClient(t).acquireToken(e);throw c}):s=this.createRedirectClient(t).acquireToken(e),await s}catch(s){throw this.browserStorage.resetRequestCache(t),n.event.status===2?this.performanceClient.startMeasurement(Jm,t).end({success:!1},s,e.account):n.end({success:!1},s,e.account),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Redirect,null,s),s}}acquireTokenPopup(e){const t=this.getRequestCorrelationId(e),n=this.performanceClient.startMeasurement(_Q,t);n.add({scenarioId:e.scenarioId});try{this.logger.verbose("0ch87b",t),wg(this.initialized,n,e.account),this.browserStorage.setInteractionInProgress(!0,bl.SIGNIN,e.overrideInteractionInProgress,t)}catch(c){return Promise.reject(c)}const a=this.getAllAccounts();this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Popup,e);let s;const l=this.getPreGeneratedPkceCodes(t);return this.canUsePlatformBroker(e)?s=this.acquireTokenNative({...e,correlationId:t},EA.acquireTokenPopup).then(c=>(n.end({success:!0,isNativeBroker:!0},void 0,c.account),c)).catch(c=>{if(c instanceof Hs&&Ju(c))return this.platformAuthProvider=void 0,this.createPopupClient(t).acquireToken(e,l);if(c instanceof os)return this.logger.verbose("0yy5fw",t),this.createPopupClient(t).acquireToken(e,l);throw c}):s=this.createPopupClient(t).acquireToken(e,l),s.then(c=>{const h=a.length(this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Popup,null,c),n.end({success:!1},c,e.account),Promise.reject(c))).finally(async()=>{this.browserStorage.setInteractionInProgress(!1),this.config.system.navigatePopups||await this.preGeneratePkceCodes(t)})}trackPageVisibilityWithMeasurement(){const e=this.ssoSilentMeasurement||this.acquireTokenByCodeAsyncMeasurement;e&&e.increment({visibilityChangeCount:1})}async ssoSilent(e){const t=this.getRequestCorrelationId(e),n={...e,prompt:e.prompt,correlationId:t};this.ssoSilentMeasurement=this.performanceClient.startMeasurement(QQ,t),this.ssoSilentMeasurement?.add({scenarioId:e.scenarioId}),wg(this.initialized,this.ssoSilentMeasurement,e.account),this.ssoSilentMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement);const a=this.getAllAccounts();this.logger.verbose("0w1b45",t),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Silent,n);let s;return this.canUsePlatformBroker(n)?s=this.acquireTokenNative(n,EA.ssoSilent).catch(l=>{if(l instanceof Hs&&Ju(l))return this.platformAuthProvider=void 0,this.createSilentIframeClient(n.correlationId).acquireToken(n);throw l}):s=this.createSilentIframeClient(n.correlationId).acquireToken(n),s.then(l=>{const c=a.length{throw this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Silent,null,l),this.ssoSilentMeasurement?.end({success:!1},l,e.account),l}).finally(()=>{document.removeEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement)})}async acquireTokenByCode(e){const t=this.getRequestCorrelationId(e);this.logger.trace("0ch6ga",t);const n=this.performanceClient.startMeasurement(TQ,t);wg(this.initialized,n),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Silent,e),n.add({scenarioId:e.scenarioId});try{if(e.code&&e.nativeAccountId)throw ut(pN);if(e.code){const a=e.code;let s=this.hybridAuthCodeResponses.get(a);return s?(this.logger.verbose("0qgp28",t),n.discard()):(this.logger.verbose("06eh73",t),s=this.acquireTokenByCodeAsync({...e,correlationId:t}).then(l=>(this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_SUCCESS,Mt.Silent,l),this.hybridAuthCodeResponses.delete(a),n.end({success:!0,isNativeBroker:l.fromPlatformBroker,accessTokenSize:l.accessToken.length,idTokenSize:l.idToken.length},void 0,l.account),l)).catch(l=>{throw this.hybridAuthCodeResponses.delete(a),this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Silent,null,l),n.end({success:!1},l),l}),this.hybridAuthCodeResponses.set(a,s)),await s}else if(e.nativeAccountId)if(this.canUsePlatformBroker(e,e.nativeAccountId)){const a=await this.acquireTokenNative({...e,correlationId:t},EA.acquireTokenByCode,e.nativeAccountId).catch(s=>{throw s instanceof Hs&&Ju(s)&&(this.platformAuthProvider=void 0),s});return n.end({success:!0},void 0,a.account),a}else throw ut(mN);else throw ut(gN)}catch(a){throw this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Silent,null,a),n.end({success:!1},a),a}}async acquireTokenByCodeAsync(e){const t=this.getRequestCorrelationId(e);return this.logger.trace("10d9hy",t),this.acquireTokenByCodeAsyncMeasurement=this.performanceClient.startMeasurement(fQ,t),this.acquireTokenByCodeAsyncMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement),await this.createSilentAuthCodeClient(t).acquireToken(e).then(s=>(this.acquireTokenByCodeAsyncMeasurement?.end({success:!0,fromCache:s.fromCache,isNativeBroker:s.fromPlatformBroker}),s)).catch(s=>{throw this.acquireTokenByCodeAsyncMeasurement?.end({success:!1},s),s}).finally(()=>{document.removeEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement)})}async acquireTokenFromCache(e,t){switch(t){case ri.Default:case ri.AccessToken:case ri.AccessTokenAndRefreshToken:const n=this.createSilentCacheClient(e.correlationId);return Ke(n.acquireToken.bind(n),eQ,this.logger,this.performanceClient,e.correlationId)(e);default:throw tt(Ic)}}async acquireTokenByRefreshToken(e,t){switch(t){case ri.Default:case ri.AccessTokenAndRefreshToken:case ri.RefreshToken:case ri.RefreshTokenAndNetwork:const n=this.createSilentRefreshClient(e.correlationId);return Ke(n.acquireToken.bind(n),nQ,this.logger,this.performanceClient,e.correlationId)(e);default:throw tt(Ic)}}async acquireTokenBySilentIframe(e){const t=this.createSilentIframeClient(e.correlationId);return Ke(t.acquireToken.bind(t),tQ,this.logger,this.performanceClient,e.correlationId)(e)}async logoutRedirect(e){const t=this.getRequestCorrelationId(e);return RC(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,bl.SIGNOUT),this.createRedirectClient(t).logout(e)}logoutPopup(e){try{const t=this.getRequestCorrelationId(e);return H2(this.initialized),this.browserStorage.setInteractionInProgress(!0,bl.SIGNOUT),this.createPopupClient(t).logout(e).finally(()=>{this.browserStorage.setInteractionInProgress(!1)})}catch(t){return Promise.reject(t)}}async clearCache(e){if(!this.isBrowserEnvironment)return;const t=this.getRequestCorrelationId(e);return this.createSilentCacheClient(t).logout(e)}getAllAccounts(e){return VQ(this.logger,this.browserStorage,this.isBrowserEnvironment,this.getRequestCorrelationId(),e)}getAccount(e){return qQ(e,this.logger,this.browserStorage,this.getRequestCorrelationId())}setActiveAccount(e){YQ(e,this.browserStorage,this.getRequestCorrelationId())}getActiveAccount(){return XQ(this.browserStorage,this.getRequestCorrelationId())}async hydrateCache(e,t){this.logger.verbose("16jycr",e.correlationId);const n=LT(e.account,e.cloudGraphHostName,e.msGraphHost);return await this.browserStorage.setAccount(n,e.correlationId,Fc(e.idTokenClaims),EA.hydrateCache),e.fromPlatformBroker?(this.logger.verbose("1fxyu8",e.correlationId),this.nativeInternalStorage.hydrateCache(e,t)):this.browserStorage.hydrateCache(e,t)}async acquireTokenNative(e,t,n,a){const s=this.getRequestCorrelationId(e);if(this.logger.trace("0b9y3p",s),!this.platformAuthProvider)throw ut(n4);return new Ap(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,t,this.performanceClient,this.platformAuthProvider,n||this.getNativeAccountId(e),this.nativeInternalStorage,s).acquireToken(e,a)}canUsePlatformBroker(e,t){const n=this.getRequestCorrelationId(e);if(this.logger.trace("1n9lbl",n),!this.platformAuthProvider)return this.logger.trace("0vnu11",n),!1;if(!Jf(this.config,this.logger,n,this.platformAuthProvider,e.authenticationScheme))return this.logger.trace("1m4bzf",n),!1;if(e.prompt)switch(e.prompt){case Ii.NONE:case Ii.CONSENT:case Ii.LOGIN:this.logger.trace("0vdv8e",n);break;default:return this.logger.trace("0pdzw6",n),!1}return!t&&!this.getNativeAccountId(e)?(this.logger.trace("16lbtk",n),!1):!0}getNativeAccountId(e){const t=e.account||this.getAccount({loginHint:e.loginHint,sid:e.sid})||this.getActiveAccount();return t&&t.nativeAccountId||""}createPopupClient(e){return new CL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider)}createRedirectClient(e){return new EL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider)}createSilentIframeClient(e){return new FL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,EA.ssoSilent,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider)}createSilentCacheClient(e){return new y4(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,e,this.platformAuthProvider)}createSilentRefreshClient(e){return new TL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,e,this.platformAuthProvider)}createSilentAuthCodeClient(e){return new NL(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,EA.acquireTokenByCode,this.performanceClient,e,this.platformAuthProvider)}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){return u4(),this.performanceClient.addPerformanceCallback(e)}removePerformanceCallback(e){return this.performanceClient.removePerformanceCallback(e)}getLogger(){return this.logger}setLogger(e){this.logger=e}initializeWrapperLibrary(e,t){this.browserStorage.setWrapperMetadata(e,t)}setNavigationClient(e){this.navigationClient=e}getConfiguration(){return this.config}getPerformanceClient(){return this.performanceClient}isBrowserEnv(){return this.isBrowserEnvironment}getRequestCorrelationId(e){return e?.correlationId?e.correlationId:this.isBrowserEnvironment?Hc():""}async loginRedirect(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("0lz9hf",t),this.acquireTokenRedirect({correlationId:t,...e||FC})}loginPopup(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("0qw7v5",t),this.acquireTokenPopup({correlationId:t,...e||FC})}async acquireTokenSilent(e){const t=this.getRequestCorrelationId(e),n=this.performanceClient.startMeasurement(FQ,t);n.add({cacheLookupPolicy:e.cacheLookupPolicy,scenarioId:e.scenarioId}),wg(this.initialized,n,e.account),this.logger.verbose("0x1c4s",t);const a=e.account||this.getActiveAccount();if(!a)throw ut(lN);return this.acquireTokenSilentDeduped(e,a,t).then(s=>(n.end({success:!0,fromCache:s.fromCache,isNativeBroker:s.fromPlatformBroker,accessTokenSize:s.accessToken.length,idTokenSize:s.idToken.length},void 0,s.account),{...s,state:e.state,correlationId:t})).catch(s=>{throw s instanceof en&&s.setCorrelationId(t),n.end({success:!1},s,a),s})}async acquireTokenSilentDeduped(e,t,n){const a=t0(this.config.auth.clientId,{...e,authority:e.authority||this.config.auth.authority},t.homeAccountId),s=JSON.stringify(a),l=this.activeSilentTokenRequests.get(s);if(typeof l>"u"){this.logger.verbose("0fcjbk",n),this.performanceClient.addFields({deduped:!1},n);const c=Ke(this.acquireTokenSilentAsync.bind(this),WN,this.logger,this.performanceClient,n)({...e,correlationId:n},t);return this.activeSilentTokenRequests.set(s,c),c.finally(()=>{this.activeSilentTokenRequests.delete(s)})}else return this.logger.verbose("1yq7nb",n),this.performanceClient.addFields({deduped:!0},n),l}async acquireTokenSilentAsync(e,t){const n=()=>this.trackPageVisibility(e.correlationId);this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_START,Mt.Silent,e),e.correlationId&&this.performanceClient.incrementFields({visibilityChangeCount:0},e.correlationId),document.addEventListener("visibilitychange",n);const a=await Ke(ZQ,iQ,this.logger,this.performanceClient,e.correlationId)(e,t,this.config,this.performanceClient,this.logger),s=e.cacheLookupPolicy||ri.Default;return this.acquireTokenSilentNoIframe(a,s).catch(async c=>{if(LL(c,s))if(this.activeIframeRequest)if(s!==ri.Skip){const[f,g]=this.activeIframeRequest;this.logger.verbose("1w8fso",a.correlationId);const y=this.performanceClient.startMeasurement(AQ,a.correlationId);y.add({awaitIframeCorrelationId:g});const C=await f;if(y.end({success:C}),C)return this.logger.verbose("0ywzzi",a.correlationId),this.acquireTokenSilentNoIframe(a,s);throw this.logger.info("17y14q",a.correlationId),c}else return this.logger.warning("1bd4p8",a.correlationId),Ke(this.acquireTokenBySilentIframe.bind(this),kC,this.logger,this.performanceClient,a.correlationId)(a);else{let f;return this.activeIframeRequest=[new Promise(g=>{f=g}),a.correlationId],this.logger.verbose("0rh08z",a.correlationId),Ke(this.acquireTokenBySilentIframe.bind(this),kC,this.logger,this.performanceClient,a.correlationId)(a).then(g=>(f(!0),g)).catch(g=>{throw f(!1),g}).finally(()=>{this.activeIframeRequest=void 0})}else throw c}).then(c=>(this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_SUCCESS,Mt.Silent,c),e.correlationId&&this.performanceClient.addFields({fromCache:c.fromCache,isNativeBroker:c.fromPlatformBroker},e.correlationId),c)).catch(c=>{throw this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_FAILURE,Mt.Silent,null,c),c}).finally(()=>{document.removeEventListener("visibilitychange",n)})}async acquireTokenSilentNoIframe(e,t){return Jf(this.config,this.logger,e.correlationId,this.platformAuthProvider,e.authenticationScheme)&&e.account.nativeAccountId?(this.logger.verbose("0sczo4",e.correlationId),this.acquireTokenNative(e,EA.acquireTokenSilent_silentFlow,e.account.nativeAccountId,t).catch(async n=>{throw n instanceof Hs&&Ju(n)?(this.logger.verbose("07rkmb",e.correlationId),this.platformAuthProvider=void 0,tt(Ic)):n})):(this.logger.verbose("0ox81t",e.correlationId),t===ri.AccessToken&&this.logger.verbose("0fvwxe",e.correlationId),Ke(this.acquireTokenFromCache.bind(this),XN,this.logger,this.performanceClient,e.correlationId)(e,t).catch(n=>{if(t===ri.AccessToken)throw n;return this.eventHandler.emitEvent(Rt.ACQUIRE_TOKEN_NETWORK_START,Mt.Silent,e),Ke(this.acquireTokenByRefreshToken.bind(this),JN,this.logger,this.performanceClient,e.correlationId)(e,t)}))}async preGeneratePkceCodes(e){return this.logger.verbose("1x6uj6",e),this.pkceCode=await Ke(Pc,Dc,this.logger,this.performanceClient,e)(this.performanceClient,this.logger,e),Promise.resolve()}getPreGeneratedPkceCodes(e){const t=this.pkceCode?{...this.pkceCode}:void 0;return this.pkceCode=void 0,t?this.logger.verbose("12js1o",e):this.logger.verbose("1oe9ci",e),this.performanceClient.addFields({usePreGeneratedPkce:!!t},e),t}logMultipleInstances(e,t){const n=this.config.auth.clientId;if(!window)return;window.msal=window.msal||{},window.msal.clientIds=window.msal.clientIds||[],window.msal.clientIds.length>0&&this.logger.verbose("1qtz3l",t),window.msal.clientIds.push(n),QL(n,e,this.logger,t)}}function LL(A,e){const t=!(A instanceof os&&A.subError!==B2),n=A.errorCode===va.INVALID_GRANT_ERROR||A.errorCode===Ic,a=t&&n||A.errorCode===tw||A.errorCode===Ox,s=J_.includes(e);return a&&s}class $2{static loggerCallback(e,t){switch(e){case vn.Error:console.error(t);return;case vn.Info:console.info(t);return;case vn.Verbose:console.debug(t);return;case vn.Warning:console.warn(t);return;default:console.log(t);return}}constructor(e){this.browserEnvironment=typeof window<"u",this.config=vL(e,this.browserEnvironment);let t;try{t=window[xa.SessionStorage]}catch{}const n=t?.getItem(RQ),a=t?.getItem(kQ)?.toLowerCase(),s=a==="true"?!0:a==="false"?!1:void 0,l={...this.config.system.loggerOptions},c=n&&Object.keys(vn).includes(n)?vn[n]:void 0;c&&(l.loggerCallback=$2.loggerCallback,l.logLevel=c),s!==void 0&&(l.piiLoggingEnabled=s),this.logger=new Ml(l,GQ,Mc),this.available=!1}getConfig(){return this.config}getLogger(){return this.logger}isAvailable(){return this.available}isBrowserEnvironment(){return this.browserEnvironment}}class wh extends $2{getModuleName(){return wh.MODULE_NAME}getId(){return wh.ID}async initialize(e){return this.available=typeof window<"u",this.available}}wh.MODULE_NAME="";wh.ID="StandardOperatingContext";class OL{constructor(e,t){this.controller=t||new Z2(new wh(e))}async initialize(e){return this.controller.initialize(e)}async acquireTokenPopup(e){return this.controller.acquireTokenPopup(e)}acquireTokenRedirect(e){return this.controller.acquireTokenRedirect(e)}acquireTokenSilent(e){return this.controller.acquireTokenSilent(e)}acquireTokenByCode(e){return this.controller.acquireTokenByCode(e)}addEventCallback(e,t){return this.controller.addEventCallback(e,t)}removeEventCallback(e){return this.controller.removeEventCallback(e)}addPerformanceCallback(e){return this.controller.addPerformanceCallback(e)}removePerformanceCallback(e){return this.controller.removePerformanceCallback(e)}getAccount(e){return this.controller.getAccount(e)}getAllAccounts(e){return this.controller.getAllAccounts(e)}handleRedirectPromise(e){return this.controller.handleRedirectPromise(e)}loginPopup(e){return this.controller.loginPopup(e)}loginRedirect(e){return this.controller.loginRedirect(e)}logoutRedirect(e){return this.controller.logoutRedirect(e)}logoutPopup(e){return this.controller.logoutPopup(e)}ssoSilent(e){return this.controller.ssoSilent(e)}getLogger(){return this.controller.getLogger()}setLogger(e){this.controller.setLogger(e)}setActiveAccount(e){this.controller.setActiveAccount(e)}getActiveAccount(){return this.controller.getActiveAccount()}initializeWrapperLibrary(e,t){return this.controller.initializeWrapperLibrary(e,t)}setNavigationClient(e){this.controller.setNavigationClient(e)}getConfiguration(){return this.controller.getConfiguration()}async hydrateCache(e,t){return this.controller.hydrateCache(e,t)}clearCache(e){return this.controller.clearCache(e)}}const RL={initialize:()=>Promise.reject(wr(ni)),acquireTokenPopup:()=>Promise.reject(wr(ni)),acquireTokenRedirect:()=>Promise.reject(wr(ni)),acquireTokenSilent:()=>Promise.reject(wr(ni)),acquireTokenByCode:()=>Promise.reject(wr(ni)),getAllAccounts:()=>[],getAccount:()=>null,handleRedirectPromise:()=>Promise.reject(wr(ni)),loginPopup:()=>Promise.reject(wr(ni)),loginRedirect:()=>Promise.reject(wr(ni)),logoutRedirect:()=>Promise.reject(wr(ni)),logoutPopup:()=>Promise.reject(wr(ni)),ssoSilent:()=>Promise.reject(wr(ni)),addEventCallback:()=>null,removeEventCallback:()=>{},addPerformanceCallback:()=>"",removePerformanceCallback:()=>!1,getLogger:()=>{throw wr(ni)},setLogger:()=>{},setActiveAccount:()=>{},getActiveAccount:()=>null,initializeWrapperLibrary:()=>{},setNavigationClient:()=>{},getConfiguration:()=>{throw wr(ni)},hydrateCache:()=>Promise.reject(wr(ni)),clearCache:()=>Promise.reject(wr(ni))};class kL{static getInteractionStatusFromEvent(e,t){switch(e.eventType){case Rt.ACQUIRE_TOKEN_START:if(e.interactionType===Mt.Redirect||e.interactionType===Mt.Popup)return Fr.AcquireToken;break;case Rt.HANDLE_REDIRECT_START:return Fr.HandleRedirect;case Rt.LOGOUT_START:return Fr.Logout;case Rt.LOGOUT_END:if(t&&t!==Fr.Logout)break;return Fr.None;case Rt.HANDLE_REDIRECT_END:if(t&&t!==Fr.HandleRedirect)break;return Fr.None;case Rt.ACQUIRE_TOKEN_SUCCESS:case Rt.ACQUIRE_TOKEN_FAILURE:case Rt.RESTORE_FROM_BFCACHE:if(e.interactionType===Mt.Redirect||e.interactionType===Mt.Popup){if(t&&t!==Fr.AcquireToken)break;return Fr.None}break}return null}}const HL="modulepreload",DL=function(A){return"/lux-studio/"+A},JC={},Wm=function(e,t,n){let a=Promise.resolve();if(t&&t.length>0){let h=function(f){return Promise.all(f.map(g=>Promise.resolve(g).then(y=>({status:"fulfilled",value:y}),y=>({status:"rejected",reason:y}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");a=h(t.map(f=>{if(f=DL(f),f in JC)return;JC[f]=!0;const g=f.endsWith(".css"),y=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${y}`))return;const C=document.createElement("link");if(C.rel=g?"stylesheet":HL,g||(C.as="script"),C.crossOrigin="",C.href=f,c&&C.setAttribute("nonce",c),document.head.appendChild(C),g)return new Promise((v,I)=>{C.addEventListener("load",v),C.addEventListener("error",()=>I(new Error(`Unable to preload CSS for ${f}`)))})}))}function s(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return a.then(l=>{for(const c of l||[])c.status==="rejected"&&s(c.reason);return e().catch(s)})};const ML={instance:RL,inProgress:Fr.None,accounts:[],logger:new Ml({})},ev=ae.createContext(ML);ev.Consumer;function WC(A,e){if(A.length!==e.length)return!1;const t=[...e];return A.every(n=>{const a=t.shift();return!n||!a?!1:n.homeAccountId===a.homeAccountId&&n.localAccountId===a.localAccountId&&n.username===a.username})}const PL="@azure/msal-react",ZC="5.0.3";const _p={UNBLOCK_INPROGRESS:"UNBLOCK_INPROGRESS",EVENT:"EVENT"},jL=(A,e)=>{const{type:t,payload:n}=e;let a=A.inProgress;switch(t){case _p.UNBLOCK_INPROGRESS:A.inProgress===Fr.Startup&&(a=Fr.None,n.logger.info("MsalProvider - handleRedirectPromise resolved, setting inProgress to 'none'",""));break;case _p.EVENT:const l=n.message,c=kL.getInteractionStatusFromEvent(l,A.inProgress);c&&(n.logger.info(`MsalProvider - '${l.eventType}' results in setting inProgress from '${A.inProgress}' to '${c}'`,""),a=c);break;default:throw new Error(`Unknown action type: ${t}`)}if(a===Fr.Startup)return A;const s=n.instance.getAllAccounts();return a!==A.inProgress&&!WC(s,A.accounts)?{...A,inProgress:a,accounts:s}:a!==A.inProgress?{...A,inProgress:a}:WC(s,A.accounts)?A:{...A,accounts:s}};function KL({instance:A,children:e}){ae.useEffect(()=>{A.initializeWrapperLibrary(q_.React,ZC)},[A]);const t=ae.useMemo(()=>A.getLogger().clone(PL,ZC),[A]),[n,a]=ae.useReducer(jL,void 0,()=>({inProgress:Fr.Startup,accounts:[]}));ae.useEffect(()=>{const l=A.addEventCallback(c=>{a({payload:{instance:A,logger:t,message:c},type:_p.EVENT})});return t.verbose(`MsalProvider - Registered event callback with id: '${l}'`,""),A.initialize().then(()=>{A.handleRedirectPromise().catch(()=>{}).finally(()=>{a({payload:{instance:A,logger:t},type:_p.UNBLOCK_INPROGRESS})})}).catch(()=>{}),()=>{l&&(t.verbose(`MsalProvider - Removing event callback '${l}'`,""),A.removeEventCallback(l))}},[A,t]);const s={instance:A,inProgress:n.inProgress,accounts:n.accounts,logger:t};return ai.createElement(ev.Provider,{value:s},e)}const E4=()=>ae.useContext(ev);function GL(A,e){return A.length>0}function zL(A){const{accounts:e,inProgress:t}=E4();return ae.useMemo(()=>t===Fr.Startup?!1:GL(e),[e,t,A])}const VL={auth:{clientId:"9079054c-9620-4757-a256-23413042f1ef",authority:"https://login.microsoftonline.com/e519c2e6-bc6d-4fdf-8d9c-923c2f002385",redirectUri:"https://ai-sandbox.oliver.solutions/lux-studio/",postLogoutRedirectUri:"https://ai-sandbox.oliver.solutions/lux-studio/"},cache:{cacheLocation:"localStorage",storeAuthStateInCookie:!1}},qL={scopes:["User.Read"]},x4=ae.createContext(null),tv=()=>{const A=ae.useContext(x4);if(!A)throw new Error("useAuth must be used within an AuthProvider");return A},YL=({children:A})=>{const{instance:e,accounts:t,inProgress:n}=E4(),a=zL(),[s,l]=ae.useState(null),[c,h]=ae.useState(!0);ae.useEffect(()=>{e.handleRedirectPromise().then(C=>{C&&console.log("Redirect login successful")}).catch(C=>{console.error("Redirect error:",C)})},[e]),ae.useEffect(()=>{if(n===Fr.None){if(t.length>0){const C=t[0];l({id:C.localAccountId,name:C.name||C.username,email:C.username})}else l(null);h(!1)}},[t,n]);const f=async()=>{try{await e.loginRedirect(qL)}catch(C){throw console.error("Login failed:",C),C}},g=async()=>{try{await e.logoutRedirect({postLogoutRedirectUri:window.location.origin})}catch(C){throw console.error("Logout failed:",C),C}},y={user:s,isAuthenticated:a,isLoading:c||n!==Fr.None,login:f,logout:g};return b.jsx(x4.Provider,{value:y,children:A})};const XL=A=>A.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),JL=A=>A.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),$C=A=>{const e=JL(A);return e.charAt(0).toUpperCase()+e.slice(1)},S4=(...A)=>A.filter((e,t,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===t).join(" ").trim(),WL=A=>{for(const e in A)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var ZL={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const $L=ae.forwardRef(({color:A="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:n,className:a="",children:s,iconNode:l,...c},h)=>ae.createElement("svg",{ref:h,...ZL,width:e,height:e,stroke:A,strokeWidth:n?Number(t)*24/Number(e):t,className:S4("lucide",a),...!s&&!WL(c)&&{"aria-hidden":"true"},...c},[...l.map(([f,g])=>ae.createElement(f,g)),...Array.isArray(s)?s:[s]]));const Wt=(A,e)=>{const t=ae.forwardRef(({className:n,...a},s)=>ae.createElement($L,{ref:s,iconNode:e,className:S4(`lucide-${XL($C(A))}`,`lucide-${A}`,n),...a}));return t.displayName=$C(A),t};const e6=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],t6=Wt("arrow-left",e6);const A6=[["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"}]],n6=Wt("camera",A6);const r6=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],So=Wt("check",r6);const i6=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],a6=Wt("chevron-right",i6);const s6=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],o6=Wt("chevron-left",s6);const l6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],c6=Wt("circle-alert",l6);const u6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],eb=Wt("circle-question-mark",u6);const h6=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],f6=Wt("clock",h6);const d6=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],g6=Wt("copy",d6);const p6=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],xc=Wt("download",p6);const m6=[["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:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],w6=Wt("file-down",m6);const v6=[["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"}]],Sc=Wt("folder-open",v6);const y6=[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],B6=Wt("folder-plus",y6);const C6=[["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"}]],b6=Wt("grid-3x3",C6);const E6=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],x6=Wt("grip-vertical",E6);const S6=[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19 3 3v-5.5",key:"9ldu5r"}],["path",{d:"m17 22 3-3",key:"1nkfve"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]],U6=Wt("image-down",S6);const I6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],_c=Wt("image",I6);const F6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],tb=Wt("info",F6);const T6=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Zm=Wt("layers",T6);const _6=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],N6=Wt("list",_6);const Q6=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ss=Wt("loader-circle",Q6);const L6=[["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"}]],O6=Wt("log-out",L6);const R6=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],k6=Wt("message-square",R6);const H6=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],D6=Wt("pause",H6);const M6=[["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"}]],U4=Wt("pen",M6);const P6=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],j6=Wt("play",P6);const K6=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Wf=Wt("plus",K6);const G6=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Np=Wt("refresh-cw",G6);const z6=[["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"}]],V6=Wt("scissors",z6);const q6=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Y6=Wt("search",q6);const X6=[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]],J6=Wt("skip-back",X6);const W6=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],Z6=Wt("skip-forward",W6);const $6=[["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M12 21v-9",key:"17s77i"}],["path",{d:"M12 8V3",key:"13r4qs"}],["path",{d:"M17 16h4",key:"h1uq16"}],["path",{d:"M19 12V3",key:"o1uvq1"}],["path",{d:"M19 21v-5",key:"qua636"}],["path",{d:"M3 14h4",key:"bcjad9"}],["path",{d:"M5 10V3",key:"cb8scm"}],["path",{d:"M5 21v-7",key:"1w1uti"}]],eO=Wt("sliders-vertical",$6);const tO=[["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"}]],lw=Wt("sparkles",tO);const AO=[["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"}]],nO=Wt("square-check-big",AO);const rO=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],iO=Wt("square",rO);const aO=[["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"}]],Lf=Wt("trash-2",aO);const sO=[["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"}]],oO=Wt("triangle-alert",sO);const lO=[["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"}]],cO=Wt("upload",lO);const uO=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],Io=Wt("video",uO);const hO=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],I4=Wt("volume-2",hO);const fO=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],F4=Wt("volume-x",fO);const dO=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],gO=Wt("wand-sparkles",dO);const pO=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ds=Wt("x",pO),mO=({activeTab:A,onTabChange:e,activeProjectId:t})=>{const n=[{id:"projects",label:"Projects",icon:Sc,requiresProject:!1},{id:"image",label:"Image Gen",icon:_c,requiresProject:!0},{id:"video",label:"Video Gen",icon:Io,requiresProject:!0}];return b.jsx("div",{className:"flex items-center gap-6",children:n.map(a=>{const s=a.icon,l=A===a.id,c=a.requiresProject&&!t;return b.jsxs("button",{onClick:()=>!c&&e(a.id),disabled:c,title:c?"Select a project first":a.label,className:`relative flex items-center gap-2 px-1 py-2 font-medium transition-all ${c?"text-slate-600 cursor-not-allowed":l?"text-cinema-gold":"text-slate-400 hover:text-slate-200"}`,children:[b.jsx(s,{className:"w-4 h-4"}),b.jsx("span",{children:a.label}),b.jsx("span",{className:`absolute bottom-0 left-0 right-0 h-0.5 bg-cinema-gold transition-all ${l?"opacity-100":"opacity-0"}`})]},a.id)})})};var Ab;(function(A){A.STRING="string",A.NUMBER="number",A.INTEGER="integer",A.BOOLEAN="boolean",A.ARRAY="array",A.OBJECT="object"})(Ab||(Ab={}));var nb;(function(A){A.LANGUAGE_UNSPECIFIED="language_unspecified",A.PYTHON="python"})(nb||(nb={}));var rb;(function(A){A.OUTCOME_UNSPECIFIED="outcome_unspecified",A.OUTCOME_OK="outcome_ok",A.OUTCOME_FAILED="outcome_failed",A.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(rb||(rb={}));const ib=["user","model","function","system"];var ab;(function(A){A.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",A.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",A.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",A.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",A.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",A.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(ab||(ab={}));var sb;(function(A){A.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",A.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",A.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",A.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",A.BLOCK_NONE="BLOCK_NONE"})(sb||(sb={}));var ob;(function(A){A.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",A.NEGLIGIBLE="NEGLIGIBLE",A.LOW="LOW",A.MEDIUM="MEDIUM",A.HIGH="HIGH"})(ob||(ob={}));var lb;(function(A){A.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",A.SAFETY="SAFETY",A.OTHER="OTHER"})(lb||(lb={}));var Of;(function(A){A.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",A.STOP="STOP",A.MAX_TOKENS="MAX_TOKENS",A.SAFETY="SAFETY",A.RECITATION="RECITATION",A.LANGUAGE="LANGUAGE",A.BLOCKLIST="BLOCKLIST",A.PROHIBITED_CONTENT="PROHIBITED_CONTENT",A.SPII="SPII",A.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",A.OTHER="OTHER"})(Of||(Of={}));var cb;(function(A){A.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",A.RETRIEVAL_QUERY="RETRIEVAL_QUERY",A.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",A.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",A.CLASSIFICATION="CLASSIFICATION",A.CLUSTERING="CLUSTERING"})(cb||(cb={}));var ub;(function(A){A.MODE_UNSPECIFIED="MODE_UNSPECIFIED",A.AUTO="AUTO",A.ANY="ANY",A.NONE="NONE"})(ub||(ub={}));var hb;(function(A){A.MODE_UNSPECIFIED="MODE_UNSPECIFIED",A.MODE_DYNAMIC="MODE_DYNAMIC"})(hb||(hb={}));class Vr extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class Mu extends Vr{constructor(e,t){super(e),this.response=t}}class T4 extends Vr{constructor(e,t,n,a){super(e),this.status=t,this.statusText=n,this.errorDetails=a}}class Ll extends Vr{}class _4 extends Vr{}const wO="https://generativelanguage.googleapis.com",vO="v1beta",yO="0.24.1",BO="genai-js";var jc;(function(A){A.GENERATE_CONTENT="generateContent",A.STREAM_GENERATE_CONTENT="streamGenerateContent",A.COUNT_TOKENS="countTokens",A.EMBED_CONTENT="embedContent",A.BATCH_EMBED_CONTENTS="batchEmbedContents"})(jc||(jc={}));class CO{constructor(e,t,n,a,s){this.model=e,this.task=t,this.apiKey=n,this.stream=a,this.requestOptions=s}toString(){var e,t;const n=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||vO;let s=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||wO}/${n}/${this.model}:${this.task}`;return this.stream&&(s+="?alt=sse"),s}}function bO(A){const e=[];return A?.apiClient&&e.push(A.apiClient),e.push(`${BO}/${yO}`),e.join(" ")}async function EO(A){var e;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",bO(A.requestOptions)),t.append("x-goog-api-key",A.apiKey);let n=(e=A.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(a){throw new Ll(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${a.message}`)}for(const[a,s]of n.entries()){if(a==="x-goog-api-key")throw new Ll(`Cannot set reserved header name ${a}`);if(a==="x-goog-api-client")throw new Ll(`Header name ${a} can only be set using the apiClient field`);t.append(a,s)}}return t}async function xO(A,e,t,n,a,s){const l=new CO(A,e,t,n,s);return{url:l.toString(),fetchOptions:Object.assign(Object.assign({},FO(s)),{method:"POST",headers:await EO(l),body:a})}}async function fd(A,e,t,n,a,s={},l=fetch){const{url:c,fetchOptions:h}=await xO(A,e,t,n,a,s);return SO(c,h,l)}async function SO(A,e,t=fetch){let n;try{n=await t(A,e)}catch(a){UO(a,A)}return n.ok||await IO(n,A),n}function UO(A,e){let t=A;throw t.name==="AbortError"?(t=new _4(`Request aborted when fetching ${e.toString()}: ${A.message}`),t.stack=A.stack):A instanceof T4||A instanceof Ll||(t=new Vr(`Error fetching from ${e.toString()}: ${A.message}`),t.stack=A.stack),t}async function IO(A,e){let t="",n;try{const a=await A.json();t=a.error.message,a.error.details&&(t+=` ${JSON.stringify(a.error.details)}`,n=a.error.details)}catch{}throw new T4(`Error fetching from ${e.toString()}: [${A.status} ${A.statusText}] ${t}`,A.status,A.statusText,n)}function FO(A){const e={};if(A?.signal!==void 0||A?.timeout>=0){const t=new AbortController;A?.timeout>=0&&setTimeout(()=>t.abort(),A.timeout),A?.signal&&A.signal.addEventListener("abort",()=>{t.abort()}),e.signal=t.signal}return e}function Av(A){return A.text=()=>{if(A.candidates&&A.candidates.length>0){if(A.candidates.length>1&&console.warn(`This response had ${A.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),np(A.candidates[0]))throw new Mu(`${yl(A)}`,A);return TO(A)}else if(A.promptFeedback)throw new Mu(`Text not available. ${yl(A)}`,A);return""},A.functionCall=()=>{if(A.candidates&&A.candidates.length>0){if(A.candidates.length>1&&console.warn(`This response had ${A.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),np(A.candidates[0]))throw new Mu(`${yl(A)}`,A);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),fb(A)[0]}else if(A.promptFeedback)throw new Mu(`Function call not available. ${yl(A)}`,A)},A.functionCalls=()=>{if(A.candidates&&A.candidates.length>0){if(A.candidates.length>1&&console.warn(`This response had ${A.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),np(A.candidates[0]))throw new Mu(`${yl(A)}`,A);return fb(A)}else if(A.promptFeedback)throw new Mu(`Function call not available. ${yl(A)}`,A)},A}function TO(A){var e,t,n,a;const s=[];if(!((t=(e=A.candidates)===null||e===void 0?void 0:e[0].content)===null||t===void 0)&&t.parts)for(const l of(a=(n=A.candidates)===null||n===void 0?void 0:n[0].content)===null||a===void 0?void 0:a.parts)l.text&&s.push(l.text),l.executableCode&&s.push("\n```"+l.executableCode.language+` +`+l.executableCode.code+"\n```\n"),l.codeExecutionResult&&s.push("\n```\n"+l.codeExecutionResult.output+"\n```\n");return s.length>0?s.join(""):""}function fb(A){var e,t,n,a;const s=[];if(!((t=(e=A.candidates)===null||e===void 0?void 0:e[0].content)===null||t===void 0)&&t.parts)for(const l of(a=(n=A.candidates)===null||n===void 0?void 0:n[0].content)===null||a===void 0?void 0:a.parts)l.functionCall&&s.push(l.functionCall);if(s.length>0)return s}const _O=[Of.RECITATION,Of.SAFETY,Of.LANGUAGE];function np(A){return!!A.finishReason&&_O.includes(A.finishReason)}function yl(A){var e,t,n;let a="";if((!A.candidates||A.candidates.length===0)&&A.promptFeedback)a+="Response was blocked",!((e=A.promptFeedback)===null||e===void 0)&&e.blockReason&&(a+=` due to ${A.promptFeedback.blockReason}`),!((t=A.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(a+=`: ${A.promptFeedback.blockReasonMessage}`);else if(!((n=A.candidates)===null||n===void 0)&&n[0]){const s=A.candidates[0];np(s)&&(a+=`Candidate was blocked due to ${s.finishReason}`,s.finishMessage&&(a+=`: ${s.finishMessage}`))}return a}function Zf(A){return this instanceof Zf?(this.v=A,this):new Zf(A)}function NO(A,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(A,e||[]),a,s=[];return a={},l("next"),l("throw"),l("return"),a[Symbol.asyncIterator]=function(){return this},a;function l(C){n[C]&&(a[C]=function(v){return new Promise(function(I,x){s.push([C,v,I,x])>1||c(C,v)})})}function c(C,v){try{h(n[C](v))}catch(I){y(s[0][3],I)}}function h(C){C.value instanceof Zf?Promise.resolve(C.value.v).then(f,g):y(s[0][2],C)}function f(C){c("next",C)}function g(C){c("throw",C)}function y(C,v){C(v),s.shift(),s.length&&c(s[0][0],s[0][1])}}const db=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function QO(A){const e=A.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),t=RO(e),[n,a]=t.tee();return{stream:OO(n),response:LO(a)}}async function LO(A){const e=[],t=A.getReader();for(;;){const{done:n,value:a}=await t.read();if(n)return Av(kO(e));e.push(a)}}function OO(A){return NO(this,arguments,function*(){const t=A.getReader();for(;;){const{value:n,done:a}=yield Zf(t.read());if(a)break;yield yield Zf(Av(n))}})}function RO(A){const e=A.getReader();return new ReadableStream({start(n){let a="";return s();function s(){return e.read().then(({value:l,done:c})=>{if(c){if(a.trim()){n.error(new Vr("Failed to parse stream"));return}n.close();return}a+=l;let h=a.match(db),f;for(;h;){try{f=JSON.parse(h[1])}catch{n.error(new Vr(`Error parsing JSON response: "${h[1]}"`));return}n.enqueue(f),a=a.substring(h[0].length),h=a.match(db)}return s()}).catch(l=>{let c=l;throw c.stack=l.stack,c.name==="AbortError"?c=new _4("Request aborted when reading from the stream"):c=new Vr("Error reading from the stream"),c})}}})}function kO(A){const e=A[A.length-1],t={promptFeedback:e?.promptFeedback};for(const n of A){if(n.candidates){let a=0;for(const s of n.candidates)if(t.candidates||(t.candidates=[]),t.candidates[a]||(t.candidates[a]={index:a}),t.candidates[a].citationMetadata=s.citationMetadata,t.candidates[a].groundingMetadata=s.groundingMetadata,t.candidates[a].finishReason=s.finishReason,t.candidates[a].finishMessage=s.finishMessage,t.candidates[a].safetyRatings=s.safetyRatings,s.content&&s.content.parts){t.candidates[a].content||(t.candidates[a].content={role:s.content.role||"user",parts:[]});const l={};for(const c of s.content.parts)c.text&&(l.text=c.text),c.functionCall&&(l.functionCall=c.functionCall),c.executableCode&&(l.executableCode=c.executableCode),c.codeExecutionResult&&(l.codeExecutionResult=c.codeExecutionResult),Object.keys(l).length===0&&(l.text=""),t.candidates[a].content.parts.push(l)}a++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function N4(A,e,t,n){const a=await fd(e,jc.STREAM_GENERATE_CONTENT,A,!0,JSON.stringify(t),n);return QO(a)}async function Q4(A,e,t,n){const s=await(await fd(e,jc.GENERATE_CONTENT,A,!1,JSON.stringify(t),n)).json();return{response:Av(s)}}function L4(A){if(A!=null){if(typeof A=="string")return{role:"system",parts:[{text:A}]};if(A.text)return{role:"system",parts:[A]};if(A.parts)return A.role?A:{role:"system",parts:A.parts}}}function $f(A){let e=[];if(typeof A=="string")e=[{text:A}];else for(const t of A)typeof t=="string"?e.push({text:t}):e.push(t);return HO(e)}function HO(A){const e={role:"user",parts:[]},t={role:"function",parts:[]};let n=!1,a=!1;for(const s of A)"functionResponse"in s?(t.parts.push(s),a=!0):(e.parts.push(s),n=!0);if(n&&a)throw new Vr("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!n&&!a)throw new Vr("No content is provided for sending chat message.");return n?e:t}function DO(A,e){var t;let n={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(t=e?.cachedContent)===null||t===void 0?void 0:t.name,contents:[]};const a=A.generateContentRequest!=null;if(A.contents){if(a)throw new Ll("CountTokensRequest must have one of contents or generateContentRequest, not both.");n.contents=A.contents}else if(a)n=Object.assign(Object.assign({},n),A.generateContentRequest);else{const s=$f(A);n.contents=[s]}return{generateContentRequest:n}}function gb(A){let e;return A.contents?e=A:e={contents:[$f(A)]},A.systemInstruction&&(e.systemInstruction=L4(A.systemInstruction)),e}function MO(A){return typeof A=="string"||Array.isArray(A)?{content:$f(A)}:A}const pb=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],PO={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function jO(A){let e=!1;for(const t of A){const{role:n,parts:a}=t;if(!e&&n!=="user")throw new Vr(`First content should be with role 'user', got ${n}`);if(!ib.includes(n))throw new Vr(`Each item should include role field. Got ${n} but valid roles are: ${JSON.stringify(ib)}`);if(!Array.isArray(a))throw new Vr("Content should have 'parts' property with an array of Parts");if(a.length===0)throw new Vr("Each Content should have at least one part");const s={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const c of a)for(const h of pb)h in c&&(s[h]+=1);const l=PO[n];for(const c of pb)if(!l.includes(c)&&s[c]>0)throw new Vr(`Content with role '${n}' can't contain '${c}' part`);e=!0}}function mb(A){var e;if(A.candidates===void 0||A.candidates.length===0)return!1;const t=(e=A.candidates[0])===null||e===void 0?void 0:e.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(const n of t.parts)if(n===void 0||Object.keys(n).length===0||n.text!==void 0&&n.text==="")return!1;return!0}const wb="SILENT_ERROR";class KO{constructor(e,t,n,a={}){this.model=t,this.params=n,this._requestOptions=a,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&(jO(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){var n,a,s,l,c,h;await this._sendPromise;const f=$f(e),g={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(a=this.params)===null||a===void 0?void 0:a.generationConfig,tools:(s=this.params)===null||s===void 0?void 0:s.tools,toolConfig:(l=this.params)===null||l===void 0?void 0:l.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(h=this.params)===null||h===void 0?void 0:h.cachedContent,contents:[...this._history,f]},y=Object.assign(Object.assign({},this._requestOptions),t);let C;return this._sendPromise=this._sendPromise.then(()=>Q4(this._apiKey,this.model,g,y)).then(v=>{var I;if(mb(v.response)){this._history.push(f);const x=Object.assign({parts:[],role:"model"},(I=v.response.candidates)===null||I===void 0?void 0:I[0].content);this._history.push(x)}else{const x=yl(v.response);x&&console.warn(`sendMessage() was unsuccessful. ${x}. Inspect response object for details.`)}C=v}).catch(v=>{throw this._sendPromise=Promise.resolve(),v}),await this._sendPromise,C}async sendMessageStream(e,t={}){var n,a,s,l,c,h;await this._sendPromise;const f=$f(e),g={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(a=this.params)===null||a===void 0?void 0:a.generationConfig,tools:(s=this.params)===null||s===void 0?void 0:s.tools,toolConfig:(l=this.params)===null||l===void 0?void 0:l.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(h=this.params)===null||h===void 0?void 0:h.cachedContent,contents:[...this._history,f]},y=Object.assign(Object.assign({},this._requestOptions),t),C=N4(this._apiKey,this.model,g,y);return this._sendPromise=this._sendPromise.then(()=>C).catch(v=>{throw new Error(wb)}).then(v=>v.response).then(v=>{if(mb(v)){this._history.push(f);const I=Object.assign({},v.candidates[0].content);I.role||(I.role="model"),this._history.push(I)}else{const I=yl(v);I&&console.warn(`sendMessageStream() was unsuccessful. ${I}. Inspect response object for details.`)}}).catch(v=>{v.message!==wb&&console.error(v)}),C}}async function GO(A,e,t,n){return(await fd(e,jc.COUNT_TOKENS,A,!1,JSON.stringify(t),n)).json()}async function zO(A,e,t,n){return(await fd(e,jc.EMBED_CONTENT,A,!1,JSON.stringify(t),n)).json()}async function VO(A,e,t,n){const a=t.requests.map(l=>Object.assign(Object.assign({},l),{model:e}));return(await fd(e,jc.BATCH_EMBED_CONTENTS,A,!1,JSON.stringify({requests:a}),n)).json()}class vb{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=L4(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){var n;const a=gb(e),s=Object.assign(Object.assign({},this._requestOptions),t);return Q4(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},a),s)}async generateContentStream(e,t={}){var n;const a=gb(e),s=Object.assign(Object.assign({},this._requestOptions),t);return N4(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},a),s)}startChat(e){var t;return new KO(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(t=this.cachedContent)===null||t===void 0?void 0:t.name},e),this._requestOptions)}async countTokens(e,t={}){const n=DO(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),a=Object.assign(Object.assign({},this._requestOptions),t);return GO(this.apiKey,this.model,n,a)}async embedContent(e,t={}){const n=MO(e),a=Object.assign(Object.assign({},this._requestOptions),t);return zO(this.apiKey,this.model,n,a)}async batchEmbedContents(e,t={}){const n=Object.assign(Object.assign({},this._requestOptions),t);return VO(this.apiKey,this.model,e,n)}}class O4{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new Vr("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new vb(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new Ll("Cached content must contain a `name` field.");if(!e.model)throw new Ll("Cached content must contain a `model` field.");const a=["model","systemInstruction"];for(const l of a)if(t?.[l]&&e[l]&&t?.[l]!==e[l]){if(l==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,h=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(c===h)continue}throw new Ll(`Different value for "${l}" specified in modelParams (${t[l]}) and cachedContent (${e[l]})`)}const s=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new vb(this.apiKey,s,n)}}const qO="CinemaStudioPro",YO=3,XO={projects:{keyPath:"id",indexes:["name","updatedAt","userId"]},items:{keyPath:"id",indexes:["projectId","type","createdAt"]},storyboards:{keyPath:"id",indexes:["projectId","updatedAt"]}},JO=()=>{const[A,e]=ae.useState(null),[t,n]=ae.useState(!1),[a,s]=ae.useState(null);ae.useEffect(()=>(new Promise((x,_)=>{const T=indexedDB.open(qO,YO);T.onerror=()=>{_(new Error("Failed to open database"))},T.onsuccess=k=>{x(k.target.result)},T.onupgradeneeded=k=>{const z=k.target.result,H=k.target.transaction;Object.entries(XO).forEach(([re,le])=>{let ce;z.objectStoreNames.contains(re)?ce=H.objectStore(re):ce=z.createObjectStore(re,{keyPath:le.keyPath}),le.indexes.forEach($=>{ce.indexNames.contains($)||ce.createIndex($,$,{unique:!1})})})}}).then(x=>{e(x),n(!0)}).catch(x=>{s(x.message),console.error("IndexedDB initialization failed:",x)}),()=>{A&&A.close()}),[]);const l=ae.useCallback((I,x)=>new Promise((_,T)=>{if(!A){T(new Error("Database not initialized"));return}const H=A.transaction(I,"readwrite").objectStore(I).add(x);H.onsuccess=()=>_(x),H.onerror=()=>T(new Error(`Failed to add to ${I}`))}),[A]),c=ae.useCallback((I,x)=>new Promise((_,T)=>{if(!A){T(new Error("Database not initialized"));return}const H=A.transaction(I,"readwrite").objectStore(I).put(x);H.onsuccess=()=>_(x),H.onerror=()=>T(new Error(`Failed to update ${I}`))}),[A]),h=ae.useCallback((I,x)=>new Promise((_,T)=>{if(!A){T(new Error("Database not initialized"));return}const H=A.transaction(I,"readonly").objectStore(I).get(x);H.onsuccess=()=>_(H.result),H.onerror=()=>T(new Error(`Failed to get from ${I}`))}),[A]),f=ae.useCallback(I=>new Promise((x,_)=>{if(!A){_(new Error("Database not initialized"));return}const z=A.transaction(I,"readonly").objectStore(I).getAll();z.onsuccess=()=>x(z.result||[]),z.onerror=()=>_(new Error(`Failed to get all from ${I}`))}),[A]),g=ae.useCallback((I,x,_)=>new Promise((T,k)=>{if(!A){k(new Error("Database not initialized"));return}const le=A.transaction(I,"readonly").objectStore(I).index(x).getAll(_);le.onsuccess=()=>T(le.result||[]),le.onerror=()=>k(new Error(`Failed to query ${I} by ${x}`))}),[A]),y=ae.useCallback((I,x)=>new Promise((_,T)=>{if(!A){T(new Error("Database not initialized"));return}const H=A.transaction(I,"readwrite").objectStore(I).delete(x);H.onsuccess=()=>_(!0),H.onerror=()=>T(new Error(`Failed to delete from ${I}`))}),[A]),C=ae.useCallback(I=>new Promise((x,_)=>{if(!A){_(new Error("Database not initialized"));return}const z=A.transaction(I,"readwrite").objectStore(I).clear();z.onsuccess=()=>x(!0),z.onerror=()=>_(new Error(`Failed to clear ${I}`))}),[A]),v=ae.useCallback(I=>new Promise((x,_)=>{if(!A){_(new Error("Database not initialized"));return}const z=A.transaction(I,"readonly").objectStore(I).count();z.onsuccess=()=>x(z.result),z.onerror=()=>_(new Error(`Failed to count ${I}`))}),[A]);return{isReady:t,error:a,add:l,put:c,get:h,getAll:f,getByIndex:g,remove:y,clear:C,count:v}},nv=()=>{const{isReady:A,error:e,add:t,put:n,get:a,getAll:s,getByIndex:l,remove:c}=JO(),{user:h}=tv(),f=h?.id||"local",[g,y]=ae.useState([]),[C,v]=ae.useState(!0),[I,x]=ae.useState(null),_=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,N=>{const G=Math.random()*16|0;return(N==="x"?G:G&3|8).toString(16)});ae.useEffect(()=>{A&&T()},[A]);const T=async()=>{v(!0);try{const N=await s("projects"),G=[];for(const he of N)if(he.userId)he.userId===f&&G.push(he);else{const Ne={...he,userId:f};await n("projects",Ne),G.push(Ne)}const W=G.sort((he,Ne)=>Ne.updatedAt-he.updatedAt);y(W),x(null)}catch(N){x(N.message),console.error("Failed to load projects:",N)}finally{v(!1)}},k=ae.useCallback(async N=>{if(!N?.trim())throw new Error("Project name is required");const G={id:_(),userId:f,name:N.trim(),createdAt:Date.now(),updatedAt:Date.now()};try{return await t("projects",G),y(W=>[G,...W]),G}catch(W){throw x(W.message),W}},[t]),z=ae.useCallback(async N=>{try{const G=await l("items","projectId",N);for(const W of G)await c("items",W.id);return await c("projects",N),y(W=>W.filter(he=>he.id!==N)),!0}catch(G){throw x(G.message),G}},[l,c]),H=ae.useCallback(async(N,G)=>{if(!G?.trim())throw new Error("Project name is required");try{const W=await a("projects",N);if(!W)throw new Error("Project not found");const he={...W,name:G.trim(),updatedAt:Date.now()};return await n("projects",he),y(Ne=>Ne.map(P=>P.id===N?he:P).sort((P,S)=>S.updatedAt-P.updatedAt)),he}catch(W){throw x(W.message),W}},[a,n]),re=ae.useCallback(async(N,G)=>{const W={id:_(),projectId:N,type:G.type,prompt:G.prompt,settings:G.settings||{},referenceImages:G.referenceImages||[],thumbnail:G.thumbnail||null,data:G.data,mimeType:G.mimeType||"image/png",createdAt:Date.now()};try{await t("items",W);const he=await a("projects",N);return he&&(await n("projects",{...he,updatedAt:Date.now()}),y(Ne=>Ne.map(P=>P.id===N?{...P,updatedAt:Date.now()}:P).sort((P,S)=>S.updatedAt-P.updatedAt))),W}catch(he){throw x(he.message),he}},[t,a,n]),le=ae.useCallback(async(N,G)=>{try{await c("items",G);const W=await a("projects",N);return W&&await n("projects",{...W,updatedAt:Date.now()}),!0}catch(W){throw x(W.message),W}},[a,n,c]),ce=ae.useCallback(async N=>{try{return(await l("items","projectId",N)).sort((W,he)=>he.createdAt-W.createdAt)}catch(G){throw x(G.message),G}},[l]),$=ae.useCallback(async N=>{try{const G=await a("projects",N);if(!G)throw new Error("Project not found");const W=await ce(N);return{...G,items:W}}catch(G){throw x(G.message),G}},[a,ce]),Y=ae.useCallback(async N=>{try{const G=await $(N);return{version:1,exportedAt:Date.now(),project:G}}catch(G){throw x(G.message),G}},[$]),de=ae.useCallback(async(N,G,W=[])=>{if(!G?.trim())throw new Error("Storyboard name is required");const he=W.map((P,S)=>({imageId:P,order:S,annotation:""})),Ne={id:_(),projectId:N,name:G.trim(),frames:he,createdAt:Date.now(),updatedAt:Date.now()};try{return await t("storyboards",Ne),Ne}catch(P){throw x(P.message),P}},[t]),R=ae.useCallback(async N=>{try{return(await l("storyboards","projectId",N)).sort((W,he)=>he.updatedAt-W.updatedAt)}catch(G){throw x(G.message),G}},[l]),V=ae.useCallback(async N=>{try{return await a("storyboards",N)}catch(G){throw x(G.message),G}},[a]),ne=ae.useCallback(async(N,G)=>{try{const W=await a("storyboards",N);if(!W)throw new Error("Storyboard not found");const he={...W,...G,updatedAt:Date.now()};return await n("storyboards",he),he}catch(W){throw x(W.message),W}},[a,n]),Ae=ae.useCallback(async N=>{try{return await c("storyboards",N),!0}catch(G){throw x(G.message),G}},[c]),Ce=ae.useCallback(async N=>{try{const{project:G}=N,W={...G,id:_(),userId:f,name:`${G.name} (imported)`,createdAt:Date.now(),updatedAt:Date.now()};if(await t("projects",W),G.items)for(const he of G.items)await t("items",{...he,id:_(),projectId:W.id,createdAt:Date.now()});return await T(),W}catch(G){throw x(G.message),G}},[t,T]);return{projects:g,isLoading:C,isReady:A,error:I||e,createProject:k,deleteProject:z,renameProject:H,addItemToProject:re,removeItemFromProject:le,getProjectItems:ce,getProjectWithItems:$,exportProject:Y,importProject:Ce,refreshProjects:T,createStoryboard:de,getStoryboards:R,getStoryboard:V,updateStoryboard:ne,deleteStoryboard:Ae}},Sl=A=>`/lux-studio/api/${A}`,WO=({activeProjectId:A,editData:e,onEditLoaded:t})=>{const{addItemToProject:n,getProjectWithItems:a,isReady:s}=nv(),l=[{value:"Arri Alexa 35",display:"Arri Alexa 35",sensorFormat:"Super 35",tooltip:"The Hollywood Standard. Best for natural skin tones and a classic cinematic 'blockbuster' feel.",tags:"Narrative / Drama",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Laowa Probe"],physics:"ArriRaw sensor readout, high dynamic range, natural noise floor, thick color science"},{value:"Sony Venice 2",display:"Sony Venice 2",sensorFormat:"Full Frame",tooltip:"The Low-Light King. Excellent for night scenes, clean shadows, and a modern aesthetic.",tags:"Commercial / Night",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Arri Signature","Laowa Probe"],physics:"Dual ISO digital sensor, clean shadows, modern color science, high frequency detail"},{value:"Red V-Raptor",display:"Red V-Raptor",sensorFormat:"Full Frame",tooltip:"Hyper-Real Action. Perfect for high-speed motion, sports, and razor-sharp detail.",tags:"Action / Sports",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Arri Signature","Laowa Probe"],physics:"RedCode RAW 8K, clinical sharpness, high shutter angle clarity, hyper-realistic texture"},{value:"Arriflex 416",display:"Arriflex 416",sensorFormat:"Super 16 (Film)",tooltip:"Gritty & Nostalgic. High grain, soft focus, and vibrant, messy colors. The 'Indie' look.",tags:"Vintage / Music Video",compatibleLenses:["Zeiss Super Speed","Laowa Probe"],physics:"Super 16mm film gate, heavy grain structure, soft optical resolution, vibrant chemical color"},{value:"Arricam LT",display:"Arricam LT",sensorFormat:"35mm (Film)",tooltip:"The Golden Age. Fine grain, organic texture, and rich colors. The classic movie look before digital.",tags:"Period Piece / Premium",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Laowa Probe"],physics:"35mm motion picture film stock, organic grain structure, halation on highlights, photochemical dynamic range"},{value:"Fujifilm GFX 100",display:"Fujifilm GFX 100",sensorFormat:"Medium Format",tooltip:"The Studio Master. Massive resolution and depth. Unbeatable for print-quality stills.",tags:"Product / Fashion",compatibleLenses:["Fujinon GF","Arri Signature","Laowa Probe"],physics:"Medium format digital sensor, zero circle of confusion, extreme resolution, pore-level detail"},{value:"Phantom Flex4K",display:"Phantom Flex4K",sensorFormat:"Super 35",tooltip:"The Time Machine. 1000fps slow motion.",tags:"High-Speed / Sports",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Laowa Probe","Angénieux Optimo"],physics:"High-speed global shutter sensor, frozen fluid dynamics, zero motion blur, deep saturation, specialized for 1000fps playback"},{value:"Blackmagic URSA Cine 12K",display:"URSA Cine 12K",sensorFormat:"Full Frame",tooltip:"Resolution Monster. Infinite reframing capability.",tags:"Future-Proof / VFX",compatibleLenses:["Panavision C-Series","Cooke S7/i","Canon K-35","Arri Signature","Laowa Probe","Canon TS-E","Angénieux Optimo"],physics:"12K RGB sensor, extreme resolution, zero aliasing, distinct non-bayer pattern texture, analytics-grade sharpness"}],c=[{value:"Panavision C-Series",display:"Panavision C-Series",compatibleFormats:["Super 35","35mm"],tooltip:"Classic Widescreen. Horizontal blue flares, oval bokeh. The sci-fi blockbuster look.",keywords:"Flares, Oval Bokeh",physics:"anamorphic optics, characteristic oval bokeh, horizontal blue lens flares, slight barrel distortion"},{value:"Cooke S7/i",display:"Cooke S7/i",compatibleFormats:["Full Frame","Super 35","35mm"],tooltip:"The 'Cooke Look.' Warm, gentle, and incredibly flattering. Gold standard for portraits.",keywords:"Warmth, Face Focus",physics:"Cooke speed panchrio look, warm color rendering, gentle focus falloff, flattering face compression"},{value:"Canon K-35",display:"Canon K-35",compatibleFormats:["Full Frame","Super 35","35mm"],tooltip:"Dreamy & Retro. Low contrast, glowing highlights. 1970s/80s vibe.",keywords:"Glow, Retro",physics:"vintage aspherical elements, glowing highlights, low contrast, rainbow flaring, soft sharpness"},{value:"Arri Signature",display:"Arri Signature",compatibleFormats:["Large Format","Full Frame"],tooltip:"Modern Perfection. Ultra-clean, no distortion, pure reality. The invisible lens.",keywords:"Clean, Realistic",physics:"telecentric optical design, zero breathing, ultra-flat field, modern rendering, pure black levels"},{value:"Zeiss Super Speed",display:"Zeiss Super Speed",compatibleFormats:["Super 16 ONLY"],tooltip:"The 16mm Classic. Sharp but textured. Designed specifically for the smaller 16mm film frame.",keywords:"Triangular Bokeh, Grit",physics:"vintage high-speed glass, triangular bokeh at wide apertures, chromatic aberration, gritty texture"},{value:"Fujinon GF",display:"Fujinon GF",compatibleFormats:["Medium Format ONLY"],tooltip:"Studio Glass. Clinically sharp, specifically designed for the massive GFX sensor.",keywords:"Clinical Sharpness",physics:"modern medium format optics, clinical edge-to-edge sharpness, zero distortion, high micro-contrast"},{value:"Laowa Probe",display:"Laowa Probe",compatibleFormats:["All Formats"],tooltip:"Insect-Eye View. Extreme close-ups of small objects/textures.",keywords:"Macro",physics:"macro bug-eye perspective, extreme depth of field, tubular lens construction, surreal wide-angle macro"},{value:"Helios 44-2",display:"Helios 44-2 (Vintage)",compatibleFormats:["Full Frame","Super 35","35mm"],tooltip:"Swirly Bokeh. The cult classic.",keywords:"Swirly Bokeh, Vintage",physics:"Vintage Soviet glass, characteristic swirly bokeh at edges, low contrast flaring, soft center focus, dreamlike aberrations"},{value:"Canon TS-E",display:"Canon Tilt-Shift",compatibleFormats:["Full Frame","Medium Format"],tooltip:"Miniature Effect. Selective focus control.",keywords:"Tilt-Shift, Miniature",physics:"Tilted focal plane, miniature faking effect, selective focus slice, corrected perspective lines, architectural rigidity"},{value:"Angénieux Optimo",display:"Angénieux Optimo",compatibleFormats:["Super 35","Full Frame"],tooltip:"The Hollywood Zoom. Perfect versatility.",keywords:"Cinema Zoom",physics:"Cinema zoom optics, warm organic contrast, breathing-free focus pulls, uniform field illumination"}],h=[{value:"Portrait Studio",lighting:"Rembrandt lighting, softbox diffusion, 3-point setup",defaultCamera:"Arri Alexa 35",defaultLens:"Cooke S7/i",focusType:"stylistic"},{value:"Product (Crisp)",lighting:"Infinity curve, bright diffuse lighting, shadowless, high key",defaultCamera:"Fujifilm GFX 100",defaultLens:"Fujinon GF",focusType:"realism"},{value:"Food Photography",lighting:"Natural window light simulation, back-lighting for steam/texture, warm reflector fill, medium depth of field, focus on texture",defaultCamera:"Sony Venice 2",defaultLens:"Cooke S7/i",focusType:"stylistic"},{value:"Golden Hour (Outdoor)",lighting:"Sun low on horizon, warm orange glow, long dramatic shadows, volumetric backlight, magic hour atmosphere, cinematic depth",defaultCamera:"Arricam LT",defaultLens:"Cooke S7/i",focusType:"stylistic",example:"A vintage Lancia Stratos rally car drifting sideways on a dirt track, kicking up a massive wall of dust that glows incandescent gold in the backlight, creating a dramatic silhouette against the sunset."},{value:"Blue Hour (City)",lighting:"Twilight, deep blue ambient sky light contrasting with warm practical street lamps, moody, atmospheric, balanced exposure",defaultCamera:"Sony Venice 2",defaultLens:"Arri Signature",focusType:"stylistic"},{value:"Neon Cyberpunk",lighting:"Harsh neon signage, mixed color temp, wet reflections",defaultCamera:"Red V-Raptor",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Nostalgic Memory",lighting:"Hazy atmosphere, overexposed highlights, light leaks, warm color grade, sentimental mood, soft focus throughout",defaultCamera:"Arriflex 416",defaultLens:"Zeiss Super Speed",focusType:"stylistic"},{value:"Corporate Headshot",lighting:"Clean white background, high-key lighting, professional balanced fill, sharp focus on eyes, moderate depth of field",defaultCamera:"Fuji GFX 100",defaultLens:"Cooke S7/i",focusType:"realism"},{value:"Macro: Luxury Jewelry",lighting:"Sparkling point-source lighting, black velvet background, high contrast reflection control, focus stacking simulation for complete sharpness",defaultCamera:"Fuji GFX 100",defaultLens:"Macro / Probe Lens",focusType:"realism"},{value:"Macro: Nature Details",lighting:"Diffused natural sunlight, shallow depth of field, vibrant greens, morning dew, microscopic texture",defaultCamera:"Arri Alexa 35",defaultLens:"Macro / Probe Lens",focusType:"stylistic"},{value:"Wildlife / Safari",lighting:"Telephoto compression, frozen motion, golden hour backlight, natural habitat, separation from background",defaultCamera:"Red V-Raptor",defaultLens:"Cooke S7/i",focusType:"stylistic"},{value:"Sports Action",lighting:"High shutter speed, frozen particles/sweat, stadium floodlights, dynamic composition, sharp subject focus",defaultCamera:"Red V-Raptor",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Street Photography",lighting:"Candid moment, natural available light, messy urban background, hyperfocal distance, deep depth of field, everything in focus",defaultCamera:"Arriflex 416",defaultLens:"Canon K-35",focusType:"realism"},{value:"Architecture",lighting:"Balanced mixed lighting, straight lines, airy atmosphere",defaultCamera:"Fujifilm GFX 100",defaultLens:"Fujinon GF",focusType:"realism"},{value:"Fashion Editorial",lighting:"Avant-garde lighting, colored gels, stark shadows, high fashion pose, studio backdrop, stylized depth",defaultCamera:"Sony Venice 2",defaultLens:"Canon K-35",focusType:"stylistic"},{value:"Cinematic Horror",lighting:"Underexposed, single harsh source (flashlight), heavy shadows",defaultCamera:"Arricam LT",defaultLens:"Canon K-35",focusType:"stylistic"},{value:"Docu / Realism",lighting:"Natural window key light, negative fill, messy authentic background",defaultCamera:"Arri Alexa 35",defaultLens:"Arri Signature",focusType:"realism"},{value:"Symmetrical Whimsy",lighting:"Even soft lighting, centered symmetrical composition, muted earth tones with subtle color accents, overcast natural light, deadpan framing, tactile real-world textures",defaultCamera:"Arricam LT",defaultLens:"Arri Signature",focusType:"realism"},{value:"IMAX Scale Epic",lighting:"Naturalistic practical lighting, cool color temperature, high contrast, immense sense of scale, deep depth of field",defaultCamera:"Arri Alexa 35",defaultLens:"Arri Signature",focusType:"realism"},{value:"Clinical Thriller",lighting:"Low-key chiaroscuro, controlled shadows, sickly green/yellow color grade, precise stabilized motion",defaultCamera:"Red V-Raptor",defaultLens:"Arri Signature",focusType:"stylistic"},{value:"Brutalist Atmosphere",lighting:"Single source silhouette, atmospheric haze, monochromatic orange/sepia tones, stark geometry, visual silence",defaultCamera:"Arri Alexa 35",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Technicolor Dream",lighting:"Artificial studio lighting, high saturation, vibrant pinks and cyans, glossy plastic textures, high-key brightness",defaultCamera:"Arri Alexa 35",defaultLens:"Cooke S7/i",focusType:"stylistic"},{value:"Obsessive Symmetry",lighting:"One-point perspective, deep focus, wide angle distortion, cold practical lighting, clinical perfection",defaultCamera:"Arricam LT",defaultLens:"Arri Signature",focusType:"realism"},{value:"Hong Kong Nostalgia",lighting:"Step-printing effect, motion blur, neon-soaked humidity, intimate handheld, rain-slicked textures",defaultCamera:"Arriflex 416",defaultLens:"Zeiss Super Speed",focusType:"stylistic"},{value:"Industrial Haze",lighting:"Volumetric lighting, visible shafts of light (god rays), atmospheric smoke, high-density industrial detail",defaultCamera:"Arri Alexa 35",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Gothic Fantasy",lighting:"German Expressionist lighting, high contrast long shadows, twisted geometry, desaturated palette",defaultCamera:"Arri Alexa 35",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"LED Volume (Virtual Production)",lighting:"Interactive environmental lighting, soft ambient wrap from LED panels, perfect reflection matching, zero green spill",defaultCamera:"Arri Alexa 35",defaultLens:"Arri Signature",focusType:"realism"},{value:"Automotive: Showroom",lighting:"Massive softbox ceiling, continuous highlight lines along bodywork, negative fill to shape curves, pure white infinity cove",defaultCamera:"Sony Venice 2",defaultLens:"Arri Signature",focusType:"realism",example:"A silver concept car parked on a pure white infinity curve, continuous highlight lines tracing the aerodynamic bodywork."},{value:"Knolling / Flat Lay",lighting:"Overhead soft diffuse light, shadowless cavity, high-key evenness, precise grid alignment",defaultCamera:"Fujifilm GFX 100",defaultLens:"Fujinon GF",focusType:"realism"},{value:"Conflict Photography",lighting:"Harsh midday sun, atmospheric dust and smoke, high contrast, documentary style reality, blown highlights, raw and unpolished",defaultCamera:"Arriflex 416",defaultLens:"Zeiss Super Speed",focusType:"realism"},{value:"NYC Street Editorial",lighting:"Natural city canyon light, bounce board fill for face, sharp modern contrast, motion blur in background, high-resolution gloss",defaultCamera:"Sony Venice 2",defaultLens:"Arri Signature",focusType:"stylistic"},{value:"Underground Rave / Flash",lighting:"Direct on-camera flash with slow shutter drag (rear-curtain sync), light trails, laser rim lighting, sweaty atmosphere, darkness crushing the background",defaultCamera:"Red V-Raptor",defaultLens:"Helios 44-2",focusType:"stylistic"},{value:"Architectural Digest Interior",lighting:"North-facing window soft light, large diffusion frames, negative fill for contrast, texture-raking angle, perfectly balanced exposure",defaultCamera:"Fujifilm GFX 100",defaultLens:"Canon TS-E",focusType:"realism"},{value:"90s Grunge Editorial",lighting:"Hard direct flash, dirty green/yellow color cast, vignetting, unretouched skin texture, claustrophobic framing",defaultCamera:"Arriflex 416",defaultLens:"Canon K-35",focusType:"stylistic"},{value:"Cassette Futurism (Retro Sci-Fi)",lighting:"Flickering CRT monitor glow, harsh overhead fluorescent strips, brutalist shadows, beige and grey color palette, industrial haze",defaultCamera:"Arriflex 416",defaultLens:"Panavision C-Series",focusType:"stylistic"},{value:"Tech Commercial (Macro)",lighting:"Slow moving light sweep (motion control), brushed metal reflections, dramatic rim lighting in a black void, sub-surface scattering on materials",defaultCamera:"Arri Alexa 35",defaultLens:"Laowa Probe",focusType:"realism"},{value:"Surreal Infrared",lighting:"Full spectrum daylight, false color infrared shift (foliage turns pink/white), deep blue skies, high contrast, dreamlike atmosphere",defaultCamera:"Arricam LT",defaultLens:"Canon K-35",focusType:"stylistic"},{value:"Spaghetti Western",lighting:"Harsh high-noon sun, heat haze distortion, sweaty skin texture, extreme close-up on eyes, deep depth of field",defaultCamera:"Arricam LT",defaultLens:"Angénieux Optimo",focusType:"stylistic"},{value:"Automotive: Process Trailer",lighting:"Dynamic passing street lights, rhythmic shadow movement, wet road reflections, motion blur on background only",defaultCamera:"Arri Alexa 35",defaultLens:"Angénieux Optimo",focusType:"stylistic",example:"A black sports car speeding through a tunnel, dynamic motion blur on the tunnel lights, sharp focus on the car badge."},{value:"Product (Liquid/Splash)",lighting:"High-speed strobe lighting, frozen droplets, backlit fluid translucency, crystal clear refraction",defaultCamera:"Phantom Flex4K",defaultLens:"Laowa Probe",focusType:"stylistic",example:"A strawberry dropping into milk, creating a perfect crown splash, frozen in mid-air with high-speed strobe lighting."},{value:"VFX / Green Screen",lighting:"Raw chromakey plate, perfectly flat shadowless green background, distinct rim light for separation, zero color spill, high-fidelity capture",defaultCamera:"Blackmagic URSA Cine 12K",defaultLens:"Arri Signature",focusType:"realism",example:"A raw chromakey plate of a superhero in a landing pose, completely isolated against a flat, pure digital green background, sharp focus, ready for compositing."},{value:"Custom",lighting:null,defaultCamera:null,defaultLens:null,focusType:"stylistic"}],f=["16:9","4:3","3:4","1:1","9:16"],[g,y]=ae.useState("Golden Hour (Outdoor)"),[C,v]=ae.useState(""),[I,x]=ae.useState(""),[_,T]=ae.useState("16:9"),[k,z]=ae.useState(""),[H,re]=ae.useState(""),[le,ce]=ae.useState(!1),[$,Y]=ae.useState(!1),[de,R]=ae.useState(""),[V,ne]=ae.useState(null),[Ae,Ce]=ae.useState(c),[N,G]=ae.useState(.3),[W,he]=ae.useState(null),[Ne,P]=ae.useState(!1),[S,Q]=ae.useState(""),[K,Z]=ae.useState([]),[se,ue]=ae.useState("2K"),[be,oe]=ae.useState([]),[ve,He]=ae.useState(!1);ae.useEffect(()=>{const Be=h.find(Ve=>Ve.value===g);Be&&Be.defaultCamera&&(v(Be.defaultCamera),x(Be.defaultLens))},[g]),ae.useEffect(()=>{const Be=h.find(Ve=>Ve.value===g);Be&&(v(Be.defaultCamera||l[0].value),x(Be.defaultLens||c[0].value))},[]),ae.useEffect(()=>{const Be=l.find(Ve=>Ve.value===C);if(Be&&Be.compatibleLenses){const Ve=c.filter(lt=>Be.compatibleLenses.includes(lt.value));Ce(Ve),!Be.compatibleLenses.includes(I)&&Ve.length>0&&x(Ve[0].value)}else Ce(c)},[C]),ae.useEffect(()=>{if(e){if(e.prompt){const Be=e.prompt.replace(/^Uploaded:\s*/i,"");z(Be)}if(e.imageData){let Be=e.imageData,Ve="image/png";if(e.imageData.startsWith("data:")){const lt=e.imageData.match(/^data:([^;]+);base64,(.+)$/);lt&&(Ve=lt[1],Be=lt[2])}he({data:Be,mime_type:Ve})}t&&t()}},[e,t]),ae.useEffect(()=>{(async()=>{if(!A||!s){oe([]);return}try{const Ve=await a(A);if(Ve&&Ve.items){const lt=Ve.items.filter(it=>it.type==="image");oe(lt)}}catch(Ve){console.error("Failed to load project images:",Ve)}})()},[A,s,a]);const Xe=Be=>{K.length>=14||K.some(Ve=>Ve.projectItemId===Be.id)||(Z(Ve=>[...Ve,{data:Be.data,mime_type:Be.mimeType,name:Be.prompt?.substring(0,20)||"Project Image",projectItemId:Be.id}]),He(!1))},$e=Be=>({"16:9":"A cinematic 16:9 horizontal composition featuring","4:3":"A classic 4:3 format composition featuring","3:4":"A 3:4 portrait format composition featuring","1:1":"A square 1:1 format composition featuring","9:16":"A 9:16 portrait format composition featuring"})[Be]||"",nt=Be=>({Architecture:"Strictly AVOID: messy, dirt, grime, imperfections, motion blur, handheld, shaky","Product (Crisp)":"Strictly AVOID: messy, dirt, grime, imperfections, motion blur, handheld, shaky","Corporate Headshot":"Strictly AVOID: shadow over eyes, silhouette, dark, moody, gritty, high contrast","Portrait Studio":"Strictly AVOID: shadow over eyes, silhouette, dark, moody, gritty, high contrast","Cinematic Horror":"Strictly AVOID: bright, cheerful, clean, pristine, high-key, sunshine","Nostalgic Memory":"Strictly AVOID: bright, cheerful, clean, pristine, high-key, sunshine"})[Be]||"",X=Be=>({"Neon Cyberpunk":"Hovering vehicle, rain, neon lights","Golden Hour (Outdoor)":"Vintage convertible, dust kicking up, lens flare","Cinematic Horror":"Distressed clothing, expressions of terror, flashlight beams cutting through fog, unseen threat in shadows","Corporate Headshot":"Business professional attire, confident posture, subtle smile, perfectly groomed","Portrait Studio":"Professional studio setup, controlled lighting, posed subject","Fashion Editorial":"High fashion couture, avant-garde styling, dramatic poses, editorial expression","Street Photography":"Authentic street fashion, candid moments, urban environment, real people","Blue Hour (City)":"Urban nightlife fashion, city lights reflecting, atmospheric fog, metropolitan energy","Wildlife / Safari":"Natural habitat, majestic animals, golden savanna light, environmental storytelling","Symmetrical Whimsy":"Perfectly centered vintage car, pastel luggage on roof, quirkily dressed driver","IMAX Scale Epic":"Lone rover traversing massive alien glacier, tiny against the landscape","Clinical Thriller":"Sterile hospital corridor, flickering fluorescent light, solitary figure","Brutalist Atmosphere":"Concrete monolith, lone figure dwarfed by structure, dust particles","Technicolor Dream":"Plastic fantastic furniture, bubble machines, candy-colored wardrobe","Obsessive Symmetry":"Identical twins in matching outfits, geometric patterns, perfect alignment","Hong Kong Nostalgia":"Taxi in heavy rain, neon lights reflecting on wet glass, lonely passenger","Industrial Haze":"Factory interior, steam pipes, worker silhouette against machinery","Gothic Fantasy":"Twisted architecture, dramatic cape, fog machine atmosphere"})[Be]||"",We=Be=>({"Arri Alexa 35":"ArriRaw sensor data, pleasing noise floor, high dynamic range, natural skin micro-texture","Sony Venice 2":"Clean digital sensor, zero noise, high-frequency detail, modern sharpness","Red V-Raptor":"8K RedCode RAW, clinical detail, hyper-sharp edges, high shutter angle crispness","Arriflex 416":"Kodak Vision3 500T film stock, heavy film grain, halation, soft organic edges, chemical color process","Arricam LT":"Kodak Vision3 50D film stock, fine grain, organic resolution, rich photochemical colors","Fujifilm GFX 100":"100 Megapixel medium format sensor, pore-level skin detail, textile fiber detail, print quality resolution","Phantom Flex4K":"High-speed sensor readout, frozen temporal resolution, saturated color depth, zero motion blur artifacts","Blackmagic URSA Cine 12K":"12K RGB pattern, infinite reframing capability, zero aliasing, analytics-grade edge definition"})[Be]||"",Tt=()=>{if(!k.trim()){R("Please enter a scene description");return}const Ve=h.find(rA=>rA.value===g)?.lighting||"",lt=We(C),it=$e(_),ct=Ve?`, ${Ve}`:"",rt=`${it} ${k}${ct}, ${lt}, shot on ${C}, ${I}, cinematic composition, aspect ratio ${_}`;re(rt),R("")},Fe=async()=>{if(!k.trim()){R("Please enter a scene description");return}const Be="AIzaSyDs7EKdC9NLM5UqWlGUqeQO96TmSA-kos8";console.log("API Key status:","Present"),ce(!0),R("");try{console.log("Initializing Gemini AI...");const Ve=new O4(Be),lt=["gemini-2.5-flash","gemini-2.5-pro","gemini-2.0-flash-exp","gemini-2.0-flash","gemini-2.0-flash-001","gemini-1.5-pro-latest","gemini-1.5-flash-latest","gemini-1.5-flash","gemini-1.5-pro","gemini-pro"];let it=null,ct=null;for(const eA of lt)try{console.log(`Trying model: ${eA}`),it=Ve.getGenerativeModel({model:eA}),console.log(`Successfully initialized model: ${eA}`);break}catch(mt){console.log(`Model ${eA} not available, trying next...`),ct=mt}if(!it)throw ct||new Error("No Gemini models available");const rt=h.find(eA=>eA.value===g),rA=l.find(eA=>eA.value===C),zt=c.find(eA=>eA.value===I),St=$e(_),_t=nt(g),Vt=X(g),bt=We(C),fA=k.split(" ").length,It=rA?.physics||"",Nt=zt?.physics||"",Zt=rt?.lighting||"";console.log("=== PROMPT GENERATION DEBUG ==="),console.log("Application:",g),console.log("Lighting Style:",Zt),console.log("Camera:",C),console.log("Lens:",I),console.log("Aspect Ratio:",_),console.log("Scene:",k),console.log("================================");const pe=Math.round(N*100);let Le;N<=.2?Le=`LITERAL MODE (${pe}%): Use the user's scene description almost verbatim. Only reformat for prompt structure. Do NOT add subjects, objects, or narrative elements not explicitly mentioned. Keep it minimal and faithful to the input.`:N<=.5?Le=`CONSERVATIVE MODE (${pe}%): Preserve the exact subject matter from the input. You may add sensory atmosphere (air quality, light quality, material textures) but do NOT add new people, objects, or story elements. Enhance what's there, don't invent.`:N<=.8?Le=`CREATIVE MODE (${pe}%): Expand the scene with environmental context and secondary details. Add mood-setting elements, background activity, and atmospheric touches. You may introduce minor supporting elements that complement the main subject. Make the scene feel lived-in and rich.`:Le=`INVENTIVE MODE (${pe}%): Full creative license. Invent dramatic moments, narrative tension, and unexpected compelling details. Add story-driven elements, emotional subtext, and cinematic intrigue. Transform a simple description into a visually striking scene with depth and meaning. Be bold.`;const at=`You are an expert Cinematographer creating image prompts. INPUT: - Scene Description: "${k}" @@ -34,9 +34,9 @@ SENSORY TEXTURE (scale intensity with creative freedom): OUTPUT FORMAT: ${St} [Scene Content at appropriate creative level] [Atmosphere & Light] [Camera characteristics] [Lens characteristics] -Return ONLY the final prompt text. No markdown, no preamble, no "Here is your prompt".`;console.log("Sending request to Gemini...");const xA=(await(await it.generateContent(at)).response).text();console.log("Gemini response received"),re(xA.trim())}catch(Ve){console.error("Gemini API Error:",Ve),Ve.message&&(Ve.message.includes("not found")||Ve.message.includes("404"))?(R("Gemini models not available. Please check your API key."),console.log("Available models might vary by API key. Check https://ai.google.dev/models/gemini")):Ve.message&&Ve.message.includes("API key")?R("Invalid API key. Please check your .env file and restart the server."):R(`AI generation failed: ${Ve.message||"Unknown error"}. Using fallback.`),Tt()}finally{ce(!1)}},Se=()=>{navigator.clipboard.writeText(H),Y(!0),setTimeout(()=>Y(!1),2e3)},Ye=async()=>{if(!H){Q("Please generate a prompt first");return}P(!0),Q("");try{const Be=new FormData;Be.append("action","generate"),Be.append("prompt",H),Be.append("aspectRatio",_),Be.append("imageSize",se),W&&(Be.append("uploadedImage",W.data),Be.append("uploadedImageType",W.mime_type)),K.forEach((it,ct)=>{Be.append(`referenceImage_${ct}`,it.data),Be.append(`referenceImageType_${ct}`,it.mime_type)}),Be.append("referenceImageCount",K.length.toString());const lt=await(await fetch(Sc("api.php"),{method:"POST",body:Be})).json();if(lt.success){const ct=await(await fetch(Sc("get_current_image.php"))).json();if(ct.success){if(he({data:ct.data,mime_type:ct.mime_type}),A)try{await n(A,{type:"image",prompt:H,settings:{camera:C,lens:I,application:g,aspectRatio:_,imageResolution:se},thumbnail:null,data:ct.data,mimeType:ct.mime_type})}catch(rt){console.error("Failed to save to project:",rt)}}else Q(ct.error||"Failed to retrieve generated image")}else Q(lt.error||"Image generation failed")}catch(Be){Q(`Network error: ${Be.message}. Make sure PHP server is running on port 5015.`)}finally{P(!1)}},Ze=async()=>{try{const Be=new FormData;Be.append("action","reset"),await fetch(Sc("api.php"),{method:"POST",body:Be}),he(null),Q("")}catch(Be){console.error("Reset failed:",Be)}},At=()=>{if(!W)return;const Be=document.createElement("a");Be.href=`data:${W.mime_type};base64,${W.data}`,Be.download=`lux-studio-${Date.now()}.png`,Be.click()},st=Be=>{const Ve=Array.from(Be.target.files),lt=14-K.length;Ve.slice(0,lt).forEach(ct=>{if(!ct.type.startsWith("image/")){Q(`${ct.name} is not an image file`);return}if(ct.size>10*1024*1024){Q(`${ct.name} exceeds 10MB limit`);return}const rt=new FileReader;rt.onload=()=>{Z(rA=>[...rA,{data:rt.result.split(",")[1],mime_type:ct.type,name:ct.name}])},rt.readAsDataURL(ct)}),Be.target.value=""},ht=Be=>{Z(Ve=>Ve.filter((lt,it)=>it!==Be))},Ut=({text:Be,position:Ve="top"})=>Be?b.jsx("div",{className:`absolute z-50 p-3 bg-slate-900 border border-slate-700 text-slate-300 rounded-lg shadow-2xl max-w-xs pointer-events-none +Return ONLY the final prompt text. No markdown, no preamble, no "Here is your prompt".`;console.log("Sending request to Gemini...");const xA=(await(await it.generateContent(at)).response).text();console.log("Gemini response received"),re(xA.trim())}catch(Ve){console.error("Gemini API Error:",Ve),Ve.message&&(Ve.message.includes("not found")||Ve.message.includes("404"))?(R("Gemini models not available. Please check your API key."),console.log("Available models might vary by API key. Check https://ai.google.dev/models/gemini")):Ve.message&&Ve.message.includes("API key")?R("Invalid API key. Please check your .env file and restart the server."):R(`AI generation failed: ${Ve.message||"Unknown error"}. Using fallback.`),Tt()}finally{ce(!1)}},Se=()=>{navigator.clipboard.writeText(H),Y(!0),setTimeout(()=>Y(!1),2e3)},Ye=async()=>{if(!H){Q("Please generate a prompt first");return}P(!0),Q("");try{const Be=new FormData;Be.append("action","generate"),Be.append("prompt",H),Be.append("aspectRatio",_),Be.append("imageSize",se),W&&(Be.append("uploadedImage",W.data),Be.append("uploadedImageType",W.mime_type)),K.forEach((it,ct)=>{Be.append(`referenceImage_${ct}`,it.data),Be.append(`referenceImageType_${ct}`,it.mime_type)}),Be.append("referenceImageCount",K.length.toString());const lt=await(await fetch(Sl("api.php"),{method:"POST",body:Be})).json();if(lt.success){const ct=await(await fetch(Sl("get_current_image.php"))).json();if(ct.success){if(he({data:ct.data,mime_type:ct.mime_type}),A)try{await n(A,{type:"image",prompt:H,settings:{camera:C,lens:I,application:g,aspectRatio:_,imageResolution:se},thumbnail:null,data:ct.data,mimeType:ct.mime_type})}catch(rt){console.error("Failed to save to project:",rt)}}else Q(ct.error||"Failed to retrieve generated image")}else Q(lt.error||"Image generation failed")}catch(Be){Q(`Network error: ${Be.message}. Make sure PHP server is running on port 5015.`)}finally{P(!1)}},Ze=async()=>{try{const Be=new FormData;Be.append("action","reset"),await fetch(Sl("api.php"),{method:"POST",body:Be}),he(null),Q("")}catch(Be){console.error("Reset failed:",Be)}},At=()=>{if(!W)return;const Be=document.createElement("a");Be.href=`data:${W.mime_type};base64,${W.data}`,Be.download=`lux-studio-${Date.now()}.png`,Be.click()},st=Be=>{const Ve=Array.from(Be.target.files),lt=14-K.length;Ve.slice(0,lt).forEach(ct=>{if(!ct.type.startsWith("image/")){Q(`${ct.name} is not an image file`);return}if(ct.size>10*1024*1024){Q(`${ct.name} exceeds 10MB limit`);return}const rt=new FileReader;rt.onload=()=>{Z(rA=>[...rA,{data:rt.result.split(",")[1],mime_type:ct.type,name:ct.name}])},rt.readAsDataURL(ct)}),Be.target.value=""},ht=Be=>{Z(Ve=>Ve.filter((lt,it)=>it!==Be))},Ut=({text:Be,position:Ve="top"})=>Be?b.jsx("div",{className:`absolute z-50 p-3 bg-slate-900 border border-slate-700 text-slate-300 rounded-lg shadow-2xl max-w-xs pointer-events-none ${Ve==="top"?"bottom-full mb-2":"top-full mt-2"} left-0 right-0`,style:{textTransform:"none"},children:b.jsxs("div",{className:"relative text-xs leading-relaxed font-normal tracking-normal",children:[b.jsx("span",{style:{textTransform:"none",fontWeight:"normal"},children:Be}),b.jsx("div",{className:`absolute w-2 h-2 bg-slate-900 border-l border-t border-slate-700 transform rotate-45 - ${Ve==="top"?"bottom-[-5px]":"top-[-5px] rotate-[225deg]"} left-6`})]})}):null;return b.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-6",children:[b.jsx("div",{className:"lg:col-span-4",children:b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-6",children:[b.jsxs("h2",{className:"text-lg font-bold text-slate-200 flex items-center space-x-2",children:[b.jsx(n6,{className:"w-5 h-5 text-cinema-gold"}),b.jsx("span",{children:"Technical Specs"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:["Application / Lighting",b.jsx(tb,{className:"w-3 h-3 text-slate-500"}),b.jsxs("span",{className:"text-xs font-normal normal-case",children:["(",h.length-1," presets + Auteur Styles)"]})]}),b.jsxs("select",{value:g,onChange:Be=>y(Be.target.value),className:"w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 focus:border-cinema-gold focus:outline-none focus:ring-2 focus:ring-cinema-gold/20 transition-all",children:[b.jsxs("optgroup",{label:"Studio & Portrait",children:[b.jsx("option",{value:"Portrait Studio",children:"Portrait Studio"}),b.jsx("option",{value:"Corporate Headshot",children:"Corporate Headshot"})]}),b.jsxs("optgroup",{label:"Product & Macro",children:[b.jsx("option",{value:"Product (Crisp)",children:"Product (Crisp)"}),b.jsx("option",{value:"Food Photography",children:"Food Photography"}),b.jsx("option",{value:"Macro: Luxury Jewelry",children:"Macro: Luxury Jewelry"}),b.jsx("option",{value:"Macro: Nature Details",children:"Macro: Nature Details"}),b.jsx("option",{value:"Tech Commercial (Macro)",children:"Tech Commercial (Macro)"})]}),b.jsxs("optgroup",{label:"Outdoor & Natural",children:[b.jsx("option",{value:"Golden Hour (Outdoor)",children:"Golden Hour (Outdoor)"}),b.jsx("option",{value:"Blue Hour (City)",children:"Blue Hour (City)"}),b.jsx("option",{value:"Wildlife / Safari",children:"Wildlife / Safari"})]}),b.jsx("optgroup",{label:"Action & Motion",children:b.jsx("option",{value:"Sports Action",children:"Sports Action"})}),b.jsxs("optgroup",{label:"Creative & Artistic",children:[b.jsx("option",{value:"Neon Cyberpunk",children:"Neon Cyberpunk"}),b.jsx("option",{value:"Nostalgic Memory",children:"Nostalgic Memory"}),b.jsx("option",{value:"Cinematic Horror",children:"Cinematic Horror"}),b.jsx("option",{value:"Cassette Futurism (Retro Sci-Fi)",children:"Cassette Futurism (Retro Sci-Fi)"}),b.jsx("option",{value:"Surreal Infrared",children:"Surreal Infrared"}),b.jsx("option",{value:"Spaghetti Western",children:"Spaghetti Western"})]}),b.jsxs("optgroup",{label:"Auteur Styles",children:[b.jsx("option",{value:"Symmetrical Whimsy",children:"Symmetrical Whimsy"}),b.jsx("option",{value:"IMAX Scale Epic",children:"IMAX Scale Epic"}),b.jsx("option",{value:"Clinical Thriller",children:"Clinical Thriller"}),b.jsx("option",{value:"Brutalist Atmosphere",children:"Brutalist Atmosphere"}),b.jsx("option",{value:"Technicolor Dream",children:"Technicolor Dream"}),b.jsx("option",{value:"Obsessive Symmetry",children:"Obsessive Symmetry"}),b.jsx("option",{value:"Hong Kong Nostalgia",children:"Hong Kong Nostalgia"}),b.jsx("option",{value:"Industrial Haze",children:"Industrial Haze"}),b.jsx("option",{value:"Gothic Fantasy",children:"Gothic Fantasy"})]}),b.jsxs("optgroup",{label:"Professional Production",children:[b.jsx("option",{value:"LED Volume (Virtual Production)",children:"LED Volume (Virtual Production)"}),b.jsx("option",{value:"Automotive: Showroom",children:"Automotive: Showroom"}),b.jsx("option",{value:"Automotive: Process Trailer",children:"Automotive: Process Trailer"}),b.jsx("option",{value:"Product (Liquid/Splash)",children:"Product (Liquid/Splash)"}),b.jsx("option",{value:"VFX / Green Screen",children:"VFX / Green Screen"}),b.jsx("option",{value:"Knolling / Flat Lay",children:"Knolling / Flat Lay"})]}),b.jsxs("optgroup",{label:"Editorial & Fashion",children:[b.jsx("option",{value:"NYC Street Editorial",children:"NYC Street Editorial"}),b.jsx("option",{value:"90s Grunge Editorial",children:"90s Grunge Editorial"}),b.jsx("option",{value:"Fashion Editorial",children:"Fashion Editorial"}),b.jsx("option",{value:"Underground Rave / Flash",children:"Underground Rave / Flash"})]}),b.jsxs("optgroup",{label:"Documentary & Journalism",children:[b.jsx("option",{value:"Conflict Photography",children:"Conflict Photography"}),b.jsx("option",{value:"Street Photography",children:"Street Photography"}),b.jsx("option",{value:"Docu / Realism",children:"Docu / Realism"})]}),b.jsxs("optgroup",{label:"Architectural & Interior",children:[b.jsx("option",{value:"Architectural Digest Interior",children:"Architectural Digest Interior"}),b.jsx("option",{value:"Architecture",children:"Architecture"})]}),b.jsx("optgroup",{label:"Other",children:b.jsx("option",{value:"Custom",children:"Custom"})})]})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:["Camera Body",b.jsxs("div",{className:"relative",onMouseEnter:()=>ne("camera"),onMouseLeave:()=>ne(null),children:[b.jsx(eb,{className:"w-3 h-3 text-slate-500 cursor-help"}),V==="camera"&&b.jsx(Ut,{text:l.find(Be=>Be.value===C)?.tooltip,position:"bottom"})]})]}),b.jsxs("div",{className:"relative",children:[b.jsx("select",{value:C,onChange:Be=>v(Be.target.value),className:"w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 focus:border-cinema-gold focus:outline-none focus:ring-2 focus:ring-cinema-gold/20 transition-all",children:l.map(Be=>b.jsx("option",{value:Be.value,children:Be.display},Be.value))}),b.jsx("div",{className:"text-xs text-slate-500 mt-1",children:l.find(Be=>Be.value===C)?.tags})]})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:["Lens Kit",b.jsxs("div",{className:"relative",onMouseEnter:()=>ne("lens"),onMouseLeave:()=>ne(null),children:[b.jsx(eb,{className:"w-3 h-3 text-slate-500 cursor-help"}),V==="lens"&&b.jsx(Ut,{text:c.find(Be=>Be.value===I)?.tooltip,position:"bottom"})]})]}),b.jsxs("div",{className:"relative",children:[b.jsx("select",{value:I,onChange:Be=>x(Be.target.value),className:"w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 focus:border-cinema-gold focus:outline-none focus:ring-2 focus:ring-cinema-gold/20 transition-all",children:Ae.map(Be=>b.jsx("option",{value:Be.value,children:Be.display},Be.value))}),b.jsx("div",{className:"text-xs text-slate-500 mt-1",children:Ae.find(Be=>Be.value===I)?.keywords})]})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Aspect Ratio"}),b.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(Be=>b.jsx("button",{onClick:()=>T(Be),className:`px-4 py-2 rounded-lg font-medium transition-all ${_===Be?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"}`,children:Be},Be))})]}),b.jsx("div",{className:"bg-slate-800/50 rounded-lg p-4 text-xs text-slate-400",children:b.jsxs("div",{className:"flex items-start gap-2",children:[b.jsx(tb,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),b.jsxs("div",{children:[b.jsx("strong",{children:"Pro Tip:"})," Select an Application to auto-configure optimal camera and lens settings."]})]})}),b.jsxs("div",{className:"space-y-3 pt-4 border-t border-slate-800",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:[b.jsx(eO,{className:"w-4 h-4"}),"Creative Freedom"]}),b.jsxs("span",{className:"text-xs text-cinema-gold font-mono",children:[(N*100).toFixed(0),"%"]})]}),b.jsx("input",{type:"range",min:"0",max:"100",value:N*100,onChange:Be=>G(Be.target.value/100),className:"w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer slider",style:{background:`linear-gradient(to right, #f59e0b 0%, #f59e0b ${N*100}%, #475569 ${N*100}%, #475569 100%)`}}),b.jsxs("div",{className:"flex justify-between text-xs text-slate-500",children:[b.jsx("span",{children:"Strict"}),b.jsx("span",{children:"Creative"})]})]}),b.jsxs("div",{className:"space-y-3",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Scene Description"}),b.jsx("textarea",{value:k,onChange:Be=>z(Be.target.value),placeholder:"Describe your scene...",className:"w-full h-28 px-4 py-3 bg-slate-900/50 border border-slate-800 rounded-xl text-slate-200 placeholder-slate-500 focus:border-cinema-gold focus:outline-none focus:ring-2 focus:ring-cinema-gold/20 transition-all resize-none text-sm"}),b.jsxs("div",{className:"flex flex-col gap-2",children:[b.jsx("button",{onClick:Fe,disabled:le,className:"flex items-center justify-center space-x-2 w-full px-4 py-3 bg-gradient-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white font-medium rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:le?b.jsxs(b.Fragment,{children:[b.jsx(ss,{className:"w-5 h-5 animate-spin"}),b.jsx("span",{children:"Optimizing..."})]}):b.jsxs(b.Fragment,{children:[b.jsx(lw,{className:"w-5 h-5"}),b.jsx("span",{children:"Optimize"})]})}),b.jsx("button",{onClick:Tt,className:"w-full px-4 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 font-medium rounded-lg transition-all",children:"Simple Generate"})]}),de&&b.jsx("div",{className:"text-red-400 text-sm bg-red-950/20 border border-red-900/50 rounded-lg px-4 py-2",children:de})]})]})}),b.jsxs("div",{className:"lg:col-span-8 space-y-6",children:[b.jsxs("div",{className:"relative bg-gradient-to-br from-slate-900 to-slate-950 border border-slate-800 rounded-xl overflow-hidden",children:[b.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-cinema-gold"}),b.jsxs("div",{className:"p-6 space-y-4",children:[b.jsx("h3",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Optimized Prompt"}),b.jsx("div",{className:"min-h-[120px]",children:b.jsx("textarea",{value:H,onChange:Be=>re(Be.target.value),className:"w-full min-h-[120px] bg-transparent text-slate-200 font-mono text-sm leading-relaxed resize-y border-0 focus:outline-none focus:ring-0 placeholder:text-slate-500 placeholder:italic",placeholder:"Your optimized prompt will appear here. You can also type or edit directly..."})}),H&&b.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-slate-800",children:[b.jsx("button",{onClick:Se,className:"flex items-center space-x-2 px-5 py-2.5 bg-white hover:bg-slate-100 text-slate-950 font-medium rounded-lg transition-all transform hover:scale-105",children:$?b.jsxs(b.Fragment,{children:[b.jsx(So,{className:"w-4 h-4"}),b.jsx("span",{children:"Copied!"})]}):b.jsxs(b.Fragment,{children:[b.jsx(g6,{className:"w-4 h-4"}),b.jsx("span",{children:"Copy Prompt"})]})}),b.jsxs("div",{className:"text-xs text-slate-500",children:[H.split(" ").length," words"]})]})]})]}),b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-4",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsxs("h3",{className:"text-lg font-bold text-slate-200 flex items-center gap-2",children:[b.jsx(_c,{className:"w-5 h-5 text-cinema-gold"}),"Generated Image"]}),W&&b.jsxs("div",{className:"flex items-center gap-3",children:[b.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-amber-900/50 text-amber-400 border border-amber-800",children:"Edit Mode: Next prompt will modify this image"}),b.jsxs("button",{onClick:Ze,className:"text-xs px-3 py-1 bg-slate-700 hover:bg-slate-600 text-slate-300 rounded-lg transition-all flex items-center gap-1",children:[b.jsx(Np,{className:"w-3 h-3"}),"Start Fresh"]})]})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Reference Images (Optional)"}),b.jsxs("span",{className:"text-xs text-slate-500",children:[K.length,"/14"]})]}),b.jsxs("div",{className:"flex flex-wrap gap-2",children:[K.map((Be,Ve)=>b.jsxs("div",{className:"relative group",children:[b.jsx("img",{src:`data:${Be.mime_type};base64,${Be.data}`,alt:Be.name,className:"w-12 h-12 object-cover rounded-lg border border-slate-700"}),b.jsx("button",{onClick:()=>ht(Ve),className:"absolute -top-1 -right-1 w-4 h-4 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:b.jsx(Ds,{className:"w-3 h-3 text-white"})})]},Ve)),K.length<14&&b.jsxs(b.Fragment,{children:[be.length>0&&b.jsxs("button",{onClick:()=>He(!ve),className:`w-12 h-12 flex flex-col items-center justify-center border-2 border-dashed rounded-lg transition-colors ${ve?"border-cinema-gold bg-cinema-gold/10":"border-slate-700 hover:border-cinema-gold"}`,title:"Select from project",children:[b.jsx(xc,{className:"w-4 h-4 text-cinema-gold"}),b.jsx("span",{className:"text-[8px] text-slate-400 mt-0.5",children:"Project"})]}),b.jsxs("label",{className:"w-12 h-12 flex flex-col items-center justify-center border-2 border-dashed border-slate-700 hover:border-slate-600 rounded-lg cursor-pointer transition-colors",children:[b.jsx(Wf,{className:"w-4 h-4 text-slate-500"}),b.jsx("span",{className:"text-[8px] text-slate-500 mt-0.5",children:"Upload"}),b.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:st,className:"hidden"})]})]})]}),ve&&be.length>0&&b.jsxs("div",{className:"bg-slate-800 border border-slate-700 rounded-lg p-3",children:[b.jsxs("div",{className:"flex items-center justify-between mb-2",children:[b.jsx("span",{className:"text-xs font-bold text-slate-400",children:"From Project"}),b.jsx("button",{onClick:()=>He(!1),className:"text-slate-500 hover:text-slate-300",children:b.jsx(Ds,{className:"w-4 h-4"})})]}),b.jsx("div",{className:"grid grid-cols-4 gap-2 max-h-32 overflow-y-auto",children:be.map(Be=>b.jsx("button",{onClick:()=>Xe(Be),disabled:K.some(Ve=>Ve.projectItemId===Be.id),className:`relative aspect-square rounded overflow-hidden border-2 transition-all ${K.some(Ve=>Ve.projectItemId===Be.id)?"border-green-500 opacity-50":"border-transparent hover:border-cinema-gold"}`,children:b.jsx("img",{src:`data:${Be.mimeType};base64,${Be.data}`,alt:Be.prompt||"Project image",className:"w-full h-full object-cover"})},Be.id))})]}),b.jsx("p",{className:"text-xs text-slate-500",children:"JPEG, PNG, WebP - Max 10MB each - Describe how to use references in your prompt"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Output Resolution"}),b.jsx("div",{className:"flex gap-2",children:["1K","2K","4K"].map(Be=>b.jsx("button",{onClick:()=>ue(Be),className:`px-4 py-2 rounded-lg text-sm font-medium transition-all ${se===Be?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"}`,children:Be},Be))}),b.jsxs("p",{className:"text-xs text-slate-500",children:[se==="1K"&&"~1024px - Fastest, web/social",se==="2K"&&"~2048px - Recommended for most uses",se==="4K"&&"~4096px - Print quality, slower"]})]}),b.jsx("div",{className:`${_==="9:16"||_==="3:4"?"max-w-xs mx-auto":""}`,children:b.jsx("div",{className:`${_==="9:16"?"aspect-[9/16]":_==="3:4"?"aspect-[3/4]":_==="1:1"?"aspect-square":_==="4:3"?"aspect-[4/3]":"aspect-video"} bg-slate-950 rounded-lg border-2 ${W?"border-cinema-gold":"border-dashed border-slate-700"} flex items-center justify-center overflow-hidden`,children:Ne?b.jsxs("div",{className:"text-center p-8",children:[b.jsx(ss,{className:"w-10 h-10 animate-spin text-cinema-gold mx-auto"}),b.jsx("p",{className:"text-slate-400 mt-3",children:"Generating image..."}),b.jsx("p",{className:"text-slate-500 text-xs mt-1",children:"This may take up to 2 minutes"})]}):W?b.jsx("img",{src:`data:${W.mime_type};base64,${W.data}`,alt:"Generated",className:"max-w-full max-h-full object-contain rounded"}):b.jsxs("div",{className:"text-center p-8",children:[b.jsx(_c,{className:"w-12 h-12 text-slate-700 mx-auto mb-3"}),b.jsx("p",{className:"text-slate-500",children:'Generate a prompt first, then click "Generate Image"'}),b.jsxs("p",{className:"text-slate-600 text-xs mt-2",children:["Requires PHP backend running on port ","5015"]})]})})}),S&&b.jsx("div",{className:"text-red-400 text-sm bg-red-950/20 border border-red-900/50 rounded-lg px-4 py-2",children:S}),b.jsxs("div",{className:"flex gap-3",children:[b.jsx("button",{onClick:Ye,disabled:!H||Ne,className:"flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-cinema-gold hover:bg-amber-400 text-slate-950 font-medium rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:Ne?b.jsxs(b.Fragment,{children:[b.jsx(ss,{className:"w-5 h-5 animate-spin"}),b.jsx("span",{children:"Generating..."})]}):b.jsxs(b.Fragment,{children:[b.jsx(lw,{className:"w-5 h-5"}),b.jsx("span",{children:W?"Edit Image":"Generate Image"})]})}),W&&b.jsxs(b.Fragment,{children:[b.jsx("button",{onClick:At,className:"px-4 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all",title:"Download Image",children:b.jsx(Ec,{className:"w-5 h-5"})}),b.jsx("button",{onClick:Ze,className:"px-4 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all",title:"Start New Image",children:b.jsx(Np,{className:"w-5 h-5"})})]})]})]}),b.jsxs("div",{className:"bg-slate-900/30 rounded-lg p-4 space-y-3",children:[b.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs",children:[b.jsxs("div",{children:[b.jsx("span",{className:"text-slate-500",children:"Application:"}),b.jsx("span",{className:"ml-2 text-slate-300",children:g})]}),b.jsxs("div",{children:[b.jsx("span",{className:"text-slate-500",children:"Camera:"}),b.jsx("span",{className:"ml-2 text-slate-300",children:C})]}),b.jsxs("div",{children:[b.jsx("span",{className:"text-slate-500",children:"Lens:"}),b.jsx("span",{className:"ml-2 text-slate-300",children:I})]}),b.jsxs("div",{children:[b.jsx("span",{className:"text-slate-500",children:"Aspect:"}),b.jsx("span",{className:"ml-2 text-slate-300",children:_})]})]}),b.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsx("span",{className:"text-xs text-slate-500",children:"Focus Mode:"}),b.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${h.find(Be=>Be.value===g)?.focusType==="realism"?"bg-green-900/50 text-green-400 border border-green-800":"bg-purple-900/50 text-purple-400 border border-purple-800"}`,children:h.find(Be=>Be.value===g)?.focusType==="realism"?"🔬 Realism (Deep Focus)":"🎬 Stylistic (Cinematic)"})]}),b.jsx("p",{className:"text-xs text-slate-500 mt-2",children:h.find(Be=>Be.value===g)?.focusType==="realism"?"Prioritizes sharpness and deep focus for technical accuracy.":"Embraces bokeh and depth effects for emotional impact."})]})]})]})]})},R4=({src:A,onFrameExtract:e,onSaveToProject:t,className:n="",autoPlay:a=!1})=>{const s=ae.useRef(null),l=ae.useRef(null),c=A?.startsWith("/generated_videos/")?`/api/stream_video.php?file=${encodeURIComponent(A.replace("/generated_videos/",""))}`:A,[h,f]=ae.useState(!1),[g,y]=ae.useState(0),[C,v]=ae.useState(0),[I,x]=ae.useState(1),[_,T]=ae.useState(a),[k,z]=ae.useState(null),[H,re]=ae.useState(!1),[le,ce]=ae.useState(!1),[$,Y]=ae.useState(!1),[de,R]=ae.useState(null),V=ae.useRef(null),ne=24,Ae=1/ne;ae.useEffect(()=>{const oe=s.current;if(!oe)return;const ve=()=>y(oe.currentTime),He=()=>v(oe.duration),Xe=()=>f(!0),$e=()=>f(!1),nt=()=>f(!1),X=()=>{const We=oe.videoWidth/oe.videoHeight;We<.9?R("portrait"):We>1.1?R("landscape"):R("square")};return oe.addEventListener("timeupdate",ve),oe.addEventListener("durationchange",He),oe.addEventListener("play",Xe),oe.addEventListener("pause",$e),oe.addEventListener("ended",nt),oe.addEventListener("loadedmetadata",X),()=>{oe.removeEventListener("timeupdate",ve),oe.removeEventListener("durationchange",He),oe.removeEventListener("play",Xe),oe.removeEventListener("pause",$e),oe.removeEventListener("ended",nt),oe.removeEventListener("loadedmetadata",X)}},[]);const Ce=()=>{const oe=s.current;oe&&(h?oe.pause():oe.play())},N=oe=>{const ve=s.current,He=V.current;if(!ve||!He)return;const Xe=He.getBoundingClientRect(),nt=Math.max(0,Math.min(oe-Xe.left,Xe.width))/Xe.width;ve.currentTime=nt*C},G=oe=>{oe.preventDefault(),ce(!0),s.current?.pause(),N(oe.clientX)};ae.useEffect(()=>{if(!le)return;const oe=He=>{N(He.clientX)},ve=()=>{ce(!1)};return document.addEventListener("mousemove",oe),document.addEventListener("mouseup",ve),()=>{document.removeEventListener("mousemove",oe),document.removeEventListener("mouseup",ve)}},[le,C]);const W=()=>{const oe=s.current;oe&&(oe.pause(),oe.currentTime=Math.min(C,oe.currentTime+Ae))},he=()=>{const oe=s.current;oe&&(oe.pause(),oe.currentTime=Math.max(0,oe.currentTime-Ae))},Ne=()=>{const oe=s.current;oe&&(oe.currentTime=Math.min(C,oe.currentTime+1))},P=()=>{const oe=s.current;oe&&(oe.currentTime=Math.max(0,oe.currentTime-1))},S=()=>{const oe=s.current;oe&&(oe.muted=!oe.muted,T(!_))},Q=()=>{const oe=s.current,ve=l.current;if(!oe||!ve)return;oe.pause(),ve.width=oe.videoWidth,ve.height=oe.videoHeight,ve.getContext("2d").drawImage(oe,0,0,ve.width,ve.height);const Xe=ve.toDataURL("image/png"),$e=Xe.split(",")[1];z({dataUrl:Xe,base64:$e,width:oe.videoWidth,height:oe.videoHeight,timestamp:g}),Y(!1),re(!0),e&&e({data:$e,mime_type:"image/png",width:oe.videoWidth,height:oe.videoHeight,timestamp:g})},K=()=>{if(!k)return;const oe=document.createElement("a");oe.href=k.dataUrl,oe.download=`frame-${Math.round(k.timestamp*1e3)}ms.png`,oe.click()},Z=oe=>{const ve=Math.floor(oe/60),He=Math.floor(oe%60),Xe=Math.floor(oe%1*100);return`${ve.toString().padStart(2,"0")}:${He.toString().padStart(2,"0")}.${Xe.toString().padStart(2,"0")}`},se=Math.floor(g*ne),ue=Math.floor(C*ne),be=de==="portrait"?"max-w-sm mx-auto":"w-full";return b.jsxs("div",{className:`relative ${be} ${n}`,children:[b.jsx("canvas",{ref:l,className:"hidden"}),b.jsx("video",{ref:s,src:c,className:"w-full rounded-lg",onClick:Ce,preload:"auto",playsInline:!0,autoPlay:a,muted:a}),b.jsxs("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/90 to-transparent p-4 rounded-b-lg",children:[b.jsx("div",{ref:V,className:"w-full h-2 bg-slate-700 rounded-full cursor-pointer mb-3 group hover:h-3 transition-all",onMouseDown:G,children:b.jsx("div",{className:"h-full bg-cinema-gold rounded-full relative",style:{width:`${C?g/C*100:0}%`},children:b.jsx("div",{className:`absolute right-0 top-1/2 -translate-y-1/2 w-4 h-4 bg-cinema-gold rounded-full shadow-lg transition-opacity ${le?"opacity-100 scale-110":"opacity-0 group-hover:opacity-100"}`})})}),b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsxs("div",{className:"flex items-center gap-2",children:[b.jsx("button",{onClick:he,className:"p-1.5 hover:bg-white/20 rounded transition-colors",title:"Previous frame",children:b.jsx(o6,{className:"w-4 h-4"})}),b.jsx("button",{onClick:P,className:"p-1.5 hover:bg-white/20 rounded transition-colors",title:"Back 1s",children:b.jsx(J6,{className:"w-4 h-4"})}),b.jsx("button",{onClick:Ce,className:"p-2 bg-cinema-gold hover:bg-amber-400 text-slate-950 rounded-lg transition-colors",children:h?b.jsx(D6,{className:"w-5 h-5"}):b.jsx(j6,{className:"w-5 h-5 ml-0.5"})}),b.jsx("button",{onClick:Ne,className:"p-1.5 hover:bg-white/20 rounded transition-colors",title:"Forward 1s",children:b.jsx(Z6,{className:"w-4 h-4"})}),b.jsx("button",{onClick:W,className:"p-1.5 hover:bg-white/20 rounded transition-colors",title:"Next frame",children:b.jsx(a6,{className:"w-4 h-4"})}),b.jsx("button",{onClick:S,className:"p-1.5 hover:bg-white/20 rounded transition-colors ml-2",children:_?b.jsx(F4,{className:"w-4 h-4"}):b.jsx(I4,{className:"w-4 h-4"})})]}),b.jsxs("div",{className:"text-xs font-mono text-slate-300",children:[Z(g)," / ",Z(C),b.jsxs("span",{className:"ml-2 text-slate-500",children:["Frame ",se,"/",ue]})]}),b.jsx("div",{className:"flex items-center gap-2",children:b.jsxs("button",{onClick:Q,className:"flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 rounded-lg text-sm transition-colors",title:"Extract current frame",children:[b.jsx(V6,{className:"w-4 h-4"}),b.jsx("span",{children:"Extract Frame"})]})})]})]}),H&&k&&b.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>re(!1),children:b.jsxs("div",{className:"bg-slate-900 rounded-xl p-6 max-w-2xl w-full",onClick:oe=>oe.stopPropagation(),children:[b.jsxs("h3",{className:"text-lg font-bold text-slate-200 mb-4 flex items-center gap-2",children:[b.jsx(_c,{className:"w-5 h-5 text-cinema-gold"}),"Extracted Frame"]}),b.jsx("div",{className:"bg-slate-950 rounded-lg p-2 mb-4",children:b.jsx("img",{src:k.dataUrl,alt:"Extracted frame",className:"max-w-full max-h-[50vh] mx-auto rounded"})}),b.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 mb-4",children:[b.jsxs("span",{children:["Time: ",Z(k.timestamp)]}),b.jsxs("span",{children:[k.width," x ",k.height]})]}),b.jsxs("div",{className:"flex gap-3",children:[b.jsxs("button",{onClick:K,className:"flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-200 font-medium rounded-lg transition-colors",children:[b.jsx(Ec,{className:"w-4 h-4"}),"Download"]}),t?b.jsx("button",{onClick:async()=>{$||(await t({data:k.base64,mimeType:"image/png",prompt:`Extracted frame at ${Z(k.timestamp)}`,width:k.width,height:k.height}),Y(!0))},className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 font-medium rounded-lg transition-colors ${$?"bg-green-600 text-white cursor-default":"bg-cinema-gold hover:bg-amber-400 text-slate-950"}`,children:$?b.jsxs(b.Fragment,{children:[b.jsx(So,{className:"w-4 h-4"}),"Saved!"]}):b.jsxs(b.Fragment,{children:[b.jsx(B6,{className:"w-4 h-4"}),"Save to Project"]})}):b.jsx("button",{onClick:()=>re(!1),className:"flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-slate-700 hover:bg-slate-600 text-slate-200 font-medium rounded-lg transition-colors",children:"Close"})]})]})})]})},ZO=({activeProjectId:A,rerunData:e,onRerunLoaded:t})=>{const[n,a]=ae.useState(""),[s,l]=ae.useState("fast"),[c,h]=ae.useState(4),[f,g]=ae.useState("16:9"),[y,C]=ae.useState("720p"),[v,I]=ae.useState(!0),[x,_]=ae.useState([]),[T,k]=ae.useState("frame"),[z,H]=ae.useState(""),[re,le]=ae.useState("");ae.useEffect(()=>{if(e){if(le(e.prompt||""),a(""),e.settings&&(l(e.settings.modelType||"fast"),h(e.settings.duration||4),g(e.settings.aspectRatio||"16:9"),C(e.settings.resolution||"720p"),I(e.settings.generateAudio??!0),H(e.settings.dialogue||""),k(e.settings.referenceMode||"frame")),e.referenceImages&&e.referenceImages.length>0){const Fe=e.referenceImages.map((Se,Ye)=>({data:Se.data,mime_type:Se.mime_type,name:`Reference ${Ye+1}`}));_(Fe)}else _([]);t&&t()}},[e,t]);const[ce,$]=ae.useState(!1),[Y,de]=ae.useState(!1),[R,V]=ae.useState(null),[ne,Ae]=ae.useState(""),[Ce,N]=ae.useState(0),{addItemToProject:G,getProjectWithItems:W,isReady:he}=nv(),[Ne,P]=ae.useState([]),[S,Q]=ae.useState(!1),[K,Z]=ae.useState(null);ae.useEffect(()=>{if(x.length===0){Z(null);return}const Fe=x[0],Se=document.createElement("img");Se.onload=()=>{const Ye=Se.width/Se.height;Ye<.9?Z("portrait"):Ye>1.1?Z("landscape"):Z("square")},Se.src=`data:${Fe.mime_type};base64,${Fe.data}`},[x]);const se=K&&(f==="16:9"&&K==="portrait"||f==="9:16"&&K==="landscape");ae.useEffect(()=>{(async()=>{if(!A||!he){P([]);return}try{const Se=await W(A);if(Se&&Se.items){const Ye=Se.items.filter(Ze=>Ze.type==="image");P(Ye)}}catch(Se){console.error("Failed to load project images:",Se)}})()},[A,he,W]);const ue=Fe=>{x.length>=2||x.some(Se=>Se.projectItemId===Fe.id)||(x.length===0&&(h(8),g("16:9")),_(Se=>[...Se,{data:Fe.data,mime_type:Fe.mimeType,name:Fe.prompt?.substring(0,20)||"Project Image",projectItemId:Fe.id}]),Q(!1))},be=[{value:"fast",label:"Fast",description:"Faster, lower cost"},{value:"standard",label:"Standard",description:"Higher quality"}],oe=Fe=>({fast:{4:"~$1.50",6:"~$2.25",8:"~$3"},standard:{4:"~$3",6:"~$4.50",8:"~$6"}})[s][Fe],ve=[{value:4,label:"4s"},{value:6,label:"6s"},{value:8,label:"8s"}],He=Fe=>{const Se=Array.from(Fe.target.files),Ye=2-x.length;Se.slice(0,Ye).forEach(At=>{if(!At.type.startsWith("image/")){Ae(`${At.name} is not an image file`);return}if(At.size>10*1024*1024){Ae(`${At.name} exceeds 10MB limit`);return}const st=new FileReader;st.onload=()=>{_(ht=>(ht.length===0&&(h(8),g("16:9")),[...ht,{data:st.result.split(",")[1],mime_type:At.type,name:At.name}]))},st.readAsDataURL(At)}),Fe.target.value=""},Xe=Fe=>{_(Se=>Se.filter((Ye,Ze)=>Ze!==Fe))},$e=Fe=>new Promise(Se=>{const Ye=document.createElement("video");Ye.crossOrigin="anonymous",Ye.muted=!0,Ye.onloadeddata=()=>{Ye.currentTime=.5},Ye.onseeked=()=>{try{const Ze=document.createElement("canvas");Ze.width=Ye.videoWidth,Ze.height=Ye.videoHeight,Ze.getContext("2d").drawImage(Ye,0,0,Ze.width,Ze.height);const st=Ze.toDataURL("image/jpeg",.8);Se(st.split(",")[1])}catch(Ze){console.error("Failed to extract thumbnail:",Ze),Se(null)}},Ye.onerror=()=>{console.error("Video load error for thumbnail"),Se(null)},setTimeout(()=>Se(null),5e3),Ye.src=Fe,Ye.load()}),nt=async()=>{if(!n.trim()){Ae("Please enter a scene description");return}de(!0),Ae("");try{const Fe=await fetch(Sc("get_config.php"));if(!Fe.ok)throw new Error("Failed to fetch config");const Se=await Fe.json();if(!Se.apiKey){console.warn("No API key found, using simple prompt"),X();return}const Ze=new O4(Se.apiKey).getGenerativeModel({model:"gemini-2.0-flash-lite"}),At=x.length>0,st=T==="frame"&&x.length>1,ht=T==="subject"&&At,Ut=T==="frame"&&At,Be=`You are a video prompt formatter for Google Veo 3.1. + ${Ve==="top"?"bottom-[-5px]":"top-[-5px] rotate-[225deg]"} left-6`})]})}):null;return b.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-6",children:[b.jsx("div",{className:"lg:col-span-4",children:b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-6",children:[b.jsxs("h2",{className:"text-lg font-bold text-slate-200 flex items-center space-x-2",children:[b.jsx(n6,{className:"w-5 h-5 text-cinema-gold"}),b.jsx("span",{children:"Technical Specs"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:["Application / Lighting",b.jsx(tb,{className:"w-3 h-3 text-slate-500"}),b.jsxs("span",{className:"text-xs font-normal normal-case",children:["(",h.length-1," presets + Auteur Styles)"]})]}),b.jsxs("select",{value:g,onChange:Be=>y(Be.target.value),className:"w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 focus:border-cinema-gold focus:outline-none focus:ring-2 focus:ring-cinema-gold/20 transition-all",children:[b.jsxs("optgroup",{label:"Studio & Portrait",children:[b.jsx("option",{value:"Portrait Studio",children:"Portrait Studio"}),b.jsx("option",{value:"Corporate Headshot",children:"Corporate Headshot"})]}),b.jsxs("optgroup",{label:"Product & Macro",children:[b.jsx("option",{value:"Product (Crisp)",children:"Product (Crisp)"}),b.jsx("option",{value:"Food Photography",children:"Food Photography"}),b.jsx("option",{value:"Macro: Luxury Jewelry",children:"Macro: Luxury Jewelry"}),b.jsx("option",{value:"Macro: Nature Details",children:"Macro: Nature Details"}),b.jsx("option",{value:"Tech Commercial (Macro)",children:"Tech Commercial (Macro)"})]}),b.jsxs("optgroup",{label:"Outdoor & Natural",children:[b.jsx("option",{value:"Golden Hour (Outdoor)",children:"Golden Hour (Outdoor)"}),b.jsx("option",{value:"Blue Hour (City)",children:"Blue Hour (City)"}),b.jsx("option",{value:"Wildlife / Safari",children:"Wildlife / Safari"})]}),b.jsx("optgroup",{label:"Action & Motion",children:b.jsx("option",{value:"Sports Action",children:"Sports Action"})}),b.jsxs("optgroup",{label:"Creative & Artistic",children:[b.jsx("option",{value:"Neon Cyberpunk",children:"Neon Cyberpunk"}),b.jsx("option",{value:"Nostalgic Memory",children:"Nostalgic Memory"}),b.jsx("option",{value:"Cinematic Horror",children:"Cinematic Horror"}),b.jsx("option",{value:"Cassette Futurism (Retro Sci-Fi)",children:"Cassette Futurism (Retro Sci-Fi)"}),b.jsx("option",{value:"Surreal Infrared",children:"Surreal Infrared"}),b.jsx("option",{value:"Spaghetti Western",children:"Spaghetti Western"})]}),b.jsxs("optgroup",{label:"Auteur Styles",children:[b.jsx("option",{value:"Symmetrical Whimsy",children:"Symmetrical Whimsy"}),b.jsx("option",{value:"IMAX Scale Epic",children:"IMAX Scale Epic"}),b.jsx("option",{value:"Clinical Thriller",children:"Clinical Thriller"}),b.jsx("option",{value:"Brutalist Atmosphere",children:"Brutalist Atmosphere"}),b.jsx("option",{value:"Technicolor Dream",children:"Technicolor Dream"}),b.jsx("option",{value:"Obsessive Symmetry",children:"Obsessive Symmetry"}),b.jsx("option",{value:"Hong Kong Nostalgia",children:"Hong Kong Nostalgia"}),b.jsx("option",{value:"Industrial Haze",children:"Industrial Haze"}),b.jsx("option",{value:"Gothic Fantasy",children:"Gothic Fantasy"})]}),b.jsxs("optgroup",{label:"Professional Production",children:[b.jsx("option",{value:"LED Volume (Virtual Production)",children:"LED Volume (Virtual Production)"}),b.jsx("option",{value:"Automotive: Showroom",children:"Automotive: Showroom"}),b.jsx("option",{value:"Automotive: Process Trailer",children:"Automotive: Process Trailer"}),b.jsx("option",{value:"Product (Liquid/Splash)",children:"Product (Liquid/Splash)"}),b.jsx("option",{value:"VFX / Green Screen",children:"VFX / Green Screen"}),b.jsx("option",{value:"Knolling / Flat Lay",children:"Knolling / Flat Lay"})]}),b.jsxs("optgroup",{label:"Editorial & Fashion",children:[b.jsx("option",{value:"NYC Street Editorial",children:"NYC Street Editorial"}),b.jsx("option",{value:"90s Grunge Editorial",children:"90s Grunge Editorial"}),b.jsx("option",{value:"Fashion Editorial",children:"Fashion Editorial"}),b.jsx("option",{value:"Underground Rave / Flash",children:"Underground Rave / Flash"})]}),b.jsxs("optgroup",{label:"Documentary & Journalism",children:[b.jsx("option",{value:"Conflict Photography",children:"Conflict Photography"}),b.jsx("option",{value:"Street Photography",children:"Street Photography"}),b.jsx("option",{value:"Docu / Realism",children:"Docu / Realism"})]}),b.jsxs("optgroup",{label:"Architectural & Interior",children:[b.jsx("option",{value:"Architectural Digest Interior",children:"Architectural Digest Interior"}),b.jsx("option",{value:"Architecture",children:"Architecture"})]}),b.jsx("optgroup",{label:"Other",children:b.jsx("option",{value:"Custom",children:"Custom"})})]})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:["Camera Body",b.jsxs("div",{className:"relative",onMouseEnter:()=>ne("camera"),onMouseLeave:()=>ne(null),children:[b.jsx(eb,{className:"w-3 h-3 text-slate-500 cursor-help"}),V==="camera"&&b.jsx(Ut,{text:l.find(Be=>Be.value===C)?.tooltip,position:"bottom"})]})]}),b.jsxs("div",{className:"relative",children:[b.jsx("select",{value:C,onChange:Be=>v(Be.target.value),className:"w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 focus:border-cinema-gold focus:outline-none focus:ring-2 focus:ring-cinema-gold/20 transition-all",children:l.map(Be=>b.jsx("option",{value:Be.value,children:Be.display},Be.value))}),b.jsx("div",{className:"text-xs text-slate-500 mt-1",children:l.find(Be=>Be.value===C)?.tags})]})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:["Lens Kit",b.jsxs("div",{className:"relative",onMouseEnter:()=>ne("lens"),onMouseLeave:()=>ne(null),children:[b.jsx(eb,{className:"w-3 h-3 text-slate-500 cursor-help"}),V==="lens"&&b.jsx(Ut,{text:c.find(Be=>Be.value===I)?.tooltip,position:"bottom"})]})]}),b.jsxs("div",{className:"relative",children:[b.jsx("select",{value:I,onChange:Be=>x(Be.target.value),className:"w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 focus:border-cinema-gold focus:outline-none focus:ring-2 focus:ring-cinema-gold/20 transition-all",children:Ae.map(Be=>b.jsx("option",{value:Be.value,children:Be.display},Be.value))}),b.jsx("div",{className:"text-xs text-slate-500 mt-1",children:Ae.find(Be=>Be.value===I)?.keywords})]})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Aspect Ratio"}),b.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(Be=>b.jsx("button",{onClick:()=>T(Be),className:`px-4 py-2 rounded-lg font-medium transition-all ${_===Be?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"}`,children:Be},Be))})]}),b.jsx("div",{className:"bg-slate-800/50 rounded-lg p-4 text-xs text-slate-400",children:b.jsxs("div",{className:"flex items-start gap-2",children:[b.jsx(tb,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),b.jsxs("div",{children:[b.jsx("strong",{children:"Pro Tip:"})," Select an Application to auto-configure optimal camera and lens settings."]})]})}),b.jsxs("div",{className:"space-y-3 pt-4 border-t border-slate-800",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:[b.jsx(eO,{className:"w-4 h-4"}),"Creative Freedom"]}),b.jsxs("span",{className:"text-xs text-cinema-gold font-mono",children:[(N*100).toFixed(0),"%"]})]}),b.jsx("input",{type:"range",min:"0",max:"100",value:N*100,onChange:Be=>G(Be.target.value/100),className:"w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer slider",style:{background:`linear-gradient(to right, #f59e0b 0%, #f59e0b ${N*100}%, #475569 ${N*100}%, #475569 100%)`}}),b.jsxs("div",{className:"flex justify-between text-xs text-slate-500",children:[b.jsx("span",{children:"Strict"}),b.jsx("span",{children:"Creative"})]})]}),b.jsxs("div",{className:"space-y-3",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Scene Description"}),b.jsx("textarea",{value:k,onChange:Be=>z(Be.target.value),placeholder:"Describe your scene...",className:"w-full h-28 px-4 py-3 bg-slate-900/50 border border-slate-800 rounded-xl text-slate-200 placeholder-slate-500 focus:border-cinema-gold focus:outline-none focus:ring-2 focus:ring-cinema-gold/20 transition-all resize-none text-sm"}),b.jsxs("div",{className:"flex flex-col gap-2",children:[b.jsx("button",{onClick:Fe,disabled:le,className:"flex items-center justify-center space-x-2 w-full px-4 py-3 bg-gradient-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white font-medium rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:le?b.jsxs(b.Fragment,{children:[b.jsx(ss,{className:"w-5 h-5 animate-spin"}),b.jsx("span",{children:"Optimizing..."})]}):b.jsxs(b.Fragment,{children:[b.jsx(lw,{className:"w-5 h-5"}),b.jsx("span",{children:"Optimize"})]})}),b.jsx("button",{onClick:Tt,className:"w-full px-4 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 font-medium rounded-lg transition-all",children:"Simple Generate"})]}),de&&b.jsx("div",{className:"text-red-400 text-sm bg-red-950/20 border border-red-900/50 rounded-lg px-4 py-2",children:de})]})]})}),b.jsxs("div",{className:"lg:col-span-8 space-y-6",children:[b.jsxs("div",{className:"relative bg-gradient-to-br from-slate-900 to-slate-950 border border-slate-800 rounded-xl overflow-hidden",children:[b.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-cinema-gold"}),b.jsxs("div",{className:"p-6 space-y-4",children:[b.jsx("h3",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Optimized Prompt"}),b.jsx("div",{className:"min-h-[120px]",children:b.jsx("textarea",{value:H,onChange:Be=>re(Be.target.value),className:"w-full min-h-[120px] bg-transparent text-slate-200 font-mono text-sm leading-relaxed resize-y border-0 focus:outline-none focus:ring-0 placeholder:text-slate-500 placeholder:italic",placeholder:"Your optimized prompt will appear here. You can also type or edit directly..."})}),H&&b.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-slate-800",children:[b.jsx("button",{onClick:Se,className:"flex items-center space-x-2 px-5 py-2.5 bg-white hover:bg-slate-100 text-slate-950 font-medium rounded-lg transition-all transform hover:scale-105",children:$?b.jsxs(b.Fragment,{children:[b.jsx(So,{className:"w-4 h-4"}),b.jsx("span",{children:"Copied!"})]}):b.jsxs(b.Fragment,{children:[b.jsx(g6,{className:"w-4 h-4"}),b.jsx("span",{children:"Copy Prompt"})]})}),b.jsxs("div",{className:"text-xs text-slate-500",children:[H.split(" ").length," words"]})]})]})]}),b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-4",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsxs("h3",{className:"text-lg font-bold text-slate-200 flex items-center gap-2",children:[b.jsx(_c,{className:"w-5 h-5 text-cinema-gold"}),"Generated Image"]}),W&&b.jsxs("div",{className:"flex items-center gap-3",children:[b.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-amber-900/50 text-amber-400 border border-amber-800",children:"Edit Mode: Next prompt will modify this image"}),b.jsxs("button",{onClick:Ze,className:"text-xs px-3 py-1 bg-slate-700 hover:bg-slate-600 text-slate-300 rounded-lg transition-all flex items-center gap-1",children:[b.jsx(Np,{className:"w-3 h-3"}),"Start Fresh"]})]})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Reference Images (Optional)"}),b.jsxs("span",{className:"text-xs text-slate-500",children:[K.length,"/14"]})]}),b.jsxs("div",{className:"flex flex-wrap gap-2",children:[K.map((Be,Ve)=>b.jsxs("div",{className:"relative group",children:[b.jsx("img",{src:`data:${Be.mime_type};base64,${Be.data}`,alt:Be.name,className:"w-12 h-12 object-cover rounded-lg border border-slate-700"}),b.jsx("button",{onClick:()=>ht(Ve),className:"absolute -top-1 -right-1 w-4 h-4 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:b.jsx(Ds,{className:"w-3 h-3 text-white"})})]},Ve)),K.length<14&&b.jsxs(b.Fragment,{children:[be.length>0&&b.jsxs("button",{onClick:()=>He(!ve),className:`w-12 h-12 flex flex-col items-center justify-center border-2 border-dashed rounded-lg transition-colors ${ve?"border-cinema-gold bg-cinema-gold/10":"border-slate-700 hover:border-cinema-gold"}`,title:"Select from project",children:[b.jsx(Sc,{className:"w-4 h-4 text-cinema-gold"}),b.jsx("span",{className:"text-[8px] text-slate-400 mt-0.5",children:"Project"})]}),b.jsxs("label",{className:"w-12 h-12 flex flex-col items-center justify-center border-2 border-dashed border-slate-700 hover:border-slate-600 rounded-lg cursor-pointer transition-colors",children:[b.jsx(Wf,{className:"w-4 h-4 text-slate-500"}),b.jsx("span",{className:"text-[8px] text-slate-500 mt-0.5",children:"Upload"}),b.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:st,className:"hidden"})]})]})]}),ve&&be.length>0&&b.jsxs("div",{className:"bg-slate-800 border border-slate-700 rounded-lg p-3",children:[b.jsxs("div",{className:"flex items-center justify-between mb-2",children:[b.jsx("span",{className:"text-xs font-bold text-slate-400",children:"From Project"}),b.jsx("button",{onClick:()=>He(!1),className:"text-slate-500 hover:text-slate-300",children:b.jsx(Ds,{className:"w-4 h-4"})})]}),b.jsx("div",{className:"grid grid-cols-4 gap-2 max-h-32 overflow-y-auto",children:be.map(Be=>b.jsx("button",{onClick:()=>Xe(Be),disabled:K.some(Ve=>Ve.projectItemId===Be.id),className:`relative aspect-square rounded overflow-hidden border-2 transition-all ${K.some(Ve=>Ve.projectItemId===Be.id)?"border-green-500 opacity-50":"border-transparent hover:border-cinema-gold"}`,children:b.jsx("img",{src:`data:${Be.mimeType};base64,${Be.data}`,alt:Be.prompt||"Project image",className:"w-full h-full object-cover"})},Be.id))})]}),b.jsx("p",{className:"text-xs text-slate-500",children:"JPEG, PNG, WebP - Max 10MB each - Describe how to use references in your prompt"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Output Resolution"}),b.jsx("div",{className:"flex gap-2",children:["1K","2K","4K"].map(Be=>b.jsx("button",{onClick:()=>ue(Be),className:`px-4 py-2 rounded-lg text-sm font-medium transition-all ${se===Be?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"}`,children:Be},Be))}),b.jsxs("p",{className:"text-xs text-slate-500",children:[se==="1K"&&"~1024px - Fastest, web/social",se==="2K"&&"~2048px - Recommended for most uses",se==="4K"&&"~4096px - Print quality, slower"]})]}),b.jsx("div",{className:`${_==="9:16"||_==="3:4"?"max-w-xs mx-auto":""}`,children:b.jsx("div",{className:`${_==="9:16"?"aspect-[9/16]":_==="3:4"?"aspect-[3/4]":_==="1:1"?"aspect-square":_==="4:3"?"aspect-[4/3]":"aspect-video"} bg-slate-950 rounded-lg border-2 ${W?"border-cinema-gold":"border-dashed border-slate-700"} flex items-center justify-center overflow-hidden`,children:Ne?b.jsxs("div",{className:"text-center p-8",children:[b.jsx(ss,{className:"w-10 h-10 animate-spin text-cinema-gold mx-auto"}),b.jsx("p",{className:"text-slate-400 mt-3",children:"Generating image..."}),b.jsx("p",{className:"text-slate-500 text-xs mt-1",children:"This may take up to 2 minutes"})]}):W?b.jsx("img",{src:`data:${W.mime_type};base64,${W.data}`,alt:"Generated",className:"max-w-full max-h-full object-contain rounded"}):b.jsxs("div",{className:"text-center p-8",children:[b.jsx(_c,{className:"w-12 h-12 text-slate-700 mx-auto mb-3"}),b.jsx("p",{className:"text-slate-500",children:'Generate a prompt first, then click "Generate Image"'}),b.jsxs("p",{className:"text-slate-600 text-xs mt-2",children:["Requires PHP backend running on port ","5015"]})]})})}),S&&b.jsx("div",{className:"text-red-400 text-sm bg-red-950/20 border border-red-900/50 rounded-lg px-4 py-2",children:S}),b.jsxs("div",{className:"flex gap-3",children:[b.jsx("button",{onClick:Ye,disabled:!H||Ne,className:"flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-cinema-gold hover:bg-amber-400 text-slate-950 font-medium rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:Ne?b.jsxs(b.Fragment,{children:[b.jsx(ss,{className:"w-5 h-5 animate-spin"}),b.jsx("span",{children:"Generating..."})]}):b.jsxs(b.Fragment,{children:[b.jsx(lw,{className:"w-5 h-5"}),b.jsx("span",{children:W?"Edit Image":"Generate Image"})]})}),W&&b.jsxs(b.Fragment,{children:[b.jsx("button",{onClick:At,className:"px-4 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all",title:"Download Image",children:b.jsx(xc,{className:"w-5 h-5"})}),b.jsx("button",{onClick:Ze,className:"px-4 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all",title:"Start New Image",children:b.jsx(Np,{className:"w-5 h-5"})})]})]})]}),b.jsxs("div",{className:"bg-slate-900/30 rounded-lg p-4 space-y-3",children:[b.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs",children:[b.jsxs("div",{children:[b.jsx("span",{className:"text-slate-500",children:"Application:"}),b.jsx("span",{className:"ml-2 text-slate-300",children:g})]}),b.jsxs("div",{children:[b.jsx("span",{className:"text-slate-500",children:"Camera:"}),b.jsx("span",{className:"ml-2 text-slate-300",children:C})]}),b.jsxs("div",{children:[b.jsx("span",{className:"text-slate-500",children:"Lens:"}),b.jsx("span",{className:"ml-2 text-slate-300",children:I})]}),b.jsxs("div",{children:[b.jsx("span",{className:"text-slate-500",children:"Aspect:"}),b.jsx("span",{className:"ml-2 text-slate-300",children:_})]})]}),b.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsx("span",{className:"text-xs text-slate-500",children:"Focus Mode:"}),b.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${h.find(Be=>Be.value===g)?.focusType==="realism"?"bg-green-900/50 text-green-400 border border-green-800":"bg-purple-900/50 text-purple-400 border border-purple-800"}`,children:h.find(Be=>Be.value===g)?.focusType==="realism"?"🔬 Realism (Deep Focus)":"🎬 Stylistic (Cinematic)"})]}),b.jsx("p",{className:"text-xs text-slate-500 mt-2",children:h.find(Be=>Be.value===g)?.focusType==="realism"?"Prioritizes sharpness and deep focus for technical accuracy.":"Embraces bokeh and depth effects for emotional impact."})]})]})]})]})},R4=({src:A,onFrameExtract:e,onSaveToProject:t,className:n="",autoPlay:a=!1})=>{const s=ae.useRef(null),l=ae.useRef(null),c=A?.startsWith("/generated_videos/")?`${Sl("stream_video.php")}?file=${encodeURIComponent(A.replace("/generated_videos/",""))}`:A,[h,f]=ae.useState(!1),[g,y]=ae.useState(0),[C,v]=ae.useState(0),[I,x]=ae.useState(1),[_,T]=ae.useState(a),[k,z]=ae.useState(null),[H,re]=ae.useState(!1),[le,ce]=ae.useState(!1),[$,Y]=ae.useState(!1),[de,R]=ae.useState(null),V=ae.useRef(null),ne=24,Ae=1/ne;ae.useEffect(()=>{const oe=s.current;if(!oe)return;const ve=()=>y(oe.currentTime),He=()=>v(oe.duration),Xe=()=>f(!0),$e=()=>f(!1),nt=()=>f(!1),X=()=>{const We=oe.videoWidth/oe.videoHeight;We<.9?R("portrait"):We>1.1?R("landscape"):R("square")};return oe.addEventListener("timeupdate",ve),oe.addEventListener("durationchange",He),oe.addEventListener("play",Xe),oe.addEventListener("pause",$e),oe.addEventListener("ended",nt),oe.addEventListener("loadedmetadata",X),()=>{oe.removeEventListener("timeupdate",ve),oe.removeEventListener("durationchange",He),oe.removeEventListener("play",Xe),oe.removeEventListener("pause",$e),oe.removeEventListener("ended",nt),oe.removeEventListener("loadedmetadata",X)}},[]);const Ce=()=>{const oe=s.current;oe&&(h?oe.pause():oe.play())},N=oe=>{const ve=s.current,He=V.current;if(!ve||!He)return;const Xe=He.getBoundingClientRect(),nt=Math.max(0,Math.min(oe-Xe.left,Xe.width))/Xe.width;ve.currentTime=nt*C},G=oe=>{oe.preventDefault(),ce(!0),s.current?.pause(),N(oe.clientX)};ae.useEffect(()=>{if(!le)return;const oe=He=>{N(He.clientX)},ve=()=>{ce(!1)};return document.addEventListener("mousemove",oe),document.addEventListener("mouseup",ve),()=>{document.removeEventListener("mousemove",oe),document.removeEventListener("mouseup",ve)}},[le,C]);const W=()=>{const oe=s.current;oe&&(oe.pause(),oe.currentTime=Math.min(C,oe.currentTime+Ae))},he=()=>{const oe=s.current;oe&&(oe.pause(),oe.currentTime=Math.max(0,oe.currentTime-Ae))},Ne=()=>{const oe=s.current;oe&&(oe.currentTime=Math.min(C,oe.currentTime+1))},P=()=>{const oe=s.current;oe&&(oe.currentTime=Math.max(0,oe.currentTime-1))},S=()=>{const oe=s.current;oe&&(oe.muted=!oe.muted,T(!_))},Q=()=>{const oe=s.current,ve=l.current;if(!oe||!ve)return;oe.pause(),ve.width=oe.videoWidth,ve.height=oe.videoHeight,ve.getContext("2d").drawImage(oe,0,0,ve.width,ve.height);const Xe=ve.toDataURL("image/png"),$e=Xe.split(",")[1];z({dataUrl:Xe,base64:$e,width:oe.videoWidth,height:oe.videoHeight,timestamp:g}),Y(!1),re(!0),e&&e({data:$e,mime_type:"image/png",width:oe.videoWidth,height:oe.videoHeight,timestamp:g})},K=()=>{if(!k)return;const oe=document.createElement("a");oe.href=k.dataUrl,oe.download=`frame-${Math.round(k.timestamp*1e3)}ms.png`,oe.click()},Z=oe=>{const ve=Math.floor(oe/60),He=Math.floor(oe%60),Xe=Math.floor(oe%1*100);return`${ve.toString().padStart(2,"0")}:${He.toString().padStart(2,"0")}.${Xe.toString().padStart(2,"0")}`},se=Math.floor(g*ne),ue=Math.floor(C*ne),be=de==="portrait"?"max-w-sm mx-auto":"w-full";return b.jsxs("div",{className:`relative ${be} ${n}`,children:[b.jsx("canvas",{ref:l,className:"hidden"}),b.jsx("video",{ref:s,src:c,className:"w-full rounded-lg",onClick:Ce,preload:"auto",playsInline:!0,autoPlay:a,muted:a}),b.jsxs("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/90 to-transparent p-4 rounded-b-lg",children:[b.jsx("div",{ref:V,className:"w-full h-2 bg-slate-700 rounded-full cursor-pointer mb-3 group hover:h-3 transition-all",onMouseDown:G,children:b.jsx("div",{className:"h-full bg-cinema-gold rounded-full relative",style:{width:`${C?g/C*100:0}%`},children:b.jsx("div",{className:`absolute right-0 top-1/2 -translate-y-1/2 w-4 h-4 bg-cinema-gold rounded-full shadow-lg transition-opacity ${le?"opacity-100 scale-110":"opacity-0 group-hover:opacity-100"}`})})}),b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsxs("div",{className:"flex items-center gap-2",children:[b.jsx("button",{onClick:he,className:"p-1.5 hover:bg-white/20 rounded transition-colors",title:"Previous frame",children:b.jsx(o6,{className:"w-4 h-4"})}),b.jsx("button",{onClick:P,className:"p-1.5 hover:bg-white/20 rounded transition-colors",title:"Back 1s",children:b.jsx(J6,{className:"w-4 h-4"})}),b.jsx("button",{onClick:Ce,className:"p-2 bg-cinema-gold hover:bg-amber-400 text-slate-950 rounded-lg transition-colors",children:h?b.jsx(D6,{className:"w-5 h-5"}):b.jsx(j6,{className:"w-5 h-5 ml-0.5"})}),b.jsx("button",{onClick:Ne,className:"p-1.5 hover:bg-white/20 rounded transition-colors",title:"Forward 1s",children:b.jsx(Z6,{className:"w-4 h-4"})}),b.jsx("button",{onClick:W,className:"p-1.5 hover:bg-white/20 rounded transition-colors",title:"Next frame",children:b.jsx(a6,{className:"w-4 h-4"})}),b.jsx("button",{onClick:S,className:"p-1.5 hover:bg-white/20 rounded transition-colors ml-2",children:_?b.jsx(F4,{className:"w-4 h-4"}):b.jsx(I4,{className:"w-4 h-4"})})]}),b.jsxs("div",{className:"text-xs font-mono text-slate-300",children:[Z(g)," / ",Z(C),b.jsxs("span",{className:"ml-2 text-slate-500",children:["Frame ",se,"/",ue]})]}),b.jsx("div",{className:"flex items-center gap-2",children:b.jsxs("button",{onClick:Q,className:"flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 rounded-lg text-sm transition-colors",title:"Extract current frame",children:[b.jsx(V6,{className:"w-4 h-4"}),b.jsx("span",{children:"Extract Frame"})]})})]})]}),H&&k&&b.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>re(!1),children:b.jsxs("div",{className:"bg-slate-900 rounded-xl p-6 max-w-2xl w-full",onClick:oe=>oe.stopPropagation(),children:[b.jsxs("h3",{className:"text-lg font-bold text-slate-200 mb-4 flex items-center gap-2",children:[b.jsx(_c,{className:"w-5 h-5 text-cinema-gold"}),"Extracted Frame"]}),b.jsx("div",{className:"bg-slate-950 rounded-lg p-2 mb-4",children:b.jsx("img",{src:k.dataUrl,alt:"Extracted frame",className:"max-w-full max-h-[50vh] mx-auto rounded"})}),b.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 mb-4",children:[b.jsxs("span",{children:["Time: ",Z(k.timestamp)]}),b.jsxs("span",{children:[k.width," x ",k.height]})]}),b.jsxs("div",{className:"flex gap-3",children:[b.jsxs("button",{onClick:K,className:"flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-200 font-medium rounded-lg transition-colors",children:[b.jsx(xc,{className:"w-4 h-4"}),"Download"]}),t?b.jsx("button",{onClick:async()=>{$||(await t({data:k.base64,mimeType:"image/png",prompt:`Extracted frame at ${Z(k.timestamp)}`,width:k.width,height:k.height}),Y(!0))},className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 font-medium rounded-lg transition-colors ${$?"bg-green-600 text-white cursor-default":"bg-cinema-gold hover:bg-amber-400 text-slate-950"}`,children:$?b.jsxs(b.Fragment,{children:[b.jsx(So,{className:"w-4 h-4"}),"Saved!"]}):b.jsxs(b.Fragment,{children:[b.jsx(B6,{className:"w-4 h-4"}),"Save to Project"]})}):b.jsx("button",{onClick:()=>re(!1),className:"flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-slate-700 hover:bg-slate-600 text-slate-200 font-medium rounded-lg transition-colors",children:"Close"})]})]})})]})},ZO=({activeProjectId:A,rerunData:e,onRerunLoaded:t})=>{const[n,a]=ae.useState(""),[s,l]=ae.useState("fast"),[c,h]=ae.useState(4),[f,g]=ae.useState("16:9"),[y,C]=ae.useState("720p"),[v,I]=ae.useState(!0),[x,_]=ae.useState([]),[T,k]=ae.useState("frame"),[z,H]=ae.useState(""),[re,le]=ae.useState("");ae.useEffect(()=>{if(e){if(le(e.prompt||""),a(""),e.settings&&(l(e.settings.modelType||"fast"),h(e.settings.duration||4),g(e.settings.aspectRatio||"16:9"),C(e.settings.resolution||"720p"),I(e.settings.generateAudio??!0),H(e.settings.dialogue||""),k(e.settings.referenceMode||"frame")),e.referenceImages&&e.referenceImages.length>0){const Fe=e.referenceImages.map((Se,Ye)=>({data:Se.data,mime_type:Se.mime_type,name:`Reference ${Ye+1}`}));_(Fe)}else _([]);t&&t()}},[e,t]);const[ce,$]=ae.useState(!1),[Y,de]=ae.useState(!1),[R,V]=ae.useState(null),[ne,Ae]=ae.useState(""),[Ce,N]=ae.useState(0),{addItemToProject:G,getProjectWithItems:W,isReady:he}=nv(),[Ne,P]=ae.useState([]),[S,Q]=ae.useState(!1),[K,Z]=ae.useState(null);ae.useEffect(()=>{if(x.length===0){Z(null);return}const Fe=x[0],Se=document.createElement("img");Se.onload=()=>{const Ye=Se.width/Se.height;Ye<.9?Z("portrait"):Ye>1.1?Z("landscape"):Z("square")},Se.src=`data:${Fe.mime_type};base64,${Fe.data}`},[x]);const se=K&&(f==="16:9"&&K==="portrait"||f==="9:16"&&K==="landscape");ae.useEffect(()=>{(async()=>{if(!A||!he){P([]);return}try{const Se=await W(A);if(Se&&Se.items){const Ye=Se.items.filter(Ze=>Ze.type==="image");P(Ye)}}catch(Se){console.error("Failed to load project images:",Se)}})()},[A,he,W]);const ue=Fe=>{x.length>=2||x.some(Se=>Se.projectItemId===Fe.id)||(x.length===0&&(h(8),g("16:9")),_(Se=>[...Se,{data:Fe.data,mime_type:Fe.mimeType,name:Fe.prompt?.substring(0,20)||"Project Image",projectItemId:Fe.id}]),Q(!1))},be=[{value:"fast",label:"Fast",description:"Faster, lower cost"},{value:"standard",label:"Standard",description:"Higher quality"}],oe=Fe=>({fast:{4:"~$1.50",6:"~$2.25",8:"~$3"},standard:{4:"~$3",6:"~$4.50",8:"~$6"}})[s][Fe],ve=[{value:4,label:"4s"},{value:6,label:"6s"},{value:8,label:"8s"}],He=Fe=>{const Se=Array.from(Fe.target.files),Ye=2-x.length;Se.slice(0,Ye).forEach(At=>{if(!At.type.startsWith("image/")){Ae(`${At.name} is not an image file`);return}if(At.size>10*1024*1024){Ae(`${At.name} exceeds 10MB limit`);return}const st=new FileReader;st.onload=()=>{_(ht=>(ht.length===0&&(h(8),g("16:9")),[...ht,{data:st.result.split(",")[1],mime_type:At.type,name:At.name}]))},st.readAsDataURL(At)}),Fe.target.value=""},Xe=Fe=>{_(Se=>Se.filter((Ye,Ze)=>Ze!==Fe))},$e=Fe=>new Promise(Se=>{const Ye=document.createElement("video");Ye.crossOrigin="anonymous",Ye.muted=!0,Ye.onloadeddata=()=>{Ye.currentTime=.5},Ye.onseeked=()=>{try{const Ze=document.createElement("canvas");Ze.width=Ye.videoWidth,Ze.height=Ye.videoHeight,Ze.getContext("2d").drawImage(Ye,0,0,Ze.width,Ze.height);const st=Ze.toDataURL("image/jpeg",.8);Se(st.split(",")[1])}catch(Ze){console.error("Failed to extract thumbnail:",Ze),Se(null)}},Ye.onerror=()=>{console.error("Video load error for thumbnail"),Se(null)},setTimeout(()=>Se(null),5e3),Ye.src=Fe,Ye.load()}),nt=async()=>{if(!n.trim()){Ae("Please enter a scene description");return}de(!0),Ae("");try{const Fe=await fetch(Sl("get_config.php"));if(!Fe.ok)throw new Error("Failed to fetch config");const Se=await Fe.json();if(!Se.apiKey){console.warn("No API key found, using simple prompt"),X();return}const Ze=new O4(Se.apiKey).getGenerativeModel({model:"gemini-2.0-flash-lite"}),At=x.length>0,st=T==="frame"&&x.length>1,ht=T==="subject"&&At,Ut=T==="frame"&&At,Be=`You are a video prompt formatter for Google Veo 3.1. TASK: Convert the user's scene description into a clean, natural-language video prompt. @@ -94,22 +94,22 @@ Output: Elegant woman in sundress sits at sidewalk cafe, [fingers wrapped around Input: "Car chase" Output: Black muscle car tears through rain-slicked streets, [tires screeching on corners]. Gritty action style. Camera tracks low and dynamic.${v?" (Sound: roaring engine, squealing tires, horns)":""}`} -OUTPUT ONLY THE PROMPT - no explanations, no labels, no formatting.`;let Ve;if(At&&x.length>0){const rt=[];x.forEach((rA,zt)=>{rA?.data&&rt.push({inlineData:{data:rA.data.replace(/^data:[^;]+;base64,/,""),mimeType:rA.mime_type||"image/jpeg"}})}),rt.push({text:Be}),Ve=await Ze.generateContent(rt)}else Ve=await Ze.generateContent(Be);const ct=(await Ve.response).text().trim().replace(/^["']|["']$/g,"").replace(/^\*\*|\*\*$/g,"").replace(/^#+\s*/gm,"");le(ct)}catch(Fe){console.error("Optimization error:",Fe),Ae(`Optimization failed: ${Fe.message}. Using simple prompt.`),X()}finally{de(!1)}},X=()=>{const Fe=[];Fe.push(n),z&&Fe.push(`Character says: "${z}"`),le(Fe.join(" ")),de(!1)},We=async Fe=>{let Ye=0;const Ze=async()=>{if(Ye>=120)throw new Error("Video generation timed out. Please try again.");Ye++;const At=new FormData;At.append("action","check_status"),At.append("operationId",Fe);const ht=await(await fetch(Sc("video_api.php"),{method:"POST",body:At})).json();if(!ht.success)throw new Error(ht.error||"Status check failed");return ht.status==="complete"?ht.video:(ht.progress?N(ht.progress):N(Math.min(95,Ye/120*100)),await new Promise(Ut=>setTimeout(Ut,5e3)),Ze())};return Ze()},Tt=async(Fe=!1)=>{!re&&!Fe&&await nt();const Se=Fe?n:re||n;if(!Se.trim()){Ae("Please enter a scene description");return}$(!0),Ae(""),N(0);try{const Ye=new FormData;Ye.append("action","generate"),Ye.append("prompt",Se),Ye.append("modelType",s),Ye.append("duration",c.toString()),Ye.append("aspectRatio",f),Ye.append("resolution",y),Ye.append("generateAudio",v.toString()),Ye.append("referenceMode",T),x.forEach((Be,Ve)=>{Ye.append(`referenceImage_${Ve}`,Be.data),Ye.append(`referenceImageType_${Ve}`,Be.mime_type)}),Ye.append("referenceImageCount",x.length.toString());const At=await(await fetch(Sc("video_api.php"),{method:"POST",body:Ye})).json();if(!At.success)throw new Error(At.error||"Video generation failed");let st;if(At.status==="pending"&&At.operationId)N(5),st=await We(At.operationId);else if(At.status==="complete")st=At.video;else throw new Error("Unexpected response format");N(95);let ht=st.url,Ut=st.filename;if(st.url&&st.url.includes("generativelanguage.googleapis.com")){const Be=new FormData;Be.append("action","download_video"),Be.append("videoUrl",st.url);const lt=await(await fetch(Sc("video_api.php"),{method:"POST",body:Be})).json();if(lt.success&<.video)ht=lt.video.url,Ut=lt.video.filename;else throw new Error(lt.error||"Failed to download video")}if(N(100),V({url:ht,mime_type:st.mime_type||"video/mp4",filename:Ut}),A)try{const Be=await $e(ht);await G(A,{type:"video",prompt:Se,settings:{modelType:s,duration:c,aspectRatio:f,resolution:y,generateAudio:v,dialogue:z,referenceMode:T},referenceImages:x.map(Ve=>({data:Ve.data,mime_type:Ve.mime_type})),thumbnail:Be,data:ht,mimeType:"video/mp4"})}catch(Be){console.error("Failed to save to project:",Be)}}catch(Ye){Ae(`Generation failed: ${Ye.message}`)}finally{$(!1)}};return b.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-6",children:[b.jsxs("div",{className:"lg:col-span-4 space-y-6",children:[b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-6",children:[b.jsxs("h2",{className:"text-lg font-bold text-slate-200 flex items-center space-x-2",children:[b.jsx(Io,{className:"w-5 h-5 text-cinema-gold"}),b.jsx("span",{children:"Video Settings"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Model"}),b.jsx("div",{className:"flex gap-2",children:be.map(Fe=>b.jsxs("button",{onClick:()=>l(Fe.value),className:`flex-1 px-3 py-2 rounded-lg font-medium transition-all text-sm ${s===Fe.value?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"}`,children:[b.jsx("div",{children:Fe.label}),b.jsx("div",{className:"text-xs opacity-70",children:Fe.description})]},Fe.value))})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Duration"}),b.jsx("div",{className:"flex gap-2",children:ve.map(Fe=>{const Se=x.length>0&&Fe.value!==8;return b.jsxs("button",{onClick:()=>{Se||(h(Fe.value),Fe.value!==8&&y==="1080p"&&C("720p"))},disabled:Se,title:Se?"I2V requires 8s duration":"",className:`flex-1 px-3 py-2 rounded-lg font-medium transition-all text-sm ${c===Fe.value?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"} ${Se?"opacity-50 cursor-not-allowed":""}`,children:[b.jsx("div",{children:Fe.label}),b.jsx("div",{className:"text-xs opacity-70",children:oe(Fe.value)})]},Fe.value)})}),x.length>0&&b.jsx("p",{className:"text-xs text-slate-500",children:"I2V mode requires 8s duration"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Aspect Ratio"}),b.jsx("div",{className:"flex gap-2",children:["16:9","9:16"].map(Fe=>b.jsx("button",{onClick:()=>{g(Fe),Fe==="9:16"&&C("720p")},className:`flex-1 px-4 py-2 rounded-lg font-medium transition-all ${f===Fe?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"}`,children:Fe},Fe))})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Resolution"}),b.jsx("div",{className:"flex gap-2",children:["720p","1080p"].map(Fe=>{const Se=Fe==="1080p"&&(c!==8||f!=="16:9");return b.jsx("button",{onClick:()=>!Se&&C(Fe),disabled:Se,title:Se?"1080p requires 8s duration + 16:9 aspect ratio":"",className:`flex-1 px-4 py-2 rounded-lg font-medium transition-all ${y===Fe?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"} ${Se?"opacity-50 cursor-not-allowed":""}`,children:Fe},Fe)})}),(c!==8||f!=="16:9")&&b.jsx("p",{className:"text-xs text-slate-500",children:"1080p requires 8s + 16:9"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Audio"}),b.jsxs("button",{onClick:()=>I(!v),className:`w-full flex items-center justify-between px-4 py-2.5 rounded-lg font-medium transition-all text-sm ${v?"bg-green-900/50 text-green-400 border border-green-800":"bg-slate-800 text-slate-400 border border-slate-700"}`,children:[b.jsxs("span",{className:"flex items-center gap-2",children:[v?b.jsx(I4,{className:"w-4 h-4"}):b.jsx(F4,{className:"w-4 h-4"}),v?"Enabled":"Disabled"]}),b.jsx("span",{className:"text-xs opacity-70",children:"Veo 3"})]})]})]}),b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-4",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:["Scene Description ",b.jsx("span",{className:"text-cinema-gold",children:"*"})]}),b.jsx("textarea",{value:n,onChange:Fe=>{a(Fe.target.value),le("")},placeholder:"Describe your scene...",className:"w-full h-24 px-4 py-3 bg-slate-950 border border-slate-800 rounded-lg text-slate-200 placeholder-slate-500 focus:border-cinema-gold focus:outline-none resize-none text-sm"}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:[b.jsx(k6,{className:"w-3 h-3"}),"Dialogue (optional)"]}),b.jsx("input",{type:"text",value:z,onChange:Fe=>{H(Fe.target.value),le("")},placeholder:'"Hold the line!"',className:"w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 placeholder-slate-500 focus:border-cinema-gold focus:outline-none text-sm"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Reference Frames"}),b.jsxs("span",{className:"text-xs text-slate-500",children:[x.length,"/2"]})]}),b.jsx("p",{className:"text-[10px] text-slate-500",children:"Start from this frame. Add 2nd image for end frame (A→B interpolation)."}),b.jsxs("div",{className:"flex flex-wrap gap-2",children:[x.map((Fe,Se)=>b.jsxs("div",{className:"relative group",children:[b.jsx("img",{src:`data:${Fe.mime_type};base64,${Fe.data}`,alt:Fe.name,className:"w-14 h-14 object-cover rounded-lg border border-slate-700"}),b.jsx("button",{onClick:()=>Xe(Se),className:"absolute -top-1 -right-1 w-4 h-4 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:b.jsx(Ds,{className:"w-3 h-3 text-white"})}),b.jsx("span",{className:"absolute bottom-0 left-0 right-0 bg-black/70 text-[8px] text-center text-slate-300 rounded-b-lg",children:Se===0?"Start":"End"})]},Se)),x.length<2&&b.jsxs("div",{className:"flex gap-2",children:[Ne.length>0&&b.jsxs("button",{onClick:()=>Q(!S),className:`w-14 h-14 flex flex-col items-center justify-center border-2 border-dashed rounded-lg transition-colors ${S?"border-cinema-gold bg-cinema-gold/10":"border-slate-700 hover:border-cinema-gold"}`,title:"Select from project",children:[b.jsx(xc,{className:"w-4 h-4 text-cinema-gold"}),b.jsx("span",{className:"text-[8px] text-slate-400 mt-0.5",children:"Project"})]}),b.jsxs("label",{className:"w-14 h-14 flex flex-col items-center justify-center border-2 border-dashed border-slate-700 hover:border-slate-600 rounded-lg cursor-pointer transition-colors",children:[b.jsx(Wf,{className:"w-4 h-4 text-slate-500"}),b.jsx("span",{className:"text-[8px] text-slate-500 mt-0.5",children:"Upload"}),b.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:He,className:"hidden"})]})]})]}),S&&Ne.length>0&&b.jsxs("div",{className:"bg-slate-800 border border-slate-700 rounded-lg p-3",children:[b.jsxs("div",{className:"flex items-center justify-between mb-2",children:[b.jsx("span",{className:"text-xs font-bold text-slate-400",children:"From Project"}),b.jsx("button",{onClick:()=>Q(!1),className:"text-slate-500 hover:text-slate-300",children:b.jsx(Ds,{className:"w-4 h-4"})})]}),b.jsx("div",{className:"grid grid-cols-4 gap-2 max-h-24 overflow-y-auto",children:Ne.map(Fe=>b.jsx("button",{onClick:()=>ue(Fe),disabled:x.some(Se=>Se.projectItemId===Fe.id),className:`relative aspect-square rounded overflow-hidden border-2 transition-all ${x.some(Se=>Se.projectItemId===Fe.id)?"border-green-500 opacity-50":"border-transparent hover:border-cinema-gold"}`,children:b.jsx("img",{src:`data:${Fe.mimeType};base64,${Fe.data}`,alt:Fe.prompt||"Project image",className:"w-full h-full object-cover"})},Fe.id))})]}),se&&b.jsxs("div",{className:"flex items-start gap-2 p-2 bg-amber-950/30 border border-amber-700/50 rounded-lg",children:[b.jsx(oO,{className:"w-3 h-3 text-amber-500 flex-shrink-0 mt-0.5"}),b.jsxs("p",{className:"text-[10px] text-amber-400",children:["Reference is ",K,", output is ",f,". May cause cropping."]})]})]}),b.jsx("div",{className:"pt-2",children:b.jsx("button",{onClick:nt,disabled:Y||ce||!n.trim(),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white font-medium rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:Y?b.jsxs(b.Fragment,{children:[b.jsx(ss,{className:"w-5 h-5 animate-spin"}),b.jsx("span",{children:"Optimizing..."})]}):b.jsxs(b.Fragment,{children:[b.jsx(lw,{className:"w-5 h-5"}),b.jsx("span",{children:"Optimize"})]})})})]})]}),b.jsxs("div",{className:"lg:col-span-8 space-y-6",children:[b.jsxs("div",{className:"relative bg-gradient-to-br from-slate-900 to-slate-950 border border-slate-800 rounded-xl overflow-hidden",children:[b.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-cinema-gold"}),b.jsxs("div",{className:"p-6 space-y-4",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsx("h3",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Optimized Prompt"}),re&&b.jsx("span",{className:"text-[10px] text-slate-500",children:"[brackets] = AI suggestions, edit as needed"})]}),b.jsx("textarea",{value:re,onChange:Fe=>le(Fe.target.value),placeholder:'Click "Optimize" to format your prompt for Veo...',className:"w-full min-h-[80px] bg-transparent text-slate-300 text-sm font-mono leading-relaxed resize-none border-0 focus:outline-none focus:ring-0 placeholder:text-slate-500"}),re&&b.jsx("button",{onClick:()=>Tt(!1),disabled:ce,className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-cinema-gold hover:bg-amber-400 text-slate-950 font-bold rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:ce?b.jsxs(b.Fragment,{children:[b.jsx(ss,{className:"w-5 h-5 animate-spin"}),b.jsxs("span",{children:["Generating... ",Math.round(Ce),"%"]})]}):b.jsxs(b.Fragment,{children:[b.jsx(Io,{className:"w-5 h-5"}),b.jsx("span",{children:"Generate Video"})]})})]})]}),b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-4",children:[b.jsxs("h3",{className:"text-lg font-bold text-slate-200 flex items-center gap-2",children:[b.jsx(Io,{className:"w-5 h-5 text-cinema-gold"}),"Generated Video"]}),b.jsx("div",{className:`${f==="9:16"?"max-w-xs mx-auto":""}`,children:b.jsx("div",{className:`${f==="9:16"?"aspect-[9/16]":"aspect-video"} bg-slate-950 rounded-lg border-2 ${R?"border-cinema-gold":"border-dashed border-slate-700"} flex items-center justify-center overflow-hidden`,children:ce?b.jsxs("div",{className:"text-center p-8",children:[b.jsx(ss,{className:"w-10 h-10 animate-spin text-cinema-gold mx-auto"}),b.jsx("p",{className:"text-slate-400 mt-3",children:"Generating video..."}),b.jsx("div",{className:"w-48 h-2 bg-slate-800 rounded-full mt-4 mx-auto overflow-hidden",children:b.jsx("div",{className:"h-full bg-cinema-gold transition-all duration-300",style:{width:`${Ce}%`}})}),b.jsx("p",{className:"text-slate-500 text-xs mt-2",children:"This may take 1-6 minutes"})]}):R?b.jsx(R4,{src:R.url,onFrameExtract:Fe=>{x.length<3&&_(Se=>[...Se,{data:Fe.data,mime_type:Fe.mime_type,name:`frame-${Math.round(Fe.timestamp*1e3)}ms.png`}])},onSaveToProject:A?async Fe=>{await G(A,{type:"image",prompt:Fe.prompt,data:Fe.data,mimeType:Fe.mimeType,thumbnail:Fe.data})}:null,className:"w-full"}):b.jsxs("div",{className:"text-center p-8",children:[b.jsx(Io,{className:"w-12 h-12 text-slate-700 mx-auto mb-3"}),b.jsx("p",{className:"text-slate-500",children:"Enter a scene description and generate"}),b.jsx("p",{className:"text-slate-600 text-xs mt-2",children:"Powered by Veo 3.1"})]})})}),ne&&b.jsx("div",{className:"text-amber-400 text-sm bg-amber-950/20 border border-amber-900/50 rounded-lg px-4 py-2",children:ne}),R&&b.jsxs("div",{className:"flex gap-3",children:[b.jsxs("button",{onClick:()=>{const Fe=document.createElement("a");Fe.href=R.url,Fe.download=R.filename||`lux-studio-video-${Date.now()}.mp4`,Fe.click()},className:"flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-cinema-gold hover:bg-amber-400 text-slate-950 font-medium rounded-lg transition-all",children:[b.jsx(Ec,{className:"w-5 h-5"}),b.jsx("span",{children:"Download"})]}),b.jsx("button",{onClick:()=>{V(null),N(0),Ae("")},className:"px-4 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all",title:"Start New Video",children:b.jsx(Np,{className:"w-5 h-5"})})]})]})]})]})};var bf=YE();function $O(){for(var A=arguments.length,e=new Array(A),t=0;tn=>{e.forEach(a=>a(n))},e)}const c0=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Eh(A){const e=Object.prototype.toString.call(A);return e==="[object Window]"||e==="[object global]"}function rv(A){return"nodeType"in A}function _i(A){var e,t;return A?Eh(A)?A:rv(A)&&(e=(t=A.ownerDocument)==null?void 0:t.defaultView)!=null?e:window:window}function iv(A){const{Document:e}=_i(A);return A instanceof e}function dd(A){return Eh(A)?!1:A instanceof _i(A).HTMLElement}function k4(A){return A instanceof _i(A).SVGElement}function xh(A){return A?Eh(A)?A.document:rv(A)?iv(A)?A:dd(A)||k4(A)?A.ownerDocument:document:document:document}const js=c0?ae.useLayoutEffect:ae.useEffect;function av(A){const e=ae.useRef(A);return js(()=>{e.current=A}),ae.useCallback(function(){for(var t=arguments.length,n=new Array(t),a=0;a{A.current=setInterval(n,a)},[]),t=ae.useCallback(()=>{A.current!==null&&(clearInterval(A.current),A.current=null)},[]);return[e,t]}function ed(A,e){e===void 0&&(e=[A]);const t=ae.useRef(A);return js(()=>{t.current!==A&&(t.current=A)},e),t}function gd(A,e){const t=ae.useRef();return ae.useMemo(()=>{const n=A(t.current);return t.current=n,n},[...e])}function Qp(A){const e=av(A),t=ae.useRef(null),n=ae.useCallback(a=>{a!==t.current&&e?.(a,t.current),t.current=a},[]);return[t,n]}function cw(A){const e=ae.useRef();return ae.useEffect(()=>{e.current=A},[A]),e.current}let $m={};function pd(A,e){return ae.useMemo(()=>{if(e)return e;const t=$m[A]==null?0:$m[A]+1;return $m[A]=t,A+"-"+t},[A,e])}function H4(A){return function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),a=1;a{const c=Object.entries(l);for(const[h,f]of c){const g=s[h];g!=null&&(s[h]=g+A*f)}return s},{...e})}}const uh=H4(1),td=H4(-1);function tR(A){return"clientX"in A&&"clientY"in A}function sv(A){if(!A)return!1;const{KeyboardEvent:e}=_i(A.target);return e&&A instanceof e}function AR(A){if(!A)return!1;const{TouchEvent:e}=_i(A.target);return e&&A instanceof e}function uw(A){if(AR(A)){if(A.touches&&A.touches.length){const{clientX:e,clientY:t}=A.touches[0];return{x:e,y:t}}else if(A.changedTouches&&A.changedTouches.length){const{clientX:e,clientY:t}=A.changedTouches[0];return{x:e,y:t}}}return tR(A)?{x:A.clientX,y:A.clientY}:null}const Ad=Object.freeze({Translate:{toString(A){if(!A)return;const{x:e,y:t}=A;return"translate3d("+(e?Math.round(e):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(A){if(!A)return;const{scaleX:e,scaleY:t}=A;return"scaleX("+e+") scaleY("+t+")"}},Transform:{toString(A){if(A)return[Ad.Translate.toString(A),Ad.Scale.toString(A)].join(" ")}},Transition:{toString(A){let{property:e,duration:t,easing:n}=A;return e+" "+t+"ms "+n}}}),yb="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function nR(A){return A.matches(yb)?A:A.querySelector(yb)}const rR={display:"none"};function iR(A){let{id:e,value:t}=A;return ai.createElement("div",{id:e,style:rR},t)}function aR(A){let{id:e,announcement:t,ariaLiveType:n="assertive"}=A;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return ai.createElement("div",{id:e,style:a,role:"status","aria-live":n,"aria-atomic":!0},t)}function sR(){const[A,e]=ae.useState("");return{announce:ae.useCallback(n=>{n!=null&&e(n)},[]),announcement:A}}const D4=ae.createContext(null);function oR(A){const e=ae.useContext(D4);ae.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(A)},[A,e])}function lR(){const[A]=ae.useState(()=>new Set),e=ae.useCallback(n=>(A.add(n),()=>A.delete(n)),[A]);return[ae.useCallback(n=>{let{type:a,event:s}=n;A.forEach(l=>{var c;return(c=l[a])==null?void 0:c.call(l,s)})},[A]),e]}const cR={draggable:` +OUTPUT ONLY THE PROMPT - no explanations, no labels, no formatting.`;let Ve;if(At&&x.length>0){const rt=[];x.forEach((rA,zt)=>{rA?.data&&rt.push({inlineData:{data:rA.data.replace(/^data:[^;]+;base64,/,""),mimeType:rA.mime_type||"image/jpeg"}})}),rt.push({text:Be}),Ve=await Ze.generateContent(rt)}else Ve=await Ze.generateContent(Be);const ct=(await Ve.response).text().trim().replace(/^["']|["']$/g,"").replace(/^\*\*|\*\*$/g,"").replace(/^#+\s*/gm,"");le(ct)}catch(Fe){console.error("Optimization error:",Fe),Ae(`Optimization failed: ${Fe.message}. Using simple prompt.`),X()}finally{de(!1)}},X=()=>{const Fe=[];Fe.push(n),z&&Fe.push(`Character says: "${z}"`),le(Fe.join(" ")),de(!1)},We=async Fe=>{let Ye=0;const Ze=async()=>{if(Ye>=120)throw new Error("Video generation timed out. Please try again.");Ye++;const At=new FormData;At.append("action","check_status"),At.append("operationId",Fe);const ht=await(await fetch(Sl("video_api.php"),{method:"POST",body:At})).json();if(!ht.success)throw new Error(ht.error||"Status check failed");return ht.status==="complete"?ht.video:(ht.progress?N(ht.progress):N(Math.min(95,Ye/120*100)),await new Promise(Ut=>setTimeout(Ut,5e3)),Ze())};return Ze()},Tt=async(Fe=!1)=>{!re&&!Fe&&await nt();const Se=Fe?n:re||n;if(!Se.trim()){Ae("Please enter a scene description");return}$(!0),Ae(""),N(0);try{const Ye=new FormData;Ye.append("action","generate"),Ye.append("prompt",Se),Ye.append("modelType",s),Ye.append("duration",c.toString()),Ye.append("aspectRatio",f),Ye.append("resolution",y),Ye.append("generateAudio",v.toString()),Ye.append("referenceMode",T),x.forEach((Be,Ve)=>{Ye.append(`referenceImage_${Ve}`,Be.data),Ye.append(`referenceImageType_${Ve}`,Be.mime_type)}),Ye.append("referenceImageCount",x.length.toString());const At=await(await fetch(Sl("video_api.php"),{method:"POST",body:Ye})).json();if(!At.success)throw new Error(At.error||"Video generation failed");let st;if(At.status==="pending"&&At.operationId)N(5),st=await We(At.operationId);else if(At.status==="complete")st=At.video;else throw new Error("Unexpected response format");N(95);let ht=st.url,Ut=st.filename;if(st.url&&st.url.includes("generativelanguage.googleapis.com")){const Be=new FormData;Be.append("action","download_video"),Be.append("videoUrl",st.url);const lt=await(await fetch(Sl("video_api.php"),{method:"POST",body:Be})).json();if(lt.success&<.video)ht=lt.video.url,Ut=lt.video.filename;else throw new Error(lt.error||"Failed to download video")}if(N(100),V({url:ht,mime_type:st.mime_type||"video/mp4",filename:Ut}),A)try{const Be=await $e(ht);await G(A,{type:"video",prompt:Se,settings:{modelType:s,duration:c,aspectRatio:f,resolution:y,generateAudio:v,dialogue:z,referenceMode:T},referenceImages:x.map(Ve=>({data:Ve.data,mime_type:Ve.mime_type})),thumbnail:Be,data:ht,mimeType:"video/mp4"})}catch(Be){console.error("Failed to save to project:",Be)}}catch(Ye){Ae(`Generation failed: ${Ye.message}`)}finally{$(!1)}};return b.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-12 gap-6",children:[b.jsxs("div",{className:"lg:col-span-4 space-y-6",children:[b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-6",children:[b.jsxs("h2",{className:"text-lg font-bold text-slate-200 flex items-center space-x-2",children:[b.jsx(Io,{className:"w-5 h-5 text-cinema-gold"}),b.jsx("span",{children:"Video Settings"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Model"}),b.jsx("div",{className:"flex gap-2",children:be.map(Fe=>b.jsxs("button",{onClick:()=>l(Fe.value),className:`flex-1 px-3 py-2 rounded-lg font-medium transition-all text-sm ${s===Fe.value?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"}`,children:[b.jsx("div",{children:Fe.label}),b.jsx("div",{className:"text-xs opacity-70",children:Fe.description})]},Fe.value))})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Duration"}),b.jsx("div",{className:"flex gap-2",children:ve.map(Fe=>{const Se=x.length>0&&Fe.value!==8;return b.jsxs("button",{onClick:()=>{Se||(h(Fe.value),Fe.value!==8&&y==="1080p"&&C("720p"))},disabled:Se,title:Se?"I2V requires 8s duration":"",className:`flex-1 px-3 py-2 rounded-lg font-medium transition-all text-sm ${c===Fe.value?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"} ${Se?"opacity-50 cursor-not-allowed":""}`,children:[b.jsx("div",{children:Fe.label}),b.jsx("div",{className:"text-xs opacity-70",children:oe(Fe.value)})]},Fe.value)})}),x.length>0&&b.jsx("p",{className:"text-xs text-slate-500",children:"I2V mode requires 8s duration"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Aspect Ratio"}),b.jsx("div",{className:"flex gap-2",children:["16:9","9:16"].map(Fe=>b.jsx("button",{onClick:()=>{g(Fe),Fe==="9:16"&&C("720p")},className:`flex-1 px-4 py-2 rounded-lg font-medium transition-all ${f===Fe?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"}`,children:Fe},Fe))})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Resolution"}),b.jsx("div",{className:"flex gap-2",children:["720p","1080p"].map(Fe=>{const Se=Fe==="1080p"&&(c!==8||f!=="16:9");return b.jsx("button",{onClick:()=>!Se&&C(Fe),disabled:Se,title:Se?"1080p requires 8s duration + 16:9 aspect ratio":"",className:`flex-1 px-4 py-2 rounded-lg font-medium transition-all ${y===Fe?"bg-cinema-gold text-slate-950":"bg-slate-800 text-slate-400 hover:bg-slate-700"} ${Se?"opacity-50 cursor-not-allowed":""}`,children:Fe},Fe)})}),(c!==8||f!=="16:9")&&b.jsx("p",{className:"text-xs text-slate-500",children:"1080p requires 8s + 16:9"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Audio"}),b.jsxs("button",{onClick:()=>I(!v),className:`w-full flex items-center justify-between px-4 py-2.5 rounded-lg font-medium transition-all text-sm ${v?"bg-green-900/50 text-green-400 border border-green-800":"bg-slate-800 text-slate-400 border border-slate-700"}`,children:[b.jsxs("span",{className:"flex items-center gap-2",children:[v?b.jsx(I4,{className:"w-4 h-4"}):b.jsx(F4,{className:"w-4 h-4"}),v?"Enabled":"Disabled"]}),b.jsx("span",{className:"text-xs opacity-70",children:"Veo 3"})]})]})]}),b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-4",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:["Scene Description ",b.jsx("span",{className:"text-cinema-gold",children:"*"})]}),b.jsx("textarea",{value:n,onChange:Fe=>{a(Fe.target.value),le("")},placeholder:"Describe your scene...",className:"w-full h-24 px-4 py-3 bg-slate-950 border border-slate-800 rounded-lg text-slate-200 placeholder-slate-500 focus:border-cinema-gold focus:outline-none resize-none text-sm"}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-2",children:[b.jsx(k6,{className:"w-3 h-3"}),"Dialogue (optional)"]}),b.jsx("input",{type:"text",value:z,onChange:Fe=>{H(Fe.target.value),le("")},placeholder:'"Hold the line!"',className:"w-full px-4 py-2 bg-slate-800 border border-slate-700 rounded-lg text-slate-200 placeholder-slate-500 focus:border-cinema-gold focus:outline-none text-sm"})]}),b.jsxs("div",{className:"space-y-2",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Reference Frames"}),b.jsxs("span",{className:"text-xs text-slate-500",children:[x.length,"/2"]})]}),b.jsx("p",{className:"text-[10px] text-slate-500",children:"Start from this frame. Add 2nd image for end frame (A→B interpolation)."}),b.jsxs("div",{className:"flex flex-wrap gap-2",children:[x.map((Fe,Se)=>b.jsxs("div",{className:"relative group",children:[b.jsx("img",{src:`data:${Fe.mime_type};base64,${Fe.data}`,alt:Fe.name,className:"w-14 h-14 object-cover rounded-lg border border-slate-700"}),b.jsx("button",{onClick:()=>Xe(Se),className:"absolute -top-1 -right-1 w-4 h-4 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:b.jsx(Ds,{className:"w-3 h-3 text-white"})}),b.jsx("span",{className:"absolute bottom-0 left-0 right-0 bg-black/70 text-[8px] text-center text-slate-300 rounded-b-lg",children:Se===0?"Start":"End"})]},Se)),x.length<2&&b.jsxs("div",{className:"flex gap-2",children:[Ne.length>0&&b.jsxs("button",{onClick:()=>Q(!S),className:`w-14 h-14 flex flex-col items-center justify-center border-2 border-dashed rounded-lg transition-colors ${S?"border-cinema-gold bg-cinema-gold/10":"border-slate-700 hover:border-cinema-gold"}`,title:"Select from project",children:[b.jsx(Sc,{className:"w-4 h-4 text-cinema-gold"}),b.jsx("span",{className:"text-[8px] text-slate-400 mt-0.5",children:"Project"})]}),b.jsxs("label",{className:"w-14 h-14 flex flex-col items-center justify-center border-2 border-dashed border-slate-700 hover:border-slate-600 rounded-lg cursor-pointer transition-colors",children:[b.jsx(Wf,{className:"w-4 h-4 text-slate-500"}),b.jsx("span",{className:"text-[8px] text-slate-500 mt-0.5",children:"Upload"}),b.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:He,className:"hidden"})]})]})]}),S&&Ne.length>0&&b.jsxs("div",{className:"bg-slate-800 border border-slate-700 rounded-lg p-3",children:[b.jsxs("div",{className:"flex items-center justify-between mb-2",children:[b.jsx("span",{className:"text-xs font-bold text-slate-400",children:"From Project"}),b.jsx("button",{onClick:()=>Q(!1),className:"text-slate-500 hover:text-slate-300",children:b.jsx(Ds,{className:"w-4 h-4"})})]}),b.jsx("div",{className:"grid grid-cols-4 gap-2 max-h-24 overflow-y-auto",children:Ne.map(Fe=>b.jsx("button",{onClick:()=>ue(Fe),disabled:x.some(Se=>Se.projectItemId===Fe.id),className:`relative aspect-square rounded overflow-hidden border-2 transition-all ${x.some(Se=>Se.projectItemId===Fe.id)?"border-green-500 opacity-50":"border-transparent hover:border-cinema-gold"}`,children:b.jsx("img",{src:`data:${Fe.mimeType};base64,${Fe.data}`,alt:Fe.prompt||"Project image",className:"w-full h-full object-cover"})},Fe.id))})]}),se&&b.jsxs("div",{className:"flex items-start gap-2 p-2 bg-amber-950/30 border border-amber-700/50 rounded-lg",children:[b.jsx(oO,{className:"w-3 h-3 text-amber-500 flex-shrink-0 mt-0.5"}),b.jsxs("p",{className:"text-[10px] text-amber-400",children:["Reference is ",K,", output is ",f,". May cause cropping."]})]})]}),b.jsx("div",{className:"pt-2",children:b.jsx("button",{onClick:nt,disabled:Y||ce||!n.trim(),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white font-medium rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:Y?b.jsxs(b.Fragment,{children:[b.jsx(ss,{className:"w-5 h-5 animate-spin"}),b.jsx("span",{children:"Optimizing..."})]}):b.jsxs(b.Fragment,{children:[b.jsx(lw,{className:"w-5 h-5"}),b.jsx("span",{children:"Optimize"})]})})})]})]}),b.jsxs("div",{className:"lg:col-span-8 space-y-6",children:[b.jsxs("div",{className:"relative bg-gradient-to-br from-slate-900 to-slate-950 border border-slate-800 rounded-xl overflow-hidden",children:[b.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-cinema-gold"}),b.jsxs("div",{className:"p-6 space-y-4",children:[b.jsxs("div",{className:"flex items-center justify-between",children:[b.jsx("h3",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider",children:"Optimized Prompt"}),re&&b.jsx("span",{className:"text-[10px] text-slate-500",children:"[brackets] = AI suggestions, edit as needed"})]}),b.jsx("textarea",{value:re,onChange:Fe=>le(Fe.target.value),placeholder:'Click "Optimize" to format your prompt for Veo...',className:"w-full min-h-[80px] bg-transparent text-slate-300 text-sm font-mono leading-relaxed resize-none border-0 focus:outline-none focus:ring-0 placeholder:text-slate-500"}),re&&b.jsx("button",{onClick:()=>Tt(!1),disabled:ce,className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-cinema-gold hover:bg-amber-400 text-slate-950 font-bold rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:ce?b.jsxs(b.Fragment,{children:[b.jsx(ss,{className:"w-5 h-5 animate-spin"}),b.jsxs("span",{children:["Generating... ",Math.round(Ce),"%"]})]}):b.jsxs(b.Fragment,{children:[b.jsx(Io,{className:"w-5 h-5"}),b.jsx("span",{children:"Generate Video"})]})})]})]}),b.jsxs("div",{className:"bg-slate-900/50 border border-slate-800 rounded-xl p-6 space-y-4",children:[b.jsxs("h3",{className:"text-lg font-bold text-slate-200 flex items-center gap-2",children:[b.jsx(Io,{className:"w-5 h-5 text-cinema-gold"}),"Generated Video"]}),b.jsx("div",{className:`${f==="9:16"?"max-w-xs mx-auto":""}`,children:b.jsx("div",{className:`${f==="9:16"?"aspect-[9/16]":"aspect-video"} bg-slate-950 rounded-lg border-2 ${R?"border-cinema-gold":"border-dashed border-slate-700"} flex items-center justify-center overflow-hidden`,children:ce?b.jsxs("div",{className:"text-center p-8",children:[b.jsx(ss,{className:"w-10 h-10 animate-spin text-cinema-gold mx-auto"}),b.jsx("p",{className:"text-slate-400 mt-3",children:"Generating video..."}),b.jsx("div",{className:"w-48 h-2 bg-slate-800 rounded-full mt-4 mx-auto overflow-hidden",children:b.jsx("div",{className:"h-full bg-cinema-gold transition-all duration-300",style:{width:`${Ce}%`}})}),b.jsx("p",{className:"text-slate-500 text-xs mt-2",children:"This may take 1-6 minutes"})]}):R?b.jsx(R4,{src:R.url,onFrameExtract:Fe=>{x.length<3&&_(Se=>[...Se,{data:Fe.data,mime_type:Fe.mime_type,name:`frame-${Math.round(Fe.timestamp*1e3)}ms.png`}])},onSaveToProject:A?async Fe=>{await G(A,{type:"image",prompt:Fe.prompt,data:Fe.data,mimeType:Fe.mimeType,thumbnail:Fe.data})}:null,className:"w-full"}):b.jsxs("div",{className:"text-center p-8",children:[b.jsx(Io,{className:"w-12 h-12 text-slate-700 mx-auto mb-3"}),b.jsx("p",{className:"text-slate-500",children:"Enter a scene description and generate"}),b.jsx("p",{className:"text-slate-600 text-xs mt-2",children:"Powered by Veo 3.1"})]})})}),ne&&b.jsx("div",{className:"text-amber-400 text-sm bg-amber-950/20 border border-amber-900/50 rounded-lg px-4 py-2",children:ne}),R&&b.jsxs("div",{className:"flex gap-3",children:[b.jsxs("button",{onClick:()=>{const Fe=document.createElement("a");Fe.href=R.url,Fe.download=R.filename||`lux-studio-video-${Date.now()}.mp4`,Fe.click()},className:"flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-cinema-gold hover:bg-amber-400 text-slate-950 font-medium rounded-lg transition-all",children:[b.jsx(xc,{className:"w-5 h-5"}),b.jsx("span",{children:"Download"})]}),b.jsx("button",{onClick:()=>{V(null),N(0),Ae("")},className:"px-4 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-all",title:"Start New Video",children:b.jsx(Np,{className:"w-5 h-5"})})]})]})]})]})};var bf=YE();function $O(){for(var A=arguments.length,e=new Array(A),t=0;tn=>{e.forEach(a=>a(n))},e)}const c0=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Eh(A){const e=Object.prototype.toString.call(A);return e==="[object Window]"||e==="[object global]"}function rv(A){return"nodeType"in A}function _i(A){var e,t;return A?Eh(A)?A:rv(A)&&(e=(t=A.ownerDocument)==null?void 0:t.defaultView)!=null?e:window:window}function iv(A){const{Document:e}=_i(A);return A instanceof e}function dd(A){return Eh(A)?!1:A instanceof _i(A).HTMLElement}function k4(A){return A instanceof _i(A).SVGElement}function xh(A){return A?Eh(A)?A.document:rv(A)?iv(A)?A:dd(A)||k4(A)?A.ownerDocument:document:document:document}const js=c0?ae.useLayoutEffect:ae.useEffect;function av(A){const e=ae.useRef(A);return js(()=>{e.current=A}),ae.useCallback(function(){for(var t=arguments.length,n=new Array(t),a=0;a{A.current=setInterval(n,a)},[]),t=ae.useCallback(()=>{A.current!==null&&(clearInterval(A.current),A.current=null)},[]);return[e,t]}function ed(A,e){e===void 0&&(e=[A]);const t=ae.useRef(A);return js(()=>{t.current!==A&&(t.current=A)},e),t}function gd(A,e){const t=ae.useRef();return ae.useMemo(()=>{const n=A(t.current);return t.current=n,n},[...e])}function Qp(A){const e=av(A),t=ae.useRef(null),n=ae.useCallback(a=>{a!==t.current&&e?.(a,t.current),t.current=a},[]);return[t,n]}function cw(A){const e=ae.useRef();return ae.useEffect(()=>{e.current=A},[A]),e.current}let $m={};function pd(A,e){return ae.useMemo(()=>{if(e)return e;const t=$m[A]==null?0:$m[A]+1;return $m[A]=t,A+"-"+t},[A,e])}function H4(A){return function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),a=1;a{const c=Object.entries(l);for(const[h,f]of c){const g=s[h];g!=null&&(s[h]=g+A*f)}return s},{...e})}}const uh=H4(1),td=H4(-1);function tR(A){return"clientX"in A&&"clientY"in A}function sv(A){if(!A)return!1;const{KeyboardEvent:e}=_i(A.target);return e&&A instanceof e}function AR(A){if(!A)return!1;const{TouchEvent:e}=_i(A.target);return e&&A instanceof e}function uw(A){if(AR(A)){if(A.touches&&A.touches.length){const{clientX:e,clientY:t}=A.touches[0];return{x:e,y:t}}else if(A.changedTouches&&A.changedTouches.length){const{clientX:e,clientY:t}=A.changedTouches[0];return{x:e,y:t}}}return tR(A)?{x:A.clientX,y:A.clientY}:null}const Ad=Object.freeze({Translate:{toString(A){if(!A)return;const{x:e,y:t}=A;return"translate3d("+(e?Math.round(e):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(A){if(!A)return;const{scaleX:e,scaleY:t}=A;return"scaleX("+e+") scaleY("+t+")"}},Transform:{toString(A){if(A)return[Ad.Translate.toString(A),Ad.Scale.toString(A)].join(" ")}},Transition:{toString(A){let{property:e,duration:t,easing:n}=A;return e+" "+t+"ms "+n}}}),yb="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function nR(A){return A.matches(yb)?A:A.querySelector(yb)}const rR={display:"none"};function iR(A){let{id:e,value:t}=A;return ai.createElement("div",{id:e,style:rR},t)}function aR(A){let{id:e,announcement:t,ariaLiveType:n="assertive"}=A;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return ai.createElement("div",{id:e,style:a,role:"status","aria-live":n,"aria-atomic":!0},t)}function sR(){const[A,e]=ae.useState("");return{announce:ae.useCallback(n=>{n!=null&&e(n)},[]),announcement:A}}const D4=ae.createContext(null);function oR(A){const e=ae.useContext(D4);ae.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(A)},[A,e])}function lR(){const[A]=ae.useState(()=>new Set),e=ae.useCallback(n=>(A.add(n),()=>A.delete(n)),[A]);return[ae.useCallback(n=>{let{type:a,event:s}=n;A.forEach(l=>{var c;return(c=l[a])==null?void 0:c.call(l,s)})},[A]),e]}const cR={draggable:` To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. `},uR={onDragStart(A){let{active:e}=A;return"Picked up draggable item "+e.id+"."},onDragOver(A){let{active:e,over:t}=A;return t?"Draggable item "+e.id+" was moved over droppable area "+t.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(A){let{active:e,over:t}=A;return t?"Draggable item "+e.id+" was dropped over droppable area "+t.id:"Draggable item "+e.id+" was dropped."},onDragCancel(A){let{active:e}=A;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function hR(A){let{announcements:e=uR,container:t,hiddenTextDescribedById:n,screenReaderInstructions:a=cR}=A;const{announce:s,announcement:l}=sR(),c=pd("DndLiveRegion"),[h,f]=ae.useState(!1);if(ae.useEffect(()=>{f(!0)},[]),oR(ae.useMemo(()=>({onDragStart(y){let{active:C}=y;s(e.onDragStart({active:C}))},onDragMove(y){let{active:C,over:v}=y;e.onDragMove&&s(e.onDragMove({active:C,over:v}))},onDragOver(y){let{active:C,over:v}=y;s(e.onDragOver({active:C,over:v}))},onDragEnd(y){let{active:C,over:v}=y;s(e.onDragEnd({active:C,over:v}))},onDragCancel(y){let{active:C,over:v}=y;s(e.onDragCancel({active:C,over:v}))}}),[s,e])),!h)return null;const g=ai.createElement(ai.Fragment,null,ai.createElement(iR,{id:n,value:a.draggable}),ai.createElement(aR,{id:c,announcement:l}));return t?bf.createPortal(g,t):g}var or;(function(A){A.DragStart="dragStart",A.DragMove="dragMove",A.DragEnd="dragEnd",A.DragCancel="dragCancel",A.DragOver="dragOver",A.RegisterDroppable="registerDroppable",A.SetDroppableDisabled="setDroppableDisabled",A.UnregisterDroppable="unregisterDroppable"})(or||(or={}));function Lp(){}function Bb(A,e){return ae.useMemo(()=>({sensor:A,options:e??{}}),[A,e])}function fR(){for(var A=arguments.length,e=new Array(A),t=0;t[...e].filter(n=>n!=null),[...e])}const cs=Object.freeze({x:0,y:0});function M4(A,e){return Math.sqrt(Math.pow(A.x-e.x,2)+Math.pow(A.y-e.y,2))}function P4(A,e){let{data:{value:t}}=A,{data:{value:n}}=e;return t-n}function dR(A,e){let{data:{value:t}}=A,{data:{value:n}}=e;return n-t}function Cb(A){let{left:e,top:t,height:n,width:a}=A;return[{x:e,y:t},{x:e+a,y:t},{x:e,y:t+n},{x:e+a,y:t+n}]}function j4(A,e){if(!A||A.length===0)return null;const[t]=A;return t[e]}function bb(A,e,t){return e===void 0&&(e=A.left),t===void 0&&(t=A.top),{x:e+A.width*.5,y:t+A.height*.5}}const gR=A=>{let{collisionRect:e,droppableRects:t,droppableContainers:n}=A;const a=bb(e,e.left,e.top),s=[];for(const l of n){const{id:c}=l,h=t.get(c);if(h){const f=M4(bb(h),a);s.push({id:c,data:{droppableContainer:l,value:f}})}}return s.sort(P4)},pR=A=>{let{collisionRect:e,droppableRects:t,droppableContainers:n}=A;const a=Cb(e),s=[];for(const l of n){const{id:c}=l,h=t.get(c);if(h){const f=Cb(h),g=a.reduce((C,v,I)=>C+M4(f[I],v),0),y=Number((g/4).toFixed(4));s.push({id:c,data:{droppableContainer:l,value:y}})}}return s.sort(P4)};function mR(A,e){const t=Math.max(e.top,A.top),n=Math.max(e.left,A.left),a=Math.min(e.left+e.width,A.left+A.width),s=Math.min(e.top+e.height,A.top+A.height),l=a-n,c=s-t;if(n{let{collisionRect:e,droppableRects:t,droppableContainers:n}=A;const a=[];for(const s of n){const{id:l}=s,c=t.get(l);if(c){const h=mR(c,e);h>0&&a.push({id:l,data:{droppableContainer:s,value:h}})}}return a.sort(dR)};function vR(A,e,t){return{...A,scaleX:e&&t?e.width/t.width:1,scaleY:e&&t?e.height/t.height:1}}function K4(A,e){return A&&e?{x:A.left-e.left,y:A.top-e.top}:cs}function yR(A){return function(t){for(var n=arguments.length,a=new Array(n>1?n-1:0),s=1;s({...l,top:l.top+A*c.y,bottom:l.bottom+A*c.y,left:l.left+A*c.x,right:l.right+A*c.x}),{...t})}}const BR=yR(1);function CR(A){if(A.startsWith("matrix3d(")){const e=A.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(A.startsWith("matrix(")){const e=A.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function bR(A,e,t){const n=CR(e);if(!n)return A;const{scaleX:a,scaleY:s,x:l,y:c}=n,h=A.left-l-(1-a)*parseFloat(t),f=A.top-c-(1-s)*parseFloat(t.slice(t.indexOf(" ")+1)),g=a?A.width/a:A.width,y=s?A.height/s:A.height;return{width:g,height:y,top:f,right:h+g,bottom:f+y,left:h}}const ER={ignoreTransform:!1};function Sh(A,e){e===void 0&&(e=ER);let t=A.getBoundingClientRect();if(e.ignoreTransform){const{transform:f,transformOrigin:g}=_i(A).getComputedStyle(A);f&&(t=bR(t,f,g))}const{top:n,left:a,width:s,height:l,bottom:c,right:h}=t;return{top:n,left:a,width:s,height:l,bottom:c,right:h}}function Eb(A){return Sh(A,{ignoreTransform:!0})}function xR(A){const e=A.innerWidth,t=A.innerHeight;return{top:0,left:0,right:e,bottom:t,width:e,height:t}}function SR(A,e){return e===void 0&&(e=_i(A).getComputedStyle(A)),e.position==="fixed"}function UR(A,e){e===void 0&&(e=_i(A).getComputedStyle(A));const t=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const s=e[a];return typeof s=="string"?t.test(s):!1})}function u0(A,e){const t=[];function n(a){if(e!=null&&t.length>=e||!a)return t;if(iv(a)&&a.scrollingElement!=null&&!t.includes(a.scrollingElement))return t.push(a.scrollingElement),t;if(!dd(a)||k4(a)||t.includes(a))return t;const s=_i(A).getComputedStyle(a);return a!==A&&UR(a,s)&&t.push(a),SR(a,s)?t:n(a.parentNode)}return A?n(A):t}function G4(A){const[e]=u0(A,1);return e??null}function e1(A){return!c0||!A?null:Eh(A)?A:rv(A)?iv(A)||A===xh(A).scrollingElement?window:dd(A)?A:null:null}function z4(A){return Eh(A)?A.scrollX:A.scrollLeft}function V4(A){return Eh(A)?A.scrollY:A.scrollTop}function hw(A){return{x:z4(A),y:V4(A)}}var vr;(function(A){A[A.Forward=1]="Forward",A[A.Backward=-1]="Backward"})(vr||(vr={}));function q4(A){return!c0||!A?!1:A===document.scrollingElement}function Y4(A){const e={x:0,y:0},t=q4(A)?{height:window.innerHeight,width:window.innerWidth}:{height:A.clientHeight,width:A.clientWidth},n={x:A.scrollWidth-t.width,y:A.scrollHeight-t.height},a=A.scrollTop<=e.y,s=A.scrollLeft<=e.x,l=A.scrollTop>=n.y,c=A.scrollLeft>=n.x;return{isTop:a,isLeft:s,isBottom:l,isRight:c,maxScroll:n,minScroll:e}}const IR={x:.2,y:.2};function FR(A,e,t,n,a){let{top:s,left:l,right:c,bottom:h}=t;n===void 0&&(n=10),a===void 0&&(a=IR);const{isTop:f,isBottom:g,isLeft:y,isRight:C}=Y4(A),v={x:0,y:0},I={x:0,y:0},x={height:e.height*a.y,width:e.width*a.x};return!f&&s<=e.top+x.height?(v.y=vr.Backward,I.y=n*Math.abs((e.top+x.height-s)/x.height)):!g&&h>=e.bottom-x.height&&(v.y=vr.Forward,I.y=n*Math.abs((e.bottom-x.height-h)/x.height)),!C&&c>=e.right-x.width?(v.x=vr.Forward,I.x=n*Math.abs((e.right-x.width-c)/x.width)):!y&&l<=e.left+x.width&&(v.x=vr.Backward,I.x=n*Math.abs((e.left+x.width-l)/x.width)),{direction:v,speed:I}}function TR(A){if(A===document.scrollingElement){const{innerWidth:s,innerHeight:l}=window;return{top:0,left:0,right:s,bottom:l,width:s,height:l}}const{top:e,left:t,right:n,bottom:a}=A.getBoundingClientRect();return{top:e,left:t,right:n,bottom:a,width:A.clientWidth,height:A.clientHeight}}function X4(A){return A.reduce((e,t)=>uh(e,hw(t)),cs)}function _R(A){return A.reduce((e,t)=>e+z4(t),0)}function NR(A){return A.reduce((e,t)=>e+V4(t),0)}function QR(A,e){if(e===void 0&&(e=Sh),!A)return;const{top:t,left:n,bottom:a,right:s}=e(A);G4(A)&&(a<=0||s<=0||t>=window.innerHeight||n>=window.innerWidth)&&A.scrollIntoView({block:"center",inline:"center"})}const LR=[["x",["left","right"],_R],["y",["top","bottom"],NR]];class ov{constructor(e,t){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const n=u0(t),a=X4(n);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,l,c]of LR)for(const h of l)Object.defineProperty(this,h,{get:()=>{const f=c(n),g=a[s]-f;return this.rect[h]+g},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Rf{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(t=>{var n;return(n=this.target)==null?void 0:n.removeEventListener(...t)})},this.target=e}add(e,t,n){var a;(a=this.target)==null||a.addEventListener(e,t,n),this.listeners.push([e,t,n])}}function OR(A){const{EventTarget:e}=_i(A);return A instanceof e?A:xh(A)}function t1(A,e){const t=Math.abs(A.x),n=Math.abs(A.y);return typeof e=="number"?Math.sqrt(t**2+n**2)>e:"x"in e&&"y"in e?t>e.x&&n>e.y:"x"in e?t>e.x:"y"in e?n>e.y:!1}var wa;(function(A){A.Click="click",A.DragStart="dragstart",A.Keydown="keydown",A.ContextMenu="contextmenu",A.Resize="resize",A.SelectionChange="selectionchange",A.VisibilityChange="visibilitychange"})(wa||(wa={}));function xb(A){A.preventDefault()}function RR(A){A.stopPropagation()}var mA;(function(A){A.Space="Space",A.Down="ArrowDown",A.Right="ArrowRight",A.Left="ArrowLeft",A.Up="ArrowUp",A.Esc="Escape",A.Enter="Enter",A.Tab="Tab"})(mA||(mA={}));const J4={start:[mA.Space,mA.Enter],cancel:[mA.Esc],end:[mA.Space,mA.Enter,mA.Tab]},kR=(A,e)=>{let{currentCoordinates:t}=e;switch(A.code){case mA.Right:return{...t,x:t.x+25};case mA.Left:return{...t,x:t.x-25};case mA.Down:return{...t,y:t.y+25};case mA.Up:return{...t,y:t.y-25}}};class lv{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:t}}=e;this.props=e,this.listeners=new Rf(xh(t)),this.windowListeners=new Rf(_i(t)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(wa.Resize,this.handleCancel),this.windowListeners.add(wa.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(wa.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:t}=this.props,n=e.node.current;n&&QR(n),t(cs)}handleKeyDown(e){if(sv(e)){const{active:t,context:n,options:a}=this.props,{keyboardCodes:s=J4,coordinateGetter:l=kR,scrollBehavior:c="smooth"}=a,{code:h}=e;if(s.end.includes(h)){this.handleEnd(e);return}if(s.cancel.includes(h)){this.handleCancel(e);return}const{collisionRect:f}=n.current,g=f?{x:f.left,y:f.top}:cs;this.referenceCoordinates||(this.referenceCoordinates=g);const y=l(e,{active:t,context:n.current,currentCoordinates:g});if(y){const C=td(y,g),v={x:0,y:0},{scrollableAncestors:I}=n.current;for(const x of I){const _=e.code,{isTop:T,isRight:k,isLeft:z,isBottom:H,maxScroll:re,minScroll:le}=Y4(x),ce=TR(x),$={x:Math.min(_===mA.Right?ce.right-ce.width/2:ce.right,Math.max(_===mA.Right?ce.left:ce.left+ce.width/2,y.x)),y:Math.min(_===mA.Down?ce.bottom-ce.height/2:ce.bottom,Math.max(_===mA.Down?ce.top:ce.top+ce.height/2,y.y))},Y=_===mA.Right&&!k||_===mA.Left&&!z,de=_===mA.Down&&!H||_===mA.Up&&!T;if(Y&&$.x!==y.x){const R=x.scrollLeft+C.x,V=_===mA.Right&&R<=re.x||_===mA.Left&&R>=le.x;if(V&&!C.y){x.scrollTo({left:R,behavior:c});return}V?v.x=x.scrollLeft-R:v.x=_===mA.Right?x.scrollLeft-re.x:x.scrollLeft-le.x,v.x&&x.scrollBy({left:-v.x,behavior:c});break}else if(de&&$.y!==y.y){const R=x.scrollTop+C.y,V=_===mA.Down&&R<=re.y||_===mA.Up&&R>=le.y;if(V&&!C.x){x.scrollTo({top:R,behavior:c});return}V?v.y=x.scrollTop-R:v.y=_===mA.Down?x.scrollTop-re.y:x.scrollTop-le.y,v.y&&x.scrollBy({top:-v.y,behavior:c});break}}this.handleMove(e,uh(td(y,this.referenceCoordinates),v))}}}handleMove(e,t){const{onMove:n}=this.props;e.preventDefault(),n(t)}handleEnd(e){const{onEnd:t}=this.props;e.preventDefault(),this.detach(),t()}handleCancel(e){const{onCancel:t}=this.props;e.preventDefault(),this.detach(),t()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}lv.activators=[{eventName:"onKeyDown",handler:(A,e,t)=>{let{keyboardCodes:n=J4,onActivation:a}=e,{active:s}=t;const{code:l}=A.nativeEvent;if(n.start.includes(l)){const c=s.activatorNode.current;return c&&A.target!==c?!1:(A.preventDefault(),a?.({event:A.nativeEvent}),!0)}return!1}}];function Sb(A){return!!(A&&"distance"in A)}function Ub(A){return!!(A&&"delay"in A)}class cv{constructor(e,t,n){var a;n===void 0&&(n=OR(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=t;const{event:s}=e,{target:l}=s;this.props=e,this.events=t,this.document=xh(l),this.documentListeners=new Rf(this.document),this.listeners=new Rf(n),this.windowListeners=new Rf(_i(l)),this.initialCoordinates=(a=uw(s))!=null?a:cs,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:t,bypassActivationConstraint:n}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(wa.Resize,this.handleCancel),this.windowListeners.add(wa.DragStart,xb),this.windowListeners.add(wa.VisibilityChange,this.handleCancel),this.windowListeners.add(wa.ContextMenu,xb),this.documentListeners.add(wa.Keydown,this.handleKeydown),t){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ub(t)){this.timeoutId=setTimeout(this.handleStart,t.delay),this.handlePending(t);return}if(Sb(t)){this.handlePending(t);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,t){const{active:n,onPending:a}=this.props;a(n,e,this.initialCoordinates,t)}handleStart(){const{initialCoordinates:e}=this,{onStart:t}=this.props;e&&(this.activated=!0,this.documentListeners.add(wa.Click,RR,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(wa.SelectionChange,this.removeTextSelection),t(e))}handleMove(e){var t;const{activated:n,initialCoordinates:a,props:s}=this,{onMove:l,options:{activationConstraint:c}}=s;if(!a)return;const h=(t=uw(e))!=null?t:cs,f=td(a,h);if(!n&&c){if(Sb(c)){if(c.tolerance!=null&&t1(f,c.tolerance))return this.handleCancel();if(t1(f,c.distance))return this.handleStart()}if(Ub(c)&&t1(f,c.tolerance))return this.handleCancel();this.handlePending(c,f);return}e.cancelable&&e.preventDefault(),l(h)}handleEnd(){const{onAbort:e,onEnd:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleCancel(){const{onAbort:e,onCancel:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleKeydown(e){e.code===mA.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const HR={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class uv extends cv{constructor(e){const{event:t}=e,n=xh(t.target);super(e,HR,n)}}uv.activators=[{eventName:"onPointerDown",handler:(A,e)=>{let{nativeEvent:t}=A,{onActivation:n}=e;return!t.isPrimary||t.button!==0?!1:(n?.({event:t}),!0)}}];const DR={move:{name:"mousemove"},end:{name:"mouseup"}};var fw;(function(A){A[A.RightClick=2]="RightClick"})(fw||(fw={}));class MR extends cv{constructor(e){super(e,DR,xh(e.event.target))}}MR.activators=[{eventName:"onMouseDown",handler:(A,e)=>{let{nativeEvent:t}=A,{onActivation:n}=e;return t.button===fw.RightClick?!1:(n?.({event:t}),!0)}}];const A1={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class PR extends cv{constructor(e){super(e,A1)}static setup(){return window.addEventListener(A1.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(A1.move.name,e)};function e(){}}}PR.activators=[{eventName:"onTouchStart",handler:(A,e)=>{let{nativeEvent:t}=A,{onActivation:n}=e;const{touches:a}=t;return a.length>1?!1:(n?.({event:t}),!0)}}];var kf;(function(A){A[A.Pointer=0]="Pointer",A[A.DraggableRect=1]="DraggableRect"})(kf||(kf={}));var Op;(function(A){A[A.TreeOrder=0]="TreeOrder",A[A.ReversedTreeOrder=1]="ReversedTreeOrder"})(Op||(Op={}));function jR(A){let{acceleration:e,activator:t=kf.Pointer,canScroll:n,draggingRect:a,enabled:s,interval:l=5,order:c=Op.TreeOrder,pointerCoordinates:h,scrollableAncestors:f,scrollableAncestorRects:g,delta:y,threshold:C}=A;const v=GR({delta:y,disabled:!s}),[I,x]=eR(),_=ae.useRef({x:0,y:0}),T=ae.useRef({x:0,y:0}),k=ae.useMemo(()=>{switch(t){case kf.Pointer:return h?{top:h.y,bottom:h.y,left:h.x,right:h.x}:null;case kf.DraggableRect:return a}},[t,a,h]),z=ae.useRef(null),H=ae.useCallback(()=>{const le=z.current;if(!le)return;const ce=_.current.x*T.current.x,$=_.current.y*T.current.y;le.scrollBy(ce,$)},[]),re=ae.useMemo(()=>c===Op.TreeOrder?[...f].reverse():f,[c,f]);ae.useEffect(()=>{if(!s||!f.length||!k){x();return}for(const le of re){if(n?.(le)===!1)continue;const ce=f.indexOf(le),$=g[ce];if(!$)continue;const{direction:Y,speed:de}=FR(le,$,k,e,C);for(const R of["x","y"])v[R][Y[R]]||(de[R]=0,Y[R]=0);if(de.x>0||de.y>0){x(),z.current=le,I(H,l),_.current=de,T.current=Y;return}}_.current={x:0,y:0},T.current={x:0,y:0},x()},[e,H,n,x,s,l,JSON.stringify(k),JSON.stringify(v),I,f,re,g,JSON.stringify(C)])}const KR={x:{[vr.Backward]:!1,[vr.Forward]:!1},y:{[vr.Backward]:!1,[vr.Forward]:!1}};function GR(A){let{delta:e,disabled:t}=A;const n=cw(e);return gd(a=>{if(t||!n||!a)return KR;const s={x:Math.sign(e.x-n.x),y:Math.sign(e.y-n.y)};return{x:{[vr.Backward]:a.x[vr.Backward]||s.x===-1,[vr.Forward]:a.x[vr.Forward]||s.x===1},y:{[vr.Backward]:a.y[vr.Backward]||s.y===-1,[vr.Forward]:a.y[vr.Forward]||s.y===1}}},[t,e,n])}function zR(A,e){const t=e!=null?A.get(e):void 0,n=t?t.node.current:null;return gd(a=>{var s;return e==null?null:(s=n??a)!=null?s:null},[n,e])}function VR(A,e){return ae.useMemo(()=>A.reduce((t,n)=>{const{sensor:a}=n,s=a.activators.map(l=>({eventName:l.eventName,handler:e(l.handler,n)}));return[...t,...s]},[]),[A,e])}var nd;(function(A){A[A.Always=0]="Always",A[A.BeforeDragging=1]="BeforeDragging",A[A.WhileDragging=2]="WhileDragging"})(nd||(nd={}));var dw;(function(A){A.Optimized="optimized"})(dw||(dw={}));const Ib=new Map;function qR(A,e){let{dragging:t,dependencies:n,config:a}=e;const[s,l]=ae.useState(null),{frequency:c,measure:h,strategy:f}=a,g=ae.useRef(A),y=_(),C=ed(y),v=ae.useCallback(function(T){T===void 0&&(T=[]),!C.current&&l(k=>k===null?T:k.concat(T.filter(z=>!k.includes(z))))},[C]),I=ae.useRef(null),x=gd(T=>{if(y&&!t)return Ib;if(!T||T===Ib||g.current!==A||s!=null){const k=new Map;for(let z of A){if(!z)continue;if(s&&s.length>0&&!s.includes(z.id)&&z.rect.current){k.set(z.id,z.rect.current);continue}const H=z.node.current,re=H?new ov(h(H),H):null;z.rect.current=re,re&&k.set(z.id,re)}return k}return T},[A,s,t,y,h]);return ae.useEffect(()=>{g.current=A},[A]),ae.useEffect(()=>{y||v()},[t,y]),ae.useEffect(()=>{s&&s.length>0&&l(null)},[JSON.stringify(s)]),ae.useEffect(()=>{y||typeof c!="number"||I.current!==null||(I.current=setTimeout(()=>{v(),I.current=null},c))},[c,y,v,...n]),{droppableRects:x,measureDroppableContainers:v,measuringScheduled:s!=null};function _(){switch(f){case nd.Always:return!1;case nd.BeforeDragging:return t;default:return!t}}}function W4(A,e){return gd(t=>A?t||(typeof e=="function"?e(A):A):null,[e,A])}function YR(A,e){return W4(A,e)}function XR(A){let{callback:e,disabled:t}=A;const n=av(e),a=ae.useMemo(()=>{if(t||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(n)},[n,t]);return ae.useEffect(()=>()=>a?.disconnect(),[a]),a}function h0(A){let{callback:e,disabled:t}=A;const n=av(e),a=ae.useMemo(()=>{if(t||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(n)},[t]);return ae.useEffect(()=>()=>a?.disconnect(),[a]),a}function JR(A){return new ov(Sh(A),A)}function Fb(A,e,t){e===void 0&&(e=JR);const[n,a]=ae.useState(null);function s(){a(h=>{if(!A)return null;if(A.isConnected===!1){var f;return(f=h??t)!=null?f:null}const g=e(A);return JSON.stringify(h)===JSON.stringify(g)?h:g})}const l=XR({callback(h){if(A)for(const f of h){const{type:g,target:y}=f;if(g==="childList"&&y instanceof HTMLElement&&y.contains(A)){s();break}}}}),c=h0({callback:s});return js(()=>{s(),A?(c?.observe(A),l?.observe(document.body,{childList:!0,subtree:!0})):(c?.disconnect(),l?.disconnect())},[A]),n}function WR(A){const e=W4(A);return K4(A,e)}const Tb=[];function ZR(A){const e=ae.useRef(A),t=gd(n=>A?n&&n!==Tb&&A&&e.current&&A.parentNode===e.current.parentNode?n:u0(A):Tb,[A]);return ae.useEffect(()=>{e.current=A},[A]),t}function $R(A){const[e,t]=ae.useState(null),n=ae.useRef(A),a=ae.useCallback(s=>{const l=e1(s.target);l&&t(c=>c?(c.set(l,hw(l)),new Map(c)):null)},[]);return ae.useEffect(()=>{const s=n.current;if(A!==s){l(s);const c=A.map(h=>{const f=e1(h);return f?(f.addEventListener("scroll",a,{passive:!0}),[f,hw(f)]):null}).filter(h=>h!=null);t(c.length?new Map(c):null),n.current=A}return()=>{l(A),l(s)};function l(c){c.forEach(h=>{const f=e1(h);f?.removeEventListener("scroll",a)})}},[a,A]),ae.useMemo(()=>A.length?e?Array.from(e.values()).reduce((s,l)=>uh(s,l),cs):X4(A):cs,[A,e])}function _b(A,e){e===void 0&&(e=[]);const t=ae.useRef(null);return ae.useEffect(()=>{t.current=null},e),ae.useEffect(()=>{const n=A!==cs;n&&!t.current&&(t.current=A),!n&&t.current&&(t.current=null)},[A]),t.current?td(A,t.current):cs}function ek(A){ae.useEffect(()=>{if(!c0)return;const e=A.map(t=>{let{sensor:n}=t;return n.setup==null?void 0:n.setup()});return()=>{for(const t of e)t?.()}},A.map(e=>{let{sensor:t}=e;return t}))}function tk(A,e){return ae.useMemo(()=>A.reduce((t,n)=>{let{eventName:a,handler:s}=n;return t[a]=l=>{s(l,e)},t},{}),[A,e])}function Z4(A){return ae.useMemo(()=>A?xR(A):null,[A])}const Nb=[];function Ak(A,e){e===void 0&&(e=Sh);const[t]=A,n=Z4(t?_i(t):null),[a,s]=ae.useState(Nb);function l(){s(()=>A.length?A.map(h=>q4(h)?n:new ov(e(h),h)):Nb)}const c=h0({callback:l});return js(()=>{c?.disconnect(),l(),A.forEach(h=>c?.observe(h))},[A]),a}function nk(A){if(!A)return null;if(A.children.length>1)return A;const e=A.children[0];return dd(e)?e:A}function rk(A){let{measure:e}=A;const[t,n]=ae.useState(null),a=ae.useCallback(f=>{for(const{target:g}of f)if(dd(g)){n(y=>{const C=e(g);return y?{...y,width:C.width,height:C.height}:C});break}},[e]),s=h0({callback:a}),l=ae.useCallback(f=>{const g=nk(f);s?.disconnect(),g&&s?.observe(g),n(g?e(g):null)},[e,s]),[c,h]=Qp(l);return ae.useMemo(()=>({nodeRef:c,rect:t,setRef:h}),[t,c,h])}const ik=[{sensor:uv,options:{}},{sensor:lv,options:{}}],ak={current:{}},rp={draggable:{measure:Eb},droppable:{measure:Eb,strategy:nd.WhileDragging,frequency:dw.Optimized},dragOverlay:{measure:Sh}};class Hf extends Map{get(e){var t;return e!=null&&(t=super.get(e))!=null?t:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:t}=e;return!t})}getNodeFor(e){var t,n;return(t=(n=this.get(e))==null?void 0:n.node.current)!=null?t:void 0}}const sk={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Hf,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Lp},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:rp,measureDroppableContainers:Lp,windowRect:null,measuringScheduled:!1},ok={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Lp,draggableNodes:new Map,over:null,measureDroppableContainers:Lp},f0=ae.createContext(ok),$4=ae.createContext(sk);function lk(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Hf}}}function ck(A,e){switch(e.type){case or.DragStart:return{...A,draggable:{...A.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case or.DragMove:return A.draggable.active==null?A:{...A,draggable:{...A.draggable,translate:{x:e.coordinates.x-A.draggable.initialCoordinates.x,y:e.coordinates.y-A.draggable.initialCoordinates.y}}};case or.DragEnd:case or.DragCancel:return{...A,draggable:{...A.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case or.RegisterDroppable:{const{element:t}=e,{id:n}=t,a=new Hf(A.droppable.containers);return a.set(n,t),{...A,droppable:{...A.droppable,containers:a}}}case or.SetDroppableDisabled:{const{id:t,key:n,disabled:a}=e,s=A.droppable.containers.get(t);if(!s||n!==s.key)return A;const l=new Hf(A.droppable.containers);return l.set(t,{...s,disabled:a}),{...A,droppable:{...A.droppable,containers:l}}}case or.UnregisterDroppable:{const{id:t,key:n}=e,a=A.droppable.containers.get(t);if(!a||n!==a.key)return A;const s=new Hf(A.droppable.containers);return s.delete(t),{...A,droppable:{...A.droppable,containers:s}}}default:return A}}function uk(A){let{disabled:e}=A;const{active:t,activatorEvent:n,draggableNodes:a}=ae.useContext(f0),s=cw(n),l=cw(t?.id);return ae.useEffect(()=>{if(!e&&!n&&s&&l!=null){if(!sv(s)||document.activeElement===s.target)return;const c=a.get(l);if(!c)return;const{activatorNode:h,node:f}=c;if(!h.current&&!f.current)return;requestAnimationFrame(()=>{for(const g of[h.current,f.current]){if(!g)continue;const y=nR(g);if(y){y.focus();break}}})}},[n,e,a,l,s]),null}function hk(A,e){let{transform:t,...n}=e;return A!=null&&A.length?A.reduce((a,s)=>s({transform:a,...n}),t):t}function fk(A){return ae.useMemo(()=>({draggable:{...rp.draggable,...A?.draggable},droppable:{...rp.droppable,...A?.droppable},dragOverlay:{...rp.dragOverlay,...A?.dragOverlay}}),[A?.draggable,A?.droppable,A?.dragOverlay])}function dk(A){let{activeNode:e,measure:t,initialRect:n,config:a=!0}=A;const s=ae.useRef(!1),{x:l,y:c}=typeof a=="boolean"?{x:a,y:a}:a;js(()=>{if(!l&&!c||!e){s.current=!1;return}if(s.current||!n)return;const f=e?.node.current;if(!f||f.isConnected===!1)return;const g=t(f),y=K4(g,n);if(l||(y.x=0),c||(y.y=0),s.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const C=G4(f);C&&C.scrollBy({top:y.y,left:y.x})}},[e,l,c,n,t])}const eS=ae.createContext({...cs,scaleX:1,scaleY:1});var Bl;(function(A){A[A.Uninitialized=0]="Uninitialized",A[A.Initializing=1]="Initializing",A[A.Initialized=2]="Initialized"})(Bl||(Bl={}));const gk=ae.memo(function(e){var t,n,a,s;let{id:l,accessibility:c,autoScroll:h=!0,children:f,sensors:g=ik,collisionDetection:y=wR,measuring:C,modifiers:v,...I}=e;const x=ae.useReducer(ck,void 0,lk),[_,T]=x,[k,z]=lR(),[H,re]=ae.useState(Bl.Uninitialized),le=H===Bl.Initialized,{draggable:{active:ce,nodes:$,translate:Y},droppable:{containers:de}}=_,R=ce!=null?$.get(ce):null,V=ae.useRef({initial:null,translated:null}),ne=ae.useMemo(()=>{var pe;return ce!=null?{id:ce,data:(pe=R?.data)!=null?pe:ak,rect:V}:null},[ce,R]),Ae=ae.useRef(null),[Ce,N]=ae.useState(null),[G,W]=ae.useState(null),he=ed(I,Object.values(I)),Ne=pd("DndDescribedBy",l),P=ae.useMemo(()=>de.getEnabled(),[de]),S=fk(C),{droppableRects:Q,measureDroppableContainers:K,measuringScheduled:Z}=qR(P,{dragging:le,dependencies:[Y.x,Y.y],config:S.droppable}),se=zR($,ce),ue=ae.useMemo(()=>G?uw(G):null,[G]),be=Zt(),oe=YR(se,S.draggable.measure);dk({activeNode:ce!=null?$.get(ce):null,config:be.layoutShiftCompensation,initialRect:oe,measure:S.draggable.measure});const ve=Fb(se,S.draggable.measure,oe),He=Fb(se?se.parentElement:null),Xe=ae.useRef({activatorEvent:null,active:null,activeNode:se,collisionRect:null,collisions:null,droppableRects:Q,draggableNodes:$,draggingNode:null,draggingNodeRect:null,droppableContainers:de,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),$e=de.getNodeFor((t=Xe.current.over)==null?void 0:t.id),nt=rk({measure:S.dragOverlay.measure}),X=(n=nt.nodeRef.current)!=null?n:se,We=le?(a=nt.rect)!=null?a:ve:null,Tt=!!(nt.nodeRef.current&&nt.rect),Fe=WR(Tt?null:ve),Se=Z4(X?_i(X):null),Ye=ZR(le?$e??se:null),Ze=Ak(Ye),At=hk(v,{transform:{x:Y.x-Fe.x,y:Y.y-Fe.y,scaleX:1,scaleY:1},activatorEvent:G,active:ne,activeNodeRect:ve,containerNodeRect:He,draggingNodeRect:We,over:Xe.current.over,overlayNodeRect:nt.rect,scrollableAncestors:Ye,scrollableAncestorRects:Ze,windowRect:Se}),st=ue?uh(ue,Y):null,ht=$R(Ye),Ut=_b(ht),Be=_b(ht,[ve]),Ve=uh(At,Ut),lt=We?BR(We,At):null,it=ne&<?y({active:ne,collisionRect:lt,droppableRects:Q,droppableContainers:P,pointerCoordinates:st}):null,ct=j4(it,"id"),[rt,rA]=ae.useState(null),zt=Tt?At:uh(At,Be),St=vR(zt,(s=rt?.rect)!=null?s:null,ve),_t=ae.useRef(null),Vt=ae.useCallback((pe,Le)=>{let{sensor:at,options:jt}=Le;if(Ae.current==null)return;const $t=$.get(Ae.current);if(!$t)return;const xA=pe.nativeEvent,eA=new at({active:Ae.current,activeNode:$t,event:xA,options:jt,context:Xe,onAbort(FA){if(!$.get(FA))return;const{onDragAbort:tn}=he.current,rn={id:FA};tn?.(rn),k({type:"onDragAbort",event:rn})},onPending(FA,On,tn,rn){if(!$.get(FA))return;const{onDragPending:jA}=he.current,OA={id:FA,constraint:On,initialCoordinates:tn,offset:rn};jA?.(OA),k({type:"onDragPending",event:OA})},onStart(FA){const On=Ae.current;if(On==null)return;const tn=$.get(On);if(!tn)return;const{onDragStart:rn}=he.current,SA={activatorEvent:xA,active:{id:On,data:tn.data,rect:V}};bf.unstable_batchedUpdates(()=>{rn?.(SA),re(Bl.Initializing),T({type:or.DragStart,initialCoordinates:FA,active:On}),k({type:"onDragStart",event:SA}),N(_t.current),W(xA)})},onMove(FA){T({type:or.DragMove,coordinates:FA})},onEnd:mt(or.DragEnd),onCancel:mt(or.DragCancel)});_t.current=eA;function mt(FA){return async function(){const{active:tn,collisions:rn,over:SA,scrollAdjustedTranslate:jA}=Xe.current;let OA=null;if(tn&&jA){const{cancelDrop:Lr}=he.current;OA={activatorEvent:xA,active:tn,collisions:rn,delta:jA,over:SA},FA===or.DragEnd&&typeof Lr=="function"&&await Promise.resolve(Lr(OA))&&(FA=or.DragCancel)}Ae.current=null,bf.unstable_batchedUpdates(()=>{T({type:FA}),re(Bl.Uninitialized),rA(null),N(null),W(null),_t.current=null;const Lr=FA===or.DragEnd?"onDragEnd":"onDragCancel";if(OA){const Rn=he.current[Lr];Rn?.(OA),k({type:Lr,event:OA})}})}}},[$]),bt=ae.useCallback((pe,Le)=>(at,jt)=>{const $t=at.nativeEvent,xA=$.get(jt);if(Ae.current!==null||!xA||$t.dndKit||$t.defaultPrevented)return;const eA={active:xA};pe(at,Le.options,eA)===!0&&($t.dndKit={capturedBy:Le.sensor},Ae.current=jt,Vt(at,Le))},[$,Vt]),fA=VR(g,bt);ek(g),js(()=>{ve&&H===Bl.Initializing&&re(Bl.Initialized)},[ve,H]),ae.useEffect(()=>{const{onDragMove:pe}=he.current,{active:Le,activatorEvent:at,collisions:jt,over:$t}=Xe.current;if(!Le||!at)return;const xA={active:Le,activatorEvent:at,collisions:jt,delta:{x:Ve.x,y:Ve.y},over:$t};bf.unstable_batchedUpdates(()=>{pe?.(xA),k({type:"onDragMove",event:xA})})},[Ve.x,Ve.y]),ae.useEffect(()=>{const{active:pe,activatorEvent:Le,collisions:at,droppableContainers:jt,scrollAdjustedTranslate:$t}=Xe.current;if(!pe||Ae.current==null||!Le||!$t)return;const{onDragOver:xA}=he.current,eA=jt.get(ct),mt=eA&&eA.rect.current?{id:eA.id,rect:eA.rect.current,data:eA.data,disabled:eA.disabled}:null,FA={active:pe,activatorEvent:Le,collisions:at,delta:{x:$t.x,y:$t.y},over:mt};bf.unstable_batchedUpdates(()=>{rA(mt),xA?.(FA),k({type:"onDragOver",event:FA})})},[ct]),js(()=>{Xe.current={activatorEvent:G,active:ne,activeNode:se,collisionRect:lt,collisions:it,droppableRects:Q,draggableNodes:$,draggingNode:X,draggingNodeRect:We,droppableContainers:de,over:rt,scrollableAncestors:Ye,scrollAdjustedTranslate:Ve},V.current={initial:We,translated:lt}},[ne,se,it,lt,$,X,We,Q,de,rt,Ye,Ve]),jR({...be,delta:Y,draggingRect:lt,pointerCoordinates:st,scrollableAncestors:Ye,scrollableAncestorRects:Ze});const It=ae.useMemo(()=>({active:ne,activeNode:se,activeNodeRect:ve,activatorEvent:G,collisions:it,containerNodeRect:He,dragOverlay:nt,draggableNodes:$,droppableContainers:de,droppableRects:Q,over:rt,measureDroppableContainers:K,scrollableAncestors:Ye,scrollableAncestorRects:Ze,measuringConfiguration:S,measuringScheduled:Z,windowRect:Se}),[ne,se,ve,G,it,He,nt,$,de,Q,rt,K,Ye,Ze,S,Z,Se]),Nt=ae.useMemo(()=>({activatorEvent:G,activators:fA,active:ne,activeNodeRect:ve,ariaDescribedById:{draggable:Ne},dispatch:T,draggableNodes:$,over:rt,measureDroppableContainers:K}),[G,fA,ne,ve,T,Ne,$,rt,K]);return ai.createElement(D4.Provider,{value:z},ai.createElement(f0.Provider,{value:Nt},ai.createElement($4.Provider,{value:It},ai.createElement(eS.Provider,{value:St},f)),ai.createElement(uk,{disabled:c?.restoreFocus===!1})),ai.createElement(hR,{...c,hiddenTextDescribedById:Ne}));function Zt(){const pe=Ce?.autoScrollEnabled===!1,Le=typeof h=="object"?h.enabled===!1:h===!1,at=le&&!pe&&!Le;return typeof h=="object"?{...h,enabled:at}:{enabled:at}}}),pk=ae.createContext(null),Qb="button",mk="Draggable";function wk(A){let{id:e,data:t,disabled:n=!1,attributes:a}=A;const s=pd(mk),{activators:l,activatorEvent:c,active:h,activeNodeRect:f,ariaDescribedById:g,draggableNodes:y,over:C}=ae.useContext(f0),{role:v=Qb,roleDescription:I="draggable",tabIndex:x=0}=a??{},_=h?.id===e,T=ae.useContext(_?eS:pk),[k,z]=Qp(),[H,re]=Qp(),le=tk(l,e),ce=ed(t);js(()=>(y.set(e,{id:e,key:s,node:k,activatorNode:H,data:ce}),()=>{const Y=y.get(e);Y&&Y.key===s&&y.delete(e)}),[y,e]);const $=ae.useMemo(()=>({role:v,tabIndex:x,"aria-disabled":n,"aria-pressed":_&&v===Qb?!0:void 0,"aria-roledescription":I,"aria-describedby":g.draggable}),[n,v,x,_,I,g.draggable]);return{active:h,activatorEvent:c,activeNodeRect:f,attributes:$,isDragging:_,listeners:n?void 0:le,node:k,over:C,setNodeRef:z,setActivatorNodeRef:re,transform:T}}function vk(){return ae.useContext($4)}const yk="Droppable",Bk={timeout:25};function Ck(A){let{data:e,disabled:t=!1,id:n,resizeObserverConfig:a}=A;const s=pd(yk),{active:l,dispatch:c,over:h,measureDroppableContainers:f}=ae.useContext(f0),g=ae.useRef({disabled:t}),y=ae.useRef(!1),C=ae.useRef(null),v=ae.useRef(null),{disabled:I,updateMeasurementsFor:x,timeout:_}={...Bk,...a},T=ed(x??n),k=ae.useCallback(()=>{if(!y.current){y.current=!0;return}v.current!=null&&clearTimeout(v.current),v.current=setTimeout(()=>{f(Array.isArray(T.current)?T.current:[T.current]),v.current=null},_)},[_]),z=h0({callback:k,disabled:I||!l}),H=ae.useCallback(($,Y)=>{z&&(Y&&(z.unobserve(Y),y.current=!1),$&&z.observe($))},[z]),[re,le]=Qp(H),ce=ed(e);return ae.useEffect(()=>{!z||!re.current||(z.disconnect(),y.current=!1,z.observe(re.current))},[re,z]),ae.useEffect(()=>(c({type:or.RegisterDroppable,element:{id:n,key:s,disabled:t,node:re,rect:C,data:ce}}),()=>c({type:or.UnregisterDroppable,key:s,id:n})),[n]),ae.useEffect(()=>{t!==g.current.disabled&&(c({type:or.SetDroppableDisabled,id:n,key:s,disabled:t}),g.current.disabled=t)},[n,s,t,c]),{active:l,rect:C,isOver:h?.id===n,node:re,over:h,setNodeRef:le}}function hv(A,e,t){const n=A.slice();return n.splice(t<0?n.length+t:t,0,n.splice(e,1)[0]),n}function bk(A,e){return A.reduce((t,n,a)=>{const s=e.get(n);return s&&(t[a]=s),t},Array(A.length))}function vg(A){return A!==null&&A>=0}function Ek(A,e){if(A===e)return!0;if(A.length!==e.length)return!1;for(let t=0;t{let{rects:e,activeIndex:t,overIndex:n,index:a}=A;const s=hv(e,n,t),l=e[a],c=s[a];return!c||!l?null:{x:c.left-l.left,y:c.top-l.top,scaleX:c.width/l.width,scaleY:c.height/l.height}},tS="Sortable",AS=ai.createContext({activeIndex:-1,containerId:tS,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:fv,disabled:{draggable:!1,droppable:!1}});function Sk(A){let{children:e,id:t,items:n,strategy:a=fv,disabled:s=!1}=A;const{active:l,dragOverlay:c,droppableRects:h,over:f,measureDroppableContainers:g}=vk(),y=pd(tS,t),C=c.rect!==null,v=ae.useMemo(()=>n.map(le=>typeof le=="object"&&"id"in le?le.id:le),[n]),I=l!=null,x=l?v.indexOf(l.id):-1,_=f?v.indexOf(f.id):-1,T=ae.useRef(v),k=!Ek(v,T.current),z=_!==-1&&x===-1||k,H=xk(s);js(()=>{k&&I&&g(v)},[k,v,I,g]),ae.useEffect(()=>{T.current=v},[v]);const re=ae.useMemo(()=>({activeIndex:x,containerId:y,disabled:H,disableTransforms:z,items:v,overIndex:_,useDragOverlay:C,sortedRects:bk(v,h),strategy:a}),[x,y,H.draggable,H.droppable,z,v,_,h,C,a]);return ai.createElement(AS.Provider,{value:re},e)}const Uk=A=>{let{id:e,items:t,activeIndex:n,overIndex:a}=A;return hv(t,n,a).indexOf(e)},Ik=A=>{let{containerId:e,isSorting:t,wasDragging:n,index:a,items:s,newIndex:l,previousItems:c,previousContainerId:h,transition:f}=A;return!f||!n||c!==s&&a===l?!1:t?!0:l!==a&&e===h},Fk={duration:200,easing:"ease"},nS="transform",Tk=Ad.Transition.toString({property:nS,duration:0,easing:"linear"}),_k={roleDescription:"sortable"};function Nk(A){let{disabled:e,index:t,node:n,rect:a}=A;const[s,l]=ae.useState(null),c=ae.useRef(t);return js(()=>{if(!e&&t!==c.current&&n.current){const h=a.current;if(h){const f=Sh(n.current,{ignoreTransform:!0}),g={x:h.left-f.left,y:h.top-f.top,scaleX:h.width/f.width,scaleY:h.height/f.height};(g.x||g.y)&&l(g)}}t!==c.current&&(c.current=t)},[e,t,n,a]),ae.useEffect(()=>{s&&l(null)},[s]),s}function Qk(A){let{animateLayoutChanges:e=Ik,attributes:t,disabled:n,data:a,getNewIndex:s=Uk,id:l,strategy:c,resizeObserverConfig:h,transition:f=Fk}=A;const{items:g,containerId:y,activeIndex:C,disabled:v,disableTransforms:I,sortedRects:x,overIndex:_,useDragOverlay:T,strategy:k}=ae.useContext(AS),z=Lk(n,v),H=g.indexOf(l),re=ae.useMemo(()=>({sortable:{containerId:y,index:H,items:g},...a}),[y,a,H,g]),le=ae.useMemo(()=>g.slice(g.indexOf(l)),[g,l]),{rect:ce,node:$,isOver:Y,setNodeRef:de}=Ck({id:l,data:re,disabled:z.droppable,resizeObserverConfig:{updateMeasurementsFor:le,...h}}),{active:R,activatorEvent:V,activeNodeRect:ne,attributes:Ae,setNodeRef:Ce,listeners:N,isDragging:G,over:W,setActivatorNodeRef:he,transform:Ne}=wk({id:l,data:re,attributes:{..._k,...t},disabled:z.draggable}),P=$O(de,Ce),S=!!R,Q=S&&!I&&vg(C)&&vg(_),K=!T&&G,Z=K&&Q?Ne:null,ue=Q?Z??(c??k)({rects:x,activeNodeRect:ne,activeIndex:C,overIndex:_,index:H}):null,be=vg(C)&&vg(_)?s({id:l,items:g,activeIndex:C,overIndex:_}):H,oe=R?.id,ve=ae.useRef({activeId:oe,items:g,newIndex:be,containerId:y}),He=g!==ve.current.items,Xe=e({active:R,containerId:y,isDragging:G,isSorting:S,id:l,index:H,items:g,newIndex:ve.current.newIndex,previousItems:ve.current.items,previousContainerId:ve.current.containerId,transition:f,wasDragging:ve.current.activeId!=null}),$e=Nk({disabled:!Xe,index:H,node:$,rect:ce});return ae.useEffect(()=>{S&&ve.current.newIndex!==be&&(ve.current.newIndex=be),y!==ve.current.containerId&&(ve.current.containerId=y),g!==ve.current.items&&(ve.current.items=g)},[S,be,y,g]),ae.useEffect(()=>{if(oe===ve.current.activeId)return;if(oe!=null&&ve.current.activeId==null){ve.current.activeId=oe;return}const X=setTimeout(()=>{ve.current.activeId=oe},50);return()=>clearTimeout(X)},[oe]),{active:R,activeIndex:C,attributes:Ae,data:re,rect:ce,index:H,newIndex:be,items:g,isOver:Y,isSorting:S,isDragging:G,listeners:N,node:$,overIndex:_,over:W,setNodeRef:P,setActivatorNodeRef:he,setDroppableNodeRef:de,setDraggableNodeRef:Ce,transform:$e??ue,transition:nt()};function nt(){if($e||He&&ve.current.newIndex===H)return Tk;if(!(K&&!sv(V)||!f)&&(S||Xe))return Ad.Transition.toString({...f,property:nS})}}function Lk(A,e){var t,n;return typeof A=="boolean"?{draggable:A,droppable:!1}:{draggable:(t=A?.draggable)!=null?t:e.draggable,droppable:(n=A?.droppable)!=null?n:e.droppable}}function Rp(A){if(!A)return!1;const e=A.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const Ok=[mA.Down,mA.Right,mA.Up,mA.Left],Rk=(A,e)=>{let{context:{active:t,collisionRect:n,droppableRects:a,droppableContainers:s,over:l,scrollableAncestors:c}}=e;if(Ok.includes(A.code)){if(A.preventDefault(),!t||!n)return;const h=[];s.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const C=a.get(y.id);if(C)switch(A.code){case mA.Down:n.topC.top&&h.push(y);break;case mA.Left:n.left>C.left&&h.push(y);break;case mA.Right:n.left1&&(g=f[1].id),g!=null){const y=s.get(t.id),C=s.get(g),v=C?a.get(C.id):null,I=C?.node.current;if(I&&v&&y&&C){const _=u0(I).some((le,ce)=>c[ce]!==le),T=rS(y,C),k=kk(y,C),z=_||!T?{x:0,y:0}:{x:k?n.width-v.width:0,y:k?n.height-v.height:0},H={x:v.left,y:v.top};return z.x&&z.y?H:td(H,z)}}}};function rS(A,e){return!Rp(A)||!Rp(e)?!1:A.data.current.sortable.containerId===e.data.current.sortable.containerId}function kk(A,e){return!Rp(A)||!Rp(e)||!rS(A,e)?!1:A.data.current.sortable.index>1|(hn&21845)<<1;dl=(dl&52428)>>2|(dl&13107)<<2,dl=(dl&61680)>>4|(dl&3855)<<4,pw[hn]=((dl&65280)>>8|(dl&255)<<8)>>1}var Df=(function(A,e,t){for(var n=A.length,a=0,s=new $i(e);a>h]=f}else for(c=new $i(n),a=0;a>15-A[a]);return c}),Kc=new us(288);for(var hn=0;hn<144;++hn)Kc[hn]=8;for(var hn=144;hn<256;++hn)Kc[hn]=9;for(var hn=256;hn<280;++hn)Kc[hn]=7;for(var hn=280;hn<288;++hn)Kc[hn]=8;var kp=new us(32);for(var hn=0;hn<32;++hn)kp[hn]=5;var Mk=Df(Kc,9,0),Pk=Df(kp,5,0),sS=function(A){return(A+7)/8|0},jk=function(A,e,t){return(t==null||t>A.length)&&(t=A.length),new us(A.subarray(e,t))},Bo=function(A,e,t){t<<=e&7;var n=e/8|0;A[n]|=t,A[n+1]|=t>>8},pf=function(A,e,t){t<<=e&7;var n=e/8|0;A[n]|=t,A[n+1]|=t>>8,A[n+2]|=t>>16},n1=function(A,e){for(var t=[],n=0;nC&&(C=s[n].s);var v=new $i(C+1),I=mw(t[g-1],v,0);if(I>e){var n=0,x=0,_=I-e,T=1<<_;for(s.sort(function(le,ce){return v[ce.s]-v[le.s]||le.f-ce.f});ne)x+=T-(1<>=_;x>0;){var z=s[n].s;v[z]=0&&x;--n){var H=s[n].s;v[H]==e&&(--v[H],++x)}I=e}return{t:new us(v),l:I}},mw=function(A,e,t){return A.s==-1?Math.max(mw(A.l,e,t+1),mw(A.r,e,t+1)):e[A.s]=t},Rb=function(A){for(var e=A.length;e&&!A[--e];);for(var t=new $i(++e),n=0,a=A[0],s=1,l=function(h){t[n++]=h},c=1;c<=e;++c)if(A[c]==a&&c!=e)++s;else{if(!a&&s>2){for(;s>138;s-=138)l(32754);s>2&&(l(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(l(a),--s;s>6;s-=6)l(8304);s>2&&(l(s-3<<5|8208),s=0)}for(;s--;)l(a);s=1,a=A[c]}return{c:t.subarray(0,n),n:e}},mf=function(A,e){for(var t=0,n=0;n>8,A[a+2]=A[a]^255,A[a+3]=A[a+1]^255;for(var s=0;s4&&!de[Lb[V-1]];--V);var ne=f+5<<3,Ae=mf(a,Kc)+mf(s,kp)+l,Ce=mf(a,C)+mf(s,x)+l+14+3*V+mf(ce,de)+2*ce[16]+3*ce[17]+7*ce[18];if(h>=0&&ne<=Ae&&ne<=Ce)return oS(e,g,A.subarray(h,h+f));var N,G,W,he;if(Bo(e,g,1+(Ce15&&(Bo(e,g,Q[$]>>5&127),g+=Q[$]>>12)}}else N=Mk,G=Kc,W=Pk,he=kp;for(var $=0;$255){var K=Z>>18&31;pf(e,g,N[K+257]),g+=G[K+257],K>7&&(Bo(e,g,Z>>23&31),g+=gv[K]);var se=Z&31;pf(e,g,W[se]),g+=he[se],se>3&&(pf(e,g,Z>>5&8191),g+=pv[se])}else pf(e,g,N[Z]),g+=G[Z]}return pf(e,g,N[256]),g+G[256]},Kk=new dv([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lS=new us(0),Gk=function(A,e,t,n,a,s){var l=s.z||A.length,c=new us(n+l+5*(1+Math.ceil(l/7e3))+a),h=c.subarray(n,c.length-a),f=s.l,g=(s.r||0)&7;if(e){g&&(h[0]=s.r>>3);for(var y=Kk[e-1],C=y>>13,v=y&8191,I=(1<7e3||de>24576)&&(N>423||!f)){g=kb(A,h,0,H,re,le,$,de,V,Y-V,g),de=ce=$=0,V=Y;for(var G=0;G<286;++G)re[G]=0;for(var G=0;G<30;++G)le[G]=0}var W=2,he=0,Ne=v,P=Ae-Ce&32767;if(N>2&&ne==z(Y-P))for(var S=Math.min(C,N)-1,Q=Math.min(32767,Y),K=Math.min(258,N);P<=Q&&--Ne&&Ae!=Ce;){if(A[Y+W]==A[Y+W-P]){for(var Z=0;ZW){if(W=Z,he=P,Z>S)break;for(var se=Math.min(P,Z-2),ue=0,G=0;Gue&&(ue=ve,Ce=be)}}}Ae=Ce,Ce=x[Ae],P+=Ae-Ce&32767}if(he){H[de++]=268435456|gw[W]<<18|Ob[he];var He=gw[W]&31,Xe=Ob[he]&31;$+=gv[He]+pv[Xe],++re[257+He],++le[Xe],R=Y+W,++ce}else H[de++]=A[Y],++re[A[Y]]}}for(Y=Math.max(Y,R);Y=l&&(h[g/8|0]=f,$e=l),g=oS(h,g+1,A.subarray(Y,$e))}s.i=l}return jk(c,0,n+sS(g)+a)},cS=function(){var A=1,e=0;return{p:function(t){for(var n=A,a=e,s=t.length|0,l=0;l!=s;){for(var c=Math.min(l+2655,s);l>16),a=(a&65535)+15*(a>>16)}A=n,e=a},d:function(){return A%=65521,e%=65521,(A&255)<<24|(A&65280)<<8|(e&255)<<8|e>>8}}},zk=function(A,e,t,n,a){if(!a&&(a={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),l=new us(s.length+A.length);l.set(s),l.set(A,s.length),A=l,a.w=s.length}return Gk(A,e.level==null?6:e.level,e.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(A.length)))*1.5):20:12+e.mem,t,n,a)},uS=function(A,e,t){for(;t;++e)A[e]=t,t>>>=8},Vk=function(A,e){var t=e.level,n=t==0?0:t<6?1:t==9?3:2;if(A[0]=120,A[1]=n<<6|(e.dictionary&&32),A[1]|=31-(A[0]<<8|A[1])%31,e.dictionary){var a=cS();a.p(e.dictionary),uS(A,2,a.d())}};function ww(A,e){e||(e={});var t=cS();t.p(A);var n=zk(A,e,e.dictionary?6:2,4);return Vk(n,e),uS(n,n.length-4,t.d()),n}var qk=typeof TextDecoder<"u"&&new TextDecoder,Yk=0;try{qk.decode(lS,{stream:!0}),Yk=1}catch{}function Xk(A){if(Array.isArray(A))return A}function Jk(A,e){var t=A==null?null:typeof Symbol<"u"&&A[Symbol.iterator]||A["@@iterator"];if(t!=null){var n,a,s,l,c=[],h=!0,f=!1;try{if(s=(t=t.call(A)).next,e!==0)for(;!(h=(n=s.call(t)).done)&&(c.push(n.value),c.length!==e);h=!0);}catch(g){f=!0,a=g}finally{try{if(!h&&t.return!=null&&(l=t.return(),Object(l)!==l))return}finally{if(f)throw a}}return c}}function Hb(A,e){(e==null||e>A.length)&&(e=A.length);for(var t=0,n=Array(e);t{const A=new Uint8Array(4),e=new Uint32Array(A.buffer);return!((e[0]=1)&A[0])})(),r1={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};class mv{buffer;byteLength;byteOffset;length;offset;lastWrittenByte;littleEndian;_data;_mark;_marks;constructor(e=t8,t={}){let n=!1;typeof e=="number"?e=new ArrayBuffer(e):(n=!0,this.lastWrittenByte=e.byteLength);const a=t.offset?t.offset>>>0:0,s=e.byteLength-a;let l=a;(ArrayBuffer.isView(e)||e instanceof mv)&&(e.byteLength!==e.buffer.byteLength&&(l=e.byteOffset+a),e=e.buffer),n?this.lastWrittenByte=s:this.lastWrittenByte=0,this.buffer=e,this.length=s,this.byteLength=s,this.byteOffset=l,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer,l,s),this._mark=0,this._marks=[]}available(e=1){return this.offset+e<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(e=1){return this.offset+=e,this}back(e=1){return this.offset-=e,this}seek(e){return this.offset=e,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const e=this._marks.pop();if(e===void 0)throw new Error("Mark stack empty");return this.seek(e),this}rewind(){return this.offset=0,this}ensureAvailable(e=1){if(!this.available(e)){const n=(this.offset+e)*2,a=new Uint8Array(n);a.set(new Uint8Array(this.buffer)),this.buffer=a.buffer,this.length=n,this.byteLength=n,this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(e=1){return this.readArray(e,"uint8")}readArray(e,t){const n=r1[t].BYTES_PER_ELEMENT*e,a=this.byteOffset+this.offset,s=this.buffer.slice(a,a+n);if(this.littleEndian===A8&&t!=="uint8"&&t!=="int8"){const c=new Uint8Array(this.buffer.slice(a,a+n));c.reverse();const h=new r1[t](c.buffer);return this.offset+=n,h.reverse(),h}const l=new r1[t](s);return this.offset+=n,l}readInt16(){const e=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}readUint16(){const e=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,e}readInt32(){const e=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}readUint32(){const e=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}readFloat32(){const e=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}readFloat64(){const e=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}readBigInt64(){const e=this._data.getBigInt64(this.offset,this.littleEndian);return this.offset+=8,e}readBigUint64(){const e=this._data.getBigUint64(this.offset,this.littleEndian);return this.offset+=8,e}readChar(){return String.fromCharCode(this.readInt8())}readChars(e=1){let t="";for(let n=0;nthis.lastWrittenByte&&(this.lastWrittenByte=this.offset)}}function Uh(A){let e=A.length;for(;--e>=0;)A[e]=0}const n8=3,r8=258,hS=29,i8=256,a8=i8+1+hS,fS=30,s8=512,o8=new Array((a8+2)*2);Uh(o8);const l8=new Array(fS*2);Uh(l8);const c8=new Array(s8);Uh(c8);const u8=new Array(r8-n8+1);Uh(u8);const h8=new Array(hS);Uh(h8);const f8=new Array(fS);Uh(f8);const d8=(A,e,t,n)=>{let a=A&65535|0,s=A>>>16&65535|0,l=0;for(;t!==0;){l=t>2e3?2e3:t,t-=l;do a=a+e[n++]|0,s=s+a|0;while(--l);a%=65521,s%=65521}return a|s<<16|0};var vw=d8;const g8=()=>{let A,e=[];for(var t=0;t<256;t++){A=t;for(var n=0;n<8;n++)A=A&1?3988292384^A>>>1:A>>>1;e[t]=A}return e},p8=new Uint32Array(g8()),m8=(A,e,t,n)=>{const a=p8,s=n+t;A^=-1;for(let l=n;l>>8^a[(A^e[l])&255];return A^-1};var Ls=m8,yw={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},dS={Z_NO_FLUSH:0,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFLATED:8};const w8=(A,e)=>Object.prototype.hasOwnProperty.call(A,e);var v8=function(A){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(const n in t)w8(t,n)&&(A[n]=t[n])}}return A},y8=A=>{let e=0;for(let n=0,a=A.length;n=252?6:A>=248?5:A>=240?4:A>=224?3:A>=192?2:1;rd[254]=rd[254]=1;var B8=A=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(A);let e,t,n,a,s,l=A.length,c=0;for(a=0;a>>6,e[s++]=128|t&63):t<65536?(e[s++]=224|t>>>12,e[s++]=128|t>>>6&63,e[s++]=128|t&63):(e[s++]=240|t>>>18,e[s++]=128|t>>>12&63,e[s++]=128|t>>>6&63,e[s++]=128|t&63);return e};const C8=(A,e)=>{if(e<65534&&A.subarray&&pS)return String.fromCharCode.apply(null,A.length===e?A:A.subarray(0,e));let t="";for(let n=0;n{const t=e||A.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(A.subarray(0,e));let n,a;const s=new Array(t*2);for(a=0,n=0;n4){s[a++]=65533,n+=c-1;continue}for(l&=c===2?31:c===3?15:7;c>1&&n1){s[a++]=65533;continue}l<65536?s[a++]=l:(l-=65536,s[a++]=55296|l>>10&1023,s[a++]=56320|l&1023)}return C8(s,a)},E8=(A,e)=>{e=e||A.length,e>A.length&&(e=A.length);let t=e-1;for(;t>=0&&(A[t]&192)===128;)t--;return t<0||t===0?e:t+rd[A[t]]>e?t:e},Bw={string2buf:B8,buf2string:b8,utf8border:E8};function x8(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var S8=x8;const yg=16209,U8=16191;var I8=function(e,t){let n,a,s,l,c,h,f,g,y,C,v,I,x,_,T,k,z,H,re,le,ce,$,Y,de;const R=e.state;n=e.next_in,Y=e.input,a=n+(e.avail_in-5),s=e.next_out,de=e.output,l=s-(t-e.avail_out),c=s+(e.avail_out-257),h=R.dmax,f=R.wsize,g=R.whave,y=R.wnext,C=R.window,v=R.hold,I=R.bits,x=R.lencode,_=R.distcode,T=(1<>>24,v>>>=H,I-=H,H=z>>>16&255,H===0)de[s++]=z&65535;else if(H&16){re=z&65535,H&=15,H&&(I>>=H,I-=H),I<15&&(v+=Y[n++]<>>24,v>>>=H,I-=H,H=z>>>16&255,H&16){if(le=z&65535,H&=15,Ih){e.msg="invalid distance too far back",R.mode=yg;break e}if(v>>>=H,I-=H,H=s-l,le>H){if(H=le-H,H>g&&R.sane){e.msg="invalid distance too far back",R.mode=yg;break e}if(ce=0,$=C,y===0){if(ce+=f-H,H2;)de[s++]=$[ce++],de[s++]=$[ce++],de[s++]=$[ce++],re-=3;re&&(de[s++]=$[ce++],re>1&&(de[s++]=$[ce++]))}else{ce=s-le;do de[s++]=de[ce++],de[s++]=de[ce++],de[s++]=de[ce++],re-=3;while(re>2);re&&(de[s++]=de[ce++],re>1&&(de[s++]=de[ce++]))}}else if((H&64)===0){z=_[(z&65535)+(v&(1<>3,n-=re,I-=re<<3,v&=(1<{const h=c.bits;let f=0,g=0,y=0,C=0,v=0,I=0,x=0,_=0,T=0,k=0,z,H,re,le,ce,$=null,Y;const de=new Uint16Array(Pu+1),R=new Uint16Array(Pu+1);let V=null,ne,Ae,Ce;for(f=0;f<=Pu;f++)de[f]=0;for(g=0;g=1&&de[C]===0;C--);if(v>C&&(v=C),C===0)return a[s++]=1<<24|64<<16|0,a[s++]=1<<24|64<<16|0,c.bits=1,0;for(y=1;y0&&(A===Kb||C!==1))return-1;for(R[1]=0,f=1;fPb||A===Gb&&T>jb)return 1;for(;;){ne=f-x,l[g]+1=Y?(Ae=V[l[g]-Y],Ce=$[l[g]-Y]):(Ae=96,Ce=0),z=1<>x)+H]=ne<<24|Ae<<16|Ce|0;while(H!==0);for(z=1<>=1;if(z!==0?(k&=z-1,k+=z):k=0,g++,--de[f]===0){if(f===C)break;f=e[t+l[g]]}if(f>v&&(k&le)!==re){for(x===0&&(x=v),ce+=y,I=f-x,_=1<Pb||A===Gb&&T>jb)return 1;re=k&le,a[re]=v<<24|I<<16|ce-s|0}}return k!==0&&(a[ce+k]=f-x<<24|64<<16|0),c.bits=v,0};var Mf=Q8;const L8=0,mS=1,wS=2,{Z_FINISH:zb,Z_BLOCK:O8,Z_TREES:Bg,Z_OK:Gc,Z_STREAM_END:R8,Z_NEED_DICT:k8,Z_STREAM_ERROR:Sa,Z_DATA_ERROR:vS,Z_MEM_ERROR:yS,Z_BUF_ERROR:H8,Z_DEFLATED:Vb}=dS,d0=16180,qb=16181,Yb=16182,Xb=16183,Jb=16184,Wb=16185,Zb=16186,$b=16187,e5=16188,t5=16189,Hp=16190,Co=16191,a1=16192,A5=16193,s1=16194,n5=16195,r5=16196,i5=16197,a5=16198,Cg=16199,bg=16200,s5=16201,o5=16202,l5=16203,c5=16204,u5=16205,o1=16206,h5=16207,f5=16208,mn=16209,BS=16210,CS=16211,D8=852,M8=592,P8=15,j8=P8,d5=A=>(A>>>24&255)+(A>>>8&65280)+((A&65280)<<8)+((A&255)<<24);function K8(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Vc=A=>{if(!A)return 1;const e=A.state;return!e||e.strm!==A||e.modeCS?1:0},bS=A=>{if(Vc(A))return Sa;const e=A.state;return A.total_in=A.total_out=e.total=0,A.msg="",e.wrap&&(A.adler=e.wrap&1),e.mode=d0,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(D8),e.distcode=e.distdyn=new Int32Array(M8),e.sane=1,e.back=-1,Gc},ES=A=>{if(Vc(A))return Sa;const e=A.state;return e.wsize=0,e.whave=0,e.wnext=0,bS(A)},xS=(A,e)=>{let t;if(Vc(A))return Sa;const n=A.state;return e<0?(t=0,e=-e):(t=(e>>4)+5,e<48&&(e&=15)),e&&(e<8||e>15)?Sa:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,ES(A))},SS=(A,e)=>{if(!A)return Sa;const t=new K8;A.state=t,t.strm=A,t.window=null,t.mode=d0;const n=xS(A,e);return n!==Gc&&(A.state=null),n},G8=A=>SS(A,j8);let g5=!0,l1,c1;const z8=A=>{if(g5){l1=new Int32Array(512),c1=new Int32Array(32);let e=0;for(;e<144;)A.lens[e++]=8;for(;e<256;)A.lens[e++]=9;for(;e<280;)A.lens[e++]=7;for(;e<288;)A.lens[e++]=8;for(Mf(mS,A.lens,0,288,l1,0,A.work,{bits:9}),e=0;e<32;)A.lens[e++]=5;Mf(wS,A.lens,0,32,c1,0,A.work,{bits:5}),g5=!1}A.lencode=l1,A.lenbits=9,A.distcode=c1,A.distbits=5},US=(A,e,t,n)=>{let a;const s=A.state;return s.window===null&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):(a=s.wsize-s.wnext,a>n&&(a=n),s.window.set(e.subarray(t-n,t-n+a),s.wnext),n-=a,n?(s.window.set(e.subarray(t-n,t),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=a,s.wnext===s.wsize&&(s.wnext=0),s.whave{let t,n,a,s,l,c,h,f,g,y,C,v,I,x,_=0,T,k,z,H,re,le,ce,$;const Y=new Uint8Array(4);let de,R;const V=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Vc(A)||!A.output||!A.input&&A.avail_in!==0)return Sa;t=A.state,t.mode===Co&&(t.mode=a1),l=A.next_out,a=A.output,h=A.avail_out,s=A.next_in,n=A.input,c=A.avail_in,f=t.hold,g=t.bits,y=c,C=h,$=Gc;e:for(;;)switch(t.mode){case d0:if(t.wrap===0){t.mode=a1;break}for(;g<16;){if(c===0)break e;c--,f+=n[s++]<>>8&255,t.check=Ls(t.check,Y,2,0),f=0,g=0,t.mode=qb;break}if(t.head&&(t.head.done=!1),!(t.wrap&1)||(((f&255)<<8)+(f>>8))%31){A.msg="incorrect header check",t.mode=mn;break}if((f&15)!==Vb){A.msg="unknown compression method",t.mode=mn;break}if(f>>>=4,g-=4,ce=(f&15)+8,t.wbits===0&&(t.wbits=ce),ce>15||ce>t.wbits){A.msg="invalid window size",t.mode=mn;break}t.dmax=1<>8&1),t.flags&512&&t.wrap&4&&(Y[0]=f&255,Y[1]=f>>>8&255,t.check=Ls(t.check,Y,2,0)),f=0,g=0,t.mode=Yb;case Yb:for(;g<32;){if(c===0)break e;c--,f+=n[s++]<>>8&255,Y[2]=f>>>16&255,Y[3]=f>>>24&255,t.check=Ls(t.check,Y,4,0)),f=0,g=0,t.mode=Xb;case Xb:for(;g<16;){if(c===0)break e;c--,f+=n[s++]<>8),t.flags&512&&t.wrap&4&&(Y[0]=f&255,Y[1]=f>>>8&255,t.check=Ls(t.check,Y,2,0)),f=0,g=0,t.mode=Jb;case Jb:if(t.flags&1024){for(;g<16;){if(c===0)break e;c--,f+=n[s++]<>>8&255,t.check=Ls(t.check,Y,2,0)),f=0,g=0}else t.head&&(t.head.extra=null);t.mode=Wb;case Wb:if(t.flags&1024&&(v=t.length,v>c&&(v=c),v&&(t.head&&(ce=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(s,s+v),ce)),t.flags&512&&t.wrap&4&&(t.check=Ls(t.check,n,v,s)),c-=v,s+=v,t.length-=v),t.length))break e;t.length=0,t.mode=Zb;case Zb:if(t.flags&2048){if(c===0)break e;v=0;do ce=n[s+v++],t.head&&ce&&t.length<65536&&(t.head.name+=String.fromCharCode(ce));while(ce&&v>9&1,t.head.done=!0),A.adler=t.check=0,t.mode=Co;break;case t5:for(;g<32;){if(c===0)break e;c--,f+=n[s++]<>>=g&7,g-=g&7,t.mode=o1;break}for(;g<3;){if(c===0)break e;c--,f+=n[s++]<>>=1,g-=1,f&3){case 0:t.mode=A5;break;case 1:if(z8(t),t.mode=Cg,e===Bg){f>>>=2,g-=2;break e}break;case 2:t.mode=r5;break;case 3:A.msg="invalid block type",t.mode=mn}f>>>=2,g-=2;break;case A5:for(f>>>=g&7,g-=g&7;g<32;){if(c===0)break e;c--,f+=n[s++]<>>16^65535)){A.msg="invalid stored block lengths",t.mode=mn;break}if(t.length=f&65535,f=0,g=0,t.mode=s1,e===Bg)break e;case s1:t.mode=n5;case n5:if(v=t.length,v){if(v>c&&(v=c),v>h&&(v=h),v===0)break e;a.set(n.subarray(s,s+v),l),c-=v,s+=v,h-=v,l+=v,t.length-=v;break}t.mode=Co;break;case r5:for(;g<14;){if(c===0)break e;c--,f+=n[s++]<>>=5,g-=5,t.ndist=(f&31)+1,f>>>=5,g-=5,t.ncode=(f&15)+4,f>>>=4,g-=4,t.nlen>286||t.ndist>30){A.msg="too many length or distance symbols",t.mode=mn;break}t.have=0,t.mode=i5;case i5:for(;t.have>>=3,g-=3}for(;t.have<19;)t.lens[V[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,de={bits:t.lenbits},$=Mf(L8,t.lens,0,19,t.lencode,0,t.work,de),t.lenbits=de.bits,$){A.msg="invalid code lengths set",t.mode=mn;break}t.have=0,t.mode=a5;case a5:for(;t.have>>24,k=_>>>16&255,z=_&65535,!(T<=g);){if(c===0)break e;c--,f+=n[s++]<>>=T,g-=T,t.lens[t.have++]=z;else{if(z===16){for(R=T+2;g>>=T,g-=T,t.have===0){A.msg="invalid bit length repeat",t.mode=mn;break}ce=t.lens[t.have-1],v=3+(f&3),f>>>=2,g-=2}else if(z===17){for(R=T+3;g>>=T,g-=T,ce=0,v=3+(f&7),f>>>=3,g-=3}else{for(R=T+7;g>>=T,g-=T,ce=0,v=11+(f&127),f>>>=7,g-=7}if(t.have+v>t.nlen+t.ndist){A.msg="invalid bit length repeat",t.mode=mn;break}for(;v--;)t.lens[t.have++]=ce}}if(t.mode===mn)break;if(t.lens[256]===0){A.msg="invalid code -- missing end-of-block",t.mode=mn;break}if(t.lenbits=9,de={bits:t.lenbits},$=Mf(mS,t.lens,0,t.nlen,t.lencode,0,t.work,de),t.lenbits=de.bits,$){A.msg="invalid literal/lengths set",t.mode=mn;break}if(t.distbits=6,t.distcode=t.distdyn,de={bits:t.distbits},$=Mf(wS,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,de),t.distbits=de.bits,$){A.msg="invalid distances set",t.mode=mn;break}if(t.mode=Cg,e===Bg)break e;case Cg:t.mode=bg;case bg:if(c>=6&&h>=258){A.next_out=l,A.avail_out=h,A.next_in=s,A.avail_in=c,t.hold=f,t.bits=g,I8(A,C),l=A.next_out,a=A.output,h=A.avail_out,s=A.next_in,n=A.input,c=A.avail_in,f=t.hold,g=t.bits,t.mode===Co&&(t.back=-1);break}for(t.back=0;_=t.lencode[f&(1<>>24,k=_>>>16&255,z=_&65535,!(T<=g);){if(c===0)break e;c--,f+=n[s++]<>H)],T=_>>>24,k=_>>>16&255,z=_&65535,!(H+T<=g);){if(c===0)break e;c--,f+=n[s++]<>>=H,g-=H,t.back+=H}if(f>>>=T,g-=T,t.back+=T,t.length=z,k===0){t.mode=u5;break}if(k&32){t.back=-1,t.mode=Co;break}if(k&64){A.msg="invalid literal/length code",t.mode=mn;break}t.extra=k&15,t.mode=s5;case s5:if(t.extra){for(R=t.extra;g>>=t.extra,g-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=o5;case o5:for(;_=t.distcode[f&(1<>>24,k=_>>>16&255,z=_&65535,!(T<=g);){if(c===0)break e;c--,f+=n[s++]<>H)],T=_>>>24,k=_>>>16&255,z=_&65535,!(H+T<=g);){if(c===0)break e;c--,f+=n[s++]<>>=H,g-=H,t.back+=H}if(f>>>=T,g-=T,t.back+=T,k&64){A.msg="invalid distance code",t.mode=mn;break}t.offset=z,t.extra=k&15,t.mode=l5;case l5:if(t.extra){for(R=t.extra;g>>=t.extra,g-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){A.msg="invalid distance too far back",t.mode=mn;break}t.mode=c5;case c5:if(h===0)break e;if(v=C-h,t.offset>v){if(v=t.offset-v,v>t.whave&&t.sane){A.msg="invalid distance too far back",t.mode=mn;break}v>t.wnext?(v-=t.wnext,I=t.wsize-v):I=t.wnext-v,v>t.length&&(v=t.length),x=t.window}else x=a,I=l-t.offset,v=t.length;v>h&&(v=h),h-=v,t.length-=v;do a[l++]=x[I++];while(--v);t.length===0&&(t.mode=bg);break;case u5:if(h===0)break e;a[l++]=t.length,h--,t.mode=bg;break;case o1:if(t.wrap){for(;g<32;){if(c===0)break e;c--,f|=n[s++]<{if(Vc(A))return Sa;let e=A.state;return e.window&&(e.window=null),A.state=null,Gc},Y8=(A,e)=>{if(Vc(A))return Sa;const t=A.state;return(t.wrap&2)===0?Sa:(t.head=e,e.done=!1,Gc)},X8=(A,e)=>{const t=e.length;let n,a,s;return Vc(A)||(n=A.state,n.wrap!==0&&n.mode!==Hp)?Sa:n.mode===Hp&&(a=1,a=vw(a,e,t,0),a!==n.check)?vS:(s=US(A,e,t,t),s?(n.mode=BS,yS):(n.havedict=1,Gc))};var J8=ES,W8=xS,Z8=bS,$8=G8,eH=SS,tH=V8,AH=q8,nH=Y8,rH=X8,iH="pako inflate (from Nodeca project)",xo={inflateReset:J8,inflateReset2:W8,inflateResetKeep:Z8,inflateInit:$8,inflateInit2:eH,inflate:tH,inflateEnd:AH,inflateGetHeader:nH,inflateSetDictionary:rH,inflateInfo:iH};function aH(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var sH=aH;const IS=Object.prototype.toString,{Z_NO_FLUSH:oH,Z_FINISH:lH,Z_OK:id,Z_STREAM_END:u1,Z_NEED_DICT:h1,Z_STREAM_ERROR:cH,Z_DATA_ERROR:p5,Z_MEM_ERROR:uH}=dS;function md(A){this.options=gS.assign({chunkSize:1024*64,windowBits:15,to:""},A||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(A&&A.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new S8,this.strm.avail_out=0;let t=xo.inflateInit2(this.strm,e.windowBits);if(t!==id)throw new Error(yw[t]);if(this.header=new sH,xo.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Bw.string2buf(e.dictionary):IS.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=xo.inflateSetDictionary(this.strm,e.dictionary),t!==id)))throw new Error(yw[t])}md.prototype.push=function(A,e){const t=this.strm,n=this.options.chunkSize,a=this.options.dictionary;let s,l,c;if(this.ended)return!1;for(e===~~e?l=e:l=e===!0?lH:oH,IS.call(A)==="[object ArrayBuffer]"?t.input=new Uint8Array(A):t.input=A,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),s=xo.inflate(t,l),s===h1&&a&&(s=xo.inflateSetDictionary(t,a),s===id?s=xo.inflate(t,l):s===p5&&(s=h1));t.avail_in>0&&s===u1&&t.state.wrap>0&&A[t.next_in]!==0;)xo.inflateReset(t),s=xo.inflate(t,l);switch(s){case cH:case p5:case h1:case uH:return this.onEnd(s),this.ended=!0,!1}if(c=t.avail_out,t.next_out&&(t.avail_out===0||s===u1))if(this.options.to==="string"){let h=Bw.utf8border(t.output,t.next_out),f=t.next_out-h,g=Bw.buf2string(t.output,h);t.next_out=f,t.avail_out=n-f,f&&t.output.set(t.output.subarray(h,h+f),0),this.onData(g)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(!(s===id&&c===0)){if(s===u1)return s=xo.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(t.avail_in===0)break}}return!0};md.prototype.onData=function(A){this.chunks.push(A)};md.prototype.onEnd=function(A){A===id&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=gS.flattenChunks(this.chunks)),this.chunks=[],this.err=A,this.msg=this.strm.msg};function hH(A,e){const t=new md(e);if(t.push(A),t.err)throw t.msg||yw[t.err];return t.result}var fH=md,dH=hH,gH={Inflate:fH,inflate:dH};const{Inflate:pH,inflate:mH}=gH;var m5=pH,wH=mH;const FS=[];for(let A=0;A<256;A++){let e=A;for(let t=0;t<8;t++)e&1?e=3988292384^e>>>1:e=e>>>1;FS[A]=e}const w5=4294967295;function vH(A,e,t){let n=A;for(let a=0;a>>8;return n}function yH(A,e){return(vH(w5,A,e)^w5)>>>0}function v5(A,e,t){const n=A.readUint32(),a=yH(new Uint8Array(A.buffer,A.byteOffset+A.offset-e-4,e),e);if(a!==n)throw new Error(`CRC mismatch for chunk ${t}. Expected ${n}, found ${a}`)}function TS(A,e,t){for(let n=0;n>1)&255}else{for(;s>1)&255;for(;s>1)&255}}function LS(A,e,t,n,a){let s=0;if(t.length===0){for(;s=t||le>=n))for(let ce=0;ce>8&255}const IH=new Uint16Array([255]),FH=new Uint8Array(IH.buffer),TH=FH[0]===255,_H=new Uint8Array(0);function y5(A){const{data:e,width:t,height:n,channels:a,depth:s}=A,l=Math.ceil(s/8)*a,c=Math.ceil(s/8*a*t),h=new Uint8Array(n*c);let f=_H,g=0,y,C;for(let v=0;v>8&255}const ip=Uint8Array.of(137,80,78,71,13,10,26,10);function B5(A){if(!QH(A.readBytes(ip.length)))throw new Error("wrong PNG signature")}function QH(A){if(A.length79)throw new Error("keyword length must be between 1 and 79")}const kH=/^[\u0000-\u00FF]*$/;function HH(A){if(!kH.test(A))throw new Error("invalid latin1 text")}function DH(A,e,t){const n=RS(e);A[n]=MH(e,t-n.length-1)}function RS(A){for(A.mark();A.readByte()!==OH;);const e=A.offset;A.reset();const t=OS.decode(A.readBytes(e-A.offset-1));return A.skip(1),RH(t),t}function MH(A,e){return OS.decode(A.readBytes(e))}const Ji={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},f1={UNKNOWN:-1,DEFLATE:0},C5={UNKNOWN:-1,ADAPTIVE:0},d1={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},Eg={NONE:0,BACKGROUND:1,PREVIOUS:2},g1={SOURCE:0,OVER:1};class PH extends mv{_checkCrc;_inflator;_png;_apng;_end;_hasPalette;_palette;_hasTransparency;_transparency;_compressionMethod;_filterMethod;_interlaceMethod;_colorType;_isAnimated;_numberOfFrames;_numberOfPlays;_frames;_writingDataChunks;constructor(e,t={}){super(e);const{checkCrc:n=!1}=t;this._checkCrc=n,this._inflator=new m5,this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}},this._apng={width:-1,height:-1,channels:-1,depth:1,numberOfFrames:1,numberOfPlays:0,text:{},frames:[]},this._end=!1,this._hasPalette=!1,this._palette=[],this._hasTransparency=!1,this._transparency=new Uint16Array(0),this._compressionMethod=f1.UNKNOWN,this._filterMethod=C5.UNKNOWN,this._interlaceMethod=d1.UNKNOWN,this._colorType=Ji.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(B5(this);!this._end;){const e=this.readUint32(),t=this.readChars(4);this.decodeChunk(e,t)}return this.decodeImage(),this._png}decodeApng(){for(B5(this);!this._end;){const e=this.readUint32(),t=this.readChars(4);this.decodeApngChunk(e,t)}return this.decodeApngImage(),this._apng}decodeChunk(e,t){const n=this.offset;switch(t){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(e);break;case"IDAT":this.decodeIDAT(e);break;case"IEND":this._end=!0;break;case"tRNS":this.decodetRNS(e);break;case"iCCP":this.decodeiCCP(e);break;case LH:DH(this._png.text,this,e);break;case"pHYs":this.decodepHYs();break;default:this.skip(e);break}if(this.offset-n!==e)throw new Error(`Length mismatch while decoding chunk ${t}`);this._checkCrc?v5(this,e+4,t):this.skip(4)}decodeApngChunk(e,t){const n=this.offset;switch(t!=="fdAT"&&t!=="IDAT"&&this._writingDataChunks&&this.pushDataToFrame(),t){case"acTL":this.decodeACTL();break;case"fcTL":this.decodeFCTL();break;case"fdAT":this.decodeFDAT(e);break;default:this.decodeChunk(e,t),this.offset=n+e;break}if(this.offset-n!==e)throw new Error(`Length mismatch while decoding chunk ${t}`);this._checkCrc?v5(this,e+4,t):this.skip(4)}decodeIHDR(){const e=this._png;e.width=this.readUint32(),e.height=this.readUint32(),e.depth=jH(this.readUint8());const t=this.readUint8();this._colorType=t;let n;switch(t){case Ji.GREYSCALE:n=1;break;case Ji.TRUECOLOUR:n=3;break;case Ji.INDEXED_COLOUR:n=1;break;case Ji.GREYSCALE_ALPHA:n=2;break;case Ji.TRUECOLOUR_ALPHA:n=4;break;case Ji.UNKNOWN:default:throw new Error(`Unknown color type: ${t}`)}if(this._png.channels=n,this._compressionMethod=this.readUint8(),this._compressionMethod!==f1.DEFLATE)throw new Error(`Unsupported compression method: ${this._compressionMethod}`);this._filterMethod=this.readUint8(),this._interlaceMethod=this.readUint8()}decodeACTL(){this._numberOfFrames=this.readUint32(),this._numberOfPlays=this.readUint32(),this._isAnimated=!0}decodeFCTL(){const e={sequenceNumber:this.readUint32(),width:this.readUint32(),height:this.readUint32(),xOffset:this.readUint32(),yOffset:this.readUint32(),delayNumber:this.readUint16(),delayDenominator:this.readUint16(),disposeOp:this.readUint8(),blendOp:this.readUint8(),data:new Uint8Array(0)};this._frames.push(e)}decodePLTE(e){if(e%3!==0)throw new RangeError(`PLTE field length must be a multiple of 3. Got ${e}`);const t=e/3;this._hasPalette=!0;const n=[];this._palette=n;for(let a=0;athis._png.width*this._png.height)throw new Error(`tRNS chunk contains more alpha values than there are pixels (${e/2} vs ${this._png.width*this._png.height})`);this._hasTransparency=!0,this._transparency=new Uint16Array(e/2);for(let t=0;tthis._palette.length)throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${e} vs ${this._palette.length})`);let t=0;for(;t{const c=((s+t.yOffset)*this._png.width+t.xOffset+l)*this._png.channels,h=(s*t.width+l)*this._png.channels;return{index:c,frameIndex:h}};switch(t.blendOp){case g1.SOURCE:for(let s=0;s=200&&e.status<=299}function xg(A){try{A.dispatchEvent(new MouseEvent("click"))}catch{var e=document.createEvent("MouseEvents");e.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),A.dispatchEvent(e)}}var yc=Gt.saveAs||((typeof window>"u"?"undefined":PA(window))!=="object"||window!==Gt?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(A,e,t){var n=Gt.URL||Gt.webkitURL,a=document.createElement("a");e=e||A.name||"download",a.download=e,a.rel="noopener",typeof A=="string"?(a.href=A,a.origin!==location.origin?E5(a.href)?m1(A,e,t):xg(a,a.target="_blank"):xg(a)):(a.href=n.createObjectURL(A),setTimeout(function(){n.revokeObjectURL(a.href)},4e4),setTimeout(function(){xg(a)},0))}:"msSaveOrOpenBlob"in navigator?function(A,e,t){if(e=e||A.name||"download",typeof A=="string")if(E5(A))m1(A,e,t);else{var n=document.createElement("a");n.href=A,n.target="_blank",setTimeout(function(){xg(n)})}else navigator.msSaveOrOpenBlob((function(a,s){return s===void 0?s={autoBom:!1}:PA(s)!=="object"&&($A.warn("Deprecated: Expected third argument to be a object"),s={autoBom:!s}),s.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a})(A,t),e)}:function(A,e,t,n){if((n=n||open("","_blank"))&&(n.document.title=n.document.body.innerText="downloading..."),typeof A=="string")return m1(A,e,t);var a=A.type==="application/octet-stream",s=/constructor/i.test(Gt.HTMLElement)||Gt.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&s)&&(typeof FileReader>"u"?"undefined":PA(FileReader))==="object"){var c=new FileReader;c.onloadend=function(){var g=c.result;g=l?g:g.replace(/^data:[^;]*;/,"data:attachment/file;"),n?n.location.href=g:location=g,n=null},c.readAsDataURL(A)}else{var h=Gt.URL||Gt.webkitURL,f=h.createObjectURL(A);n?n.location=f:location.href=f,n=null,setTimeout(function(){h.revokeObjectURL(f)},4e4)}});function kS(A){var e;A=A||"",this.ok=!1,A.charAt(0)=="#"&&(A=A.substr(1,6)),A={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"}[A=(A=A.replace(/ /g,"")).toLowerCase()]||A;for(var t=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(c){return[parseInt(c[1]),parseInt(c[2]),parseInt(c[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(c){return[parseInt(c[1],16),parseInt(c[2],16),parseInt(c[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(c){return[parseInt(c[1]+c[1],16),parseInt(c[2]+c[2],16),parseInt(c[3]+c[3],16)]}}],n=0;n255?255:this.r,this.g=this.g<0||isNaN(this.g)?0:this.g>255?255:this.g,this.b=this.b<0||isNaN(this.b)?0:this.b>255?255:this.b,this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"},this.toHex=function(){var c=this.r.toString(16),h=this.g.toString(16),f=this.b.toString(16);return c.length==1&&(c="0"+c),h.length==1&&(h="0"+h),f.length==1&&(f="0"+f),"#"+c+h+f}}var ap=Gt.atob.bind(Gt),x5=Gt.btoa.bind(Gt);function w1(A,e){var t=A[0],n=A[1],a=A[2],s=A[3];t=Dr(t,n,a,s,e[0],7,-680876936),s=Dr(s,t,n,a,e[1],12,-389564586),a=Dr(a,s,t,n,e[2],17,606105819),n=Dr(n,a,s,t,e[3],22,-1044525330),t=Dr(t,n,a,s,e[4],7,-176418897),s=Dr(s,t,n,a,e[5],12,1200080426),a=Dr(a,s,t,n,e[6],17,-1473231341),n=Dr(n,a,s,t,e[7],22,-45705983),t=Dr(t,n,a,s,e[8],7,1770035416),s=Dr(s,t,n,a,e[9],12,-1958414417),a=Dr(a,s,t,n,e[10],17,-42063),n=Dr(n,a,s,t,e[11],22,-1990404162),t=Dr(t,n,a,s,e[12],7,1804603682),s=Dr(s,t,n,a,e[13],12,-40341101),a=Dr(a,s,t,n,e[14],17,-1502002290),t=Mr(t,n=Dr(n,a,s,t,e[15],22,1236535329),a,s,e[1],5,-165796510),s=Mr(s,t,n,a,e[6],9,-1069501632),a=Mr(a,s,t,n,e[11],14,643717713),n=Mr(n,a,s,t,e[0],20,-373897302),t=Mr(t,n,a,s,e[5],5,-701558691),s=Mr(s,t,n,a,e[10],9,38016083),a=Mr(a,s,t,n,e[15],14,-660478335),n=Mr(n,a,s,t,e[4],20,-405537848),t=Mr(t,n,a,s,e[9],5,568446438),s=Mr(s,t,n,a,e[14],9,-1019803690),a=Mr(a,s,t,n,e[3],14,-187363961),n=Mr(n,a,s,t,e[8],20,1163531501),t=Mr(t,n,a,s,e[13],5,-1444681467),s=Mr(s,t,n,a,e[2],9,-51403784),a=Mr(a,s,t,n,e[7],14,1735328473),t=Pr(t,n=Mr(n,a,s,t,e[12],20,-1926607734),a,s,e[5],4,-378558),s=Pr(s,t,n,a,e[8],11,-2022574463),a=Pr(a,s,t,n,e[11],16,1839030562),n=Pr(n,a,s,t,e[14],23,-35309556),t=Pr(t,n,a,s,e[1],4,-1530992060),s=Pr(s,t,n,a,e[4],11,1272893353),a=Pr(a,s,t,n,e[7],16,-155497632),n=Pr(n,a,s,t,e[10],23,-1094730640),t=Pr(t,n,a,s,e[13],4,681279174),s=Pr(s,t,n,a,e[0],11,-358537222),a=Pr(a,s,t,n,e[3],16,-722521979),n=Pr(n,a,s,t,e[6],23,76029189),t=Pr(t,n,a,s,e[9],4,-640364487),s=Pr(s,t,n,a,e[12],11,-421815835),a=Pr(a,s,t,n,e[15],16,530742520),t=jr(t,n=Pr(n,a,s,t,e[2],23,-995338651),a,s,e[0],6,-198630844),s=jr(s,t,n,a,e[7],10,1126891415),a=jr(a,s,t,n,e[14],15,-1416354905),n=jr(n,a,s,t,e[5],21,-57434055),t=jr(t,n,a,s,e[12],6,1700485571),s=jr(s,t,n,a,e[3],10,-1894986606),a=jr(a,s,t,n,e[10],15,-1051523),n=jr(n,a,s,t,e[1],21,-2054922799),t=jr(t,n,a,s,e[8],6,1873313359),s=jr(s,t,n,a,e[15],10,-30611744),a=jr(a,s,t,n,e[6],15,-1560198380),n=jr(n,a,s,t,e[13],21,1309151649),t=jr(t,n,a,s,e[4],6,-145523070),s=jr(s,t,n,a,e[11],10,-1120210379),a=jr(a,s,t,n,e[2],15,718787259),n=jr(n,a,s,t,e[9],21,-343485551),A[0]=Sl(t,A[0]),A[1]=Sl(n,A[1]),A[2]=Sl(a,A[2]),A[3]=Sl(s,A[3])}function g0(A,e,t,n,a,s){return e=Sl(Sl(e,A),Sl(n,s)),Sl(e<>>32-a,t)}function Dr(A,e,t,n,a,s,l){return g0(e&t|~e&n,A,e,a,s,l)}function Mr(A,e,t,n,a,s,l){return g0(e&n|t&~n,A,e,a,s,l)}function Pr(A,e,t,n,a,s,l){return g0(e^t^n,A,e,a,s,l)}function jr(A,e,t,n,a,s,l){return g0(t^(e|~n),A,e,a,s,l)}function HS(A){var e,t=A.length,n=[1732584193,-271733879,-1732584194,271733878];for(e=64;e<=A.length;e+=64)w1(n,GH(A.substring(e-64,e)));A=A.substring(e-64);var a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(e=0;e>2]|=A.charCodeAt(e)<<(e%4<<3);if(a[e>>2]|=128<<(e%4<<3),e>55)for(w1(n,a),e=0;e<16;e++)a[e]=0;return a[14]=8*t,w1(n,a),n}function GH(A){var e,t=[];for(e=0;e<64;e+=4)t[e>>2]=A.charCodeAt(e)+(A.charCodeAt(e+1)<<8)+(A.charCodeAt(e+2)<<16)+(A.charCodeAt(e+3)<<24);return t}var S5="0123456789abcdef".split("");function zH(A){for(var e="",t=0;t<4;t++)e+=S5[A>>8*t+4&15]+S5[A>>8*t&15];return e}function VH(A){return String.fromCharCode(255&A,(65280&A)>>8,(16711680&A)>>16,(4278190080&A)>>24)}function Cw(A){return HS(A).map(VH).join("")}var qH=(function(A){for(var e=0;e>16)+(e>>16)+(t>>16)<<16|65535&t}return A+e&4294967295}function bw(A,e){var t,n,a,s;if(A!==t){for(var l=(a=A,s=1+(256/A.length|0),new Array(s+1).join(a)),c=[],h=0;h<256;h++)c[h]=h;var f=0;for(h=0;h<256;h++){var g=c[h];f=(f+g+l.charCodeAt(h))%256,c[h]=c[f],c[f]=g}t=A,n=c}else c=n;var y=e.length,C=0,v=0,I="";for(h=0;h€/\f©þdSiz";var s=(e+this.padding).substr(0,32),l=(t+this.padding).substr(0,32);this.O=this.processOwnerPassword(s,l),this.P=-(1+(255^a)),this.encryptionKey=Cw(s+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(n)).substr(0,5),this.U=bw(this.encryptionKey,this.padding)}function Zu(A){if(/[^\u0000-\u00ff]/.test(A))throw new Error("Invalid PDF Name Object: "+A+", Only accept ASCII characters.");for(var e="",t=A.length,n=0;n126?"#"+("0"+a.toString(16)).slice(-2):A[n]}return e}function I5(A){if(PA(A)!=="object")throw new Error("Invalid Context passed to initialize PubSub (jsPDF-module)");var e={};this.subscribe=function(t,n,a){if(a=a||!1,typeof t!="string"||typeof n!="function"||typeof a!="boolean")throw new Error("Invalid arguments passed to PubSub.subscribe (jsPDF-module)");e.hasOwnProperty(t)||(e[t]={});var s=Math.random().toString(35);return e[t][s]=[n,!!a],s},this.unsubscribe=function(t){for(var n in e)if(e[n][t])return delete e[n][t],Object.keys(e[n]).length===0&&delete e[n],!0;return!1},this.publish=function(t){if(e.hasOwnProperty(t)){var n=Array.prototype.slice.call(arguments,1),a=[];for(var s in e[t]){var l=e[t][s];try{l[0].apply(A,n)}catch(c){Gt.console&&$A.error("jsPDF PubSub Error",c.message,c)}l[1]&&a.push(s)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return e}}function Dp(A){if(!(this instanceof Dp))return new Dp(A);var e="opacity,stroke-opacity".split(",");for(var t in A)A.hasOwnProperty(t)&&e.indexOf(t)>=0&&(this[t]=A[t]);this.id="",this.objectNumber=-1}function DS(A,e){this.gState=A,this.matrix=e,this.id="",this.objectNumber=-1}function Cc(A,e,t,n,a){if(!(this instanceof Cc))return new Cc(A,e,t,n,a);this.type=A==="axial"?2:3,this.coords=e,this.colors=t,DS.call(this,n,a)}function Ah(A,e,t,n,a){if(!(this instanceof Ah))return new Ah(A,e,t,n,a);this.boundingBox=A,this.xStep=e,this.yStep=t,this.stream="",this.cloneIndex=0,DS.call(this,n,a)}function Ft(A){var e,t=typeof arguments[0]=="string"?arguments[0]:"p",n=arguments[1],a=arguments[2],s=arguments[3],l=[],c=1,h=16,f="S",g=null;PA(A=A||{})==="object"&&(t=A.orientation,n=A.unit||n,a=A.format||a,s=A.compress||A.compressPdf||s,(g=A.encryption||null)!==null&&(g.userPassword=g.userPassword||"",g.ownerPassword=g.ownerPassword||"",g.userPermissions=g.userPermissions||[]),c=typeof A.userUnit=="number"?Math.abs(A.userUnit):1,A.precision!==void 0&&(e=A.precision),A.floatPrecision!==void 0&&(h=A.floatPrecision),f=A.defaultPathOperation||"S"),l=A.filters||(s===!0?["FlateEncode"]:l),n=n||"mm",t=(""+(t||"P")).toLowerCase();var y=A.putOnlyUsedFonts||!1,C={},v={internal:{},__private__:{}};v.__private__.PubSub=I5;var I="1.3",x=v.__private__.getPdfVersion=function(){return I};v.__private__.setPdfVersion=function(B){I=B};var _={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};v.__private__.getPageFormats=function(){return _};var T=v.__private__.getPageFormat=function(B){return _[B]};a=a||"a4";var k="compat",z="advanced",H=k;function re(){this.saveGraphicsState(),X(new mt(ct,0,0,-ct,0,Oa()*ct).toString()+" cm"),this.setFontSize(this.getFontSize()/ct),f="n",H=z}function le(){this.restoreGraphicsState(),f="S",H=k}var ce=v.__private__.combineFontStyleAndFontWeight=function(B,L){if(B=="bold"&&L=="normal"||B=="bold"&&L==400||B=="normal"&&L=="italic"||B=="bold"&&L=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return L&&(B=L==400||L==="normal"?B==="italic"?"italic":"normal":L!=700&&L!=="bold"||B!=="normal"?(L==700?"bold":L)+""+B:"bold"),B};v.advancedAPI=function(B){var L=H===k;return L&&re.call(this),typeof B!="function"||(B(this),L&&le.call(this)),this},v.compatAPI=function(B){var L=H===z;return L&&le.call(this),typeof B!="function"||(B(this),L&&re.call(this)),this},v.isAdvancedAPI=function(){return H===z};var $,Y=function(B){if(H!==z)throw new Error(B+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},de=v.roundToPrecision=v.__private__.roundToPrecision=function(B,L){var ie=e||L;if(isNaN(B)||isNaN(ie))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return B.toFixed(ie).replace(/0+$/,"")};$=v.hpf=v.__private__.hpf=typeof h=="number"?function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.hpf");return de(B,h)}:h==="smart"?function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.hpf");return de(B,B>-1&&B<1?16:5)}:function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.hpf");return de(B,16)};var R=v.f2=v.__private__.f2=function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.f2");return de(B,2)},V=v.__private__.f3=function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.f3");return de(B,3)},ne=v.scale=v.__private__.scale=function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.scale");return H===k?B*ct:H===z?B:void 0},Ae=function(B){return ne((function(L){return H===k?Oa()-L:H===z?L:void 0})(B))};v.__private__.setPrecision=v.setPrecision=function(B){typeof parseInt(B,10)=="number"&&(e=parseInt(B,10))};var Ce,N="00000000000000000000000000000000",G=v.__private__.getFileId=function(){return N},W=v.__private__.setFileId=function(B){return N=B!==void 0&&/^[a-fA-F0-9]{32}$/.test(B)?B.toUpperCase():N.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),g!==null&&(kn=new Wu(g.userPermissions,g.userPassword,g.ownerPassword,N)),N};v.setFileId=function(B){return W(B),this},v.getFileId=function(){return G()};var he=v.__private__.convertDateToPDFDate=function(B){var L=B.getTimezoneOffset(),ie=L<0?"+":"-",ge=Math.floor(Math.abs(L/60)),Ee=Math.abs(L%60),Pe=[ie,K(ge),"'",K(Ee),"'"].join("");return["D:",B.getFullYear(),K(B.getMonth()+1),K(B.getDate()),K(B.getHours()),K(B.getMinutes()),K(B.getSeconds()),Pe].join("")},Ne=v.__private__.convertPDFDateToDate=function(B){var L=parseInt(B.substr(2,4),10),ie=parseInt(B.substr(6,2),10)-1,ge=parseInt(B.substr(8,2),10),Ee=parseInt(B.substr(10,2),10),Pe=parseInt(B.substr(12,2),10),Je=parseInt(B.substr(14,2),10);return new Date(L,ie,ge,Ee,Pe,Je,0)},P=v.__private__.setCreationDate=function(B){var L;if(B===void 0&&(B=new Date),B instanceof Date)L=he(B);else{if(!/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/.test(B))throw new Error("Invalid argument passed to jsPDF.setCreationDate");L=B}return Ce=L},S=v.__private__.getCreationDate=function(B){var L=Ce;return B==="jsDate"&&(L=Ne(Ce)),L};v.setCreationDate=function(B){return P(B),this},v.getCreationDate=function(B){return S(B)};var Q,K=v.__private__.padd2=function(B){return("0"+parseInt(B)).slice(-2)},Z=v.__private__.padd2Hex=function(B){return("00"+(B=B.toString())).substr(B.length)},se=0,ue=[],be=[],oe=0,ve=[],He=[],Xe=!1,$e=be;v.__private__.setCustomOutputDestination=function(B){Xe=!0,$e=B};var nt=function(B){Xe||($e=B)};v.__private__.resetCustomOutputDestination=function(){Xe=!1,$e=be};var X=v.__private__.out=function(B){return B=B.toString(),oe+=B.length+1,$e.push(B),$e},We=v.__private__.write=function(B){return X(arguments.length===1?B.toString():Array.prototype.join.call(arguments," "))},Tt=v.__private__.getArrayBuffer=function(B){for(var L=B.length,ie=new ArrayBuffer(L),ge=new Uint8Array(ie);L--;)ge[L]=B.charCodeAt(L);return ie},Fe=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];v.__private__.getStandardFonts=function(){return Fe};var Se=A.fontSize||16;v.__private__.setFontSize=v.setFontSize=function(B){return Se=H===z?B/ct:B,this};var Ye,Ze=v.__private__.getFontSize=v.getFontSize=function(){return H===k?Se:Se*ct},At=A.R2L||!1;v.__private__.setR2L=v.setR2L=function(B){return At=B,this},v.__private__.getR2L=v.getR2L=function(){return At};var st,ht=v.__private__.setZoomMode=function(B){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(B))Ye=B;else if(isNaN(B)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(B)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+B+'" is not recognized.');Ye=B}else Ye=parseInt(B,10)};v.__private__.getZoomMode=function(){return Ye};var Ut,Be=v.__private__.setPageMode=function(B){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(B)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+B+'" is not recognized.');st=B};v.__private__.getPageMode=function(){return st};var Ve=v.__private__.setLayoutMode=function(B){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(B)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+B+'" is not recognized.');Ut=B};v.__private__.getLayoutMode=function(){return Ut},v.__private__.setDisplayMode=v.setDisplayMode=function(B,L,ie){return ht(B),Ve(L),Be(ie),this};var lt={title:"",subject:"",author:"",keywords:"",creator:""};v.__private__.getDocumentProperty=function(B){if(Object.keys(lt).indexOf(B)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return lt[B]},v.__private__.getDocumentProperties=function(){return lt},v.__private__.setDocumentProperties=v.setProperties=v.setDocumentProperties=function(B){for(var L in lt)lt.hasOwnProperty(L)&&B[L]&&(lt[L]=B[L]);return this},v.__private__.setDocumentProperty=function(B,L){if(Object.keys(lt).indexOf(B)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return lt[B]=L};var it,ct,rt,rA,zt,St={},_t={},Vt=[],bt={},fA={},It={},Nt={},Zt=null,pe=0,Le=[],at=new I5(v),jt=A.hotfixes||[],$t={},xA={},eA=[],mt=function B(L,ie,ge,Ee,Pe,Je){if(!(this instanceof B))return new B(L,ie,ge,Ee,Pe,Je);isNaN(L)&&(L=1),isNaN(ie)&&(ie=0),isNaN(ge)&&(ge=0),isNaN(Ee)&&(Ee=1),isNaN(Pe)&&(Pe=0),isNaN(Je)&&(Je=0),this._matrix=[L,ie,ge,Ee,Pe,Je]};Object.defineProperty(mt.prototype,"sx",{get:function(){return this._matrix[0]},set:function(B){this._matrix[0]=B}}),Object.defineProperty(mt.prototype,"shy",{get:function(){return this._matrix[1]},set:function(B){this._matrix[1]=B}}),Object.defineProperty(mt.prototype,"shx",{get:function(){return this._matrix[2]},set:function(B){this._matrix[2]=B}}),Object.defineProperty(mt.prototype,"sy",{get:function(){return this._matrix[3]},set:function(B){this._matrix[3]=B}}),Object.defineProperty(mt.prototype,"tx",{get:function(){return this._matrix[4]},set:function(B){this._matrix[4]=B}}),Object.defineProperty(mt.prototype,"ty",{get:function(){return this._matrix[5]},set:function(B){this._matrix[5]=B}}),Object.defineProperty(mt.prototype,"a",{get:function(){return this._matrix[0]},set:function(B){this._matrix[0]=B}}),Object.defineProperty(mt.prototype,"b",{get:function(){return this._matrix[1]},set:function(B){this._matrix[1]=B}}),Object.defineProperty(mt.prototype,"c",{get:function(){return this._matrix[2]},set:function(B){this._matrix[2]=B}}),Object.defineProperty(mt.prototype,"d",{get:function(){return this._matrix[3]},set:function(B){this._matrix[3]=B}}),Object.defineProperty(mt.prototype,"e",{get:function(){return this._matrix[4]},set:function(B){this._matrix[4]=B}}),Object.defineProperty(mt.prototype,"f",{get:function(){return this._matrix[5]},set:function(B){this._matrix[5]=B}}),Object.defineProperty(mt.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(mt.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(mt.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(mt.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),mt.prototype.join=function(B){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map($).join(B)},mt.prototype.multiply=function(B){var L=B.sx*this.sx+B.shy*this.shx,ie=B.sx*this.shy+B.shy*this.sy,ge=B.shx*this.sx+B.sy*this.shx,Ee=B.shx*this.shy+B.sy*this.sy,Pe=B.tx*this.sx+B.ty*this.shx+this.tx,Je=B.tx*this.shy+B.ty*this.sy+this.ty;return new mt(L,ie,ge,Ee,Pe,Je)},mt.prototype.decompose=function(){var B=this.sx,L=this.shy,ie=this.shx,ge=this.sy,Ee=this.tx,Pe=this.ty,Je=Math.sqrt(B*B+L*L),vt=(B/=Je)*ie+(L/=Je)*ge;ie-=B*vt,ge-=L*vt;var Et=Math.sqrt(ie*ie+ge*ge);return vt/=Et,B*(ge/=Et){const A=new Uint8Array(4),e=new Uint32Array(A.buffer);return!((e[0]=1)&A[0])})(),r1={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};class mv{buffer;byteLength;byteOffset;length;offset;lastWrittenByte;littleEndian;_data;_mark;_marks;constructor(e=t8,t={}){let n=!1;typeof e=="number"?e=new ArrayBuffer(e):(n=!0,this.lastWrittenByte=e.byteLength);const a=t.offset?t.offset>>>0:0,s=e.byteLength-a;let l=a;(ArrayBuffer.isView(e)||e instanceof mv)&&(e.byteLength!==e.buffer.byteLength&&(l=e.byteOffset+a),e=e.buffer),n?this.lastWrittenByte=s:this.lastWrittenByte=0,this.buffer=e,this.length=s,this.byteLength=s,this.byteOffset=l,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer,l,s),this._mark=0,this._marks=[]}available(e=1){return this.offset+e<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(e=1){return this.offset+=e,this}back(e=1){return this.offset-=e,this}seek(e){return this.offset=e,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const e=this._marks.pop();if(e===void 0)throw new Error("Mark stack empty");return this.seek(e),this}rewind(){return this.offset=0,this}ensureAvailable(e=1){if(!this.available(e)){const n=(this.offset+e)*2,a=new Uint8Array(n);a.set(new Uint8Array(this.buffer)),this.buffer=a.buffer,this.length=n,this.byteLength=n,this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(e=1){return this.readArray(e,"uint8")}readArray(e,t){const n=r1[t].BYTES_PER_ELEMENT*e,a=this.byteOffset+this.offset,s=this.buffer.slice(a,a+n);if(this.littleEndian===A8&&t!=="uint8"&&t!=="int8"){const c=new Uint8Array(this.buffer.slice(a,a+n));c.reverse();const h=new r1[t](c.buffer);return this.offset+=n,h.reverse(),h}const l=new r1[t](s);return this.offset+=n,l}readInt16(){const e=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}readUint16(){const e=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,e}readInt32(){const e=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}readUint32(){const e=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}readFloat32(){const e=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}readFloat64(){const e=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}readBigInt64(){const e=this._data.getBigInt64(this.offset,this.littleEndian);return this.offset+=8,e}readBigUint64(){const e=this._data.getBigUint64(this.offset,this.littleEndian);return this.offset+=8,e}readChar(){return String.fromCharCode(this.readInt8())}readChars(e=1){let t="";for(let n=0;nthis.lastWrittenByte&&(this.lastWrittenByte=this.offset)}}function Uh(A){let e=A.length;for(;--e>=0;)A[e]=0}const n8=3,r8=258,hS=29,i8=256,a8=i8+1+hS,fS=30,s8=512,o8=new Array((a8+2)*2);Uh(o8);const l8=new Array(fS*2);Uh(l8);const c8=new Array(s8);Uh(c8);const u8=new Array(r8-n8+1);Uh(u8);const h8=new Array(hS);Uh(h8);const f8=new Array(fS);Uh(f8);const d8=(A,e,t,n)=>{let a=A&65535|0,s=A>>>16&65535|0,l=0;for(;t!==0;){l=t>2e3?2e3:t,t-=l;do a=a+e[n++]|0,s=s+a|0;while(--l);a%=65521,s%=65521}return a|s<<16|0};var vw=d8;const g8=()=>{let A,e=[];for(var t=0;t<256;t++){A=t;for(var n=0;n<8;n++)A=A&1?3988292384^A>>>1:A>>>1;e[t]=A}return e},p8=new Uint32Array(g8()),m8=(A,e,t,n)=>{const a=p8,s=n+t;A^=-1;for(let l=n;l>>8^a[(A^e[l])&255];return A^-1};var Ls=m8,yw={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},dS={Z_NO_FLUSH:0,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFLATED:8};const w8=(A,e)=>Object.prototype.hasOwnProperty.call(A,e);var v8=function(A){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(const n in t)w8(t,n)&&(A[n]=t[n])}}return A},y8=A=>{let e=0;for(let n=0,a=A.length;n=252?6:A>=248?5:A>=240?4:A>=224?3:A>=192?2:1;rd[254]=rd[254]=1;var B8=A=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(A);let e,t,n,a,s,l=A.length,c=0;for(a=0;a>>6,e[s++]=128|t&63):t<65536?(e[s++]=224|t>>>12,e[s++]=128|t>>>6&63,e[s++]=128|t&63):(e[s++]=240|t>>>18,e[s++]=128|t>>>12&63,e[s++]=128|t>>>6&63,e[s++]=128|t&63);return e};const C8=(A,e)=>{if(e<65534&&A.subarray&&pS)return String.fromCharCode.apply(null,A.length===e?A:A.subarray(0,e));let t="";for(let n=0;n{const t=e||A.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(A.subarray(0,e));let n,a;const s=new Array(t*2);for(a=0,n=0;n4){s[a++]=65533,n+=c-1;continue}for(l&=c===2?31:c===3?15:7;c>1&&n1){s[a++]=65533;continue}l<65536?s[a++]=l:(l-=65536,s[a++]=55296|l>>10&1023,s[a++]=56320|l&1023)}return C8(s,a)},E8=(A,e)=>{e=e||A.length,e>A.length&&(e=A.length);let t=e-1;for(;t>=0&&(A[t]&192)===128;)t--;return t<0||t===0?e:t+rd[A[t]]>e?t:e},Bw={string2buf:B8,buf2string:b8,utf8border:E8};function x8(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var S8=x8;const yg=16209,U8=16191;var I8=function(e,t){let n,a,s,l,c,h,f,g,y,C,v,I,x,_,T,k,z,H,re,le,ce,$,Y,de;const R=e.state;n=e.next_in,Y=e.input,a=n+(e.avail_in-5),s=e.next_out,de=e.output,l=s-(t-e.avail_out),c=s+(e.avail_out-257),h=R.dmax,f=R.wsize,g=R.whave,y=R.wnext,C=R.window,v=R.hold,I=R.bits,x=R.lencode,_=R.distcode,T=(1<>>24,v>>>=H,I-=H,H=z>>>16&255,H===0)de[s++]=z&65535;else if(H&16){re=z&65535,H&=15,H&&(I>>=H,I-=H),I<15&&(v+=Y[n++]<>>24,v>>>=H,I-=H,H=z>>>16&255,H&16){if(le=z&65535,H&=15,Ih){e.msg="invalid distance too far back",R.mode=yg;break e}if(v>>>=H,I-=H,H=s-l,le>H){if(H=le-H,H>g&&R.sane){e.msg="invalid distance too far back",R.mode=yg;break e}if(ce=0,$=C,y===0){if(ce+=f-H,H2;)de[s++]=$[ce++],de[s++]=$[ce++],de[s++]=$[ce++],re-=3;re&&(de[s++]=$[ce++],re>1&&(de[s++]=$[ce++]))}else{ce=s-le;do de[s++]=de[ce++],de[s++]=de[ce++],de[s++]=de[ce++],re-=3;while(re>2);re&&(de[s++]=de[ce++],re>1&&(de[s++]=de[ce++]))}}else if((H&64)===0){z=_[(z&65535)+(v&(1<>3,n-=re,I-=re<<3,v&=(1<{const h=c.bits;let f=0,g=0,y=0,C=0,v=0,I=0,x=0,_=0,T=0,k=0,z,H,re,le,ce,$=null,Y;const de=new Uint16Array(Pu+1),R=new Uint16Array(Pu+1);let V=null,ne,Ae,Ce;for(f=0;f<=Pu;f++)de[f]=0;for(g=0;g=1&&de[C]===0;C--);if(v>C&&(v=C),C===0)return a[s++]=1<<24|64<<16|0,a[s++]=1<<24|64<<16|0,c.bits=1,0;for(y=1;y0&&(A===Kb||C!==1))return-1;for(R[1]=0,f=1;fPb||A===Gb&&T>jb)return 1;for(;;){ne=f-x,l[g]+1=Y?(Ae=V[l[g]-Y],Ce=$[l[g]-Y]):(Ae=96,Ce=0),z=1<>x)+H]=ne<<24|Ae<<16|Ce|0;while(H!==0);for(z=1<>=1;if(z!==0?(k&=z-1,k+=z):k=0,g++,--de[f]===0){if(f===C)break;f=e[t+l[g]]}if(f>v&&(k&le)!==re){for(x===0&&(x=v),ce+=y,I=f-x,_=1<Pb||A===Gb&&T>jb)return 1;re=k&le,a[re]=v<<24|I<<16|ce-s|0}}return k!==0&&(a[ce+k]=f-x<<24|64<<16|0),c.bits=v,0};var Mf=Q8;const L8=0,mS=1,wS=2,{Z_FINISH:zb,Z_BLOCK:O8,Z_TREES:Bg,Z_OK:Gc,Z_STREAM_END:R8,Z_NEED_DICT:k8,Z_STREAM_ERROR:Sa,Z_DATA_ERROR:vS,Z_MEM_ERROR:yS,Z_BUF_ERROR:H8,Z_DEFLATED:Vb}=dS,d0=16180,qb=16181,Yb=16182,Xb=16183,Jb=16184,Wb=16185,Zb=16186,$b=16187,e5=16188,t5=16189,Hp=16190,Co=16191,a1=16192,A5=16193,s1=16194,n5=16195,r5=16196,i5=16197,a5=16198,Cg=16199,bg=16200,s5=16201,o5=16202,l5=16203,c5=16204,u5=16205,o1=16206,h5=16207,f5=16208,mn=16209,BS=16210,CS=16211,D8=852,M8=592,P8=15,j8=P8,d5=A=>(A>>>24&255)+(A>>>8&65280)+((A&65280)<<8)+((A&255)<<24);function K8(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Vc=A=>{if(!A)return 1;const e=A.state;return!e||e.strm!==A||e.modeCS?1:0},bS=A=>{if(Vc(A))return Sa;const e=A.state;return A.total_in=A.total_out=e.total=0,A.msg="",e.wrap&&(A.adler=e.wrap&1),e.mode=d0,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(D8),e.distcode=e.distdyn=new Int32Array(M8),e.sane=1,e.back=-1,Gc},ES=A=>{if(Vc(A))return Sa;const e=A.state;return e.wsize=0,e.whave=0,e.wnext=0,bS(A)},xS=(A,e)=>{let t;if(Vc(A))return Sa;const n=A.state;return e<0?(t=0,e=-e):(t=(e>>4)+5,e<48&&(e&=15)),e&&(e<8||e>15)?Sa:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,ES(A))},SS=(A,e)=>{if(!A)return Sa;const t=new K8;A.state=t,t.strm=A,t.window=null,t.mode=d0;const n=xS(A,e);return n!==Gc&&(A.state=null),n},G8=A=>SS(A,j8);let g5=!0,l1,c1;const z8=A=>{if(g5){l1=new Int32Array(512),c1=new Int32Array(32);let e=0;for(;e<144;)A.lens[e++]=8;for(;e<256;)A.lens[e++]=9;for(;e<280;)A.lens[e++]=7;for(;e<288;)A.lens[e++]=8;for(Mf(mS,A.lens,0,288,l1,0,A.work,{bits:9}),e=0;e<32;)A.lens[e++]=5;Mf(wS,A.lens,0,32,c1,0,A.work,{bits:5}),g5=!1}A.lencode=l1,A.lenbits=9,A.distcode=c1,A.distbits=5},US=(A,e,t,n)=>{let a;const s=A.state;return s.window===null&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):(a=s.wsize-s.wnext,a>n&&(a=n),s.window.set(e.subarray(t-n,t-n+a),s.wnext),n-=a,n?(s.window.set(e.subarray(t-n,t),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=a,s.wnext===s.wsize&&(s.wnext=0),s.whave{let t,n,a,s,l,c,h,f,g,y,C,v,I,x,_=0,T,k,z,H,re,le,ce,$;const Y=new Uint8Array(4);let de,R;const V=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Vc(A)||!A.output||!A.input&&A.avail_in!==0)return Sa;t=A.state,t.mode===Co&&(t.mode=a1),l=A.next_out,a=A.output,h=A.avail_out,s=A.next_in,n=A.input,c=A.avail_in,f=t.hold,g=t.bits,y=c,C=h,$=Gc;e:for(;;)switch(t.mode){case d0:if(t.wrap===0){t.mode=a1;break}for(;g<16;){if(c===0)break e;c--,f+=n[s++]<>>8&255,t.check=Ls(t.check,Y,2,0),f=0,g=0,t.mode=qb;break}if(t.head&&(t.head.done=!1),!(t.wrap&1)||(((f&255)<<8)+(f>>8))%31){A.msg="incorrect header check",t.mode=mn;break}if((f&15)!==Vb){A.msg="unknown compression method",t.mode=mn;break}if(f>>>=4,g-=4,ce=(f&15)+8,t.wbits===0&&(t.wbits=ce),ce>15||ce>t.wbits){A.msg="invalid window size",t.mode=mn;break}t.dmax=1<>8&1),t.flags&512&&t.wrap&4&&(Y[0]=f&255,Y[1]=f>>>8&255,t.check=Ls(t.check,Y,2,0)),f=0,g=0,t.mode=Yb;case Yb:for(;g<32;){if(c===0)break e;c--,f+=n[s++]<>>8&255,Y[2]=f>>>16&255,Y[3]=f>>>24&255,t.check=Ls(t.check,Y,4,0)),f=0,g=0,t.mode=Xb;case Xb:for(;g<16;){if(c===0)break e;c--,f+=n[s++]<>8),t.flags&512&&t.wrap&4&&(Y[0]=f&255,Y[1]=f>>>8&255,t.check=Ls(t.check,Y,2,0)),f=0,g=0,t.mode=Jb;case Jb:if(t.flags&1024){for(;g<16;){if(c===0)break e;c--,f+=n[s++]<>>8&255,t.check=Ls(t.check,Y,2,0)),f=0,g=0}else t.head&&(t.head.extra=null);t.mode=Wb;case Wb:if(t.flags&1024&&(v=t.length,v>c&&(v=c),v&&(t.head&&(ce=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(s,s+v),ce)),t.flags&512&&t.wrap&4&&(t.check=Ls(t.check,n,v,s)),c-=v,s+=v,t.length-=v),t.length))break e;t.length=0,t.mode=Zb;case Zb:if(t.flags&2048){if(c===0)break e;v=0;do ce=n[s+v++],t.head&&ce&&t.length<65536&&(t.head.name+=String.fromCharCode(ce));while(ce&&v>9&1,t.head.done=!0),A.adler=t.check=0,t.mode=Co;break;case t5:for(;g<32;){if(c===0)break e;c--,f+=n[s++]<>>=g&7,g-=g&7,t.mode=o1;break}for(;g<3;){if(c===0)break e;c--,f+=n[s++]<>>=1,g-=1,f&3){case 0:t.mode=A5;break;case 1:if(z8(t),t.mode=Cg,e===Bg){f>>>=2,g-=2;break e}break;case 2:t.mode=r5;break;case 3:A.msg="invalid block type",t.mode=mn}f>>>=2,g-=2;break;case A5:for(f>>>=g&7,g-=g&7;g<32;){if(c===0)break e;c--,f+=n[s++]<>>16^65535)){A.msg="invalid stored block lengths",t.mode=mn;break}if(t.length=f&65535,f=0,g=0,t.mode=s1,e===Bg)break e;case s1:t.mode=n5;case n5:if(v=t.length,v){if(v>c&&(v=c),v>h&&(v=h),v===0)break e;a.set(n.subarray(s,s+v),l),c-=v,s+=v,h-=v,l+=v,t.length-=v;break}t.mode=Co;break;case r5:for(;g<14;){if(c===0)break e;c--,f+=n[s++]<>>=5,g-=5,t.ndist=(f&31)+1,f>>>=5,g-=5,t.ncode=(f&15)+4,f>>>=4,g-=4,t.nlen>286||t.ndist>30){A.msg="too many length or distance symbols",t.mode=mn;break}t.have=0,t.mode=i5;case i5:for(;t.have>>=3,g-=3}for(;t.have<19;)t.lens[V[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,de={bits:t.lenbits},$=Mf(L8,t.lens,0,19,t.lencode,0,t.work,de),t.lenbits=de.bits,$){A.msg="invalid code lengths set",t.mode=mn;break}t.have=0,t.mode=a5;case a5:for(;t.have>>24,k=_>>>16&255,z=_&65535,!(T<=g);){if(c===0)break e;c--,f+=n[s++]<>>=T,g-=T,t.lens[t.have++]=z;else{if(z===16){for(R=T+2;g>>=T,g-=T,t.have===0){A.msg="invalid bit length repeat",t.mode=mn;break}ce=t.lens[t.have-1],v=3+(f&3),f>>>=2,g-=2}else if(z===17){for(R=T+3;g>>=T,g-=T,ce=0,v=3+(f&7),f>>>=3,g-=3}else{for(R=T+7;g>>=T,g-=T,ce=0,v=11+(f&127),f>>>=7,g-=7}if(t.have+v>t.nlen+t.ndist){A.msg="invalid bit length repeat",t.mode=mn;break}for(;v--;)t.lens[t.have++]=ce}}if(t.mode===mn)break;if(t.lens[256]===0){A.msg="invalid code -- missing end-of-block",t.mode=mn;break}if(t.lenbits=9,de={bits:t.lenbits},$=Mf(mS,t.lens,0,t.nlen,t.lencode,0,t.work,de),t.lenbits=de.bits,$){A.msg="invalid literal/lengths set",t.mode=mn;break}if(t.distbits=6,t.distcode=t.distdyn,de={bits:t.distbits},$=Mf(wS,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,de),t.distbits=de.bits,$){A.msg="invalid distances set",t.mode=mn;break}if(t.mode=Cg,e===Bg)break e;case Cg:t.mode=bg;case bg:if(c>=6&&h>=258){A.next_out=l,A.avail_out=h,A.next_in=s,A.avail_in=c,t.hold=f,t.bits=g,I8(A,C),l=A.next_out,a=A.output,h=A.avail_out,s=A.next_in,n=A.input,c=A.avail_in,f=t.hold,g=t.bits,t.mode===Co&&(t.back=-1);break}for(t.back=0;_=t.lencode[f&(1<>>24,k=_>>>16&255,z=_&65535,!(T<=g);){if(c===0)break e;c--,f+=n[s++]<>H)],T=_>>>24,k=_>>>16&255,z=_&65535,!(H+T<=g);){if(c===0)break e;c--,f+=n[s++]<>>=H,g-=H,t.back+=H}if(f>>>=T,g-=T,t.back+=T,t.length=z,k===0){t.mode=u5;break}if(k&32){t.back=-1,t.mode=Co;break}if(k&64){A.msg="invalid literal/length code",t.mode=mn;break}t.extra=k&15,t.mode=s5;case s5:if(t.extra){for(R=t.extra;g>>=t.extra,g-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=o5;case o5:for(;_=t.distcode[f&(1<>>24,k=_>>>16&255,z=_&65535,!(T<=g);){if(c===0)break e;c--,f+=n[s++]<>H)],T=_>>>24,k=_>>>16&255,z=_&65535,!(H+T<=g);){if(c===0)break e;c--,f+=n[s++]<>>=H,g-=H,t.back+=H}if(f>>>=T,g-=T,t.back+=T,k&64){A.msg="invalid distance code",t.mode=mn;break}t.offset=z,t.extra=k&15,t.mode=l5;case l5:if(t.extra){for(R=t.extra;g>>=t.extra,g-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){A.msg="invalid distance too far back",t.mode=mn;break}t.mode=c5;case c5:if(h===0)break e;if(v=C-h,t.offset>v){if(v=t.offset-v,v>t.whave&&t.sane){A.msg="invalid distance too far back",t.mode=mn;break}v>t.wnext?(v-=t.wnext,I=t.wsize-v):I=t.wnext-v,v>t.length&&(v=t.length),x=t.window}else x=a,I=l-t.offset,v=t.length;v>h&&(v=h),h-=v,t.length-=v;do a[l++]=x[I++];while(--v);t.length===0&&(t.mode=bg);break;case u5:if(h===0)break e;a[l++]=t.length,h--,t.mode=bg;break;case o1:if(t.wrap){for(;g<32;){if(c===0)break e;c--,f|=n[s++]<{if(Vc(A))return Sa;let e=A.state;return e.window&&(e.window=null),A.state=null,Gc},Y8=(A,e)=>{if(Vc(A))return Sa;const t=A.state;return(t.wrap&2)===0?Sa:(t.head=e,e.done=!1,Gc)},X8=(A,e)=>{const t=e.length;let n,a,s;return Vc(A)||(n=A.state,n.wrap!==0&&n.mode!==Hp)?Sa:n.mode===Hp&&(a=1,a=vw(a,e,t,0),a!==n.check)?vS:(s=US(A,e,t,t),s?(n.mode=BS,yS):(n.havedict=1,Gc))};var J8=ES,W8=xS,Z8=bS,$8=G8,eH=SS,tH=V8,AH=q8,nH=Y8,rH=X8,iH="pako inflate (from Nodeca project)",xo={inflateReset:J8,inflateReset2:W8,inflateResetKeep:Z8,inflateInit:$8,inflateInit2:eH,inflate:tH,inflateEnd:AH,inflateGetHeader:nH,inflateSetDictionary:rH,inflateInfo:iH};function aH(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var sH=aH;const IS=Object.prototype.toString,{Z_NO_FLUSH:oH,Z_FINISH:lH,Z_OK:id,Z_STREAM_END:u1,Z_NEED_DICT:h1,Z_STREAM_ERROR:cH,Z_DATA_ERROR:p5,Z_MEM_ERROR:uH}=dS;function md(A){this.options=gS.assign({chunkSize:1024*64,windowBits:15,to:""},A||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(A&&A.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new S8,this.strm.avail_out=0;let t=xo.inflateInit2(this.strm,e.windowBits);if(t!==id)throw new Error(yw[t]);if(this.header=new sH,xo.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Bw.string2buf(e.dictionary):IS.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=xo.inflateSetDictionary(this.strm,e.dictionary),t!==id)))throw new Error(yw[t])}md.prototype.push=function(A,e){const t=this.strm,n=this.options.chunkSize,a=this.options.dictionary;let s,l,c;if(this.ended)return!1;for(e===~~e?l=e:l=e===!0?lH:oH,IS.call(A)==="[object ArrayBuffer]"?t.input=new Uint8Array(A):t.input=A,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),s=xo.inflate(t,l),s===h1&&a&&(s=xo.inflateSetDictionary(t,a),s===id?s=xo.inflate(t,l):s===p5&&(s=h1));t.avail_in>0&&s===u1&&t.state.wrap>0&&A[t.next_in]!==0;)xo.inflateReset(t),s=xo.inflate(t,l);switch(s){case cH:case p5:case h1:case uH:return this.onEnd(s),this.ended=!0,!1}if(c=t.avail_out,t.next_out&&(t.avail_out===0||s===u1))if(this.options.to==="string"){let h=Bw.utf8border(t.output,t.next_out),f=t.next_out-h,g=Bw.buf2string(t.output,h);t.next_out=f,t.avail_out=n-f,f&&t.output.set(t.output.subarray(h,h+f),0),this.onData(g)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(!(s===id&&c===0)){if(s===u1)return s=xo.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(t.avail_in===0)break}}return!0};md.prototype.onData=function(A){this.chunks.push(A)};md.prototype.onEnd=function(A){A===id&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=gS.flattenChunks(this.chunks)),this.chunks=[],this.err=A,this.msg=this.strm.msg};function hH(A,e){const t=new md(e);if(t.push(A),t.err)throw t.msg||yw[t.err];return t.result}var fH=md,dH=hH,gH={Inflate:fH,inflate:dH};const{Inflate:pH,inflate:mH}=gH;var m5=pH,wH=mH;const FS=[];for(let A=0;A<256;A++){let e=A;for(let t=0;t<8;t++)e&1?e=3988292384^e>>>1:e=e>>>1;FS[A]=e}const w5=4294967295;function vH(A,e,t){let n=A;for(let a=0;a>>8;return n}function yH(A,e){return(vH(w5,A,e)^w5)>>>0}function v5(A,e,t){const n=A.readUint32(),a=yH(new Uint8Array(A.buffer,A.byteOffset+A.offset-e-4,e),e);if(a!==n)throw new Error(`CRC mismatch for chunk ${t}. Expected ${n}, found ${a}`)}function TS(A,e,t){for(let n=0;n>1)&255}else{for(;s>1)&255;for(;s>1)&255}}function LS(A,e,t,n,a){let s=0;if(t.length===0){for(;s=t||le>=n))for(let ce=0;ce>8&255}const IH=new Uint16Array([255]),FH=new Uint8Array(IH.buffer),TH=FH[0]===255,_H=new Uint8Array(0);function y5(A){const{data:e,width:t,height:n,channels:a,depth:s}=A,l=Math.ceil(s/8)*a,c=Math.ceil(s/8*a*t),h=new Uint8Array(n*c);let f=_H,g=0,y,C;for(let v=0;v>8&255}const ip=Uint8Array.of(137,80,78,71,13,10,26,10);function B5(A){if(!QH(A.readBytes(ip.length)))throw new Error("wrong PNG signature")}function QH(A){if(A.length79)throw new Error("keyword length must be between 1 and 79")}const kH=/^[\u0000-\u00FF]*$/;function HH(A){if(!kH.test(A))throw new Error("invalid latin1 text")}function DH(A,e,t){const n=RS(e);A[n]=MH(e,t-n.length-1)}function RS(A){for(A.mark();A.readByte()!==OH;);const e=A.offset;A.reset();const t=OS.decode(A.readBytes(e-A.offset-1));return A.skip(1),RH(t),t}function MH(A,e){return OS.decode(A.readBytes(e))}const Ji={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},f1={UNKNOWN:-1,DEFLATE:0},C5={UNKNOWN:-1,ADAPTIVE:0},d1={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},Eg={NONE:0,BACKGROUND:1,PREVIOUS:2},g1={SOURCE:0,OVER:1};class PH extends mv{_checkCrc;_inflator;_png;_apng;_end;_hasPalette;_palette;_hasTransparency;_transparency;_compressionMethod;_filterMethod;_interlaceMethod;_colorType;_isAnimated;_numberOfFrames;_numberOfPlays;_frames;_writingDataChunks;constructor(e,t={}){super(e);const{checkCrc:n=!1}=t;this._checkCrc=n,this._inflator=new m5,this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}},this._apng={width:-1,height:-1,channels:-1,depth:1,numberOfFrames:1,numberOfPlays:0,text:{},frames:[]},this._end=!1,this._hasPalette=!1,this._palette=[],this._hasTransparency=!1,this._transparency=new Uint16Array(0),this._compressionMethod=f1.UNKNOWN,this._filterMethod=C5.UNKNOWN,this._interlaceMethod=d1.UNKNOWN,this._colorType=Ji.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(B5(this);!this._end;){const e=this.readUint32(),t=this.readChars(4);this.decodeChunk(e,t)}return this.decodeImage(),this._png}decodeApng(){for(B5(this);!this._end;){const e=this.readUint32(),t=this.readChars(4);this.decodeApngChunk(e,t)}return this.decodeApngImage(),this._apng}decodeChunk(e,t){const n=this.offset;switch(t){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(e);break;case"IDAT":this.decodeIDAT(e);break;case"IEND":this._end=!0;break;case"tRNS":this.decodetRNS(e);break;case"iCCP":this.decodeiCCP(e);break;case LH:DH(this._png.text,this,e);break;case"pHYs":this.decodepHYs();break;default:this.skip(e);break}if(this.offset-n!==e)throw new Error(`Length mismatch while decoding chunk ${t}`);this._checkCrc?v5(this,e+4,t):this.skip(4)}decodeApngChunk(e,t){const n=this.offset;switch(t!=="fdAT"&&t!=="IDAT"&&this._writingDataChunks&&this.pushDataToFrame(),t){case"acTL":this.decodeACTL();break;case"fcTL":this.decodeFCTL();break;case"fdAT":this.decodeFDAT(e);break;default:this.decodeChunk(e,t),this.offset=n+e;break}if(this.offset-n!==e)throw new Error(`Length mismatch while decoding chunk ${t}`);this._checkCrc?v5(this,e+4,t):this.skip(4)}decodeIHDR(){const e=this._png;e.width=this.readUint32(),e.height=this.readUint32(),e.depth=jH(this.readUint8());const t=this.readUint8();this._colorType=t;let n;switch(t){case Ji.GREYSCALE:n=1;break;case Ji.TRUECOLOUR:n=3;break;case Ji.INDEXED_COLOUR:n=1;break;case Ji.GREYSCALE_ALPHA:n=2;break;case Ji.TRUECOLOUR_ALPHA:n=4;break;case Ji.UNKNOWN:default:throw new Error(`Unknown color type: ${t}`)}if(this._png.channels=n,this._compressionMethod=this.readUint8(),this._compressionMethod!==f1.DEFLATE)throw new Error(`Unsupported compression method: ${this._compressionMethod}`);this._filterMethod=this.readUint8(),this._interlaceMethod=this.readUint8()}decodeACTL(){this._numberOfFrames=this.readUint32(),this._numberOfPlays=this.readUint32(),this._isAnimated=!0}decodeFCTL(){const e={sequenceNumber:this.readUint32(),width:this.readUint32(),height:this.readUint32(),xOffset:this.readUint32(),yOffset:this.readUint32(),delayNumber:this.readUint16(),delayDenominator:this.readUint16(),disposeOp:this.readUint8(),blendOp:this.readUint8(),data:new Uint8Array(0)};this._frames.push(e)}decodePLTE(e){if(e%3!==0)throw new RangeError(`PLTE field length must be a multiple of 3. Got ${e}`);const t=e/3;this._hasPalette=!0;const n=[];this._palette=n;for(let a=0;athis._png.width*this._png.height)throw new Error(`tRNS chunk contains more alpha values than there are pixels (${e/2} vs ${this._png.width*this._png.height})`);this._hasTransparency=!0,this._transparency=new Uint16Array(e/2);for(let t=0;tthis._palette.length)throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${e} vs ${this._palette.length})`);let t=0;for(;t{const c=((s+t.yOffset)*this._png.width+t.xOffset+l)*this._png.channels,h=(s*t.width+l)*this._png.channels;return{index:c,frameIndex:h}};switch(t.blendOp){case g1.SOURCE:for(let s=0;s=200&&e.status<=299}function xg(A){try{A.dispatchEvent(new MouseEvent("click"))}catch{var e=document.createEvent("MouseEvents");e.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),A.dispatchEvent(e)}}var Bc=Gt.saveAs||((typeof window>"u"?"undefined":PA(window))!=="object"||window!==Gt?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(A,e,t){var n=Gt.URL||Gt.webkitURL,a=document.createElement("a");e=e||A.name||"download",a.download=e,a.rel="noopener",typeof A=="string"?(a.href=A,a.origin!==location.origin?E5(a.href)?m1(A,e,t):xg(a,a.target="_blank"):xg(a)):(a.href=n.createObjectURL(A),setTimeout(function(){n.revokeObjectURL(a.href)},4e4),setTimeout(function(){xg(a)},0))}:"msSaveOrOpenBlob"in navigator?function(A,e,t){if(e=e||A.name||"download",typeof A=="string")if(E5(A))m1(A,e,t);else{var n=document.createElement("a");n.href=A,n.target="_blank",setTimeout(function(){xg(n)})}else navigator.msSaveOrOpenBlob((function(a,s){return s===void 0?s={autoBom:!1}:PA(s)!=="object"&&($A.warn("Deprecated: Expected third argument to be a object"),s={autoBom:!s}),s.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a})(A,t),e)}:function(A,e,t,n){if((n=n||open("","_blank"))&&(n.document.title=n.document.body.innerText="downloading..."),typeof A=="string")return m1(A,e,t);var a=A.type==="application/octet-stream",s=/constructor/i.test(Gt.HTMLElement)||Gt.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&s)&&(typeof FileReader>"u"?"undefined":PA(FileReader))==="object"){var c=new FileReader;c.onloadend=function(){var g=c.result;g=l?g:g.replace(/^data:[^;]*;/,"data:attachment/file;"),n?n.location.href=g:location=g,n=null},c.readAsDataURL(A)}else{var h=Gt.URL||Gt.webkitURL,f=h.createObjectURL(A);n?n.location=f:location.href=f,n=null,setTimeout(function(){h.revokeObjectURL(f)},4e4)}});function kS(A){var e;A=A||"",this.ok=!1,A.charAt(0)=="#"&&(A=A.substr(1,6)),A={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"}[A=(A=A.replace(/ /g,"")).toLowerCase()]||A;for(var t=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(c){return[parseInt(c[1]),parseInt(c[2]),parseInt(c[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(c){return[parseInt(c[1],16),parseInt(c[2],16),parseInt(c[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(c){return[parseInt(c[1]+c[1],16),parseInt(c[2]+c[2],16),parseInt(c[3]+c[3],16)]}}],n=0;n255?255:this.r,this.g=this.g<0||isNaN(this.g)?0:this.g>255?255:this.g,this.b=this.b<0||isNaN(this.b)?0:this.b>255?255:this.b,this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"},this.toHex=function(){var c=this.r.toString(16),h=this.g.toString(16),f=this.b.toString(16);return c.length==1&&(c="0"+c),h.length==1&&(h="0"+h),f.length==1&&(f="0"+f),"#"+c+h+f}}var ap=Gt.atob.bind(Gt),x5=Gt.btoa.bind(Gt);function w1(A,e){var t=A[0],n=A[1],a=A[2],s=A[3];t=Dr(t,n,a,s,e[0],7,-680876936),s=Dr(s,t,n,a,e[1],12,-389564586),a=Dr(a,s,t,n,e[2],17,606105819),n=Dr(n,a,s,t,e[3],22,-1044525330),t=Dr(t,n,a,s,e[4],7,-176418897),s=Dr(s,t,n,a,e[5],12,1200080426),a=Dr(a,s,t,n,e[6],17,-1473231341),n=Dr(n,a,s,t,e[7],22,-45705983),t=Dr(t,n,a,s,e[8],7,1770035416),s=Dr(s,t,n,a,e[9],12,-1958414417),a=Dr(a,s,t,n,e[10],17,-42063),n=Dr(n,a,s,t,e[11],22,-1990404162),t=Dr(t,n,a,s,e[12],7,1804603682),s=Dr(s,t,n,a,e[13],12,-40341101),a=Dr(a,s,t,n,e[14],17,-1502002290),t=Mr(t,n=Dr(n,a,s,t,e[15],22,1236535329),a,s,e[1],5,-165796510),s=Mr(s,t,n,a,e[6],9,-1069501632),a=Mr(a,s,t,n,e[11],14,643717713),n=Mr(n,a,s,t,e[0],20,-373897302),t=Mr(t,n,a,s,e[5],5,-701558691),s=Mr(s,t,n,a,e[10],9,38016083),a=Mr(a,s,t,n,e[15],14,-660478335),n=Mr(n,a,s,t,e[4],20,-405537848),t=Mr(t,n,a,s,e[9],5,568446438),s=Mr(s,t,n,a,e[14],9,-1019803690),a=Mr(a,s,t,n,e[3],14,-187363961),n=Mr(n,a,s,t,e[8],20,1163531501),t=Mr(t,n,a,s,e[13],5,-1444681467),s=Mr(s,t,n,a,e[2],9,-51403784),a=Mr(a,s,t,n,e[7],14,1735328473),t=Pr(t,n=Mr(n,a,s,t,e[12],20,-1926607734),a,s,e[5],4,-378558),s=Pr(s,t,n,a,e[8],11,-2022574463),a=Pr(a,s,t,n,e[11],16,1839030562),n=Pr(n,a,s,t,e[14],23,-35309556),t=Pr(t,n,a,s,e[1],4,-1530992060),s=Pr(s,t,n,a,e[4],11,1272893353),a=Pr(a,s,t,n,e[7],16,-155497632),n=Pr(n,a,s,t,e[10],23,-1094730640),t=Pr(t,n,a,s,e[13],4,681279174),s=Pr(s,t,n,a,e[0],11,-358537222),a=Pr(a,s,t,n,e[3],16,-722521979),n=Pr(n,a,s,t,e[6],23,76029189),t=Pr(t,n,a,s,e[9],4,-640364487),s=Pr(s,t,n,a,e[12],11,-421815835),a=Pr(a,s,t,n,e[15],16,530742520),t=jr(t,n=Pr(n,a,s,t,e[2],23,-995338651),a,s,e[0],6,-198630844),s=jr(s,t,n,a,e[7],10,1126891415),a=jr(a,s,t,n,e[14],15,-1416354905),n=jr(n,a,s,t,e[5],21,-57434055),t=jr(t,n,a,s,e[12],6,1700485571),s=jr(s,t,n,a,e[3],10,-1894986606),a=jr(a,s,t,n,e[10],15,-1051523),n=jr(n,a,s,t,e[1],21,-2054922799),t=jr(t,n,a,s,e[8],6,1873313359),s=jr(s,t,n,a,e[15],10,-30611744),a=jr(a,s,t,n,e[6],15,-1560198380),n=jr(n,a,s,t,e[13],21,1309151649),t=jr(t,n,a,s,e[4],6,-145523070),s=jr(s,t,n,a,e[11],10,-1120210379),a=jr(a,s,t,n,e[2],15,718787259),n=jr(n,a,s,t,e[9],21,-343485551),A[0]=Ul(t,A[0]),A[1]=Ul(n,A[1]),A[2]=Ul(a,A[2]),A[3]=Ul(s,A[3])}function g0(A,e,t,n,a,s){return e=Ul(Ul(e,A),Ul(n,s)),Ul(e<>>32-a,t)}function Dr(A,e,t,n,a,s,l){return g0(e&t|~e&n,A,e,a,s,l)}function Mr(A,e,t,n,a,s,l){return g0(e&n|t&~n,A,e,a,s,l)}function Pr(A,e,t,n,a,s,l){return g0(e^t^n,A,e,a,s,l)}function jr(A,e,t,n,a,s,l){return g0(t^(e|~n),A,e,a,s,l)}function HS(A){var e,t=A.length,n=[1732584193,-271733879,-1732584194,271733878];for(e=64;e<=A.length;e+=64)w1(n,GH(A.substring(e-64,e)));A=A.substring(e-64);var a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(e=0;e>2]|=A.charCodeAt(e)<<(e%4<<3);if(a[e>>2]|=128<<(e%4<<3),e>55)for(w1(n,a),e=0;e<16;e++)a[e]=0;return a[14]=8*t,w1(n,a),n}function GH(A){var e,t=[];for(e=0;e<64;e+=4)t[e>>2]=A.charCodeAt(e)+(A.charCodeAt(e+1)<<8)+(A.charCodeAt(e+2)<<16)+(A.charCodeAt(e+3)<<24);return t}var S5="0123456789abcdef".split("");function zH(A){for(var e="",t=0;t<4;t++)e+=S5[A>>8*t+4&15]+S5[A>>8*t&15];return e}function VH(A){return String.fromCharCode(255&A,(65280&A)>>8,(16711680&A)>>16,(4278190080&A)>>24)}function Cw(A){return HS(A).map(VH).join("")}var qH=(function(A){for(var e=0;e>16)+(e>>16)+(t>>16)<<16|65535&t}return A+e&4294967295}function bw(A,e){var t,n,a,s;if(A!==t){for(var l=(a=A,s=1+(256/A.length|0),new Array(s+1).join(a)),c=[],h=0;h<256;h++)c[h]=h;var f=0;for(h=0;h<256;h++){var g=c[h];f=(f+g+l.charCodeAt(h))%256,c[h]=c[f],c[f]=g}t=A,n=c}else c=n;var y=e.length,C=0,v=0,I="";for(h=0;h€/\f©þdSiz";var s=(e+this.padding).substr(0,32),l=(t+this.padding).substr(0,32);this.O=this.processOwnerPassword(s,l),this.P=-(1+(255^a)),this.encryptionKey=Cw(s+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(n)).substr(0,5),this.U=bw(this.encryptionKey,this.padding)}function Zu(A){if(/[^\u0000-\u00ff]/.test(A))throw new Error("Invalid PDF Name Object: "+A+", Only accept ASCII characters.");for(var e="",t=A.length,n=0;n126?"#"+("0"+a.toString(16)).slice(-2):A[n]}return e}function I5(A){if(PA(A)!=="object")throw new Error("Invalid Context passed to initialize PubSub (jsPDF-module)");var e={};this.subscribe=function(t,n,a){if(a=a||!1,typeof t!="string"||typeof n!="function"||typeof a!="boolean")throw new Error("Invalid arguments passed to PubSub.subscribe (jsPDF-module)");e.hasOwnProperty(t)||(e[t]={});var s=Math.random().toString(35);return e[t][s]=[n,!!a],s},this.unsubscribe=function(t){for(var n in e)if(e[n][t])return delete e[n][t],Object.keys(e[n]).length===0&&delete e[n],!0;return!1},this.publish=function(t){if(e.hasOwnProperty(t)){var n=Array.prototype.slice.call(arguments,1),a=[];for(var s in e[t]){var l=e[t][s];try{l[0].apply(A,n)}catch(c){Gt.console&&$A.error("jsPDF PubSub Error",c.message,c)}l[1]&&a.push(s)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return e}}function Dp(A){if(!(this instanceof Dp))return new Dp(A);var e="opacity,stroke-opacity".split(",");for(var t in A)A.hasOwnProperty(t)&&e.indexOf(t)>=0&&(this[t]=A[t]);this.id="",this.objectNumber=-1}function DS(A,e){this.gState=A,this.matrix=e,this.id="",this.objectNumber=-1}function bc(A,e,t,n,a){if(!(this instanceof bc))return new bc(A,e,t,n,a);this.type=A==="axial"?2:3,this.coords=e,this.colors=t,DS.call(this,n,a)}function Ah(A,e,t,n,a){if(!(this instanceof Ah))return new Ah(A,e,t,n,a);this.boundingBox=A,this.xStep=e,this.yStep=t,this.stream="",this.cloneIndex=0,DS.call(this,n,a)}function Ft(A){var e,t=typeof arguments[0]=="string"?arguments[0]:"p",n=arguments[1],a=arguments[2],s=arguments[3],l=[],c=1,h=16,f="S",g=null;PA(A=A||{})==="object"&&(t=A.orientation,n=A.unit||n,a=A.format||a,s=A.compress||A.compressPdf||s,(g=A.encryption||null)!==null&&(g.userPassword=g.userPassword||"",g.ownerPassword=g.ownerPassword||"",g.userPermissions=g.userPermissions||[]),c=typeof A.userUnit=="number"?Math.abs(A.userUnit):1,A.precision!==void 0&&(e=A.precision),A.floatPrecision!==void 0&&(h=A.floatPrecision),f=A.defaultPathOperation||"S"),l=A.filters||(s===!0?["FlateEncode"]:l),n=n||"mm",t=(""+(t||"P")).toLowerCase();var y=A.putOnlyUsedFonts||!1,C={},v={internal:{},__private__:{}};v.__private__.PubSub=I5;var I="1.3",x=v.__private__.getPdfVersion=function(){return I};v.__private__.setPdfVersion=function(B){I=B};var _={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};v.__private__.getPageFormats=function(){return _};var T=v.__private__.getPageFormat=function(B){return _[B]};a=a||"a4";var k="compat",z="advanced",H=k;function re(){this.saveGraphicsState(),X(new mt(ct,0,0,-ct,0,Oa()*ct).toString()+" cm"),this.setFontSize(this.getFontSize()/ct),f="n",H=z}function le(){this.restoreGraphicsState(),f="S",H=k}var ce=v.__private__.combineFontStyleAndFontWeight=function(B,L){if(B=="bold"&&L=="normal"||B=="bold"&&L==400||B=="normal"&&L=="italic"||B=="bold"&&L=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return L&&(B=L==400||L==="normal"?B==="italic"?"italic":"normal":L!=700&&L!=="bold"||B!=="normal"?(L==700?"bold":L)+""+B:"bold"),B};v.advancedAPI=function(B){var L=H===k;return L&&re.call(this),typeof B!="function"||(B(this),L&&le.call(this)),this},v.compatAPI=function(B){var L=H===z;return L&&le.call(this),typeof B!="function"||(B(this),L&&re.call(this)),this},v.isAdvancedAPI=function(){return H===z};var $,Y=function(B){if(H!==z)throw new Error(B+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},de=v.roundToPrecision=v.__private__.roundToPrecision=function(B,L){var ie=e||L;if(isNaN(B)||isNaN(ie))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return B.toFixed(ie).replace(/0+$/,"")};$=v.hpf=v.__private__.hpf=typeof h=="number"?function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.hpf");return de(B,h)}:h==="smart"?function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.hpf");return de(B,B>-1&&B<1?16:5)}:function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.hpf");return de(B,16)};var R=v.f2=v.__private__.f2=function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.f2");return de(B,2)},V=v.__private__.f3=function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.f3");return de(B,3)},ne=v.scale=v.__private__.scale=function(B){if(isNaN(B))throw new Error("Invalid argument passed to jsPDF.scale");return H===k?B*ct:H===z?B:void 0},Ae=function(B){return ne((function(L){return H===k?Oa()-L:H===z?L:void 0})(B))};v.__private__.setPrecision=v.setPrecision=function(B){typeof parseInt(B,10)=="number"&&(e=parseInt(B,10))};var Ce,N="00000000000000000000000000000000",G=v.__private__.getFileId=function(){return N},W=v.__private__.setFileId=function(B){return N=B!==void 0&&/^[a-fA-F0-9]{32}$/.test(B)?B.toUpperCase():N.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),g!==null&&(kn=new Wu(g.userPermissions,g.userPassword,g.ownerPassword,N)),N};v.setFileId=function(B){return W(B),this},v.getFileId=function(){return G()};var he=v.__private__.convertDateToPDFDate=function(B){var L=B.getTimezoneOffset(),ie=L<0?"+":"-",ge=Math.floor(Math.abs(L/60)),Ee=Math.abs(L%60),Pe=[ie,K(ge),"'",K(Ee),"'"].join("");return["D:",B.getFullYear(),K(B.getMonth()+1),K(B.getDate()),K(B.getHours()),K(B.getMinutes()),K(B.getSeconds()),Pe].join("")},Ne=v.__private__.convertPDFDateToDate=function(B){var L=parseInt(B.substr(2,4),10),ie=parseInt(B.substr(6,2),10)-1,ge=parseInt(B.substr(8,2),10),Ee=parseInt(B.substr(10,2),10),Pe=parseInt(B.substr(12,2),10),Je=parseInt(B.substr(14,2),10);return new Date(L,ie,ge,Ee,Pe,Je,0)},P=v.__private__.setCreationDate=function(B){var L;if(B===void 0&&(B=new Date),B instanceof Date)L=he(B);else{if(!/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/.test(B))throw new Error("Invalid argument passed to jsPDF.setCreationDate");L=B}return Ce=L},S=v.__private__.getCreationDate=function(B){var L=Ce;return B==="jsDate"&&(L=Ne(Ce)),L};v.setCreationDate=function(B){return P(B),this},v.getCreationDate=function(B){return S(B)};var Q,K=v.__private__.padd2=function(B){return("0"+parseInt(B)).slice(-2)},Z=v.__private__.padd2Hex=function(B){return("00"+(B=B.toString())).substr(B.length)},se=0,ue=[],be=[],oe=0,ve=[],He=[],Xe=!1,$e=be;v.__private__.setCustomOutputDestination=function(B){Xe=!0,$e=B};var nt=function(B){Xe||($e=B)};v.__private__.resetCustomOutputDestination=function(){Xe=!1,$e=be};var X=v.__private__.out=function(B){return B=B.toString(),oe+=B.length+1,$e.push(B),$e},We=v.__private__.write=function(B){return X(arguments.length===1?B.toString():Array.prototype.join.call(arguments," "))},Tt=v.__private__.getArrayBuffer=function(B){for(var L=B.length,ie=new ArrayBuffer(L),ge=new Uint8Array(ie);L--;)ge[L]=B.charCodeAt(L);return ie},Fe=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];v.__private__.getStandardFonts=function(){return Fe};var Se=A.fontSize||16;v.__private__.setFontSize=v.setFontSize=function(B){return Se=H===z?B/ct:B,this};var Ye,Ze=v.__private__.getFontSize=v.getFontSize=function(){return H===k?Se:Se*ct},At=A.R2L||!1;v.__private__.setR2L=v.setR2L=function(B){return At=B,this},v.__private__.getR2L=v.getR2L=function(){return At};var st,ht=v.__private__.setZoomMode=function(B){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(B))Ye=B;else if(isNaN(B)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(B)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+B+'" is not recognized.');Ye=B}else Ye=parseInt(B,10)};v.__private__.getZoomMode=function(){return Ye};var Ut,Be=v.__private__.setPageMode=function(B){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(B)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+B+'" is not recognized.');st=B};v.__private__.getPageMode=function(){return st};var Ve=v.__private__.setLayoutMode=function(B){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(B)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+B+'" is not recognized.');Ut=B};v.__private__.getLayoutMode=function(){return Ut},v.__private__.setDisplayMode=v.setDisplayMode=function(B,L,ie){return ht(B),Ve(L),Be(ie),this};var lt={title:"",subject:"",author:"",keywords:"",creator:""};v.__private__.getDocumentProperty=function(B){if(Object.keys(lt).indexOf(B)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return lt[B]},v.__private__.getDocumentProperties=function(){return lt},v.__private__.setDocumentProperties=v.setProperties=v.setDocumentProperties=function(B){for(var L in lt)lt.hasOwnProperty(L)&&B[L]&&(lt[L]=B[L]);return this},v.__private__.setDocumentProperty=function(B,L){if(Object.keys(lt).indexOf(B)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return lt[B]=L};var it,ct,rt,rA,zt,St={},_t={},Vt=[],bt={},fA={},It={},Nt={},Zt=null,pe=0,Le=[],at=new I5(v),jt=A.hotfixes||[],$t={},xA={},eA=[],mt=function B(L,ie,ge,Ee,Pe,Je){if(!(this instanceof B))return new B(L,ie,ge,Ee,Pe,Je);isNaN(L)&&(L=1),isNaN(ie)&&(ie=0),isNaN(ge)&&(ge=0),isNaN(Ee)&&(Ee=1),isNaN(Pe)&&(Pe=0),isNaN(Je)&&(Je=0),this._matrix=[L,ie,ge,Ee,Pe,Je]};Object.defineProperty(mt.prototype,"sx",{get:function(){return this._matrix[0]},set:function(B){this._matrix[0]=B}}),Object.defineProperty(mt.prototype,"shy",{get:function(){return this._matrix[1]},set:function(B){this._matrix[1]=B}}),Object.defineProperty(mt.prototype,"shx",{get:function(){return this._matrix[2]},set:function(B){this._matrix[2]=B}}),Object.defineProperty(mt.prototype,"sy",{get:function(){return this._matrix[3]},set:function(B){this._matrix[3]=B}}),Object.defineProperty(mt.prototype,"tx",{get:function(){return this._matrix[4]},set:function(B){this._matrix[4]=B}}),Object.defineProperty(mt.prototype,"ty",{get:function(){return this._matrix[5]},set:function(B){this._matrix[5]=B}}),Object.defineProperty(mt.prototype,"a",{get:function(){return this._matrix[0]},set:function(B){this._matrix[0]=B}}),Object.defineProperty(mt.prototype,"b",{get:function(){return this._matrix[1]},set:function(B){this._matrix[1]=B}}),Object.defineProperty(mt.prototype,"c",{get:function(){return this._matrix[2]},set:function(B){this._matrix[2]=B}}),Object.defineProperty(mt.prototype,"d",{get:function(){return this._matrix[3]},set:function(B){this._matrix[3]=B}}),Object.defineProperty(mt.prototype,"e",{get:function(){return this._matrix[4]},set:function(B){this._matrix[4]=B}}),Object.defineProperty(mt.prototype,"f",{get:function(){return this._matrix[5]},set:function(B){this._matrix[5]=B}}),Object.defineProperty(mt.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(mt.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(mt.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(mt.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),mt.prototype.join=function(B){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map($).join(B)},mt.prototype.multiply=function(B){var L=B.sx*this.sx+B.shy*this.shx,ie=B.sx*this.shy+B.shy*this.sy,ge=B.shx*this.sx+B.sy*this.shx,Ee=B.shx*this.shy+B.sy*this.sy,Pe=B.tx*this.sx+B.ty*this.shx+this.tx,Je=B.tx*this.shy+B.ty*this.sy+this.ty;return new mt(L,ie,ge,Ee,Pe,Je)},mt.prototype.decompose=function(){var B=this.sx,L=this.shy,ie=this.shx,ge=this.sy,Ee=this.tx,Pe=this.ty,Je=Math.sqrt(B*B+L*L),vt=(B/=Je)*ie+(L/=Je)*ge;ie-=B*vt,ge-=L*vt;var Et=Math.sqrt(ie*ie+ge*ge);return vt/=Et,B*(ge/=Et)>16&255,ge=Et>>8&255,Ee=255&Et}if(ge===void 0||Pe===void 0&&ie===ge&&ge===Ee)L=typeof ie=="string"?ie+" "+Je[0]:B.precision===2?R(ie/255)+" "+Je[0]:V(ie/255)+" "+Je[0];else if(Pe===void 0||PA(Pe)==="object"){if(Pe&&!isNaN(Pe.a)&&Pe.a===0)return["1.","1.","1.",Je[1]].join(" ");L=typeof ie=="string"?[ie,ge,Ee,Je[1]].join(" "):B.precision===2?[R(ie/255),R(ge/255),R(Ee/255),Je[1]].join(" "):[V(ie/255),V(ge/255),V(Ee/255),Je[1]].join(" ")}else L=typeof ie=="string"?[ie,ge,Ee,Pe,Je[2]].join(" "):B.precision===2?[R(ie),R(ge),R(Ee),R(Pe),Je[2]].join(" "):[V(ie),V(ge),V(Ee),V(Pe),Je[2]].join(" ");return L},Yr=v.__private__.getFilters=function(){return l},oi=v.__private__.putStream=function(B){var L=(B=B||{}).data||"",ie=B.filters||Yr(),ge=B.alreadyAppliedFilters||[],Ee=B.addLength1||!1,Pe=L.length,Je=B.objectId,vt=function(Hn){return Hn};if(g!==null&&Je===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");g!==null&&(vt=kn.encryptor(Je,0));var Et={};ie===!0&&(ie=["FlateEncode"]);var Pt=B.additionalKeyValues||[],qt=(Et=Ft.API.processDataByFilters!==void 0?Ft.API.processDataByFilters(L,ie):{data:L,reverseChain:[]}).reverseChain+(Array.isArray(ge)?ge.join(" "):ge.toString());if(Et.data.length!==0&&(Pt.push({key:"Length",value:Et.data.length}),Ee===!0&&Pt.push({key:"Length1",value:Pe})),qt.length!=0)if(qt.split("/").length-1==1)Pt.push({key:"Filter",value:qt});else{Pt.push({key:"Filter",value:"["+qt+"]"});for(var dA=0;dA>"),Et.data.length!==0&&(X("stream"),X(vt(Et.data)),X("endstream"))},Vs=v.__private__.putPage=function(B){var L=B.number,ie=B.data,ge=B.objId,Ee=B.contentsObjId;OA(ge,!0),X("<>"),X("endobj");var Pe=ie.join(` `);return H===z&&(Pe+=` Q`),OA(Ee,!0),oi({data:Pe,filters:Yr(),objectId:Ee}),X("endobj"),ge},Qi=v.__private__.putPages=function(){var B,L,ie=[];for(B=1;B<=pe;B++)Le[B].objId=jA(),Le[B].contentsObjId=jA();for(B=1;B<=pe;B++)ie.push(Vs({number:B,data:He[B],objId:Le[B].objId,contentsObjId:Le[B].contentsObjId,mediaBox:Le[B].mediaBox,cropBox:Le[B].cropBox,bleedBox:Le[B].bleedBox,trimBox:Le[B].trimBox,artBox:Le[B].artBox,userUnit:Le[B].userUnit,rootDictionaryObjId:Rn,resourceDictionaryObjId:RA}));OA(Rn,!0),X("<>"),X("endobj"),at.publish("postPutPages")},Li=function(B){at.publish("putFont",{font:B,out:X,newObject:SA,putStream:oi}),B.isAlreadyPutted!==!0&&(B.objectNumber=SA(),X("<<"),X("/Type /Font"),X("/BaseFont /"+Zu(B.postScriptName)),X("/Subtype /Type1"),typeof B.encoding=="string"&&X("/Encoding /"+B.encoding),X("/FirstChar 32"),X("/LastChar 255"),X(">>"),X("endobj"))},gs=function(B){B.objectNumber=SA();var L=[];L.push({key:"Type",value:"/XObject"}),L.push({key:"Subtype",value:"/Form"}),L.push({key:"BBox",value:"["+[$(B.x),$(B.y),$(B.x+B.width),$(B.y+B.height)].join(" ")+"]"}),L.push({key:"Matrix",value:"["+B.matrix.toString()+"]"});var ie=B.pages[1].join(` -`);oi({data:ie,additionalKeyValues:L,objectId:B.objectNumber}),X("endobj")},Oi=function(B,L){L||(L=21);var ie=SA(),ge=(function(Je,vt){var Et,Pt=[],qt=1/(vt-1);for(Et=0;Et<1;Et+=qt)Pt.push(Et);if(Pt.push(1),Je[0].offset!=0){var dA={offset:0,color:Je[0].color};Je.unshift(dA)}if(Je[Je.length-1].offset!=1){var sn={offset:1,color:Je[Je.length-1].color};Je.push(sn)}for(var Bn="",KA=0,Hn=0;HnJe[KA+1].offset;)KA++;var Un=Je[KA].offset,er=(Et-Un)/(Je[KA+1].offset-Un),Ra=Je[KA].color,Pi=Je[KA+1].color;Bn+=Z(Math.round((1-er)*Ra[0]+er*Pi[0]).toString(16))+Z(Math.round((1-er)*Ra[1]+er*Pi[1]).toString(16))+Z(Math.round((1-er)*Ra[2]+er*Pi[2]).toString(16))}return Bn.trim()})(B.colors,L),Ee=[];Ee.push({key:"FunctionType",value:"0"}),Ee.push({key:"Domain",value:"[0.0 1.0]"}),Ee.push({key:"Size",value:"["+L+"]"}),Ee.push({key:"BitsPerSample",value:"8"}),Ee.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),Ee.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),oi({data:ge,additionalKeyValues:Ee,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:ie}),X("endobj"),B.objectNumber=SA(),X("<< /ShadingType "+B.type),X("/ColorSpace /DeviceRGB");var Pe="/Coords ["+$(parseFloat(B.coords[0]))+" "+$(parseFloat(B.coords[1]))+" ";B.type===2?Pe+=$(parseFloat(B.coords[2]))+" "+$(parseFloat(B.coords[3])):Pe+=$(parseFloat(B.coords[2]))+" "+$(parseFloat(B.coords[3]))+" "+$(parseFloat(B.coords[4]))+" "+$(parseFloat(B.coords[5])),X(Pe+="]"),B.matrix&&X("/Matrix ["+B.matrix.toString()+"]"),X("/Function "+ie+" 0 R"),X("/Extend [true true]"),X(">>"),X("endobj")},Ri=function(B,L){var ie=jA(),ge=SA();L.push({resourcesOid:ie,objectOid:ge}),B.objectNumber=ge;var Ee=[];Ee.push({key:"Type",value:"/Pattern"}),Ee.push({key:"PatternType",value:"1"}),Ee.push({key:"PaintType",value:"1"}),Ee.push({key:"TilingType",value:"1"}),Ee.push({key:"BBox",value:"["+B.boundingBox.map($).join(" ")+"]"}),Ee.push({key:"XStep",value:$(B.xStep)}),Ee.push({key:"YStep",value:$(B.yStep)}),Ee.push({key:"Resources",value:ie+" 0 R"}),B.matrix&&Ee.push({key:"Matrix",value:"["+B.matrix.toString()+"]"}),oi({data:B.stream,additionalKeyValues:Ee,objectId:B.objectNumber}),X("endobj")},qs=function(B){for(var L in B.objectNumber=SA(),X("<<"),B)switch(L){case"opacity":X("/ca "+R(B[L]));break;case"stroke-opacity":X("/CA "+R(B[L]))}X(">>"),X("endobj")},ea=function(B){OA(B.resourcesOid,!0),X("<<"),X("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),(function(){for(var L in X("/Font <<"),St)St.hasOwnProperty(L)&&(y===!1||y===!0&&C.hasOwnProperty(L))&&X("/"+L+" "+St[L].objectNumber+" 0 R");X(">>")})(),(function(){if(Object.keys(bt).length>0){for(var L in X("/Shading <<"),bt)bt.hasOwnProperty(L)&&bt[L]instanceof Cc&&bt[L].objectNumber>=0&&X("/"+L+" "+bt[L].objectNumber+" 0 R");at.publish("putShadingPatternDict"),X(">>")}})(),(function(L){if(Object.keys(bt).length>0){for(var ie in X("/Pattern <<"),bt)bt.hasOwnProperty(ie)&&bt[ie]instanceof v.TilingPattern&&bt[ie].objectNumber>=0&&bt[ie].objectNumber>")}})(B.objectOid),(function(){if(Object.keys(It).length>0){var L;for(L in X("/ExtGState <<"),It)It.hasOwnProperty(L)&&It[L].objectNumber>=0&&X("/"+L+" "+It[L].objectNumber+" 0 R");at.publish("putGStateDict"),X(">>")}})(),(function(){for(var L in X("/XObject <<"),$t)$t.hasOwnProperty(L)&&$t[L].objectNumber>=0&&X("/"+L+" "+$t[L].objectNumber+" 0 R");at.publish("putXobjectDict"),X(">>")})(),X(">>"),X("endobj")},yn=function(B){_t[B.fontName]=_t[B.fontName]||{},_t[B.fontName][B.fontStyle]=B.id},Ml=function(B,L,ie,ge,Ee){var Pe={id:"F"+(Object.keys(St).length+1).toString(10),postScriptName:B,fontName:L,fontStyle:ie,encoding:ge,isStandardFont:Ee||!1,metadata:{}};return at.publish("addFont",{font:Pe,instance:this}),St[Pe.id]=Pe,yn(Pe),Pe.id},Xr=v.__private__.pdfEscape=v.pdfEscape=function(B,L){return(function(ie,ge){var Ee,Pe,Je,vt,Et,Pt,qt,dA,sn;if(Je=(ge=ge||{}).sourceEncoding||"Unicode",Et=ge.outputEncoding,(ge.autoencode||Et)&&St[it].metadata&&St[it].metadata[Je]&&St[it].metadata[Je].encoding&&(vt=St[it].metadata[Je].encoding,!Et&&St[it].encoding&&(Et=St[it].encoding),!Et&&vt.codePages&&(Et=vt.codePages[0]),typeof Et=="string"&&(Et=vt[Et]),Et)){for(qt=!1,Pt=[],Ee=0,Pe=ie.length;Ee>8&&(qt=!0);ie=Pt.join("")}for(Ee=ie.length;qt===void 0&&Ee!==0;)ie.charCodeAt(Ee-1)>>8&&(qt=!0),Ee--;if(!qt)return ie;for(Pt=ge.noBOM?[]:[254,255],Ee=0,Pe=ie.length;Ee>8)>>8)throw new Error("Character at position "+Ee+" of string '"+ie+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");Pt.push(sn),Pt.push(dA-(sn<<8))}return String.fromCharCode.apply(void 0,Pt)})(B,L).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},ki=v.__private__.beginPage=function(B){He[++pe]=[],Le[pe]={objId:0,contentsObjId:0,userUnit:Number(c),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(B[0]),topRightY:Number(B[1])}},jl(pe),nt(He[Q])},Ua=function(B,L){var ie,ge,Ee;switch(t=L||t,typeof B=="string"&&(ie=T(B.toLowerCase()),Array.isArray(ie)&&(ge=ie[0],Ee=ie[1])),Array.isArray(B)&&(ge=B[0]*ct,Ee=B[1]*ct),isNaN(ge)&&(ge=a[0],Ee=a[1]),(ge>14400||Ee>14400)&&($A.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),ge=Math.min(14400,ge),Ee=Math.min(14400,Ee)),a=[ge,Ee],t.substr(0,1)){case"l":Ee>ge&&(a=[Ee,ge]);break;case"p":ge>Ee&&(a=[Ee,ge])}ki(a),kt(Xs),X(Zr),Oo!==0&&X(Oo+" J"),Vn!==0&&X(Vn+" j"),at.publish("addPage",{pageNumber:pe})},Pl=function(B){B>0&&B<=pe&&(He.splice(B,1),Le.splice(B,1),pe--,Q>pe&&(Q=pe),this.setPage(Q))},jl=function(B){B>0&&B<=pe&&(Q=B)},Kl=v.__private__.getNumberOfPages=v.getNumberOfPages=function(){return He.length-1},Yc=function(B,L,ie){var ge,Ee=void 0;return ie=ie||{},B=B!==void 0?B:St[it].fontName,L=L!==void 0?L:St[it].fontStyle,ge=B.toLowerCase(),_t[ge]!==void 0&&_t[ge][L]!==void 0?Ee=_t[ge][L]:_t[B]!==void 0&&_t[B][L]!==void 0?Ee=_t[B][L]:ie.disableWarning===!1&&$A.warn("Unable to look up font label for font '"+B+"', '"+L+"'. Refer to getFontList() for available fonts."),Ee||ie.noFallback||(Ee=_t.times[L])==null&&(Ee=_t.times.normal),Ee},Jr=v.__private__.putInfo=function(){var B=SA(),L=function(ge){return ge};for(var ie in g!==null&&(L=kn.encryptor(B,0)),X("<<"),X("/Producer ("+Xr(L("jsPDF "+Ft.version))+")"),lt)lt.hasOwnProperty(ie)&<[ie]&&X("/"+ie.substr(0,1).toUpperCase()+ie.substr(1)+" ("+Xr(L(lt[ie]))+")");X("/CreationDate ("+Xr(L(Ce))+")"),X(">>"),X("endobj")},Ia=v.__private__.putCatalog=function(B){var L=(B=B||{}).rootDictionaryObjId||Rn;switch(SA(),X("<<"),X("/Type /Catalog"),X("/Pages "+L+" 0 R"),Ye||(Ye="fullwidth"),Ye){case"fullwidth":X("/OpenAction [3 0 R /FitH null]");break;case"fullheight":X("/OpenAction [3 0 R /FitV null]");break;case"fullpage":X("/OpenAction [3 0 R /Fit]");break;case"original":X("/OpenAction [3 0 R /XYZ null null 1]");break;default:var ie=""+Ye;ie.substr(ie.length-1)==="%"&&(Ye=parseInt(Ye)/100),typeof Ye=="number"&&X("/OpenAction [3 0 R /XYZ null null "+R(Ye)+"]")}switch(Ut||(Ut="continuous"),Ut){case"continuous":X("/PageLayout /OneColumn");break;case"single":X("/PageLayout /SinglePage");break;case"two":case"twoleft":X("/PageLayout /TwoColumnLeft");break;case"tworight":X("/PageLayout /TwoColumnRight")}st&&X("/PageMode /"+st),at.publish("putCatalog"),X(">>"),X("endobj")},Hi=v.__private__.putTrailer=function(){X("trailer"),X("<<"),X("/Size "+(se+1)),X("/Root "+se+" 0 R"),X("/Info "+(se-1)+" 0 R"),g!==null&&X("/Encrypt "+kn.oid+" 0 R"),X("/ID [ <"+N+"> <"+N+"> ]"),X(">>")},BA=v.__private__.putHeader=function(){X("%PDF-"+I),X("%ºß¬à")},Gl=v.__private__.putXRef=function(){var B="0000000000";X("xref"),X("0 "+(se+1)),X("0000000000 65535 f ");for(var L=1;L<=se;L++)typeof ue[L]=="function"?X((B+ue[L]()).slice(-10)+" 00000 n "):ue[L]!==void 0?X((B+ue[L]).slice(-10)+" 00000 n "):X("0000000000 00000 n ")},ta=v.__private__.buildDocument=function(){var B;se=0,oe=0,be=[],ue=[],ve=[],Rn=jA(),RA=jA(),nt(be),at.publish("buildDocument"),BA(),Qi(),(function(){at.publish("putAdditionalObjects");for(var ie=0;ie"),X("/O <"+kn.toHexString(kn.O)+">"),X("/P "+kn.P),X(">>"),X("endobj")),Jr(),Ia();var L=oe;return Gl(),Hi(),X("startxref"),X(""+L),X("%%EOF"),nt(He[Q]),be.join(` -`)},ps=v.__private__.getBlob=function(B){return new Blob([Tt(B)],{type:"application/pdf"})},zl=v.output=v.__private__.output=(rn=function(B,L){switch(typeof(L=L||{})=="string"?L={filename:L}:L.filename=L.filename||"generated.pdf",B){case void 0:return ta();case"save":v.save(L.filename);break;case"arraybuffer":return Tt(ta());case"blob":return ps(ta());case"bloburi":case"bloburl":if(Gt.URL!==void 0&&typeof Gt.URL.createObjectURL=="function")return Gt.URL&&Gt.URL.createObjectURL(ps(ta()))||void 0;$A.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var ie="",ge=ta();try{ie=x5(ge)}catch{ie=x5(unescape(encodeURIComponent(ge)))}return"data:application/pdf;filename="+L.filename+";base64,"+ie;case"pdfobjectnewwindow":if(Object.prototype.toString.call(Gt)==="[object Window]"){var Ee="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",Pe=' integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==" crossorigin="anonymous"';L.pdfObjectUrl&&(Ee=L.pdfObjectUrl,Pe="");var Je=' + diff --git a/frontend/src/components/VideoPlayer.jsx b/frontend/src/components/VideoPlayer.jsx index ef03db3..b08a94c 100644 --- a/frontend/src/components/VideoPlayer.jsx +++ b/frontend/src/components/VideoPlayer.jsx @@ -1,5 +1,6 @@ import React, { useRef, useState, useEffect } from 'react'; import { Play, Pause, SkipBack, SkipForward, Volume2, VolumeX, Download, Image, Scissors, ChevronLeft, ChevronRight, FolderPlus, Check } from 'lucide-react'; +import { getApiUrl } from '../utils/api'; /** * VideoPlayer component with frame extraction capability @@ -15,7 +16,7 @@ const VideoPlayer = ({ src, onFrameExtract, onSaveToProject, className = '', aut // Convert old /generated_videos/ URLs to streaming endpoint for seeking support const videoSrc = src?.startsWith('/generated_videos/') - ? `/api/stream_video.php?file=${encodeURIComponent(src.replace('/generated_videos/', ''))}` + ? `${getApiUrl('stream_video.php')}?file=${encodeURIComponent(src.replace('/generated_videos/', ''))}` : src; const [isPlaying, setIsPlaying] = useState(false);