@jaak.ai/stamps 2.3.0-dev.3 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +0,0 @@
1
- import{r as t,c as e,g as i,h as r}from"./p-BCfAsrzL.js";class n{events=new Map;on(t,e){if(!this.events.has(t)){this.events.set(t,[])}this.events.get(t).push(e)}off(t,e){const i=this.events.get(t);if(i){const t=i.indexOf(e);if(t>-1){i.splice(t,1)}}}emit(t,e){const i=this.events.get(t);if(i){i.forEach((t=>{try{t(e)}catch(t){}}))}}once(t,e){const i=r=>{e(r);this.off(t,i)};this.on(t,i)}clear(){this.events.clear()}}class s{eventBus;captureState={step:"front",isCapturing:false,isDetectionPaused:false,isVideoActive:false,isLoading:false,showFlipAnimation:false,showSuccessAnimation:false,bestScore:0,hasScreenshotTaken:false};capturedImages={front:{fullFrame:null,cropped:null},back:{fullFrame:null,cropped:null},metadata:{totalImages:0,processCompleted:false,backCaptureSkipped:false}};constructor(t){this.eventBus=t}getCaptureState(){return{...this.captureState}}updateCaptureState(t){const e={...this.captureState};this.captureState={...this.captureState,...t};this.eventBus.emit("state-changed",{previous:e,current:this.captureState,changes:t})}getCapturedImages(){return JSON.parse(JSON.stringify(this.capturedImages))}setCapturedImages(t){this.capturedImages={...this.capturedImages,...t,metadata:{...this.capturedImages.metadata,...t.metadata}};let e=0;if(this.capturedImages.front.fullFrame&&this.capturedImages.front.cropped){e+=2}if(this.capturedImages.back.fullFrame&&this.capturedImages.back.cropped){e+=2}this.capturedImages.metadata.totalImages=e}reset(){this.captureState={step:"front",isCapturing:false,isDetectionPaused:false,isVideoActive:false,isLoading:false,showFlipAnimation:false,showSuccessAnimation:false,bestScore:0,hasScreenshotTaken:false};this.capturedImages={front:{fullFrame:null,cropped:null},back:{fullFrame:null,cropped:null},metadata:{totalImages:0,processCompleted:false,backCaptureSkipped:false}};this.eventBus.emit("state-changed",{previous:null,current:this.captureState,changes:{reset:true}})}isProcessCompleted(){return this.captureState.step==="completed"}canProceedToBack(){return this.captureState.step==="front"&&this.capturedImages.front.fullFrame!==null&&this.capturedImages.front.cropped!==null}}class o{eventBus;availableCameras=[];selectedCameraId=null;deviceType="desktop";preferredCameraFacing=null;preferredCamera="auto";static cameraCapabilitiesCache=new Map;static deviceEnumerationCache=null;static CACHE_DURATION=3e4;currentStreamPromise;lastStreamConstraints;constructor(t,e="auto"){this.eventBus=t;this.preferredCamera=e}async detectDeviceType(){const t=navigator.userAgent;const e=/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(t);const i=/iPad|Android/i.test(t)&&window.innerWidth>=768;if(i){this.deviceType="tablet"}else if(e){this.deviceType="mobile"}else{this.deviceType="desktop"}return this.deviceType}async enumerateDevices(){try{const t=Date.now();if(o.deviceEnumerationCache&&t-o.deviceEnumerationCache.timestamp<o.CACHE_DURATION){this.availableCameras=o.deviceEnumerationCache.devices;await this.setInitialCameraPreference();this.eventBus.emit("camera-changed",this.selectedCameraId);return this.availableCameras}const e=await this.checkCameraPermission();if(e==="denied"){return[]}if(e==="prompt"){const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()))}const i=await navigator.mediaDevices.enumerateDevices();const r=i.filter((t=>t.kind==="videoinput"));this.availableCameras=r.filter((t=>{const e=this.isVirtualCamera(t);if(e){console.log(`Virtual camera detected and filtered: ${t.label}`)}return!e}));if(this.availableCameras.length===0){console.log("No physical cameras available");this.eventBus.emit("error",new Error("Cámaras virtuales no están permitidas. Use una cámara física."));return[]}o.deviceEnumerationCache={devices:this.availableCameras,timestamp:t};await this.setInitialCameraPreference();this.eventBus.emit("camera-changed",this.selectedCameraId);return this.availableCameras}catch(t){this.handleCameraPermissionError(t);return[]}}getAvailableCameras(){return[...this.availableCameras]}isMultipleCamerasAvailable(){return this.availableCameras.length>1}getSelectedCameraId(){return this.selectedCameraId}async setSelectedCamera(t){const e=this.availableCameras.find((e=>e.deviceId===t));if(!e){throw new Error(`Camera with ID ${t} not found`)}this.selectedCameraId=t;this.updatePreferredFacing(e);this.eventBus.emit("camera-changed",t)}getPreferredFacing(){return this.preferredCameraFacing}async setupCamera(t){try{const e=t||await this.getMaxResolution();if(this.currentStreamPromise&&this.constraintsEqual(e,this.lastStreamConstraints)){return await this.currentStreamPromise}this.currentStreamPromise=navigator.mediaDevices.getUserMedia({video:e,audio:false});this.lastStreamConstraints=e;const i=await this.currentStreamPromise;const r=i.getVideoTracks()[0];if(r){const t=r.getSettings();const e=t.deviceId;if(e){const t=await navigator.mediaDevices.enumerateDevices();const r=t.find((t=>t.deviceId===e));if(r&&this.isVirtualCamera(r)){console.log(`Virtual camera detected in active stream: ${r.label}`);i.getTracks().forEach((t=>t.stop()));throw new Error("Cámaras virtuales no están permitidas. Use una cámara física.")}}}return i}catch(t){const e={width:{ideal:1280},height:{ideal:720}};if(this.deviceType!=="desktop"&&this.preferredCameraFacing){e.facingMode=this.preferredCameraFacing}this.currentStreamPromise=navigator.mediaDevices.getUserMedia({video:e,audio:false});this.lastStreamConstraints=e;const i=await this.currentStreamPromise;const r=i.getVideoTracks()[0];if(r){const t=r.getSettings();const e=t.deviceId;if(e){const t=await navigator.mediaDevices.enumerateDevices();const r=t.find((t=>t.deviceId===e));if(r&&this.isVirtualCamera(r)){console.log(`Virtual camera detected in fallback stream: ${r.label}`);i.getTracks().forEach((t=>t.stop()));throw new Error("Cámaras virtuales no están permitidas. Use una cámara física.")}}}return i}}async switchCamera(t){const e=this.availableCameras.find((e=>e.deviceId===t));if(!e){await this.enumerateDevices();return}if(this.isVirtualCamera(e)){console.log(`Attempted to switch to virtual camera: ${e.label}`);this.eventBus.emit("error",new Error("No se puede cambiar a cámara virtual"));return}await this.setSelectedCamera(t)}isRearCamera(t){const e=t.getVideoTracks()[0];if(!e)return false;const i=e.getSettings();return i.facingMode==="environment"}async getCameraInfo(){const t=await Promise.all(this.availableCameras.map((async t=>{const e=await this.checkCameraAutofocus(t.deviceId);return{id:t.deviceId,label:t.label||"Unknown Camera",selected:t.deviceId===this.selectedCameraId,hasAutofocus:e}})));return{availableCameras:t,selectedCameraId:this.selectedCameraId,deviceType:this.deviceType,isMultipleCamerasAvailable:this.isMultipleCamerasAvailable(),preferredFacing:this.preferredCameraFacing}}async checkCameraPermission(){try{if(!navigator.permissions){return"prompt"}const t=await navigator.permissions.query({name:"camera"});return t.state}catch(t){return"prompt"}}handleCameraPermissionError(t){this.availableCameras=[];this.eventBus.emit("error",new Error(`Camera permission error: ${t.message}`))}async setInitialCameraPreference(){if(this.availableCameras.length===0)return;if(this.preferredCamera==="front"){await this.selectFrontCamera()}else if(this.preferredCamera==="back"){await this.selectBackCamera()}else{await this.selectAutoCamera()}}async checkCameraAutofocus(t){try{if(o.cameraCapabilitiesCache.has(t)){const e=o.cameraCapabilitiesCache.get(t);return typeof e==="boolean"?e:false}const e=await navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:t}}});const i=e.getVideoTracks()[0];const r=i.getCapabilities();e.getTracks().forEach((t=>t.stop()));const n=r.focusMode&&Array.isArray(r.focusMode)&&r.focusMode.length>0;const s=n&&(r.focusMode.includes("continuous")||r.focusMode.includes("auto"));o.cameraCapabilitiesCache.set(t,s);return s}catch(e){o.cameraCapabilitiesCache.set(t,false);return false}}async selectFrontCamera(){this.preferredCameraFacing="user";const t=this.availableCameras.filter((t=>{const e=t.label.toLowerCase();return e.includes("front")||e.includes("user")||e.includes("selfie")||e.includes("frontal")||!e.includes("back")&&!e.includes("rear")&&!e.includes("environment")}));let e=null;if(t.length>0){for(const i of t){const t=await this.checkCameraAutofocus(i.deviceId);if(t){e=i;break}}if(!e){e=t[0]}}this.selectedCameraId=e?e.deviceId:this.availableCameras[0].deviceId}async selectBackCamera(){this.preferredCameraFacing="environment";const t=this.availableCameras.filter((t=>{const e=t.label.toLowerCase();return e.includes("back")||e.includes("rear")||e.includes("environment")||e.includes("trasera")||e.includes("posterior")}));let e=null;if(t.length>0){for(const i of t){const t=await this.checkCameraAutofocus(i.deviceId);if(t){e=i;break}}if(!e){e=t[0]}}else if(this.availableCameras.length>1){const t=this.availableCameras[this.availableCameras.length-1];const i=await this.checkCameraAutofocus(t.deviceId);e=i?t:this.availableCameras[this.availableCameras.length-1]}this.selectedCameraId=e?e.deviceId:this.availableCameras[0].deviceId}async selectAutoCamera(){if(this.deviceType==="mobile"||this.deviceType==="tablet"){await this.selectBackCamera()}else{await this.selectFrontCamera()}}updatePreferredFacing(t){const e=t.label.toLowerCase().includes("back")||t.label.toLowerCase().includes("rear")||t.label.toLowerCase().includes("environment");this.preferredCameraFacing=e?"environment":"user"}async getMaxResolution(){try{if(!this.deviceType||this.deviceType==="desktop"){await this.detectDeviceType()}const t={};if(this.selectedCameraId){t.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){const e=this.deviceType==="desktop"?{ideal:this.preferredCameraFacing}:{exact:this.preferredCameraFacing};t.facingMode=e}else{if(this.preferredCamera==="front"){t.facingMode="user"}else if(this.preferredCamera==="back"){t.facingMode="environment"}else{t.facingMode=this.deviceType==="mobile"||this.deviceType==="tablet"?"environment":"user"}}let e;if(this.selectedCameraId&&o.cameraCapabilitiesCache.has(this.selectedCameraId+"_caps")){e=JSON.parse(o.cameraCapabilitiesCache.get(this.selectedCameraId+"_caps"))}else{const i=await navigator.mediaDevices.getUserMedia({video:t});const r=i.getVideoTracks()[0];e=r.getCapabilities();i.getTracks().forEach((t=>t.stop()));if(this.selectedCameraId){o.cameraCapabilitiesCache.set(this.selectedCameraId+"_caps",JSON.stringify(e))}}const i={...t};if(e.width&&e.height){const t=/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const r=this.deviceType==="mobile"||/Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let n;let s;if(r&&!t){n=Math.min(e.width.max,1280);s=Math.min(e.height.max,720)}else if(t){n=Math.min(e.width.max,1280);s=Math.min(e.height.max,720)}else{n=Math.min(e.width.max,1920);s=Math.min(e.height.max,1080)}i.width={ideal:n};i.height={ideal:s}}const r=e;if(r.focusMode&&Array.isArray(r.focusMode)){if(r.focusMode.includes("continuous")){i.focusMode="continuous"}else if(r.focusMode.includes("auto")){i.focusMode="auto"}}return i}catch(t){if(!this.deviceType||this.deviceType==="desktop"){await this.detectDeviceType()}const e=/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const i=this.deviceType==="mobile"||/Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let r;let n;if(i&&!e){r=1280;n=720}else if(e){r=1280;n=720}else{r=1920;n=1080}const s={width:{ideal:r},height:{ideal:n}};if(this.selectedCameraId){s.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){const t=this.deviceType==="desktop"?{ideal:this.preferredCameraFacing}:{exact:this.preferredCameraFacing};s.facingMode=t}else{if(this.preferredCamera==="front"){s.facingMode="user"}else if(this.preferredCamera==="back"){s.facingMode="environment"}else{s.facingMode=this.deviceType==="mobile"||this.deviceType==="tablet"?"environment":"user"}}return s}}constraintsEqual(t,e){if(!t||!e)return false;return JSON.stringify(t)===JSON.stringify(e)}static clearCaches(){o.cameraCapabilitiesCache.clear();o.deviceEnumerationCache=null}invalidateDeviceCache(){o.deviceEnumerationCache=null}isVirtualCamera(t){const e=t.label.toLowerCase();const i=["obs","virtual","snap camera","manycam","xsplit","camtwist","ecamm","nvidia broadcast","droidcam","iriun","elgato","streamlabs","wirecast","zoom virtual","teams virtual","mmhmm","camo","reincubate camo","webcamoid","splitcam","cheese","guvcview","yawcam","webcam 7","altserver"];return i.some((t=>e.includes(t)))}}class a{getDeviceInfo(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=t.connection||t.mozConnection||t.webkitConnection;const r=i&&(i.effectiveType==="slow-2g"||i.effectiveType==="2g");return{estimatedRAM:e,isLowMemory:true,isSlowConnection:r}}getSessionOptions(t){return{executionProviders:["wasm"],graphOptimizationLevel:"basic",logSeverityLevel:4,logVerbosityLevel:0,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1}}shouldUseSequentialLoading(){return true}}class c{getDeviceInfo(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=t.connection||t.mozConnection||t.webkitConnection;const r=i&&(i.effectiveType==="slow-2g"||i.effectiveType==="2g");return{estimatedRAM:e,isLowMemory:false,isSlowConnection:r}}getSessionOptions(t){return{executionProviders:["webgl","wasm"],graphOptimizationLevel:"all",logSeverityLevel:t?2:4,logVerbosityLevel:0,enableCpuMemArena:true,enableMemPattern:true,executionMode:"parallel",interOpNumThreads:2,intraOpNumThreads:2}}shouldUseSequentialLoading(){return false}}class u{getDeviceInfo(){return{estimatedRAM:3,isLowMemory:true,isSlowConnection:false}}getSessionOptions(t){return{executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,logVerbosityLevel:0,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1}}shouldUseSequentialLoading(){return true}}class l{static createStrategy(){const t=navigator;const e=navigator.userAgent;const i=/iPad|iPhone|iPod/.test(e);if(i){return new u}const r=t.deviceMemory||t.hardwareConcurrency||4;const n=r<=4;if(n){return new a}else{return new c}}}class f{debug;useDocumentClassification;useDocumentDetector;session;mobileNetSession;mobileNetClassMap;modelLoaded=false;deviceStrategy;MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v2.onnx";MOBILENET_MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/squeezenet_new_fp32.onnx";MOBILENET_CLASSES_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";INPUT_SIZE=320;CONFIDENCE_THRESHOLD=.6;preprocessCanvas;preprocessCtx;captureCanvas;static canvasPool=new Map;static MAX_POOL_SIZE=5;constructor(t=false,e=false,i=true){this.debug=t;this.useDocumentClassification=e;this.useDocumentDetector=i;this.deviceStrategy=l.createStrategy();this.initializeCanvasPool()}async loadModel(){if(this.modelLoaded||this.session){return}if(!this.useDocumentDetector){this.modelLoaded=true;return}try{const t=this.deviceStrategy.getSessionOptions(this.debug);try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH,t)}catch(t){const e=t.message.includes("failed to allocate a buffer")||t.message.includes("Out of memory")||t.message.includes("RangeError: Out of memory")||t.message.includes("no available backend found");if(e){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1,enableProfiling:false,sessionLogSeverityLevel:4,sessionLogVerbosityLevel:0};try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH,t)}catch(t){throw new Error(`no available backend found. ERR: [wasm] RangeError: Out of memory`)}}else{throw t}}this.modelLoaded=true}catch(t){throw t}}async loadClassificationModel(){if(!this.useDocumentClassification){return}try{try{const t=await fetch(this.MOBILENET_CLASSES_PATH);if(t.ok){this.mobileNetClassMap=await t.json()}}catch(t){this.mobileNetClassMap={0:"document",1:"id_card",2:"passport",3:"license",4:"other"}}const t=this.deviceStrategy.getSessionOptions(this.debug);try{this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,t)}catch(t){const e=t.message.includes("failed to allocate a buffer")||t.message.includes("Out of memory")||t.message.includes("RangeError: Out of memory")||t.message.includes("no available backend found");if(e){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1,enableProfiling:false,sessionLogSeverityLevel:4,sessionLogVerbosityLevel:0};try{this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,t)}catch(t){throw new Error(`no available backend found. ERR: [wasm] RangeError: Out of memory`)}}else{throw t}}}catch(t){throw t}}isModelLoaded(){if(!this.useDocumentDetector){return this.modelLoaded}return this.modelLoaded&&!!this.session}preprocess(t){if(!this.preprocessCanvas||!this.preprocessCtx){this.initializeCanvasPool()}this.preprocessCtx.clearRect(0,0,this.INPUT_SIZE,this.INPUT_SIZE);this.preprocessCtx.drawImage(t,0,0,this.INPUT_SIZE,this.INPUT_SIZE);const e=this.preprocessCtx.getImageData(0,0,this.INPUT_SIZE,this.INPUT_SIZE);const[i,r,n]=[[],[],[]];const{data:s}=e;for(let t=0;t<s.length;t+=4){i.push(s[t]/255);r.push(s[t+1]/255);n.push(s[t+2]/255)}const o=new Float32Array(i.concat(r,n));const a=new Uint16Array(o.length);for(let t=0;t<o.length;t++){a[t]=this.float32ToFloat16(o[t])}return new window.ort.Tensor("float16",a,[1,3,this.INPUT_SIZE,this.INPUT_SIZE])}async runInference(t){if(!this.useDocumentDetector){return[]}if(!this.session){throw new Error("Detection model not loaded")}const e={[this.session.inputNames[0]]:t};const i=await this.session.run(e);const r=i[this.session.outputNames[0]].data;const n=[];for(let t=0;t<r.length;t+=6){const[e,i,s,o,a,c]=r.slice(t,t+6);if(a>this.CONFIDENCE_THRESHOLD){n.push({x:e,y:i,w:s-e,h:o-i,score:a,classId:c})}}return n}async classifyDocument(t){if(!this.mobileNetSession||!this.mobileNetClassMap){return null}try{const e=this.preprocessMobileNet(t);const i={[this.mobileNetSession.inputNames[0]]:e};const r=await this.mobileNetSession.run(i);const n=r[Object.keys(r)[0]].data;const s=n.reduce(((t,e,i,r)=>e>r[t]?i:t),0);const o=n[s];const a=this.mobileNetClassMap[s.toString()]||"unknown";return{class:a,confidence:o,classIndex:s}}catch(t){return null}}checkSideAlignment(t,e){const{INPUT_SIZE:i,ID1_ASPECT_RATIO:r,shouldMirrorVideo:n,alignmentTolerance:s,maskSize:o,videoRef:a}=e;if(!a){return{top:false,right:false,bottom:false,left:false}}const c=a.videoWidth;const u=a.videoHeight;if(c===0||u===0){return{top:false,right:false,bottom:false,left:false}}const l=c/u;const f=1;let h,d;if(l>f){h=i;d=i/l}else{d=i;h=i*l}const p=d*r;let m,b;const v=o/100;if(p<=h){b=d*v;m=b*r}else{m=h*v;b=m/r}const w=m*(i/h);const g=b*(i/d);const y=i/2;const x=i/2;const k=y-w/2;const S=y+w/2;const _=x-g/2;const T=x+g/2;let E=t.x;let M=t.x+t.w;const C=t.y;const A=t.y+t.h;if(n){const t=E;const e=M;E=i-e;M=i-t}const P=s;const I=Math.abs(C-_)<=P;const O=Math.abs(M-S)<=P;const L=Math.abs(A-T)<=P;const j=Math.abs(E-k)<=P;return{top:I&&j,right:I&&O,bottom:L&&j,left:L&&O}}isCardInFrame(t){const e=t.x+t.w/2;const i=t.y+t.h/2;const r=this.INPUT_SIZE/2;const n=this.INPUT_SIZE/2;const s=40;const o=30;const a=Math.abs(e-r)<s&&Math.abs(i-n)<o;const c=t.w>150&&t.w<300&&t.h>90&&t.h<200;return a&&c}areAllSidesAligned(t){return t.top&&t.right&&t.bottom&&t.left}cleanup(){this.cleanupCanvasPool();if(this.session){this.session.release?.();this.session=undefined}if(this.mobileNetSession){this.mobileNetSession.release?.();this.mobileNetSession=undefined}this.mobileNetClassMap=undefined;this.modelLoaded=false}initializeCanvasPool(){this.preprocessCanvas=document.createElement("canvas");this.preprocessCanvas.width=this.INPUT_SIZE;this.preprocessCanvas.height=this.INPUT_SIZE;this.preprocessCtx=this.preprocessCanvas.getContext("2d",{alpha:false,willReadFrequently:true});this.captureCanvas=document.createElement("canvas")}cleanupCanvasPool(){if(this.preprocessCanvas){this.preprocessCtx=undefined;this.preprocessCanvas=undefined}if(this.captureCanvas){this.captureCanvas=undefined}}float32ToFloat16(t){const e=new ArrayBuffer(4);const i=new DataView(e);i.setFloat32(0,t,true);const r=i.getUint32(0,true);const n=r>>31&1;const s=r>>23&255;const o=r&8388607;let a=s-127+15;if(s===0){a=0}else if(s===255){a=31}else if(a>=31){a=31;return n<<15|a<<10}else if(a<=0){return n<<15}return n<<15|a<<10|o>>13}preprocessMobileNet(t){const e=this.getCanvas(224,224);const i=e.getContext("2d");i.clearRect(0,0,224,224);i.drawImage(t,0,0,224,224);const r=i.getImageData(0,0,224,224);const n=r.data;const s=224*224;const o=new Float32Array(3*s);for(let t=0;t<s;t++){o[t]=n[t*4+0]/255;o[s+t]=n[t*4+1]/255;o[2*s+t]=n[t*4+2]/255}this.returnCanvas(e);return new window.ort.Tensor("float32",o,[1,3,224,224])}getCanvas(t,e){const i=`${t}x${e}`;if(!f.canvasPool.has(i)){f.canvasPool.set(i,[])}const r=f.canvasPool.get(i);let n=r.pop();if(!n){n=document.createElement("canvas");n.width=t;n.height=e}else{const i=n.getContext("2d");i.clearRect(0,0,t,e)}return n}returnCanvas(t){const e=`${t.width}x${t.height}`;if(!f.canvasPool.has(e)){f.canvasPool.set(e,[])}const i=f.canvasPool.get(e);if(i.length<f.MAX_POOL_SIZE){i.push(t)}}static clearCanvasPools(){f.canvasPool.clear()}getPoolStats(){const t={};f.canvasPool.forEach(((e,i)=>{t[i]=e.length}));return t}}var h=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};var d="1.9.0";var p=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function m(t){var e=new Set([t]);var i=new Set;var r=t.match(p);if(!r){return function(){return false}}var n={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(n.prerelease!=null){return function e(i){return i===t}}function s(t){i.add(t);return false}function o(t){e.add(t);return true}return function t(r){if(e.has(r)){return true}if(i.has(r)){return false}var a=r.match(p);if(!a){return s(r)}var c={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(c.prerelease!=null){return s(r)}if(n.major!==c.major){return s(r)}if(n.major===0){if(n.minor===c.minor&&n.patch<=c.patch){return o(r)}return s(r)}if(n.minor<=c.minor){return o(r)}return s(r)}}var b=m(d);var v=d.split(".")[0];var w=Symbol.for("opentelemetry.js.api."+v);var g=h;function y(t,e,i,r){var n;if(r===void 0){r=false}var s=g[w]=(n=g[w])!==null&&n!==void 0?n:{version:d};if(!r&&s[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);i.error(o.stack||o.message);return false}if(s.version!==d){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+d);i.error(o.stack||o.message);return false}s[t]=e;i.debug("@opentelemetry/api: Registered a global for "+t+" v"+d+".");return true}function x(t){var e,i;var r=(e=g[w])===null||e===void 0?void 0:e.version;if(!r||!b(r)){return}return(i=g[w])===null||i===void 0?void 0:i[t]}function k(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+d+".");var i=g[w];if(i){delete i[t]}}var S=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var _=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++){if(s||!(r in e)){if(!s)s=Array.prototype.slice.call(e,0,r);s[r]=e[r]}}return t.concat(s||Array.prototype.slice.call(e))};var T=function(){function t(t){this._namespace=t.namespace||"DiagComponentLogger"}t.prototype.debug=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return E("debug",this._namespace,t)};t.prototype.error=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return E("error",this._namespace,t)};t.prototype.info=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return E("info",this._namespace,t)};t.prototype.warn=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return E("warn",this._namespace,t)};t.prototype.verbose=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return E("verbose",this._namespace,t)};return t}();function E(t,e,i){var r=x("diag");if(!r){return}i.unshift(e);return r[t].apply(r,_([],S(i),false))}var M;(function(t){t[t["NONE"]=0]="NONE";t[t["ERROR"]=30]="ERROR";t[t["WARN"]=50]="WARN";t[t["INFO"]=60]="INFO";t[t["DEBUG"]=70]="DEBUG";t[t["VERBOSE"]=80]="VERBOSE";t[t["ALL"]=9999]="ALL"})(M||(M={}));function C(t,e){if(t<M.NONE){t=M.NONE}else if(t>M.ALL){t=M.ALL}e=e||{};function i(i,r){var n=e[i];if(typeof n==="function"&&t>=r){return n.bind(e)}return function(){}}return{error:i("error",M.ERROR),warn:i("warn",M.WARN),info:i("info",M.INFO),debug:i("debug",M.DEBUG),verbose:i("verbose",M.VERBOSE)}}var A=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var P=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++){if(s||!(r in e)){if(!s)s=Array.prototype.slice.call(e,0,r);s[r]=e[r]}}return t.concat(s||Array.prototype.slice.call(e))};var I="diag";var O=function(){function t(){function t(t){return function(){var e=[];for(var i=0;i<arguments.length;i++){e[i]=arguments[i]}var r=x("diag");if(!r)return;return r[t].apply(r,P([],A(e),false))}}var e=this;var i=function(t,i){var r,n,s;if(i===void 0){i={logLevel:M.INFO}}if(t===e){var o=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");e.error((r=o.stack)!==null&&r!==void 0?r:o.message);return false}if(typeof i==="number"){i={logLevel:i}}var a=x("diag");var c=C((n=i.logLevel)!==null&&n!==void 0?n:M.INFO,t);if(a&&!i.suppressOverrideMessage){var u=(s=(new Error).stack)!==null&&s!==void 0?s:"<failed to generate stacktrace>";a.warn("Current logger will be overwritten from "+u);c.warn("Current logger will overwrite one already registered from "+u)}return y("diag",c,e,true)};e.setLogger=i;e.disable=function(){k(I,e)};e.createComponentLogger=function(t){return new T(t)};e.verbose=t("verbose");e.debug=t("debug");e.info=t("info");e.warn=t("warn");e.error=t("error")}t.instance=function(){if(!this._instance){this._instance=new t}return this._instance};return t}();var L=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var j=undefined&&undefined.__values||function(t){var e=typeof Symbol==="function"&&Symbol.iterator,i=e&&t[e],r=0;if(i)return i.call(t);if(t&&typeof t.length==="number")return{next:function(){if(t&&r>=t.length)t=void 0;return{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};var N=function(){function t(t){this._entries=t?new Map(t):new Map}t.prototype.getEntry=function(t){var e=this._entries.get(t);if(!e){return undefined}return Object.assign({},e)};t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map((function(t){var e=L(t,2),i=e[0],r=e[1];return[i,r]}))};t.prototype.setEntry=function(e,i){var r=new t(this._entries);r._entries.set(e,i);return r};t.prototype.removeEntry=function(e){var i=new t(this._entries);i._entries.delete(e);return i};t.prototype.removeEntries=function(){var e,i;var r=[];for(var n=0;n<arguments.length;n++){r[n]=arguments[n]}var s=new t(this._entries);try{for(var o=j(r),a=o.next();!a.done;a=o.next()){var c=a.value;s._entries.delete(c)}}catch(t){e={error:t}}finally{try{if(a&&!a.done&&(i=o.return))i.call(o)}finally{if(e)throw e.error}}return s};t.prototype.clear=function(){return new t};return t}();var R=Symbol("BaggageEntryMetadata");var z=O.instance();function $(t){if(t===void 0){t={}}return new N(new Map(Object.entries(t)))}function D(t){if(typeof t!=="string"){z.error("Cannot create baggage metadata from unknown type: "+typeof t);t=""}return{__TYPE__:R,toString:function(){return t}}}function F(t){return Symbol.for(t)}var U=function(){function t(e){var i=this;i._currentContext=e?new Map(e):new Map;i.getValue=function(t){return i._currentContext.get(t)};i.setValue=function(e,r){var n=new t(i._currentContext);n._currentContext.set(e,r);return n};i.deleteValue=function(e){var r=new t(i._currentContext);r._currentContext.delete(e);return r}}return t}();var B=new U;var q=undefined&&undefined.__extends||function(){var t=function(e,i){t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i))t[i]=e[i]};return t(e,i)};return function(e,i){if(typeof i!=="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(e,i);function r(){this.constructor=e}e.prototype=i===null?Object.create(i):(r.prototype=i.prototype,new r)}}();var V=function(){function t(){}t.prototype.createGauge=function(t,e){return it};t.prototype.createHistogram=function(t,e){return rt};t.prototype.createCounter=function(t,e){return et};t.prototype.createUpDownCounter=function(t,e){return nt};t.prototype.createObservableGauge=function(t,e){return ot};t.prototype.createObservableCounter=function(t,e){return st};t.prototype.createObservableUpDownCounter=function(t,e){return at};t.prototype.addBatchObservableCallback=function(t,e){};t.prototype.removeBatchObservableCallback=function(t){};return t}();var H=function(){function t(){}return t}();var G=function(t){q(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.add=function(t,e){};return e}(H);var Z=function(t){q(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.add=function(t,e){};return e}(H);var W=function(t){q(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.record=function(t,e){};return e}(H);var X=function(t){q(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.record=function(t,e){};return e}(H);var Y=function(){function t(){}t.prototype.addCallback=function(t){};t.prototype.removeCallback=function(t){};return t}();var J=function(t){q(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Y);var K=function(t){q(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Y);var Q=function(t){q(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Y);var tt=new V;var et=new G;var it=new W;var rt=new X;var nt=new Z;var st=new J;var ot=new K;var at=new Q;function ct(){return tt}var ut;(function(t){t[t["INT"]=0]="INT";t[t["DOUBLE"]=1]="DOUBLE"})(ut||(ut={}));var lt={get:function(t,e){if(t==null){return undefined}return t[e]},keys:function(t){if(t==null){return[]}return Object.keys(t)}};var ft={set:function(t,e,i){if(t==null){return}t[e]=i}};var ht=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var dt=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++){if(s||!(r in e)){if(!s)s=Array.prototype.slice.call(e,0,r);s[r]=e[r]}}return t.concat(s||Array.prototype.slice.call(e))};var pt=function(){function t(){}t.prototype.active=function(){return B};t.prototype.with=function(t,e,i){var r=[];for(var n=3;n<arguments.length;n++){r[n-3]=arguments[n]}return e.call.apply(e,dt([i],ht(r),false))};t.prototype.bind=function(t,e){return e};t.prototype.enable=function(){return this};t.prototype.disable=function(){return this};return t}();var mt=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var bt=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++){if(s||!(r in e)){if(!s)s=Array.prototype.slice.call(e,0,r);s[r]=e[r]}}return t.concat(s||Array.prototype.slice.call(e))};var vt="context";var wt=new pt;var gt=function(){function t(){}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalContextManager=function(t){return y(vt,t,O.instance())};t.prototype.active=function(){return this._getContextManager().active()};t.prototype.with=function(t,e,i){var r;var n=[];for(var s=3;s<arguments.length;s++){n[s-3]=arguments[s]}return(r=this._getContextManager()).with.apply(r,bt([t,e,i],mt(n),false))};t.prototype.bind=function(t,e){return this._getContextManager().bind(t,e)};t.prototype._getContextManager=function(){return x(vt)||wt};t.prototype.disable=function(){this._getContextManager().disable();k(vt,O.instance())};return t}();var yt;(function(t){t[t["NONE"]=0]="NONE";t[t["SAMPLED"]=1]="SAMPLED"})(yt||(yt={}));var xt="0000000000000000";var kt="00000000000000000000000000000000";var St={traceId:kt,spanId:xt,traceFlags:yt.NONE};var _t=function(){function t(t){if(t===void 0){t=St}this._spanContext=t}t.prototype.spanContext=function(){return this._spanContext};t.prototype.setAttribute=function(t,e){return this};t.prototype.setAttributes=function(t){return this};t.prototype.addEvent=function(t,e){return this};t.prototype.addLink=function(t){return this};t.prototype.addLinks=function(t){return this};t.prototype.setStatus=function(t){return this};t.prototype.updateName=function(t){return this};t.prototype.end=function(t){};t.prototype.isRecording=function(){return false};t.prototype.recordException=function(t,e){};return t}();var Tt=F("OpenTelemetry Context Key SPAN");function Et(t){return t.getValue(Tt)||undefined}function Mt(){return Et(gt.getInstance().active())}function Ct(t,e){return t.setValue(Tt,e)}function At(t){return t.deleteValue(Tt)}function Pt(t,e){return Ct(t,new _t(e))}function It(t){var e;return(e=Et(t))===null||e===void 0?void 0:e.spanContext()}var Ot=/^([0-9a-f]{32})$/i;var Lt=/^[0-9a-f]{16}$/i;function jt(t){return Ot.test(t)&&t!==kt}function Nt(t){return Lt.test(t)&&t!==xt}function Rt(t){return jt(t.traceId)&&Nt(t.spanId)}function zt(t){return new _t(t)}var $t=gt.getInstance();var Dt=function(){function t(){}t.prototype.startSpan=function(t,e,i){if(i===void 0){i=$t.active()}var r=Boolean(e===null||e===void 0?void 0:e.root);if(r){return new _t}var n=i&&It(i);if(Ft(n)&&Rt(n)){return new _t(n)}else{return new _t}};t.prototype.startActiveSpan=function(t,e,i,r){var n;var s;var o;if(arguments.length<2){return}else if(arguments.length===2){o=e}else if(arguments.length===3){n=e;o=i}else{n=e;s=i;o=r}var a=s!==null&&s!==void 0?s:$t.active();var c=this.startSpan(t,n,a);var u=Ct(a,c);return $t.with(u,o,undefined,c)};return t}();function Ft(t){return typeof t==="object"&&typeof t["spanId"]==="string"&&typeof t["traceId"]==="string"&&typeof t["traceFlags"]==="number"}var Ut=new Dt;var Bt=function(){function t(t,e,i,r){this._provider=t;this.name=e;this.version=i;this.options=r}t.prototype.startSpan=function(t,e,i){return this._getTracer().startSpan(t,e,i)};t.prototype.startActiveSpan=function(t,e,i,r){var n=this._getTracer();return Reflect.apply(n.startActiveSpan,n,arguments)};t.prototype._getTracer=function(){if(this._delegate){return this._delegate}var t=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!t){return Ut}this._delegate=t;return this._delegate};return t}();var qt=function(){function t(){}t.prototype.getTracer=function(t,e,i){return new Dt};return t}();var Vt=new qt;var Ht=function(){function t(){}t.prototype.getTracer=function(t,e,i){var r;return(r=this.getDelegateTracer(t,e,i))!==null&&r!==void 0?r:new Bt(this,t,e,i)};t.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Vt};t.prototype.setDelegate=function(t){this._delegate=t};t.prototype.getDelegateTracer=function(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(t,e,i)};return t}();var Gt;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(Gt||(Gt={}));var Zt;(function(t){t[t["INTERNAL"]=0]="INTERNAL";t[t["SERVER"]=1]="SERVER";t[t["CLIENT"]=2]="CLIENT";t[t["PRODUCER"]=3]="PRODUCER";t[t["CONSUMER"]=4]="CONSUMER"})(Zt||(Zt={}));var Wt;(function(t){t[t["UNSET"]=0]="UNSET";t[t["OK"]=1]="OK";t[t["ERROR"]=2]="ERROR"})(Wt||(Wt={}));var Xt=gt.getInstance();var Yt=O.instance();var Jt=function(){function t(){}t.prototype.getMeter=function(t,e,i){return tt};return t}();var Kt=new Jt;var Qt="metrics";var te=function(){function t(){}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalMeterProvider=function(t){return y(Qt,t,O.instance())};t.prototype.getMeterProvider=function(){return x(Qt)||Kt};t.prototype.getMeter=function(t,e,i){return this.getMeterProvider().getMeter(t,e,i)};t.prototype.disable=function(){k(Qt,O.instance())};return t}();var ee=te.getInstance();var ie=function(){function t(){}t.prototype.inject=function(t,e){};t.prototype.extract=function(t,e){return t};t.prototype.fields=function(){return[]};return t}();var re=F("OpenTelemetry Baggage Key");function ne(t){return t.getValue(re)||undefined}function se(){return ne(gt.getInstance().active())}function oe(t,e){return t.setValue(re,e)}function ae(t){return t.deleteValue(re)}var ce="propagation";var ue=new ie;var le=function(){function t(){this.createBaggage=$;this.getBaggage=ne;this.getActiveBaggage=se;this.setBaggage=oe;this.deleteBaggage=ae}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalPropagator=function(t){return y(ce,t,O.instance())};t.prototype.inject=function(t,e,i){if(i===void 0){i=ft}return this._getGlobalPropagator().inject(t,e,i)};t.prototype.extract=function(t,e,i){if(i===void 0){i=lt}return this._getGlobalPropagator().extract(t,e,i)};t.prototype.fields=function(){return this._getGlobalPropagator().fields()};t.prototype.disable=function(){k(ce,O.instance())};t.prototype._getGlobalPropagator=function(){return x(ce)||ue};return t}();var fe=le.getInstance();var he="trace";var de=function(){function t(){this._proxyTracerProvider=new Ht;this.wrapSpanContext=zt;this.isSpanContextValid=Rt;this.deleteSpan=At;this.getSpan=Et;this.getActiveSpan=Mt;this.getSpanContext=It;this.setSpan=Ct;this.setSpanContext=Pt}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalTracerProvider=function(t){var e=y(he,this._proxyTracerProvider,O.instance());if(e){this._proxyTracerProvider.setDelegate(t)}return e};t.prototype.getTracerProvider=function(){return x(he)||this._proxyTracerProvider};t.prototype.getTracer=function(t,e){return this.getTracerProvider().getTracer(t,e)};t.prototype.disable=function(){k(he,O.instance());this._proxyTracerProvider=new Ht};return t}();var pe=de.getInstance();const me=F("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function be(t){return t.setValue(me,true)}function ve(t){return t.getValue(me)===true}const we="=";const ge=";";const ye=",";const xe="baggage";const ke=180;const Se=4096;const _e=8192;function Te(t){return t.reduce(((t,e)=>{const i=`${t}${t!==""?ye:""}${e}`;return i.length>_e?t:i}),"")}function Ee(t){return t.getAllEntries().map((([t,e])=>{let i=`${encodeURIComponent(t)}=${encodeURIComponent(e.value)}`;if(e.metadata!==undefined){i+=ge+e.metadata.toString()}return i}))}function Me(t){const e=t.split(ge);if(e.length<=0)return;const i=e.shift();if(!i)return;const r=i.indexOf(we);if(r<=0)return;const n=decodeURIComponent(i.substring(0,r).trim());const s=decodeURIComponent(i.substring(r+1).trim());let o;if(e.length>0){o=D(e.join(ge))}return{key:n,value:s,metadata:o}}class Ce{inject(t,e,i){const r=fe.getBaggage(t);if(!r||ve(t))return;const n=Ee(r).filter((t=>t.length<=Se)).slice(0,ke);const s=Te(n);if(s.length>0){i.set(e,xe,s)}}extract(t,e,i){const r=i.get(e,xe);const n=Array.isArray(r)?r.join(ye):r;if(!n)return t;const s={};if(n.length===0){return t}const o=n.split(ye);o.forEach((t=>{const e=Me(t);if(e){const t={value:e.value};if(e.metadata){t.metadata=e.metadata}s[e.key]=t}}));if(Object.entries(s).length===0){return t}return fe.setBaggage(t,fe.createBaggage(s))}fields(){return[xe]}}function Ae(t){const e={};if(typeof t!=="object"||t==null){return e}for(const i in t){if(!Object.prototype.hasOwnProperty.call(t,i)){continue}if(!Pe(i)){Yt.warn(`Invalid attribute key: ${i}`);continue}const r=t[i];if(!Ie(r)){Yt.warn(`Invalid attribute value set for key: ${i}`);continue}if(Array.isArray(r)){e[i]=r.slice()}else{e[i]=r}}return e}function Pe(t){return typeof t==="string"&&t!==""}function Ie(t){if(t==null){return true}if(Array.isArray(t)){return Oe(t)}return Le(typeof t)}function Oe(t){let e;for(const i of t){if(i==null)continue;const t=typeof i;if(t===e){continue}if(!e){if(Le(t)){e=t;continue}return false}return false}return true}function Le(t){switch(t){case"number":case"boolean":case"string":return true}return false}function je(){return t=>{Yt.error(Ne(t))}}function Ne(t){if(typeof t==="string"){return t}else{return JSON.stringify(Re(t))}}function Re(t){const e={};let i=t;while(i!==null){Object.getOwnPropertyNames(i).forEach((t=>{if(e[t])return;const r=i[t];if(r){e[t]=String(r)}}));i=Object.getPrototypeOf(i)}return e}let ze=je();function $e(t){try{ze(t)}catch{}}function De(t){return undefined}const Fe=performance;const Ue="2.2.0";const Be="exception.message";const qe="exception.stacktrace";const Ve="exception.type";const He="service.name";const Ge="telemetry.sdk.language";const Ze="webjs";const We="telemetry.sdk.name";const Xe="telemetry.sdk.version";const Ye="process.runtime.name";const Je={[We]:"opentelemetry",[Ye]:"browser",[Ge]:Ze,[Xe]:Ue};const Ke=9;const Qe=6;const ti=Math.pow(10,Qe);const ei=Math.pow(10,Ke);function ii(t){const e=t/1e3;const i=Math.trunc(e);const r=Math.round(t%1e3*ti);return[i,r]}function ri(){let t=Fe.timeOrigin;if(typeof t!=="number"){const e=Fe;t=e.timing&&e.timing.fetchStart}return t}function ni(t){const e=ii(ri());const i=ii(typeof t==="number"?t:Fe.now());return li(e,i)}function si(t,e){let i=e[0]-t[0];let r=e[1]-t[1];if(r<0){i-=1;r+=ei}return[i,r]}function oi(t){return t[0]*ei+t[1]}function ai(t){return t[0]*1e6+t[1]/1e3}function ci(t){return Array.isArray(t)&&t.length===2&&typeof t[0]==="number"&&typeof t[1]==="number"}function ui(t){return ci(t)||typeof t==="number"||t instanceof Date}function li(t,e){const i=[t[0]+e[0],t[1]+e[1]];if(i[1]>=ei){i[1]-=ei;i[0]+=1}return i}var fi;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(fi||(fi={}));class hi{_propagators;_fields;constructor(t={}){this._propagators=t.propagators??[];this._fields=Array.from(new Set(this._propagators.map((t=>typeof t.fields==="function"?t.fields():[])).reduce(((t,e)=>t.concat(e)),[])))}inject(t,e,i){for(const r of this._propagators){try{r.inject(t,e,i)}catch(t){Yt.warn(`Failed to inject with ${r.constructor.name}. Err: ${t.message}`)}}}extract(t,e,i){return this._propagators.reduce(((t,r)=>{try{return r.extract(t,e,i)}catch(t){Yt.warn(`Failed to extract with ${r.constructor.name}. Err: ${t.message}`)}return t}),t)}fields(){return this._fields.slice()}}const di="[_0-9a-z-*/]";const pi=`[a-z]${di}{0,255}`;const mi=`[a-z0-9]${di}{0,240}@[a-z]${di}{0,13}`;const bi=new RegExp(`^(?:${pi}|${mi})$`);const vi=/^[ -~]{0,255}[!-~]$/;const wi=/,|=/;function gi(t){return bi.test(t)}function yi(t){return vi.test(t)&&!wi.test(t)}const xi=32;const ki=512;const Si=",";const _i="=";class Ti{_internalState=new Map;constructor(t){if(t)this._parse(t)}set(t,e){const i=this._clone();if(i._internalState.has(t)){i._internalState.delete(t)}i._internalState.set(t,e);return i}unset(t){const e=this._clone();e._internalState.delete(t);return e}get(t){return this._internalState.get(t)}serialize(){return this._keys().reduce(((t,e)=>{t.push(e+_i+this.get(e));return t}),[]).join(Si)}_parse(t){if(t.length>ki)return;this._internalState=t.split(Si).reverse().reduce(((t,e)=>{const i=e.trim();const r=i.indexOf(_i);if(r!==-1){const n=i.slice(0,r);const s=i.slice(r+1,e.length);if(gi(n)&&yi(s)){t.set(n,s)}}return t}),new Map);if(this._internalState.size>xi){this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,xi))}}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const t=new Ti;t._internalState=new Map(this._internalState);return t}}const Ei="traceparent";const Mi="tracestate";const Ci="00";const Ai="(?!ff)[\\da-f]{2}";const Pi="(?![0]{32})[\\da-f]{32}";const Ii="(?![0]{16})[\\da-f]{16}";const Oi="[\\da-f]{2}";const Li=new RegExp(`^\\s?(${Ai})-(${Pi})-(${Ii})-(${Oi})(-.*)?\\s?$`);function ji(t){const e=Li.exec(t);if(!e)return null;if(e[1]==="00"&&e[5])return null;return{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}class Ni{inject(t,e,i){const r=pe.getSpanContext(t);if(!r||ve(t)||!Rt(r))return;const n=`${Ci}-${r.traceId}-${r.spanId}-0${Number(r.traceFlags||yt.NONE).toString(16)}`;i.set(e,Ei,n);if(r.traceState){i.set(e,Mi,r.traceState.serialize())}}extract(t,e,i){const r=i.get(e,Ei);if(!r)return t;const n=Array.isArray(r)?r[0]:r;if(typeof n!=="string")return t;const s=ji(n);if(!s)return t;s.isRemote=true;const o=i.get(e,Mi);if(o){const t=Array.isArray(o)?o.join(","):o;s.traceState=new Ti(typeof t==="string"?t:undefined)}return pe.setSpanContext(t,s)}fields(){return[Ei,Mi]}}const Ri="[object Object]";const zi="[object Null]";const $i="[object Undefined]";const Di=Function.prototype;const Fi=Di.toString;const Ui=Fi.call(Object);const Bi=Object.getPrototypeOf;const qi=Object.prototype;const Vi=qi.hasOwnProperty;const Hi=Symbol?Symbol.toStringTag:undefined;const Gi=qi.toString;function Zi(t){if(!Wi(t)||Xi(t)!==Ri){return false}const e=Bi(t);if(e===null){return true}const i=Vi.call(e,"constructor")&&e.constructor;return typeof i=="function"&&i instanceof i&&Fi.call(i)===Ui}function Wi(t){return t!=null&&typeof t=="object"}function Xi(t){if(t==null){return t===undefined?$i:zi}return Hi&&Hi in Object(t)?Yi(t):Ji(t)}function Yi(t){const e=Vi.call(t,Hi),i=t[Hi];let r=false;try{t[Hi]=undefined;r=true}catch{}const n=Gi.call(t);if(r){if(e){t[Hi]=i}else{delete t[Hi]}}return n}function Ji(t){return Gi.call(t)}const Ki=20;function Qi(...t){let e=t.shift();const i=new WeakMap;while(t.length>0){e=er(e,t.shift(),0,i)}return e}function tr(t){if(rr(t)){return t.slice()}return t}function er(t,e,i=0,r){let n;if(i>Ki){return undefined}i++;if(or(t)||or(e)||nr(e)){n=tr(e)}else if(rr(t)){n=t.slice();if(rr(e)){for(let t=0,i=e.length;t<i;t++){n.push(tr(e[t]))}}else if(sr(e)){const t=Object.keys(e);for(let i=0,r=t.length;i<r;i++){const r=t[i];n[r]=tr(e[r])}}}else if(sr(t)){if(sr(e)){if(!ar(t,e)){return e}n=Object.assign({},t);const s=Object.keys(e);for(let o=0,a=s.length;o<a;o++){const a=s[o];const c=e[a];if(or(c)){if(typeof c==="undefined"){delete n[a]}else{n[a]=c}}else{const s=n[a];const o=c;if(ir(t,a,r)||ir(e,a,r)){delete n[a]}else{if(sr(s)&&sr(o)){const i=r.get(s)||[];const n=r.get(o)||[];i.push({obj:t,key:a});n.push({obj:e,key:a});r.set(s,i);r.set(o,n)}n[a]=er(n[a],c,i,r)}}}}else{n=e}}return n}function ir(t,e,i){const r=i.get(t[e])||[];for(let i=0,n=r.length;i<n;i++){const n=r[i];if(n.key===e&&n.obj===t){return true}}return false}function rr(t){return Array.isArray(t)}function nr(t){return typeof t==="function"}function sr(t){return!or(t)&&!rr(t)&&!nr(t)&&typeof t==="object"}function or(t){return typeof t==="string"||typeof t==="number"||typeof t==="boolean"||typeof t==="undefined"||t instanceof Date||t instanceof RegExp||t===null}function ar(t,e){if(!Zi(t)||!Zi(e)){return false}return true}class cr{_promise;_resolve;_reject;constructor(){this._promise=new Promise(((t,e)=>{this._resolve=t;this._reject=e}))}get promise(){return this._promise}resolve(t){this._resolve(t)}reject(t){this._reject(t)}}class ur{_callback;_that;_isCalled=false;_deferred=new cr;constructor(t,e){this._callback=t;this._that=e}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...t){if(!this._isCalled){this._isCalled=true;try{Promise.resolve(this._callback.call(this._that,...t)).then((t=>this._deferred.resolve(t)),(t=>this._deferred.reject(t)))}catch(t){this._deferred.reject(t)}}return this._deferred.promise}}function lr(t,e){return new Promise((i=>{Xt.with(be(Xt.active()),(()=>{t.export(e,(t=>{i(t)}))}))}))}const fr={_export:lr};function hr(){return"unknown_service"}const dr=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";class pr{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,e){const i=new pr({},e);i._rawAttributes=vr(t);i._asyncAttributesPending=t.filter((([t,e])=>dr(e))).length>0;return i}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(dr(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=vr(this._rawAttributes);this._schemaUrl=wr(e?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(!this.asyncAttributesPending){return}for(let t=0;t<this._rawAttributes.length;t++){const[e,i]=this._rawAttributes[t];this._rawAttributes[t]=[e,dr(i)?await i:i]}this._asyncAttributesPending=false}get attributes(){if(this.asyncAttributesPending){Yt.error("Accessing resource attributes before async attributes settled")}if(this._memoizedAttributes){return this._memoizedAttributes}const t={};for(const[e,i]of this._rawAttributes){if(dr(i)){Yt.debug(`Unsettled resource attribute ${e} skipped`);continue}if(i!=null){t[e]??=i}}if(!this._asyncAttributesPending){this._memoizedAttributes=t}return t}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;const e=gr(this,t);const i=e?{schemaUrl:e}:undefined;return pr.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],i)}}function mr(t,e){return pr.FromAttributeList(Object.entries(t),e)}function br(){return mr({[He]:hr(),[Ge]:Je[Ge],[We]:Je[We],[Xe]:Je[Xe]})}function vr(t){return t.map((([t,e])=>{if(dr(e)){return[t,e.catch((e=>{Yt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function wr(t){if(typeof t==="string"||t===undefined){return t}Yt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t);return undefined}function gr(t,e){const i=t?.schemaUrl;const r=e?.schemaUrl;const n=i===undefined||i==="";const s=r===undefined||r==="";if(n){return r}if(s){return i}if(i===r){return i}Yt.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',i,r);return undefined}const yr="exception";class xr{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:Wt.UNSET};endTime=[0,0];_ended=false;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(t){const e=Date.now();this._spanContext=t.spanContext;this._performanceStartTime=Fe.now();this._performanceOffset=e-(this._performanceStartTime+ri());this._startTimeProvided=t.startTime!=null;this._spanLimits=t.spanLimits;this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0;this._spanProcessor=t.spanProcessor;this.name=t.name;this.parentSpanContext=t.parentSpanContext;this.kind=t.kind;this.links=t.links||[];this.startTime=this._getTime(t.startTime??e);this.resource=t.resource;this.instrumentationScope=t.scope;if(t.attributes!=null){this.setAttributes(t.attributes)}this._spanProcessor.onStart(this,t.context)}spanContext(){return this._spanContext}setAttribute(t,e){if(e==null||this._isSpanEnded())return this;if(t.length===0){Yt.warn(`Invalid attribute key: ${t}`);return this}if(!Ie(e)){Yt.warn(`Invalid attribute value set for key: ${t}`);return this}const{attributeCountLimit:i}=this._spanLimits;if(i!==undefined&&Object.keys(this.attributes).length>=i&&!Object.prototype.hasOwnProperty.call(this.attributes,t)){this._droppedAttributesCount++;return this}this.attributes[t]=this._truncateToSize(e);return this}setAttributes(t){for(const[e,i]of Object.entries(t)){this.setAttribute(e,i)}return this}addEvent(t,e,i){if(this._isSpanEnded())return this;const{eventCountLimit:r}=this._spanLimits;if(r===0){Yt.warn("No events allowed.");this._droppedEventsCount++;return this}if(r!==undefined&&this.events.length>=r){if(this._droppedEventsCount===0){Yt.debug("Dropping extra events.")}this.events.shift();this._droppedEventsCount++}if(ui(e)){if(!ui(i)){i=e}e=undefined}const n=Ae(e);this.events.push({name:t,attributes:n,time:this._getTime(i),droppedAttributesCount:0});return this}addLink(t){this.links.push(t);return this}addLinks(t){this.links.push(...t);return this}setStatus(t){if(this._isSpanEnded())return this;this.status={...t};if(this.status.message!=null&&typeof t.message!=="string"){Yt.warn(`Dropping invalid status.message of type '${typeof t.message}', expected 'string'`);delete this.status.message}return this}updateName(t){if(this._isSpanEnded())return this;this.name=t;return this}end(t){if(this._isSpanEnded()){Yt.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this._ended=true;this.endTime=this._getTime(t);this._duration=si(this.startTime,this.endTime);if(this._duration[0]<0){Yt.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime);this.endTime=this.startTime.slice();this._duration=[0,0]}if(this._droppedEventsCount>0){Yt.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`)}this._spanProcessor.onEnd(this)}_getTime(t){if(typeof t==="number"&&t<=Fe.now()){return ni(t+this._performanceOffset)}if(typeof t==="number"){return ii(t)}if(t instanceof Date){return ii(t.getTime())}if(ci(t)){return t}if(this._startTimeProvided){return ii(Date.now())}const e=Fe.now()-this._performanceStartTime;return li(this.startTime,ii(e))}isRecording(){return this._ended===false}recordException(t,e){const i={};if(typeof t==="string"){i[Be]=t}else if(t){if(t.code){i[Ve]=t.code.toString()}else if(t.name){i[Ve]=t.name}if(t.message){i[Be]=t.message}if(t.stack){i[qe]=t.stack}}if(i[Ve]||i[Be]){this.addEvent(yr,i,e)}else{Yt.warn(`Failed to record an exception ${t}`)}}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){const t=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);Yt.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,t)}return this._ended}_truncateToLimitUtil(t,e){if(t.length<=e){return t}return t.substring(0,e)}_truncateToSize(t){const e=this._attributeValueLengthLimit;if(e<=0){Yt.warn(`Attribute value limit must be positive, got ${e}`);return t}if(typeof t==="string"){return this._truncateToLimitUtil(t,e)}if(Array.isArray(t)){return t.map((t=>typeof t==="string"?this._truncateToLimitUtil(t,e):t))}return t}}var kr;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(kr||(kr={}));class Sr{shouldSample(){return{decision:kr.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class _r{shouldSample(){return{decision:kr.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class Tr{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(t){this._root=t.root;if(!this._root){$e(new Error("ParentBasedSampler must have a root sampler configured"));this._root=new _r}this._remoteParentSampled=t.remoteParentSampled??new _r;this._remoteParentNotSampled=t.remoteParentNotSampled??new Sr;this._localParentSampled=t.localParentSampled??new _r;this._localParentNotSampled=t.localParentNotSampled??new Sr}shouldSample(t,e,i,r,n,s){const o=pe.getSpanContext(t);if(!o||!Rt(o)){return this._root.shouldSample(t,e,i,r,n,s)}if(o.isRemote){if(o.traceFlags&yt.SAMPLED){return this._remoteParentSampled.shouldSample(t,e,i,r,n,s)}return this._remoteParentNotSampled.shouldSample(t,e,i,r,n,s)}if(o.traceFlags&yt.SAMPLED){return this._localParentSampled.shouldSample(t,e,i,r,n,s)}return this._localParentNotSampled.shouldSample(t,e,i,r,n,s)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}class Er{_ratio;_upperBound;constructor(t=0){this._ratio=t;this._ratio=this._normalize(t);this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(t,e){return{decision:jt(e)&&this._accumulate(e)<this._upperBound?kr.RECORD_AND_SAMPLED:kr.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(t){if(typeof t!=="number"||isNaN(t))return 0;return t>=1?1:t<=0?0:t}_accumulate(t){let e=0;for(let i=0;i<t.length/8;i++){const r=i*8;const n=parseInt(t.slice(r,r+8),16);e=(e^n)>>>0}return e}}var Mr;(function(t){t["AlwaysOff"]="always_off";t["AlwaysOn"]="always_on";t["ParentBasedAlwaysOff"]="parentbased_always_off";t["ParentBasedAlwaysOn"]="parentbased_always_on";t["ParentBasedTraceIdRatio"]="parentbased_traceidratio";t["TraceIdRatio"]="traceidratio"})(Mr||(Mr={}));const Cr=1;function Ar(){return{sampler:Pr(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function Pr(){const t=Mr.ParentBasedAlwaysOn;switch(t){case Mr.AlwaysOn:return new _r;case Mr.AlwaysOff:return new Sr;case Mr.ParentBasedAlwaysOn:return new Tr({root:new _r});case Mr.ParentBasedAlwaysOff:return new Tr({root:new Sr});case Mr.TraceIdRatio:return new Er(Ir());case Mr.ParentBasedTraceIdRatio:return new Tr({root:new Er(Ir())});default:Yt.error(`OTEL_TRACES_SAMPLER value "${t}" invalid, defaulting to "${Mr.ParentBasedAlwaysOn}".`);return new Tr({root:new _r})}}function Ir(){{Yt.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${Cr}.`);return Cr}}const Or=128;const Lr=Infinity;function jr(t){const e={sampler:Pr()};const i=Ar();const r=Object.assign({},i,e,t);r.generalLimits=Object.assign({},i.generalLimits,t.generalLimits||{});r.spanLimits=Object.assign({},i.spanLimits,t.spanLimits||{});return r}function Nr(t){const e=Object.assign({},t.spanLimits);e.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??De()??De()??Or;e.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??De()??De()??Lr;return Object.assign({},t,{spanLimits:e})}class Rr{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=false;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(t,e){this._exporter=t;this._maxExportBatchSize=typeof e?.maxExportBatchSize==="number"?e.maxExportBatchSize:512;this._maxQueueSize=typeof e?.maxQueueSize==="number"?e.maxQueueSize:2048;this._scheduledDelayMillis=typeof e?.scheduledDelayMillis==="number"?e.scheduledDelayMillis:5e3;this._exportTimeoutMillis=typeof e?.exportTimeoutMillis==="number"?e.exportTimeoutMillis:3e4;this._shutdownOnce=new ur(this._shutdown,this);if(this._maxExportBatchSize>this._maxQueueSize){Yt.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");this._maxExportBatchSize=this._maxQueueSize}}forceFlush(){if(this._shutdownOnce.isCalled){return this._shutdownOnce.promise}return this._flushAll()}onStart(t,e){}onEnd(t){if(this._shutdownOnce.isCalled){return}if((t.spanContext().traceFlags&yt.SAMPLED)===0){return}this._addToBuffer(t)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then((()=>this.onShutdown())).then((()=>this._flushAll())).then((()=>this._exporter.shutdown()))}_addToBuffer(t){if(this._finishedSpans.length>=this._maxQueueSize){if(this._droppedSpansCount===0){Yt.debug("maxQueueSize reached, dropping spans")}this._droppedSpansCount++;return}if(this._droppedSpansCount>0){Yt.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);this._droppedSpansCount=0}this._finishedSpans.push(t);this._maybeStartTimer()}_flushAll(){return new Promise(((t,e)=>{const i=[];const r=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let t=0,e=r;t<e;t++){i.push(this._flushOneBatch())}Promise.all(i).then((()=>{t()})).catch(e)}))}_flushOneBatch(){this._clearTimer();if(this._finishedSpans.length===0){return Promise.resolve()}return new Promise(((t,e)=>{const i=setTimeout((()=>{e(new Error("Timeout"))}),this._exportTimeoutMillis);Xt.with(be(Xt.active()),(()=>{let r;if(this._finishedSpans.length<=this._maxExportBatchSize){r=this._finishedSpans;this._finishedSpans=[]}else{r=this._finishedSpans.splice(0,this._maxExportBatchSize)}const n=()=>this._exporter.export(r,(r=>{clearTimeout(i);if(r.code===fi.SUCCESS){t()}else{e(r.error??new Error("BatchSpanProcessor: span export failed"))}}));let s=null;for(let t=0,e=r.length;t<e;t++){const e=r[t];if(e.resource.asyncAttributesPending&&e.resource.waitForAsyncAttributes){s??=[];s.push(e.resource.waitForAsyncAttributes())}}if(s===null){n()}else{Promise.all(s).then(n,(t=>{$e(t);e(t)}))}}))}))}_maybeStartTimer(){if(this._isExporting)return;const t=()=>{this._isExporting=true;this._flushOneBatch().finally((()=>{this._isExporting=false;if(this._finishedSpans.length>0){this._clearTimer();this._maybeStartTimer()}})).catch((t=>{this._isExporting=false;$e(t)}))};if(this._finishedSpans.length>=this._maxExportBatchSize){return t()}if(this._timer!==undefined)return;this._timer=setTimeout((()=>t()),this._scheduledDelayMillis);if(typeof this._timer!=="number"){this._timer.unref()}}_clearTimer(){if(this._timer!==undefined){clearTimeout(this._timer);this._timer=undefined}}}class zr extends Rr{_visibilityChangeListener;_pageHideListener;constructor(t,e){super(t,e);this.onInit(e)}onInit(t){if(t?.disableAutoFlushOnDocumentHide!==true&&typeof document!=="undefined"){this._visibilityChangeListener=()=>{if(document.visibilityState==="hidden"){this.forceFlush().catch((t=>{$e(t)}))}};this._pageHideListener=()=>{this.forceFlush().catch((t=>{$e(t)}))};document.addEventListener("visibilitychange",this._visibilityChangeListener);document.addEventListener("pagehide",this._pageHideListener)}}onShutdown(){if(typeof document!=="undefined"){if(this._visibilityChangeListener){document.removeEventListener("visibilitychange",this._visibilityChangeListener)}if(this._pageHideListener){document.removeEventListener("pagehide",this._pageHideListener)}}}}const $r=8;const Dr=16;class Fr{generateTraceId=Br(Dr);generateSpanId=Br($r)}const Ur=Array(32);function Br(t){return function e(){for(let e=0;e<t*2;e++){Ur[e]=Math.floor(Math.random()*16)+48;if(Ur[e]>=58){Ur[e]+=39}}return String.fromCharCode.apply(null,Ur.slice(0,t*2))}}class qr{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(t,e,i,r){const n=jr(e);this._sampler=n.sampler;this._generalLimits=n.generalLimits;this._spanLimits=n.spanLimits;this._idGenerator=e.idGenerator||new Fr;this._resource=i;this._spanProcessor=r;this.instrumentationScope=t}startSpan(t,e={},i=Xt.active()){if(e.root){i=pe.deleteSpan(i)}const r=pe.getSpan(i);if(ve(i)){Yt.debug("Instrumentation suppressed, returning Noop Span");const t=pe.wrapSpanContext(St);return t}const n=r?.spanContext();const s=this._idGenerator.generateSpanId();let o;let a;let c;if(!n||!pe.isSpanContextValid(n)){a=this._idGenerator.generateTraceId()}else{a=n.traceId;c=n.traceState;o=n}const u=e.kind??Zt.INTERNAL;const l=(e.links??[]).map((t=>({context:t.context,attributes:Ae(t.attributes)})));const f=Ae(e.attributes);const h=this._sampler.shouldSample(i,a,t,u,f,l);c=h.traceState??c;const d=h.decision===Gt.RECORD_AND_SAMPLED?yt.SAMPLED:yt.NONE;const p={traceId:a,spanId:s,traceFlags:d,traceState:c};if(h.decision===Gt.NOT_RECORD){Yt.debug("Recording is off, propagating context in a non-recording span");const t=pe.wrapSpanContext(p);return t}const m=Ae(Object.assign(f,h.attributes));const b=new xr({resource:this._resource,scope:this.instrumentationScope,context:i,spanContext:p,name:t,kind:u,links:l,parentSpanContext:o,attributes:m,startTime:e.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits});return b}startActiveSpan(t,e,i,r){let n;let s;let o;if(arguments.length<2){return}else if(arguments.length===2){o=e}else if(arguments.length===3){n=e;o=i}else{n=e;s=i;o=r}const a=s??Xt.active();const c=this.startSpan(t,n,a);const u=pe.setSpan(a,c);return Xt.with(u,o,undefined,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class Vr{_spanProcessors;constructor(t){this._spanProcessors=t}forceFlush(){const t=[];for(const e of this._spanProcessors){t.push(e.forceFlush())}return new Promise((e=>{Promise.all(t).then((()=>{e()})).catch((t=>{$e(t||new Error("MultiSpanProcessor: forceFlush failed"));e()}))}))}onStart(t,e){for(const i of this._spanProcessors){i.onStart(t,e)}}onEnd(t){for(const e of this._spanProcessors){e.onEnd(t)}}shutdown(){const t=[];for(const e of this._spanProcessors){t.push(e.shutdown())}return new Promise(((e,i)=>{Promise.all(t).then((()=>{e()}),i)}))}}var Hr;(function(t){t[t["resolved"]=0]="resolved";t[t["timeout"]=1]="timeout";t[t["error"]=2]="error";t[t["unresolved"]=3]="unresolved"})(Hr||(Hr={}));class Gr{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(t={}){const e=Qi({},Ar(),Nr(t));this._resource=e.resource??br();this._config=Object.assign({},e,{resource:this._resource});const i=[];if(t.spanProcessors?.length){i.push(...t.spanProcessors)}this._activeSpanProcessor=new Vr(i)}getTracer(t,e,i){const r=`${t}@${e||""}:${i?.schemaUrl||""}`;if(!this._tracers.has(r)){this._tracers.set(r,new qr({name:t,version:e,schemaUrl:i?.schemaUrl},this._config,this._resource,this._activeSpanProcessor))}return this._tracers.get(r)}forceFlush(){const t=this._config.forceFlushTimeoutMillis;const e=this._activeSpanProcessor["_spanProcessors"].map((e=>new Promise((i=>{let r;const n=setTimeout((()=>{i(new Error(`Span processor did not completed within timeout period of ${t} ms`));r=Hr.timeout}),t);e.forceFlush().then((()=>{clearTimeout(n);if(r!==Hr.timeout){r=Hr.resolved;i(r)}})).catch((t=>{clearTimeout(n);r=Hr.error;i(t)}))}))));return new Promise(((t,i)=>{Promise.all(e).then((e=>{const r=e.filter((t=>t!==Hr.resolved));if(r.length>0){i(r)}else{t()}})).catch((t=>i([t])))}))}shutdown(){return this._activeSpanProcessor.shutdown()}}class Zr{_enabled=false;_currentContext=B;_bindFunction(t=B,e){const i=this;const r=function(...r){return i.with(t,(()=>e.apply(this,r)))};Object.defineProperty(r,"length",{enumerable:false,configurable:true,writable:false,value:e.length});return r}active(){return this._currentContext}bind(t,e){if(t===undefined){t=this.active()}if(typeof e==="function"){return this._bindFunction(t,e)}return e}disable(){this._currentContext=B;this._enabled=false;return this}enable(){if(this._enabled){return this}this._enabled=true;this._currentContext=B;return this}with(t,e,i,...r){const n=this._currentContext;this._currentContext=t||B;try{return e.call(i,...r)}finally{this._currentContext=n}}}function Wr(t){if(t===null){return}if(t===undefined){const t=new Zr;t.enable();Xt.setGlobalContextManager(t);return}t.enable();Xt.setGlobalContextManager(t)}function Xr(t){if(t===null){return}if(t===undefined){fe.setGlobalPropagator(new hi({propagators:[new Ni,new Ce]}));return}fe.setGlobalPropagator(t)}class Yr extends Gr{constructor(t={}){super(t)}register(t={}){pe.setGlobalTracerProvider(this);Xr(t.propagator);Wr(t.contextManager)}}function Jr(t,e){if(t.nodeType===Node.DOCUMENT_NODE){return"/"}const i=Qr(t,e);if(e&&i.indexOf("@id")>0){return i}let r="";if(t.parentNode){r+=Jr(t.parentNode,false)}r+=i;return r}function Kr(t){if(!t.parentNode){return 0}const e=[t.nodeType];if(t.nodeType===Node.CDATA_SECTION_NODE){e.push(Node.TEXT_NODE)}let i=Array.from(t.parentNode.childNodes);i=i.filter((i=>{const r=i.localName;return e.indexOf(i.nodeType)>=0&&r===t.localName}));if(i.length>=1){return i.indexOf(t)+1}return 0}function Qr(t,e){const i=t.nodeType;const r=Kr(t);let n="";if(i===Node.ELEMENT_NODE){const i=t.getAttribute("id");if(e&&i){return`//*[@id="${i}"]`}n=t.localName}else if(i===Node.TEXT_NODE||i===Node.CDATA_SECTION_NODE){n="text()"}else if(i===Node.COMMENT_NODE){n="comment()"}else{return""}if(n&&r>1){return`/${n}[${r}]`}return`/${n}`}class tn{_delegate;constructor(t){this._delegate=t}export(t,e){this._delegate.export(t,e)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class en extends Error{code;name="OTLPExporterError";data;constructor(t,e,i){super(t);this.data=i;this.code=e}}function rn(t){if(Number.isFinite(t)&&t>0){return t}throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${t}')`)}function nn(t){if(t==null){return undefined}return async()=>t}function sn(t,e,i){return{timeoutMillis:rn(t.timeoutMillis??e.timeoutMillis??i.timeoutMillis),concurrencyLimit:t.concurrencyLimit??e.concurrencyLimit??i.concurrencyLimit,compression:t.compression??e.compression??i.compression}}function on(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class an{_concurrencyLimit;_sendingPromises=[];constructor(t){this._concurrencyLimit=t}pushPromise(t){if(this.hasReachedLimit()){throw new Error("Concurrency Limit reached")}this._sendingPromises.push(t);const e=()=>{const e=this._sendingPromises.indexOf(t);void this._sendingPromises.splice(e,1)};t.then(e,e)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function cn(t){return new an(t.concurrencyLimit)}function un(t){return Object.prototype.hasOwnProperty.call(t,"partialSuccess")}function ln(){return{handleResponse(t){if(t==null||!un(t)||t.partialSuccess==null||Object.keys(t.partialSuccess).length===0){return}Yt.warn("Received Partial Success response:",JSON.stringify(t.partialSuccess))}}}class fn{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(t,e,i,r,n){this._transport=t;this._serializer=e;this._responseHandler=i;this._promiseQueue=r;this._timeout=n;this._diagLogger=Yt.createComponentLogger({namespace:"OTLPExportDelegate"})}export(t,e){this._diagLogger.debug("items to be sent",t);if(this._promiseQueue.hasReachedLimit()){e({code:fi.FAILED,error:new Error("Concurrent export limit reached")});return}const i=this._serializer.serializeRequest(t);if(i==null){e({code:fi.FAILED,error:new Error("Nothing to send")});return}this._promiseQueue.pushPromise(this._transport.send(i,this._timeout).then((t=>{if(t.status==="success"){if(t.data!=null){try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(t.data))}catch(e){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",e,t.data)}}e({code:fi.SUCCESS});return}else if(t.status==="failure"&&t.error){e({code:fi.FAILED,error:t.error});return}else if(t.status==="retryable"){e({code:fi.FAILED,error:new en("Export failed with retryable status")})}else{e({code:fi.FAILED,error:new en("Export failed with unknown error")})}}),(t=>e({code:fi.FAILED,error:t}))))}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started");await this.forceFlush();this._transport.shutdown()}}function hn(t,e){return new fn(t.transport,t.serializer,ln(),t.promiseHandler,e.timeout)}function dn(t,e,i){return hn({transport:i,serializer:e,promiseHandler:cn(t)},{timeout:t.timeoutMillis})}function pn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t["default"]:t}function mn(t){if(t>=48&&t<=57){return t-48}if(t>=97&&t<=102){return t-87}return t-55}function bn(t){const e=new Uint8Array(t.length/2);let i=0;for(let r=0;r<t.length;r+=2){const n=mn(t.charCodeAt(r));const s=mn(t.charCodeAt(r+1));e[i++]=n<<4|s}return e}function vn(t){const e=BigInt(1e9);return BigInt(Math.trunc(t[0]))*e+BigInt(Math.trunc(t[1]))}function wn(t){const e=Number(BigInt.asUintN(32,t));const i=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:i}}function gn(t){const e=vn(t);return wn(e)}function yn(t){const e=vn(t);return e.toString()}const xn=typeof BigInt!=="undefined"?yn:oi;function kn(t){return t}function Sn(t){if(t===undefined)return undefined;return bn(t)}const _n={encodeHrTime:gn,encodeSpanContext:bn,encodeOptionalSpanContext:Sn};function Tn(t){if(t===undefined){return _n}const e=t.useLongBits??true;const i=t.useHex??false;return{encodeHrTime:e?gn:xn,encodeSpanContext:i?kn:bn,encodeOptionalSpanContext:i?kn:Sn}}function En(t){const e={attributes:Cn(t.attributes),droppedAttributesCount:0};const i=t.schemaUrl;if(i&&i!=="")e.schemaUrl=i;return e}function Mn(t){return{name:t.name,version:t.version}}function Cn(t){return Object.keys(t).map((e=>An(e,t[e])))}function An(t,e){return{key:t,value:Pn(e)}}function Pn(t){const e=typeof t;if(e==="string")return{stringValue:t};if(e==="number"){if(!Number.isInteger(t))return{doubleValue:t};return{intValue:t}}if(e==="boolean")return{boolValue:t};if(t instanceof Uint8Array)return{bytesValue:t};if(Array.isArray(t))return{arrayValue:{values:t.map(Pn)}};if(e==="object"&&t!=null)return{kvlistValue:{values:Object.entries(t).map((([t,e])=>An(t,e)))}};return{}}var In;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(In||(In={}));var On;(function(t){t["COUNTER"]="COUNTER";t["GAUGE"]="GAUGE";t["HISTOGRAM"]="HISTOGRAM";t["UP_DOWN_COUNTER"]="UP_DOWN_COUNTER";t["OBSERVABLE_COUNTER"]="OBSERVABLE_COUNTER";t["OBSERVABLE_GAUGE"]="OBSERVABLE_GAUGE";t["OBSERVABLE_UP_DOWN_COUNTER"]="OBSERVABLE_UP_DOWN_COUNTER"})(On||(On={}));var Ln;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(Ln||(Ln={}));function jn(t){return t!==undefined&&t!==null}function Nn(t){let e=Object.keys(t);if(e.length===0)return"";e=e.sort();return JSON.stringify(e.map((e=>[e,t[e]])))}function Rn(t){return`${t.name}:${t.version??""}:${t.schemaUrl??""}`}class zn extends Error{constructor(t){super(t);Object.setPrototypeOf(this,zn.prototype)}}function $n(t,e){let i;const r=new Promise((function t(r,n){i=setTimeout((function t(){n(new zn("Operation timed out."))}),e)}));return Promise.race([t,r]).then((t=>{clearTimeout(i);return t}),(t=>{clearTimeout(i);throw t}))}async function Dn(t){return Promise.all(t.map((async t=>{try{const e=await t;return{status:"fulfilled",value:e}}catch(t){return{status:"rejected",reason:t}}})))}function Fn(t){return t.status==="rejected"}function Un(t,e){const i=[];t.forEach((t=>{i.push(...e(t))}));return i}function Bn(t,e){if(t.size!==e.size){return false}for(const i of t){if(!e.has(i)){return false}}return true}function qn(t,e){let i=0;let r=t.length-1;let n=t.length;while(r>=i){const s=i+Math.trunc((r-i)/2);if(t[s]<e){i=s+1}else{n=s;r=s-1}}return n}function Vn(t,e){return t.toLowerCase()===e.toLowerCase()}var Hn;(function(t){t[t["DROP"]=0]="DROP";t[t["SUM"]=1]="SUM";t[t["LAST_VALUE"]=2]="LAST_VALUE";t[t["HISTOGRAM"]=3]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=4]="EXPONENTIAL_HISTOGRAM"})(Hn||(Hn={}));class Gn{kind=Hn.DROP;createAccumulation(){return undefined}merge(t,e){return undefined}diff(t,e){return undefined}toMetricData(t,e,i,r){return undefined}}function Zn(t){const e=t.map((()=>0));e.push(0);return{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:false,min:Infinity,max:-Infinity}}class Wn{startTime;_boundaries;_recordMinMax;_current;constructor(t,e,i=true,r=Zn(e)){this.startTime=t;this._boundaries=e;this._recordMinMax=i;this._current=r}record(t){if(Number.isNaN(t)){return}this._current.count+=1;this._current.sum+=t;if(this._recordMinMax){this._current.min=Math.min(t,this._current.min);this._current.max=Math.max(t,this._current.max);this._current.hasMinMax=true}const e=qn(this._boundaries,t);this._current.buckets.counts[e]+=1}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Xn{_boundaries;_recordMinMax;kind=Hn.HISTOGRAM;constructor(t,e){this._boundaries=t;this._recordMinMax=e}createAccumulation(t){return new Wn(t,this._boundaries,this._recordMinMax)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();const n=i.buckets.counts;const s=r.buckets.counts;const o=new Array(n.length);for(let t=0;t<n.length;t++){o[t]=n[t]+s[t]}let a=Infinity;let c=-Infinity;if(this._recordMinMax){if(i.hasMinMax&&r.hasMinMax){a=Math.min(i.min,r.min);c=Math.max(i.max,r.max)}else if(i.hasMinMax){a=i.min;c=i.max}else if(r.hasMinMax){a=r.min;c=r.max}}return new Wn(t.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:i.count+r.count,sum:i.sum+r.sum,hasMinMax:this._recordMinMax&&(i.hasMinMax||r.hasMinMax),min:a,max:c})}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();const n=i.buckets.counts;const s=r.buckets.counts;const o=new Array(n.length);for(let t=0;t<n.length;t++){o[t]=s[t]-n[t]}return new Wn(e.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:r.count-i.count,sum:r.sum-i.sum,hasMinMax:false,min:Infinity,max:-Infinity})}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:Ln.HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===On.GAUGE||t.type===On.UP_DOWN_COUNTER||t.type===On.OBSERVABLE_GAUGE||t.type===On.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:r,value:{min:n.hasMinMax?n.min:undefined,max:n.hasMinMax?n.max:undefined,sum:!s?n.sum:undefined,buckets:n.buckets,count:n.count}}}))}}}class Yn{backing;indexBase;indexStart;indexEnd;constructor(t=new Jn,e=0,i=0,r=0){this.backing=t;this.indexBase=e;this.indexStart=i;this.indexEnd=r}get offset(){return this.indexStart}get length(){if(this.backing.length===0){return 0}if(this.indexEnd===this.indexStart&&this.at(0)===0){return 0}return this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},((t,e)=>this.at(e)))}at(t){const e=this.indexBase-this.indexStart;if(t<e){t+=this.backing.length}t-=e;return this.backing.countAt(t)}incrementBucket(t,e){this.backing.increment(t,e)}decrementBucket(t,e){this.backing.decrement(t,e)}trim(){for(let t=0;t<this.length;t++){if(this.at(t)!==0){this.indexStart+=t;break}else if(t===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}}for(let t=this.length-1;t>=0;t--){if(this.at(t)!==0){this.indexEnd-=this.length-t-1;break}}this._rotate()}downscale(t){this._rotate();const e=1+this.indexEnd-this.indexStart;const i=1<<t;let r=0;let n=0;for(let t=this.indexStart;t<=this.indexEnd;){let s=t%i;if(s<0){s+=i}for(let o=s;o<i&&r<e;o++){this._relocateBucket(n,r);r++;t++}n++}this.indexStart>>=t;this.indexEnd>>=t;this.indexBase=this.indexStart}clone(){return new Yn(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const t=this.indexBase-this.indexStart;if(t===0){return}else if(t>0){this.backing.reverse(0,this.backing.length);this.backing.reverse(0,t);this.backing.reverse(t,this.backing.length)}else{this.backing.reverse(0,this.backing.length);this.backing.reverse(0,this.backing.length+t)}this.indexBase=this.indexStart}_relocateBucket(t,e){if(t===e){return}this.incrementBucket(t,this.backing.emptyBucket(e))}}class Jn{_counts;constructor(t=[0]){this._counts=t}get length(){return this._counts.length}countAt(t){return this._counts[t]}growTo(t,e,i){const r=new Array(t).fill(0);r.splice(i,this._counts.length-e,...this._counts.slice(e));r.splice(0,e,...this._counts.slice(0,e));this._counts=r}reverse(t,e){const i=Math.floor((t+e)/2)-t;for(let r=0;r<i;r++){const i=this._counts[t+r];this._counts[t+r]=this._counts[e-r-1];this._counts[e-r-1]=i}}emptyBucket(t){const e=this._counts[t];this._counts[t]=0;return e}increment(t,e){this._counts[t]+=e}decrement(t,e){if(this._counts[t]>=e){this._counts[t]-=e}else{this._counts[t]=0}}clone(){return new Jn([...this._counts])}}const Kn=52;const Qn=2146435072;const ts=1048575;const es=1023;const is=-1023+1;const rs=es;const ns=Math.pow(2,-1022);function ss(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=(i&Qn)>>20;return r-es}function os(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=e.getUint32(4);const n=(i&ts)*Math.pow(2,32);return n+r}function as(t,e){if(t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)){return t}return t*Math.pow(2,e)}function cs(t){t--;t|=t>>1;t|=t>>2;t|=t>>4;t|=t>>8;t|=t>>16;t++;return t}class us extends Error{}class ls{_shift;constructor(t){this._shift=-t}mapToIndex(t){if(t<ns){return this._minNormalLowerBoundaryIndex()}const e=ss(t);const i=this._rightShift(os(t)-1,Kn);return e+i>>this._shift}lowerBoundary(t){const e=this._minNormalLowerBoundaryIndex();if(t<e){throw new us(`underflow: ${t} is < minimum lower boundary: ${e}`)}const i=this._maxNormalLowerBoundaryIndex();if(t>i){throw new us(`overflow: ${t} is > maximum lower boundary: ${i}`)}return as(1,t<<this._shift)}get scale(){if(this._shift===0){return 0}return-this._shift}_minNormalLowerBoundaryIndex(){let t=is>>this._shift;if(this._shift<2){t--}return t}_maxNormalLowerBoundaryIndex(){return rs>>this._shift}_rightShift(t,e){return Math.floor(t*Math.pow(2,-e))}}class fs{_scale;_scaleFactor;_inverseFactor;constructor(t){this._scale=t;this._scaleFactor=as(Math.LOG2E,t);this._inverseFactor=as(Math.LN2,-t)}mapToIndex(t){if(t<=ns){return this._minNormalLowerBoundaryIndex()-1}if(os(t)===0){const e=ss(t);return(e<<this._scale)-1}const e=Math.floor(Math.log(t)*this._scaleFactor);const i=this._maxNormalLowerBoundaryIndex();if(e>=i){return i}return e}lowerBoundary(t){const e=this._maxNormalLowerBoundaryIndex();if(t>=e){if(t===e){return 2*Math.exp((t-(1<<this._scale))/this._scaleFactor)}throw new us(`overflow: ${t} is > maximum lower boundary: ${e}`)}const i=this._minNormalLowerBoundaryIndex();if(t<=i){if(t===i){return ns}else if(t===i-1){return Math.exp((t+(1<<this._scale))/this._scaleFactor)/2}throw new us(`overflow: ${t} is < minimum lower boundary: ${i}`)}return Math.exp(t*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return is<<this._scale}_maxNormalLowerBoundaryIndex(){return(rs+1<<this._scale)-1}}const hs=-10;const ds=20;const ps=Array.from({length:31},((t,e)=>{if(e>10){return new fs(e-10)}return new ls(e-10)}));function ms(t){if(t>ds||t<hs){throw new us(`expected scale >= ${hs} && <= ${ds}, got: ${t}`)}return ps[t+10]}class bs{low;high;static combine(t,e){return new bs(Math.min(t.low,e.low),Math.max(t.high,e.high))}constructor(t,e){this.low=t;this.high=e}}const vs=20;const ws=160;const gs=2;class ys{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(t,e=ws,i=true,r=0,n=0,s=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new Yn,u=new Yn,l=ms(vs)){this.startTime=t;this._maxSize=e;this._recordMinMax=i;this._sum=r;this._count=n;this._zeroCount=s;this._min=o;this._max=a;this._positive=c;this._negative=u;this._mapping=l;if(this._maxSize<gs){Yt.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${gs}`);this._maxSize=gs}}record(t){this.updateByIncrement(t,1)}setStartTime(t){this.startTime=t}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){if(this._count===this._zeroCount){return 0}return this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(t,e){if(Number.isNaN(t)){return}if(t>this._max){this._max=t}if(t<this._min){this._min=t}this._count+=e;if(t===0){this._zeroCount+=e;return}this._sum+=t*e;if(t>0){this._updateBuckets(this._positive,t,e)}else{this._updateBuckets(this._negative,-t,e)}}merge(t){if(this._count===0){this._min=t.min;this._max=t.max}else if(t.count!==0){if(t.min<this.min){this._min=t.min}if(t.max>this.max){this._max=t.max}}this.startTime=t.startTime;this._sum+=t.sum;this._count+=t.count;this._zeroCount+=t.zeroCount;const e=this._minScale(t);this._downscale(this.scale-e);this._mergeBuckets(this.positive,t,t.positive,e);this._mergeBuckets(this.negative,t,t.negative,e)}diff(t){this._min=Infinity;this._max=-Infinity;this._sum-=t.sum;this._count-=t.count;this._zeroCount-=t.zeroCount;const e=this._minScale(t);this._downscale(this.scale-e);this._diffBuckets(this.positive,t,t.positive,e);this._diffBuckets(this.negative,t,t.negative,e)}clone(){return new ys(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(t,e,i){let r=this._mapping.mapToIndex(e);let n=false;let s=0;let o=0;if(t.length===0){t.indexStart=r;t.indexEnd=t.indexStart;t.indexBase=t.indexStart}else if(r<t.indexStart&&t.indexEnd-r>=this._maxSize){n=true;o=r;s=t.indexEnd}else if(r>t.indexEnd&&r-t.indexStart>=this._maxSize){n=true;o=t.indexStart;s=r}if(n){const t=this._changeScale(s,o);this._downscale(t);r=this._mapping.mapToIndex(e)}this._incrementIndexBy(t,r,i)}_incrementIndexBy(t,e,i){if(i===0){return}if(t.length===0){t.indexStart=t.indexEnd=t.indexBase=e}if(e<t.indexStart){const i=t.indexEnd-e;if(i>=t.backing.length){this._grow(t,i+1)}t.indexStart=e}else if(e>t.indexEnd){const i=e-t.indexStart;if(i>=t.backing.length){this._grow(t,i+1)}t.indexEnd=e}let r=e-t.indexBase;if(r<0){r+=t.backing.length}t.incrementBucket(r,i)}_grow(t,e){const i=t.backing.length;const r=t.indexBase-t.indexStart;const n=i-r;let s=cs(e);if(s>this._maxSize){s=this._maxSize}const o=s-r;t.backing.growTo(s,n,o)}_changeScale(t,e){let i=0;while(t-e>=this._maxSize){t>>=1;e>>=1;i++}return i}_downscale(t){if(t===0){return}if(t<0){throw new Error(`impossible change of scale: ${this.scale}`)}const e=this._mapping.scale-t;this._positive.downscale(t);this._negative.downscale(t);this._mapping=ms(e)}_minScale(t){const e=Math.min(this.scale,t.scale);const i=bs.combine(this._highLowAtScale(this.positive,this.scale,e),this._highLowAtScale(t.positive,t.scale,e));const r=bs.combine(this._highLowAtScale(this.negative,this.scale,e),this._highLowAtScale(t.negative,t.scale,e));return Math.min(e-this._changeScale(i.high,i.low),e-this._changeScale(r.high,r.low))}_highLowAtScale(t,e,i){if(t.length===0){return new bs(0,-1)}const r=e-i;return new bs(t.indexStart>>r,t.indexEnd>>r)}_mergeBuckets(t,e,i,r){const n=i.offset;const s=e.scale-r;for(let e=0;e<i.length;e++){this._incrementIndexBy(t,n+e>>s,i.at(e))}}_diffBuckets(t,e,i,r){const n=i.offset;const s=e.scale-r;for(let e=0;e<i.length;e++){const r=n+e>>s;let o=r-t.indexBase;if(o<0){o+=t.backing.length}t.decrementBucket(o,i.at(e))}t.trim()}}class xs{_maxSize;_recordMinMax;kind=Hn.EXPONENTIAL_HISTOGRAM;constructor(t,e){this._maxSize=t;this._recordMinMax=e}createAccumulation(t){return new ys(t,this._maxSize,this._recordMinMax)}merge(t,e){const i=e.clone();i.merge(t);return i}diff(t,e){const i=e.clone();i.diff(t);return i}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:Ln.EXPONENTIAL_HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===On.GAUGE||t.type===On.UP_DOWN_COUNTER||t.type===On.OBSERVABLE_GAUGE||t.type===On.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:r,value:{min:n.hasMinMax?n.min:undefined,max:n.hasMinMax?n.max:undefined,sum:!s?n.sum:undefined,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},count:n.count,scale:n.scale,zeroCount:n.zeroCount}}}))}}}class ks{startTime;_current;sampleTime;constructor(t,e=0,i=[0,0]){this.startTime=t;this._current=e;this.sampleTime=i}record(t){this._current=t;this.sampleTime=ii(Date.now())}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Ss{kind=Hn.LAST_VALUE;createAccumulation(t){return new ks(t)}merge(t,e){const i=ai(e.sampleTime)>=ai(t.sampleTime)?e:t;return new ks(t.startTime,i.toPointValue(),i.sampleTime)}diff(t,e){const i=ai(e.sampleTime)>=ai(t.sampleTime)?e:t;return new ks(e.startTime,i.toPointValue(),i.sampleTime)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:Ln.GAUGE,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()})))}}}class _s{startTime;monotonic;_current;reset;constructor(t,e,i=0,r=false){this.startTime=t;this.monotonic=e;this._current=i;this.reset=r}record(t){if(this.monotonic&&t<0){return}this._current+=t}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Ts{monotonic;kind=Hn.SUM;constructor(t){this.monotonic=t}createAccumulation(t){return new _s(t,this.monotonic)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();if(e.reset){return new _s(e.startTime,this.monotonic,r,e.reset)}return new _s(t.startTime,this.monotonic,i+r)}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();if(this.monotonic&&i>r){return new _s(e.startTime,this.monotonic,r,true)}return new _s(e.startTime,this.monotonic,r-i)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:Ln.SUM,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()}))),isMonotonic:this.monotonic}}}class Es{static DEFAULT_INSTANCE=new Gn;createAggregator(t){return Es.DEFAULT_INSTANCE}}class Ms{static MONOTONIC_INSTANCE=new Ts(true);static NON_MONOTONIC_INSTANCE=new Ts(false);createAggregator(t){switch(t.type){case On.COUNTER:case On.OBSERVABLE_COUNTER:case On.HISTOGRAM:{return Ms.MONOTONIC_INSTANCE}default:{return Ms.NON_MONOTONIC_INSTANCE}}}}class Cs{static DEFAULT_INSTANCE=new Ss;createAggregator(t){return Cs.DEFAULT_INSTANCE}}class As{static DEFAULT_INSTANCE=new Xn([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],true);createAggregator(t){return As.DEFAULT_INSTANCE}}class Ps{_recordMinMax;_boundaries;constructor(t,e=true){this._recordMinMax=e;if(t==null){throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array")}t=t.concat();t=t.sort(((t,e)=>t-e));const i=t.lastIndexOf(-Infinity);let r=t.indexOf(Infinity);if(r===-1){r=undefined}this._boundaries=t.slice(i+1,r)}createAggregator(t){return new Xn(this._boundaries,this._recordMinMax)}}class Is{_maxSize;_recordMinMax;constructor(t=160,e=true){this._maxSize=t;this._recordMinMax=e}createAggregator(t){return new xs(this._maxSize,this._recordMinMax)}}class Os{_resolve(t){switch(t.type){case On.COUNTER:case On.UP_DOWN_COUNTER:case On.OBSERVABLE_COUNTER:case On.OBSERVABLE_UP_DOWN_COUNTER:{return js}case On.GAUGE:case On.OBSERVABLE_GAUGE:{return Ns}case On.HISTOGRAM:{if(t.advice.explicitBucketBoundaries){return new Ps(t.advice.explicitBucketBoundaries)}return Rs}}Yt.warn(`Unable to recognize instrument type: ${t.type}`);return Ls}createAggregator(t){return this._resolve(t).createAggregator(t)}}const Ls=new Es;const js=new Ms;const Ns=new Cs;const Rs=new As;const zs=new Os;var $s;(function(t){t[t["DEFAULT"]=0]="DEFAULT";t[t["DROP"]=1]="DROP";t[t["SUM"]=2]="SUM";t[t["LAST_VALUE"]=3]="LAST_VALUE";t[t["EXPLICIT_BUCKET_HISTOGRAM"]=4]="EXPLICIT_BUCKET_HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=5]="EXPONENTIAL_HISTOGRAM"})($s||($s={}));function Ds(t){switch(t.type){case $s.DEFAULT:return zs;case $s.DROP:return Ls;case $s.SUM:return js;case $s.LAST_VALUE:return Ns;case $s.EXPONENTIAL_HISTOGRAM:{const e=t;return new Is(e.options?.maxSize,e.options?.recordMinMax)}case $s.EXPLICIT_BUCKET_HISTOGRAM:{const e=t;if(e.options==null){return Rs}else{return new Ps(e.options?.boundaries,e.options?.recordMinMax)}}default:throw new Error("Unsupported Aggregation")}}const Fs=t=>({type:$s.DEFAULT});const Us=t=>In.CUMULATIVE;class Bs{_shutdown=false;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(t){this._aggregationSelector=t?.aggregationSelector??Fs;this._aggregationTemporalitySelector=t?.aggregationTemporalitySelector??Us;this._metricProducers=t?.metricProducers??[];this._cardinalitySelector=t?.cardinalitySelector}setMetricProducer(t){if(this._sdkMetricProducer){throw new Error("MetricReader can not be bound to a MeterProvider again.")}this._sdkMetricProducer=t;this.onInitialized()}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}selectCardinalityLimit(t){return this._cardinalitySelector?this._cardinalitySelector(t):2e3}onInitialized(){}async collect(t){if(this._sdkMetricProducer===undefined){throw new Error("MetricReader is not bound to a MetricProducer")}if(this._shutdown){throw new Error("MetricReader is shutdown")}const[e,...i]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:t?.timeoutMillis}),...this._metricProducers.map((e=>e.collect({timeoutMillis:t?.timeoutMillis})))]);const r=e.errors.concat(Un(i,(t=>t.errors)));const n=e.resourceMetrics.resource;const s=e.resourceMetrics.scopeMetrics.concat(Un(i,(t=>t.resourceMetrics.scopeMetrics)));return{resourceMetrics:{resource:n,scopeMetrics:s},errors:r}}async shutdown(t){if(this._shutdown){Yt.error("Cannot call shutdown twice.");return}if(t?.timeoutMillis==null){await this.onShutdown()}else{await $n(this.onShutdown(),t.timeoutMillis)}this._shutdown=true}async forceFlush(t){if(this._shutdown){Yt.warn("Cannot forceFlush on already shutdown MetricReader.");return}if(t?.timeoutMillis==null){await this.onForceFlush();return}await $n(this.onForceFlush(),t.timeoutMillis)}}class qs extends Bs{_interval;_exporter;_exportInterval;_exportTimeout;constructor(t){super({aggregationSelector:t.exporter.selectAggregation?.bind(t.exporter),aggregationTemporalitySelector:t.exporter.selectAggregationTemporality?.bind(t.exporter),metricProducers:t.metricProducers});if(t.exportIntervalMillis!==undefined&&t.exportIntervalMillis<=0){throw Error("exportIntervalMillis must be greater than 0")}if(t.exportTimeoutMillis!==undefined&&t.exportTimeoutMillis<=0){throw Error("exportTimeoutMillis must be greater than 0")}if(t.exportTimeoutMillis!==undefined&&t.exportIntervalMillis!==undefined&&t.exportIntervalMillis<t.exportTimeoutMillis){throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis")}this._exportInterval=t.exportIntervalMillis??6e4;this._exportTimeout=t.exportTimeoutMillis??3e4;this._exporter=t.exporter}async _runOnce(){try{await $n(this._doRun(),this._exportTimeout)}catch(t){if(t instanceof zn){Yt.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);return}$e(t)}}async _doRun(){const{resourceMetrics:t,errors:e}=await this.collect({timeoutMillis:this._exportTimeout});if(e.length>0){Yt.error("PeriodicExportingMetricReader: metrics collection errors",...e)}if(t.resource.asyncAttributesPending){try{await(t.resource.waitForAsyncAttributes?.())}catch(t){Yt.debug("Error while resolving async portion of resource: ",t);$e(t)}}if(t.scopeMetrics.length===0){return}const i=await fr._export(this._exporter,t);if(i.code!==fi.SUCCESS){throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${i.error})`)}}onInitialized(){this._interval=setInterval((()=>{void this._runOnce()}),this._exportInterval);if(typeof this._interval!=="number"){this._interval.unref()}}async onForceFlush(){await this._runOnce();await this._exporter.forceFlush()}async onShutdown(){if(this._interval){clearInterval(this._interval)}await this.onForceFlush();await this._exporter.shutdown()}}class Vs{_registeredViews=[];addView(t){this._registeredViews.push(t)}findViews(t,e){const i=this._registeredViews.filter((i=>this._matchInstrument(i.instrumentSelector,t)&&this._matchMeter(i.meterSelector,e)));return i}_matchInstrument(t,e){return(t.getType()===undefined||e.type===t.getType())&&t.getNameFilter().match(e.name)&&t.getUnitFilter().match(e.unit)}_matchMeter(t,e){return t.getNameFilter().match(e.name)&&(e.version===undefined||t.getVersionFilter().match(e.version))&&(e.schemaUrl===undefined||t.getSchemaUrlFilter().match(e.schemaUrl))}}function Hs(t,e,i){if(!Xs(t)){Yt.warn(`Invalid metric name: "${t}". The metric name should be a ASCII string with a length no greater than 255 characters.`)}return{name:t,type:e,description:i?.description??"",unit:i?.unit??"",valueType:i?.valueType??ut.DOUBLE,advice:i?.advice??{}}}function Gs(t,e){return{name:t.name??e.name,description:t.description??e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function Zs(t,e){return Vn(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}const Ws=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function Xs(t){return t.match(Ws)!=null}class Ys{_writableMetricStorage;_descriptor;constructor(t,e){this._writableMetricStorage=t;this._descriptor=e}_record(t,e={},i=Xt.active()){if(typeof t!=="number"){Yt.warn(`non-number value provided to metric ${this._descriptor.name}: ${t}`);return}if(this._descriptor.valueType===ut.INT&&!Number.isInteger(t)){Yt.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`);t=Math.trunc(t);if(!Number.isInteger(t)){return}}this._writableMetricStorage.record(t,e,i,ii(Date.now()))}}class Js extends Ys{add(t,e,i){this._record(t,e,i)}}class Ks extends Ys{add(t,e,i){if(t<0){Yt.warn(`negative value provided to counter ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class Qs extends Ys{record(t,e,i){this._record(t,e,i)}}class to extends Ys{record(t,e,i){if(t<0){Yt.warn(`negative value provided to histogram ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class eo{_observableRegistry;_metricStorages;_descriptor;constructor(t,e,i){this._observableRegistry=i;this._descriptor=t;this._metricStorages=e}addCallback(t){this._observableRegistry.addCallback(t,this)}removeCallback(t){this._observableRegistry.removeCallback(t,this)}}class io extends eo{}class ro extends eo{}class no extends eo{}function so(t){return t instanceof eo}class oo{_meterSharedState;constructor(t){this._meterSharedState=t}createGauge(t,e){const i=Hs(t,On.GAUGE,e);const r=this._meterSharedState.registerMetricStorage(i);return new Qs(r,i)}createHistogram(t,e){const i=Hs(t,On.HISTOGRAM,e);const r=this._meterSharedState.registerMetricStorage(i);return new to(r,i)}createCounter(t,e){const i=Hs(t,On.COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new Ks(r,i)}createUpDownCounter(t,e){const i=Hs(t,On.UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new Js(r,i)}createObservableGauge(t,e){const i=Hs(t,On.OBSERVABLE_GAUGE,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new ro(i,r,this._meterSharedState.observableRegistry)}createObservableCounter(t,e){const i=Hs(t,On.OBSERVABLE_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new io(i,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(t,e){const i=Hs(t,On.OBSERVABLE_UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new no(i,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.addBatchCallback(t,e)}removeBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.removeBatchCallback(t,e)}}class ao{_instrumentDescriptor;constructor(t){this._instrumentDescriptor=t}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(t){this._instrumentDescriptor=Hs(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:t,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class co{_hash;_valueMap=new Map;_keyMap=new Map;constructor(t){this._hash=t}get(t,e){e??=this._hash(t);return this._valueMap.get(e)}getOrDefault(t,e){const i=this._hash(t);if(this._valueMap.has(i)){return this._valueMap.get(i)}const r=e();if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,r);return r}set(t,e,i){i??=this._hash(t);if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,e)}has(t,e){e??=this._hash(t);return this._valueMap.has(e)}*keys(){const t=this._keyMap.entries();let e=t.next();while(e.done!==true){yield[e.value[1],e.value[0]];e=t.next()}}*entries(){const t=this._valueMap.entries();let e=t.next();while(e.done!==true){yield[this._keyMap.get(e.value[0]),e.value[1],e.value[0]];e=t.next()}}get size(){return this._valueMap.size}}class uo extends co{constructor(){super(Nn)}}class lo{_aggregator;_activeCollectionStorage=new uo;_cumulativeMemoStorage=new uo;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":true};_overflowHashCode;constructor(t,e){this._aggregator=t;this._cardinalityLimit=(e??2e3)-1;this._overflowHashCode=Nn(this._overflowAttributes)}record(t,e,i,r){let n=this._activeCollectionStorage.get(e);if(!n){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const e=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,(()=>this._aggregator.createAccumulation(r)));e?.record(t);return}n=this._aggregator.createAccumulation(r);this._activeCollectionStorage.set(e,n)}n?.record(t)}batchCumulate(t,e){Array.from(t.entries()).forEach((([t,i,r])=>{const n=this._aggregator.createAccumulation(e);n?.record(i);let s=n;if(this._cumulativeMemoStorage.has(t,r)){const e=this._cumulativeMemoStorage.get(t,r);s=this._aggregator.diff(e,n)}else{if(this._cumulativeMemoStorage.size>=this._cardinalityLimit){t=this._overflowAttributes;r=this._overflowHashCode;if(this._cumulativeMemoStorage.has(t,r)){const e=this._cumulativeMemoStorage.get(t,r);s=this._aggregator.diff(e,n)}}}if(this._activeCollectionStorage.has(t,r)){const e=this._activeCollectionStorage.get(t,r);s=this._aggregator.merge(e,s)}this._cumulativeMemoStorage.set(t,n,r);this._activeCollectionStorage.set(t,s,r)}))}collect(){const t=this._activeCollectionStorage;this._activeCollectionStorage=new uo;return t}}class fo{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(t,e){this._aggregator=t;e.forEach((t=>{this._unreportedAccumulations.set(t,[])}))}buildMetrics(t,e,i,r){this._stashAccumulations(i);const n=this._getMergedUnreportedAccumulations(t);let s=n;let o;if(this._reportHistory.has(t)){const e=this._reportHistory.get(t);const i=e.collectionTime;o=e.aggregationTemporality;if(o===In.CUMULATIVE){s=fo.merge(e.accumulations,n,this._aggregator)}else{s=fo.calibrateStartTime(e.accumulations,n,i)}}else{o=t.selectAggregationTemporality(e.type)}this._reportHistory.set(t,{accumulations:s,collectionTime:r,aggregationTemporality:o});const a=ho(s);if(a.length===0){return undefined}return this._aggregator.toMetricData(e,o,a,r)}_stashAccumulations(t){const e=this._unreportedAccumulations.keys();for(const i of e){let e=this._unreportedAccumulations.get(i);if(e===undefined){e=[];this._unreportedAccumulations.set(i,e)}e.push(t)}}_getMergedUnreportedAccumulations(t){let e=new uo;const i=this._unreportedAccumulations.get(t);this._unreportedAccumulations.set(t,[]);if(i===undefined){return e}for(const t of i){e=fo.merge(e,t,this._aggregator)}return e}static merge(t,e,i){const r=t;const n=e.entries();let s=n.next();while(s.done!==true){const[e,o,a]=s.value;if(t.has(e,a)){const n=t.get(e,a);const s=i.merge(n,o);r.set(e,s,a)}else{r.set(e,o,a)}s=n.next()}return r}static calibrateStartTime(t,e,i){for(const[r,n]of t.keys()){const t=e.get(r,n);t?.setStartTime(i)}return e}}function ho(t){return Array.from(t.entries())}class po extends ao{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(t,e,i,r,n){super(t);this._attributesProcessor=i;this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new lo(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new fo(e,r)}record(t,e){const i=new uo;Array.from(t.entries()).forEach((([t,e])=>{i.set(this._attributesProcessor.process(t),e)}));this._deltaMetricStorage.batchCumulate(i,e)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}function mo(t,e){let i="";if(t.unit!==e.unit){i+=`\t- Unit '${t.unit}' does not match '${e.unit}'\n`}if(t.type!==e.type){i+=`\t- Type '${t.type}' does not match '${e.type}'\n`}if(t.valueType!==e.valueType){i+=`\t- Value Type '${t.valueType}' does not match '${e.valueType}'\n`}if(t.description!==e.description){i+=`\t- Description '${t.description}' does not match '${e.description}'\n`}return i}function bo(t,e){return`\t- use valueType '${t.valueType}' on instrument creation or use an instrument name other than '${e.name}'`}function vo(t,e){return`\t- use unit '${t.unit}' on instrument creation or use an instrument name other than '${e.name}'`}function wo(t,e){const i={name:e.name,type:e.type,unit:e.unit};const r=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${r}'`}function go(t,e){const i={name:e.name,type:e.type,unit:e.unit};const r=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${r}'\n \t- OR - create a new view with the name ${t.name} and description '${t.description}' and InstrumentSelector ${r}\n \t- OR - create a new view with the name ${e.name} and description '${t.description}' and InstrumentSelector ${r}`}function yo(t,e){if(t.valueType!==e.valueType){return bo(t,e)}if(t.unit!==e.unit){return vo(t,e)}if(t.type!==e.type){return wo(t,e)}if(t.description!==e.description){return go(t,e)}return""}class xo{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new xo}getStorages(t){let e=[];for(const t of this._sharedRegistry.values()){e=e.concat(t)}const i=this._perCollectorRegistry.get(t);if(i!=null){for(const t of i.values()){e=e.concat(t)}}return e}register(t){this._registerStorage(t,this._sharedRegistry)}registerForCollector(t,e){let i=this._perCollectorRegistry.get(t);if(i==null){i=new Map;this._perCollectorRegistry.set(t,i)}this._registerStorage(e,i)}findOrUpdateCompatibleStorage(t){const e=this._sharedRegistry.get(t.name);if(e===undefined){return null}return this._findOrUpdateCompatibleStorage(t,e)}findOrUpdateCompatibleCollectorStorage(t,e){const i=this._perCollectorRegistry.get(t);if(i===undefined){return null}const r=i.get(e.name);if(r===undefined){return null}return this._findOrUpdateCompatibleStorage(e,r)}_registerStorage(t,e){const i=t.getInstrumentDescriptor();const r=e.get(i.name);if(r===undefined){e.set(i.name,[t]);return}r.push(t)}_findOrUpdateCompatibleStorage(t,e){let i=null;for(const r of e){const e=r.getInstrumentDescriptor();if(Zs(e,t)){if(e.description!==t.description){if(t.description.length>e.description.length){r.updateDescription(t.description)}Yt.warn("A view or instrument with the name ",t.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",mo(e,t),"The longer description will be used.\nTo resolve the conflict:",yo(e,t))}i=r}else{Yt.warn("A view or instrument with the name ",t.name," has already been registered and is incompatible with another registered view.\n","Details:\n",mo(e,t),"To resolve the conflict:\n",yo(e,t))}}return i}}class ko{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,i,r){this._backingStorages.forEach((n=>{n.record(t,e,i,r)}))}}class So{_instrumentName;_valueType;_buffer=new uo;constructor(t,e){this._instrumentName=t;this._valueType=e}observe(t,e={}){if(typeof t!=="number"){Yt.warn(`non-number value provided to metric ${this._instrumentName}: ${t}`);return}if(this._valueType===ut.INT&&!Number.isInteger(t)){Yt.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`);t=Math.trunc(t);if(!Number.isInteger(t)){return}}this._buffer.set(e,t)}}class _o{_buffer=new Map;observe(t,e,i={}){if(!so(t)){return}let r=this._buffer.get(t);if(r==null){r=new uo;this._buffer.set(t,r)}if(typeof e!=="number"){Yt.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}if(t._descriptor.valueType===ut.INT&&!Number.isInteger(e)){Yt.warn(`INT value type cannot accept a floating-point value for ${t._descriptor.name}, ignoring the fractional digits.`);e=Math.trunc(e);if(!Number.isInteger(e)){return}}r.set(i,e)}}class To{_callbacks=[];_batchCallbacks=[];addCallback(t,e){const i=this._findCallback(t,e);if(i>=0){return}this._callbacks.push({callback:t,instrument:e})}removeCallback(t,e){const i=this._findCallback(t,e);if(i<0){return}this._callbacks.splice(i,1)}addBatchCallback(t,e){const i=new Set(e.filter(so));if(i.size===0){Yt.error("BatchObservableCallback is not associated with valid instruments",e);return}const r=this._findBatchCallback(t,i);if(r>=0){return}this._batchCallbacks.push({callback:t,instruments:i})}removeBatchCallback(t,e){const i=new Set(e.filter(so));const r=this._findBatchCallback(t,i);if(r<0){return}this._batchCallbacks.splice(r,1)}async observe(t,e){const i=this._observeCallbacks(t,e);const r=this._observeBatchCallbacks(t,e);const n=await Dn([...i,...r]);const s=n.filter(Fn).map((t=>t.reason));return s}_observeCallbacks(t,e){return this._callbacks.map((async({callback:i,instrument:r})=>{const n=new So(r._descriptor.name,r._descriptor.valueType);let s=Promise.resolve(i(n));if(e!=null){s=$n(s,e)}await s;r._metricStorages.forEach((e=>{e.record(n._buffer,t)}))}))}_observeBatchCallbacks(t,e){return this._batchCallbacks.map((async({callback:i,instruments:r})=>{const n=new _o;let s=Promise.resolve(i(n));if(e!=null){s=$n(s,e)}await s;r.forEach((e=>{const i=n._buffer.get(e);if(i==null){return}e._metricStorages.forEach((e=>{e.record(i,t)}))}))}))}_findCallback(t,e){return this._callbacks.findIndex((i=>i.callback===t&&i.instrument===e))}_findBatchCallback(t,e){return this._batchCallbacks.findIndex((i=>i.callback===t&&Bn(i.instruments,e)))}}class Eo extends ao{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(t,e,i,r,n){super(t);this._attributesProcessor=i;this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new lo(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new fo(e,r)}record(t,e,i,r){e=this._attributesProcessor.process(e,i);this._deltaMetricStorage.record(t,e,i,r)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}class Mo{process(t,e){return t}}class Co{_processors;constructor(t){this._processors=t}process(t,e){let i=t;for(const t of this._processors){i=t.process(i,e)}return i}}function Ao(){return Io}function Po(t){return new Co(t)}const Io=new Mo;class Oo{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new xo;observableRegistry=new To;meter;constructor(t,e){this._meterProviderSharedState=t;this._instrumentationScope=e;this.meter=new oo(this)}registerMetricStorage(t){const e=this._registerMetricStorage(t,Eo);if(e.length===1){return e[0]}return new ko(e)}registerAsyncMetricStorage(t){const e=this._registerMetricStorage(t,po);return e}async collect(t,e,i){const r=await this.observableRegistry.observe(e,i?.timeoutMillis);const n=this.metricStorageRegistry.getStorages(t);if(n.length===0){return null}const s=n.map((i=>i.collect(t,e))).filter(jn);if(s.length===0){return{errors:r}}return{scopeMetrics:{scope:this._instrumentationScope,metrics:s},errors:r}}_registerMetricStorage(t,e){const i=this._meterProviderSharedState.viewRegistry.findViews(t,this._instrumentationScope);let r=i.map((i=>{const r=Gs(i,t);const n=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(n!=null){return n}const s=i.aggregation.createAggregator(r);const o=new e(r,s,i.attributesProcessor,this._meterProviderSharedState.metricCollectors,i.aggregationCardinalityLimit);this.metricStorageRegistry.register(o);return o}));if(r.length===0){const i=this._meterProviderSharedState.selectAggregations(t.type);const n=i.map((([i,r])=>{const n=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(i,t);if(n!=null){return n}const s=r.createAggregator(t);const o=i.selectCardinalityLimit(t.type);const a=new e(t,s,Ao(),[i],o);this.metricStorageRegistry.registerForCollector(i,a);return a}));r=r.concat(n)}return r}}class Lo{resource;viewRegistry=new Vs;metricCollectors=[];meterSharedStates=new Map;constructor(t){this.resource=t}getMeterSharedState(t){const e=Rn(t);let i=this.meterSharedStates.get(e);if(i==null){i=new Oo(this,t);this.meterSharedStates.set(e,i)}return i}selectAggregations(t){const e=[];for(const i of this.metricCollectors){e.push([i,Ds(i.selectAggregation(t))])}return e}}class jo{_sharedState;_metricReader;constructor(t,e){this._sharedState=t;this._metricReader=e}async collect(t){const e=ii(Date.now());const i=[];const r=[];const n=Array.from(this._sharedState.meterSharedStates.values()).map((async n=>{const s=await n.collect(this,e,t);if(s?.scopeMetrics!=null){i.push(s.scopeMetrics)}if(s?.errors!=null){r.push(...s.errors)}}));await Promise.all(n);return{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:i},errors:r}}async forceFlush(t){await this._metricReader.forceFlush(t)}async shutdown(t){await this._metricReader.shutdown(t)}selectAggregationTemporality(t){return this._metricReader.selectAggregationTemporality(t)}selectAggregation(t){return this._metricReader.selectAggregation(t)}selectCardinalityLimit(t){return this._metricReader.selectCardinalityLimit?.(t)??2e3}}const No=/[\^$\\.+?()[\]{}|]/g;class Ro{_matchAll;_regexp;constructor(t){if(t==="*"){this._matchAll=true;this._regexp=/.*/}else{this._matchAll=false;this._regexp=new RegExp(Ro.escapePattern(t))}}match(t){if(this._matchAll){return true}return this._regexp.test(t)}static escapePattern(t){return`^${t.replace(No,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}}class zo{_matchAll;_pattern;constructor(t){this._matchAll=t===undefined;this._pattern=t}match(t){if(this._matchAll){return true}if(t===this._pattern){return true}return false}}class $o{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new Ro(t?.name??"*");this._type=t?.type;this._unitFilter=new zo(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class Do{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new zo(t?.name);this._versionFilter=new zo(t?.version);this._schemaUrlFilter=new zo(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function Fo(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}function Uo(t){if(Fo(t)){throw new Error("Cannot create view with no selector arguments supplied")}if(t.name!=null&&(t?.instrumentName==null||Ro.hasWildcard(t.instrumentName))){throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}}class Bo{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){Uo(t);if(t.attributesProcessors!=null){this.attributesProcessor=Po(t.attributesProcessors)}else{this.attributesProcessor=Ao()}this.name=t.name;this.description=t.description;this.aggregation=Ds(t.aggregation??{type:$s.DEFAULT});this.instrumentSelector=new $o({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit});this.meterSelector=new Do({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl});this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}}class qo{_sharedState;_shutdown=false;constructor(t){this._sharedState=new Lo(t?.resource??br());if(t?.views!=null&&t.views.length>0){for(const e of t.views){this._sharedState.viewRegistry.addView(new Bo(e))}}if(t?.readers!=null&&t.readers.length>0){for(const e of t.readers){const t=new jo(this._sharedState,e);e.setMetricProducer(t);this._sharedState.metricCollectors.push(t)}}}getMeter(t,e="",i={}){if(this._shutdown){Yt.warn("A shutdown MeterProvider cannot provide a Meter");return ct()}return this._sharedState.getMeterSharedState({name:t,version:e,schemaUrl:i.schemaUrl}).meter}async shutdown(t){if(this._shutdown){Yt.warn("shutdown may only be called once per MeterProvider");return}this._shutdown=true;await Promise.all(this._sharedState.metricCollectors.map((e=>e.shutdown(t))))}async forceFlush(t){if(this._shutdown){Yt.warn("invalid attempt to force flush after MeterProvider shutdown");return}await Promise.all(this._sharedState.metricCollectors.map((e=>e.forceFlush(t))))}}var Vo;(function(t){t[t["AGGREGATION_TEMPORALITY_UNSPECIFIED"]=0]="AGGREGATION_TEMPORALITY_UNSPECIFIED";t[t["AGGREGATION_TEMPORALITY_DELTA"]=1]="AGGREGATION_TEMPORALITY_DELTA";t[t["AGGREGATION_TEMPORALITY_CUMULATIVE"]=2]="AGGREGATION_TEMPORALITY_CUMULATIVE"})(Vo||(Vo={}));function Ho(t,e){const i=Tn(e);const r=En(t.resource);return{resource:r,schemaUrl:r.schemaUrl,scopeMetrics:Go(t.scopeMetrics,i)}}function Go(t,e){return Array.from(t.map((t=>({scope:Mn(t.scope),metrics:t.metrics.map((t=>Zo(t,e))),schemaUrl:t.scope.schemaUrl}))))}function Zo(t,e){const i={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit};const r=Ko(t.aggregationTemporality);switch(t.dataPointType){case Ln.SUM:i.sum={aggregationTemporality:r,isMonotonic:t.isMonotonic,dataPoints:Xo(t,e)};break;case Ln.GAUGE:i.gauge={dataPoints:Xo(t,e)};break;case Ln.HISTOGRAM:i.histogram={aggregationTemporality:r,dataPoints:Yo(t,e)};break;case Ln.EXPONENTIAL_HISTOGRAM:i.exponentialHistogram={aggregationTemporality:r,dataPoints:Jo(t,e)};break}return i}function Wo(t,e,i){const r={attributes:Cn(t.attributes),startTimeUnixNano:i.encodeHrTime(t.startTime),timeUnixNano:i.encodeHrTime(t.endTime)};switch(e){case ut.INT:r.asInt=t.value;break;case ut.DOUBLE:r.asDouble=t.value;break}return r}function Xo(t,e){return t.dataPoints.map((i=>Wo(i,t.descriptor.valueType,e)))}function Yo(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:Cn(t.attributes),bucketCounts:i.buckets.counts,explicitBounds:i.buckets.boundaries,count:i.count,sum:i.sum,min:i.min,max:i.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}}))}function Jo(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:Cn(t.attributes),count:i.count,min:i.min,max:i.max,sum:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},scale:i.scale,zeroCount:i.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}}))}function Ko(t){switch(t){case In.DELTA:return Vo.AGGREGATION_TEMPORALITY_DELTA;case In.CUMULATIVE:return Vo.AGGREGATION_TEMPORALITY_CUMULATIVE}}function Qo(t,e){return{resourceMetrics:t.map((t=>Ho(t,e)))}}const ta=256;const ea=512;function ia(t,e){let i=t&255|ta;if(e){i|=ea}return i}function ra(t,e){const i=t.spanContext();const r=t.status;const n=t.parentSpanContext?.spanId?e.encodeSpanContext(t.parentSpanContext?.spanId):undefined;return{traceId:e.encodeSpanContext(i.traceId),spanId:e.encodeSpanContext(i.spanId),parentSpanId:n,traceState:i.traceState?.serialize(),name:t.name,kind:t.kind==null?0:t.kind+1,startTimeUnixNano:e.encodeHrTime(t.startTime),endTimeUnixNano:e.encodeHrTime(t.endTime),attributes:Cn(t.attributes),droppedAttributesCount:t.droppedAttributesCount,events:t.events.map((t=>sa(t,e))),droppedEventsCount:t.droppedEventsCount,status:{code:r.code,message:r.message},links:t.links.map((t=>na(t,e))),droppedLinksCount:t.droppedLinksCount,flags:ia(i.traceFlags,t.parentSpanContext?.isRemote)}}function na(t,e){return{attributes:t.attributes?Cn(t.attributes):[],spanId:e.encodeSpanContext(t.context.spanId),traceId:e.encodeSpanContext(t.context.traceId),traceState:t.context.traceState?.serialize(),droppedAttributesCount:t.droppedAttributesCount||0,flags:ia(t.context.traceFlags,t.context.isRemote)}}function sa(t,e){return{attributes:t.attributes?Cn(t.attributes):[],name:t.name,timeUnixNano:e.encodeHrTime(t.time),droppedAttributesCount:t.droppedAttributesCount||0}}function oa(t,e){const i=Tn(e);return{resourceSpans:ca(t,i)}}function aa(t){const e=new Map;for(const i of t){let t=e.get(i.resource);if(!t){t=new Map;e.set(i.resource,t)}const r=`${i.instrumentationScope.name}@${i.instrumentationScope.version||""}:${i.instrumentationScope.schemaUrl||""}`;let n=t.get(r);if(!n){n=[];t.set(r,n)}n.push(i)}return e}function ca(t,e){const i=aa(t);const r=[];const n=i.entries();let s=n.next();while(!s.done){const[t,i]=s.value;const o=[];const a=i.values();let c=a.next();while(!c.done){const t=c.value;if(t.length>0){const i=t.map((t=>ra(t,e)));o.push({scope:Mn(t[0].instrumentationScope),spans:i,schemaUrl:t[0].instrumentationScope.schemaUrl})}c=a.next()}const u=En(t);const l={resource:u,scopeSpans:o,schemaUrl:u.schemaUrl};r.push(l);s=n.next()}return r}const ua={serializeRequest:t=>{const e=Qo([t],{useLongBits:false});const i=new TextEncoder;return i.encode(JSON.stringify(e))},deserializeResponse:t=>{if(t.length===0){return{}}const e=new TextDecoder;return JSON.parse(e.decode(t))}};const la={serializeRequest:t=>{const e=oa(t,{useHex:true,useLongBits:false});const i=new TextEncoder;return i.encode(JSON.stringify(e))},deserializeResponse:t=>{if(t.length===0){return{}}const e=new TextDecoder;return JSON.parse(e.decode(t))}};const fa=5;const ha=1e3;const da=5e3;const pa=1.5;const ma=.2;function ba(){return Math.random()*(2*ma)-ma}class va{_transport;constructor(t){this._transport=t}retry(t,e,i){return new Promise(((r,n)=>{setTimeout((()=>{this._transport.send(t,e).then(r,n)}),i)}))}async send(t,e){const i=Date.now()+e;let r=await this._transport.send(t,e);let n=fa;let s=ha;while(r.status==="retryable"&&n>0){n--;const e=Math.max(Math.min(s,da)+ba(),0);s=s*pa;const o=r.retryInMillis??e;const a=i-Date.now();if(o>a){return r}r=await this.retry(t,a,o)}return r}shutdown(){return this._transport.shutdown()}}function wa(t){return new va(t.transport)}function ga(t){const e=[429,502,503,504];return e.includes(t)}function ya(t){if(t==null){return undefined}const e=Number.parseInt(t,10);if(Number.isInteger(e)){return e>0?e*1e3:-1}const i=new Date(t).getTime()-Date.now();if(i>=0){return i}return 0}class xa{_parameters;constructor(t){this._parameters=t}async send(t,e){const i=await this._parameters.headers();const r=await new Promise((r=>{const n=new XMLHttpRequest;n.timeout=e;n.open("POST",this._parameters.url);Object.entries(i).forEach((([t,e])=>{n.setRequestHeader(t,e)}));n.ontimeout=t=>{r({status:"failure",error:new Error("XHR request timed out")})};n.onreadystatechange=()=>{if(n.status>=200&&n.status<=299){Yt.debug("XHR success");r({status:"success"})}else if(n.status&&ga(n.status)){r({status:"retryable",retryInMillis:ya(n.getResponseHeader("Retry-After"))})}else if(n.status!==0){r({status:"failure",error:new Error("XHR request failed with non-retryable status")})}};n.onabort=()=>{r({status:"failure",error:new Error("XHR request aborted")})};n.onerror=()=>{r({status:"failure",error:new Error("XHR request errored")})};n.send(t)}));return r}shutdown(){}}function ka(t){return new xa(t)}class Sa{_params;constructor(t){this._params=t}async send(t){const e=(await this._params.headers())["Content-Type"];return new Promise((i=>{if(navigator.sendBeacon(this._params.url,new Blob([t],{type:e}))){Yt.debug("SendBeacon success");i({status:"success"})}else{i({status:"failure",error:new Error("SendBeacon failed")})}}))}shutdown(){}}function _a(t){return new Sa(t)}class Ta{_parameters;constructor(t){this._parameters=t}async send(t,e){const i=new AbortController;const r=setTimeout((()=>i.abort()),e);try{const e=!!globalThis.location;const r=new URL(this._parameters.url);const n=await fetch(r.href,{method:"POST",headers:await this._parameters.headers(),body:t,signal:i.signal,keepalive:e,mode:e?globalThis.location?.origin===r.origin?"same-origin":"cors":"no-cors"});if(n.status>=200&&n.status<=299){Yt.debug("response success");return{status:"success"}}else if(ga(n.status)){const t=n.headers.get("Retry-After");const e=ya(t);return{status:"retryable",retryInMillis:e}}return{status:"failure",error:new Error("Fetch request failed with non-retryable status")}}catch(t){if(t?.name==="AbortError"){return{status:"failure",error:new Error("Fetch request timed out",{cause:t})}}return{status:"failure",error:new Error("Fetch request errored",{cause:t})}}finally{clearTimeout(r)}}shutdown(){}}function Ea(t){return new Ta(t)}function Ma(t,e){return dn(t,e,wa({transport:ka(t)}))}function Ca(t,e){return dn(t,e,wa({transport:Ea(t)}))}function Aa(t,e){return dn(t,e,wa({transport:_a({url:t.url,headers:t.headers})}))}function Pa(t){const e={};Object.entries(t??{}).forEach((([t,i])=>{if(typeof i!=="undefined"){e[t]=String(i)}else{Yt.warn(`Header "${t}" has invalid value (${i}) and will be ignored`)}}));return e}function Ia(t,e,i){return async()=>{const r={...await i()};const n={};if(e!=null){Object.assign(n,await e())}if(t!=null){Object.assign(n,Pa(await t()))}return Object.assign(n,r)}}function Oa(t){if(t==null){return undefined}try{const e=globalThis.location?.href;return new URL(t,e).href}catch{throw new Error(`Configuration: Could not parse user-provided export URL: '${t}'`)}}function La(t,e,i){return{...sn(t,e,i),headers:Ia(t.headers,e.headers,i.headers),url:Oa(t.url)??e.url??i.url}}function ja(t,e){return{...on(),headers:async()=>t,url:"http://localhost:4318/"+e}}function Na(t){if(typeof t.headers==="function"){return t.headers}return nn(t.headers)}function Ra(t,e,i){return La({url:t.url,timeoutMillis:t.timeoutMillis,headers:Na(t),concurrencyLimit:t.concurrencyLimit},{},ja(i,e))}function za(t,e,i,r){const n=$a(t.headers);const s=Ra(t,i,r);return n(s,e)}function $a(t){if(!t&&typeof navigator.sendBeacon==="function"){return Aa}else if(typeof globalThis.fetch!=="undefined"){return Ca}else{return Ma}}class Da extends tn{constructor(t={}){super(za(t,la,"v1/traces",{"Content-Type":"application/json"}))}}function Fa(t){return typeof t==="object"&&t!==null&&"addEventListener"in t&&typeof t.addEventListener==="function"&&"removeEventListener"in t&&typeof t.removeEventListener==="function"}const Ua="OT_ZONE_CONTEXT";class Ba{_enabled=false;_zoneCounter=0;_activeContextFromZone(t){return t&&t.get(Ua)||B}_bindFunction(t,e){const i=this;const r=function(...r){return i.with(t,(()=>e.apply(this,r)))};Object.defineProperty(r,"length",{enumerable:false,configurable:true,writable:false,value:e.length});return r}_bindListener(t,e){const i=e;if(i.__ot_listeners!==undefined){return e}i.__ot_listeners={};if(typeof i.addEventListener==="function"){i.addEventListener=this._patchAddEventListener(i,i.addEventListener,t)}if(typeof i.removeEventListener==="function"){i.removeEventListener=this._patchRemoveEventListener(i,i.removeEventListener)}return e}_createZoneName(){this._zoneCounter++;const t=Math.random();return`${this._zoneCounter}-${t}`}_createZone(t,e){return Zone.current.fork({name:t,properties:{[Ua]:e}})}_getActiveZone(){return Zone.current}_patchAddEventListener(t,e,i){const r=this;return function(n,s,o){if(t.__ot_listeners===undefined){t.__ot_listeners={}}let a=t.__ot_listeners[n];if(a===undefined){a=new WeakMap;t.__ot_listeners[n]=a}const c=r.bind(i,s);a.set(s,c);return e.call(this,n,c,o)}}_patchRemoveEventListener(t,e){return function(i,r){if(t.__ot_listeners===undefined||t.__ot_listeners[i]===undefined){return e.call(this,i,r)}const n=t.__ot_listeners[i];const s=n.get(r);n.delete(r);return e.call(this,i,s||r)}}active(){if(!this._enabled){return B}const t=this._getActiveZone();const e=this._activeContextFromZone(t);if(e){return e}return B}bind(t,e){if(t===undefined){t=this.active()}if(typeof e==="function"){return this._bindFunction(t,e)}else if(Fa(e)){this._bindListener(t,e)}return e}disable(){this._enabled=false;return this}enable(){this._enabled=true;return this}with(t,e,i,...r){const n=this._createZoneName();const s=this._createZone(n,t);return s.run(e,i,r)}}var qa={};var Va;function Ha(){if(Va)return qa;Va=1;var t=qa&&qa.__assign||function(){t=Object.assign||function(t){for(var e,i=1,r=arguments.length;i<r;i++){e=arguments[i];for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n))t[n]=e[n]}return t};return t.apply(this,arguments)};
2
- /**
3
- * @license Angular v<unknown>
4
- * (c) 2010-2025 Google LLC. https://angular.io/
5
- * License: MIT
6
- */(function(t){t()})((function(){var e=globalThis;function i(t){var i=e["__Zone_symbol_prefix"]||"__zone_symbol__";return i+t}function r(){var t=e["performance"];function r(e){t&&t["mark"]&&t["mark"](e)}function n(e,i){t&&t["measure"]&&t["measure"](e,i)}r("Zone");var s=function(){function t(t,e){this._parent=t;this._name=e?e.name||"unnamed":"<root>";this._properties=e&&e.properties||{};this._zoneDelegate=new a(this,this._parent&&this._parent._zoneDelegate,e)}t.assertZonePatched=function(){if(e["Promise"]!==C["ZoneAwarePromise"]){throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` "+"has been overwritten.\n"+"Most likely cause is that a Promise polyfill has been loaded "+"after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. "+"If you must load one, do so before loading zone.js.)")}};Object.defineProperty(t,"root",{get:function(){var e=t.current;while(e.parent){e=e.parent}return e},enumerable:false,configurable:true});Object.defineProperty(t,"current",{get:function(){return P.zone},enumerable:false,configurable:true});Object.defineProperty(t,"currentTask",{get:function(){return I},enumerable:false,configurable:true});t.__load_patch=function(s,o,a){if(a===void 0){a=false}if(C.hasOwnProperty(s)){var c=e[i("forceDuplicateZoneCheck")]===true;if(!a&&c){throw Error("Already loaded patch: "+s)}}else if(!e["__Zone_disable_"+s]){var u="Zone:"+s;r(u);C[s]=o(e,t,A);n(u,u)}};Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},enumerable:false,configurable:true});Object.defineProperty(t.prototype,"name",{get:function(){return this._name},enumerable:false,configurable:true});t.prototype.get=function(t){var e=this.getZoneWith(t);if(e)return e._properties[t]};t.prototype.getZoneWith=function(t){var e=this;while(e){if(e._properties.hasOwnProperty(t)){return e}e=e._parent}return null};t.prototype.fork=function(t){if(!t)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,t)};t.prototype.wrap=function(t,e){if(typeof t!=="function"){throw new Error("Expecting function got: "+t)}var i=this._zoneDelegate.intercept(this,t,e);var r=this;return function(){return r.runGuarded(i,this,arguments,e)}};t.prototype.run=function(t,e,i,r){P={parent:P,zone:this};try{return this._zoneDelegate.invoke(this,t,e,i,r)}finally{P=P.parent}};t.prototype.runGuarded=function(t,e,i,r){if(e===void 0){e=null}P={parent:P,zone:this};try{try{return this._zoneDelegate.invoke(this,t,e,i,r)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{P=P.parent}};t.prototype.runTask=function(t,e,i){if(t.zone!=this){throw new Error("A task can only be run in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")")}var r=t;var n=t.type,s=t.data,o=s===void 0?{}:s,a=o.isPeriodic,c=a===void 0?false:a,u=o.isRefreshable,l=u===void 0?false:u;if(t.state===g&&(n===M||n===E)){return}var f=t.state!=k;f&&r._transitionTo(k,x);var h=I;I=r;P={parent:P,zone:this};try{if(n==E&&t.data&&!c&&!l){t.cancelFn=undefined}try{return this._zoneDelegate.invokeTask(this,r,e,i)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{var d=t.state;if(d!==g&&d!==_){if(n==M||c||l&&d===y){f&&r._transitionTo(x,k,y)}else{var p=r._zoneDelegates;this._updateTaskCount(r,-1);f&&r._transitionTo(g,k,g);if(l){r._zoneDelegates=p}}}P=P.parent;I=h}};t.prototype.scheduleTask=function(t){if(t.zone&&t.zone!==this){var e=this;while(e){if(e===t.zone){throw Error("can not reschedule task to ".concat(this.name," which is descendants of the original zone ").concat(t.zone.name))}e=e.parent}}t._transitionTo(y,g);var i=[];t._zoneDelegates=i;t._zone=this;try{t=this._zoneDelegate.scheduleTask(this,t)}catch(e){t._transitionTo(_,y,g);this._zoneDelegate.handleError(this,e);throw e}if(t._zoneDelegates===i){this._updateTaskCount(t,1)}if(t.state==y){t._transitionTo(x,y)}return t};t.prototype.scheduleMicroTask=function(t,e,i,r){return this.scheduleTask(new c(T,t,e,i,r,undefined))};t.prototype.scheduleMacroTask=function(t,e,i,r,n){return this.scheduleTask(new c(E,t,e,i,r,n))};t.prototype.scheduleEventTask=function(t,e,i,r,n){return this.scheduleTask(new c(M,t,e,i,r,n))};t.prototype.cancelTask=function(t){if(t.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")");if(t.state!==x&&t.state!==k){return}t._transitionTo(S,x,k);try{this._zoneDelegate.cancelTask(this,t)}catch(e){t._transitionTo(_,S);this._zoneDelegate.handleError(this,e);throw e}this._updateTaskCount(t,-1);t._transitionTo(g,S);t.runCount=-1;return t};t.prototype._updateTaskCount=function(t,e){var i=t._zoneDelegates;if(e==-1){t._zoneDelegates=null}for(var r=0;r<i.length;r++){i[r]._updateTaskCount(t.type,e)}};t.__symbol__=i;return t}();var o={name:"",onHasTask:function(t,e,i,r){return t.hasTask(i,r)},onScheduleTask:function(t,e,i,r){return t.scheduleTask(i,r)},onInvokeTask:function(t,e,i,r,n,s){return t.invokeTask(i,r,n,s)},onCancelTask:function(t,e,i,r){return t.cancelTask(i,r)}};var a=function(){function t(t,e,i){this._taskCounts={microTask:0,macroTask:0,eventTask:0};this._zone=t;this._parentDelegate=e;this._forkZS=i&&(i&&i.onFork?i:e._forkZS);this._forkDlgt=i&&(i.onFork?e:e._forkDlgt);this._forkCurrZone=i&&(i.onFork?this._zone:e._forkCurrZone);this._interceptZS=i&&(i.onIntercept?i:e._interceptZS);this._interceptDlgt=i&&(i.onIntercept?e:e._interceptDlgt);this._interceptCurrZone=i&&(i.onIntercept?this._zone:e._interceptCurrZone);this._invokeZS=i&&(i.onInvoke?i:e._invokeZS);this._invokeDlgt=i&&(i.onInvoke?e:e._invokeDlgt);this._invokeCurrZone=i&&(i.onInvoke?this._zone:e._invokeCurrZone);this._handleErrorZS=i&&(i.onHandleError?i:e._handleErrorZS);this._handleErrorDlgt=i&&(i.onHandleError?e:e._handleErrorDlgt);this._handleErrorCurrZone=i&&(i.onHandleError?this._zone:e._handleErrorCurrZone);this._scheduleTaskZS=i&&(i.onScheduleTask?i:e._scheduleTaskZS);this._scheduleTaskDlgt=i&&(i.onScheduleTask?e:e._scheduleTaskDlgt);this._scheduleTaskCurrZone=i&&(i.onScheduleTask?this._zone:e._scheduleTaskCurrZone);this._invokeTaskZS=i&&(i.onInvokeTask?i:e._invokeTaskZS);this._invokeTaskDlgt=i&&(i.onInvokeTask?e:e._invokeTaskDlgt);this._invokeTaskCurrZone=i&&(i.onInvokeTask?this._zone:e._invokeTaskCurrZone);this._cancelTaskZS=i&&(i.onCancelTask?i:e._cancelTaskZS);this._cancelTaskDlgt=i&&(i.onCancelTask?e:e._cancelTaskDlgt);this._cancelTaskCurrZone=i&&(i.onCancelTask?this._zone:e._cancelTaskCurrZone);this._hasTaskZS=null;this._hasTaskDlgt=null;this._hasTaskDlgtOwner=null;this._hasTaskCurrZone=null;var r=i&&i.onHasTask;var n=e&&e._hasTaskZS;if(r||n){this._hasTaskZS=r?i:o;this._hasTaskDlgt=e;this._hasTaskDlgtOwner=this;this._hasTaskCurrZone=this._zone;if(!i.onScheduleTask){this._scheduleTaskZS=o;this._scheduleTaskDlgt=e;this._scheduleTaskCurrZone=this._zone}if(!i.onInvokeTask){this._invokeTaskZS=o;this._invokeTaskDlgt=e;this._invokeTaskCurrZone=this._zone}if(!i.onCancelTask){this._cancelTaskZS=o;this._cancelTaskDlgt=e;this._cancelTaskCurrZone=this._zone}}}Object.defineProperty(t.prototype,"zone",{get:function(){return this._zone},enumerable:false,configurable:true});t.prototype.fork=function(t,e){return this._forkZS?this._forkZS.onFork(this._forkDlgt,this.zone,t,e):new s(t,e)};t.prototype.intercept=function(t,e,i){return this._interceptZS?this._interceptZS.onIntercept(this._interceptDlgt,this._interceptCurrZone,t,e,i):e};t.prototype.invoke=function(t,e,i,r,n){return this._invokeZS?this._invokeZS.onInvoke(this._invokeDlgt,this._invokeCurrZone,t,e,i,r,n):e.apply(i,r)};t.prototype.handleError=function(t,e){return this._handleErrorZS?this._handleErrorZS.onHandleError(this._handleErrorDlgt,this._handleErrorCurrZone,t,e):true};t.prototype.scheduleTask=function(t,e){var i=e;if(this._scheduleTaskZS){if(this._hasTaskZS){i._zoneDelegates.push(this._hasTaskDlgtOwner)}i=this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt,this._scheduleTaskCurrZone,t,e);if(!i)i=e}else{if(e.scheduleFn){e.scheduleFn(e)}else if(e.type==T){b(e)}else{throw new Error("Task is missing scheduleFn.")}}return i};t.prototype.invokeTask=function(t,e,i,r){return this._invokeTaskZS?this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt,this._invokeTaskCurrZone,t,e,i,r):e.callback.apply(i,r)};t.prototype.cancelTask=function(t,e){var i;if(this._cancelTaskZS){i=this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt,this._cancelTaskCurrZone,t,e)}else{if(!e.cancelFn){throw Error("Task is not cancelable")}i=e.cancelFn(e)}return i};t.prototype.hasTask=function(t,e){try{this._hasTaskZS&&this._hasTaskZS.onHasTask(this._hasTaskDlgt,this._hasTaskCurrZone,t,e)}catch(e){this.handleError(t,e)}};t.prototype._updateTaskCount=function(t,e){var i=this._taskCounts;var r=i[t];var n=i[t]=r+e;if(n<0){throw new Error("More tasks executed then were scheduled.")}if(r==0||n==0){var s={microTask:i["microTask"]>0,macroTask:i["macroTask"]>0,eventTask:i["eventTask"]>0,change:t};this.hasTask(this._zone,s)}};return t}();var c=function(){function t(i,r,n,s,o,a){this._zone=null;this.runCount=0;this._zoneDelegates=null;this._state="notScheduled";this.type=i;this.source=r;this.data=s;this.scheduleFn=o;this.cancelFn=a;if(!n){throw new Error("callback is not defined")}this.callback=n;var c=this;if(i===M&&s&&s.useG){this.invoke=t.invokeTask}else{this.invoke=function(){return t.invokeTask.call(e,c,this,arguments)}}}t.invokeTask=function(t,e,i){if(!t){t=this}O++;try{t.runCount++;return t.zone.runTask(t,e,i)}finally{if(O==1){v()}O--}};Object.defineProperty(t.prototype,"zone",{get:function(){return this._zone},enumerable:false,configurable:true});Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:false,configurable:true});t.prototype.cancelScheduleRequest=function(){this._transitionTo(g,y)};t.prototype._transitionTo=function(t,e,i){if(this._state===e||this._state===i){this._state=t;if(t==g){this._zoneDelegates=null}}else{throw new Error("".concat(this.type," '").concat(this.source,"': can not transition to '").concat(t,"', expecting state '").concat(e,"'").concat(i?" or '"+i+"'":"",", was '").concat(this._state,"'."))}};t.prototype.toString=function(){if(this.data&&typeof this.data.handleId!=="undefined"){return this.data.handleId.toString()}else{return Object.prototype.toString.call(this)}};t.prototype.toJSON=function(){return{type:this.type,state:this.state,source:this.source,zone:this.zone.name,runCount:this.runCount}};return t}();var u=i("setTimeout");var l=i("Promise");var f=i("then");var h=[];var d=false;var p;function m(t){if(!p){if(e[l]){p=e[l].resolve(0)}}if(p){var i=p[f];if(!i){i=p["then"]}i.call(p,t)}else{e[u](t,0)}}function b(t){if(O===0&&h.length===0){m(v)}t&&h.push(t)}function v(){if(!d){d=true;while(h.length){var t=h;h=[];for(var e=0;e<t.length;e++){var i=t[e];try{i.zone.runTask(i,null,null)}catch(t){A.onUnhandledError(t)}}}A.microtaskDrainDone();d=false}}var w={name:"NO ZONE"};var g="notScheduled",y="scheduling",x="scheduled",k="running",S="canceling",_="unknown";var T="microTask",E="macroTask",M="eventTask";var C={};var A={symbol:i,currentZoneFrame:function(){return P},onUnhandledError:L,microtaskDrainDone:L,scheduleMicroTask:b,showUncaughtError:function(){return!s[i("ignoreConsoleErrorUncaughtError")]},patchEventTarget:function(){return[]},patchOnProperties:L,patchMethod:function(){return L},bindArguments:function(){return[]},patchThen:function(){return L},patchMacroTask:function(){return L},patchEventPrototype:function(){return L},isIEOrEdge:function(){return false},getGlobalObjects:function(){return undefined},ObjectDefineProperty:function(){return L},ObjectGetOwnPropertyDescriptor:function(){return undefined},ObjectCreate:function(){return undefined},ArraySlice:function(){return[]},patchClass:function(){return L},wrapWithCurrentZone:function(){return L},filterProperties:function(){return[]},attachOriginToPatched:function(){return L},_redefineProperty:function(){return L},patchCallbacks:function(){return L},nativeScheduleMicroTask:m};var P={parent:null,zone:new s(null,null)};var I=null;var O=0;function L(){}n("Zone","Zone");return s}function n(){var t;var e=globalThis;var n=e[i("forceDuplicateZoneCheck")]===true;if(e["Zone"]&&(n||typeof e["Zone"].__symbol__!=="function")){throw new Error("Zone already loaded.")}(t=e["Zone"])!==null&&t!==void 0?t:e["Zone"]=r();return e["Zone"]}var s=Object.getOwnPropertyDescriptor;var o=Object.defineProperty;var a=Object.getPrototypeOf;var c=Object.create;var u=Array.prototype.slice;var l="addEventListener";var f="removeEventListener";var h=i(l);var d=i(f);var p="true";var m="false";var b=i("");function v(t,e){return Zone.current.wrap(t,e)}function w(t,e,i,r,n){return Zone.current.scheduleMacroTask(t,e,i,r,n)}var g=i;var y=typeof window!=="undefined";var x=y?window:undefined;var k=y&&x||globalThis;var S="removeAttribute";function _(t,e){for(var i=t.length-1;i>=0;i--){if(typeof t[i]==="function"){t[i]=v(t[i],e+"_"+i)}}return t}function T(t,e){var i=t.constructor["name"];var r=function(r){var n=e[r];var o=t[n];if(o){var a=s(t,n);if(!E(a)){return"continue"}t[n]=function(t){var e=function(){return t.apply(this,_(arguments,i+"."+n))};F(e,t);return e}(o)}};for(var n=0;n<e.length;n++){r(n)}}function E(t){if(!t){return true}if(t.writable===false){return false}return!(typeof t.get==="function"&&typeof t.set==="undefined")}var M=typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope;var C=!("nw"in k)&&typeof k.process!=="undefined"&&k.process.toString()==="[object process]";var A=!C&&!M&&!!(y&&x["HTMLElement"]);var P=typeof k.process!=="undefined"&&k.process.toString()==="[object process]"&&!M&&!!(y&&x["HTMLElement"]);var I={};var O=g("enable_beforeunload");var L=function(t){t=t||k.event;if(!t){return}var e=I[t.type];if(!e){e=I[t.type]=g("ON_PROPERTY"+t.type)}var i=this||t.target||k;var r=i[e];var n;if(A&&i===x&&t.type==="error"){var s=t;n=r&&r.call(this,s.message,s.filename,s.lineno,s.colno,s.error);if(n===true){t.preventDefault()}}else{n=r&&r.apply(this,arguments);if(t.type==="beforeunload"&&k[O]&&typeof n==="string"){t.returnValue=n}else if(n!=undefined&&!n){t.preventDefault()}}return n};function j(t,e,i){var r=s(t,e);if(!r&&i){var n=s(i,e);if(n){r={enumerable:true,configurable:true}}}if(!r||!r.configurable){return}var a=g("on"+e+"patched");if(t.hasOwnProperty(a)&&t[a]){return}delete r.writable;delete r.value;var c=r.get;var u=r.set;var l=e.slice(2);var f=I[l];if(!f){f=I[l]=g("ON_PROPERTY"+l)}r.set=function(e){var i=this;if(!i&&t===k){i=k}if(!i){return}var r=i[f];if(typeof r==="function"){i.removeEventListener(l,L)}u===null||u===void 0?void 0:u.call(i,null);i[f]=e;if(typeof e==="function"){i.addEventListener(l,L,false)}};r.get=function(){var i=this;if(!i&&t===k){i=k}if(!i){return null}var n=i[f];if(n){return n}else if(c){var s=c.call(this);if(s){r.set.call(this,s);if(typeof i[S]==="function"){i.removeAttribute(e)}return s}}return null};o(t,e,r);t[a]=true}function N(t,e,i){if(e){for(var r=0;r<e.length;r++){j(t,"on"+e[r],i)}}else{var n=[];for(var s in t){if(s.slice(0,2)=="on"){n.push(s)}}for(var o=0;o<n.length;o++){j(t,n[o],i)}}}var R=g("originalInstance");function z(t){var e=k[t];if(!e)return;k[g(t)]=e;k[t]=function(){var i=_(arguments,t);switch(i.length){case 0:this[R]=new e;break;case 1:this[R]=new e(i[0]);break;case 2:this[R]=new e(i[0],i[1]);break;case 3:this[R]=new e(i[0],i[1],i[2]);break;case 4:this[R]=new e(i[0],i[1],i[2],i[3]);break;default:throw new Error("Arg list too long.")}};F(k[t],e);var i=new e((function(){}));var r;for(r in i){if(t==="XMLHttpRequest"&&r==="responseBlob")continue;(function(e){if(typeof i[e]==="function"){k[t].prototype[e]=function(){return this[R][e].apply(this[R],arguments)}}else{o(k[t].prototype,e,{set:function(i){if(typeof i==="function"){this[R][e]=v(i,t+"."+e);F(this[R][e],i)}else{this[R][e]=i}},get:function(){return this[R][e]}})}})(r)}for(r in e){if(r!=="prototype"&&e.hasOwnProperty(r)){k[t][r]=e[r]}}}function $(t,e,i){var r=t;while(r&&!r.hasOwnProperty(e)){r=a(r)}if(!r&&t[e]){r=t}var n=g(e);var o=null;if(r&&(!(o=r[n])||!r.hasOwnProperty(n))){o=r[n]=r[e];var c=r&&s(r,e);if(E(c)){var u=i(o,n,e);r[e]=function(){return u(this,arguments)};F(r[e],o)}}return o}function D(t,e,i){var r=null;function n(t){var e=t.data;e.args[e.cbIdx]=function(){t.invoke.apply(this,arguments)};r.apply(e.target,e.args);return t}r=$(t,e,(function(t){return function(e,r){var s=i(e,r);if(s.cbIdx>=0&&typeof r[s.cbIdx]==="function"){return w(s.name,r[s.cbIdx],s,n)}else{return t.apply(e,r)}}}))}function F(t,e){t[g("OriginalDelegate")]=e}var U=false;var B=false;function q(){if(U){return B}U=true;try{var t=x.navigator.userAgent;if(t.indexOf("MSIE ")!==-1||t.indexOf("Trident/")!==-1||t.indexOf("Edge/")!==-1){B=true}}catch(t){}return B}function V(t){return typeof t==="function"}function H(t){return typeof t==="number"}var G={useG:true};var Z={};var W={};var X=new RegExp("^"+b+"(\\w+)(true|false)$");var Y=g("propagationStopped");function J(t,e){var i=(e?e(t):t)+m;var r=(e?e(t):t)+p;var n=b+i;var s=b+r;Z[t]={};Z[t][m]=n;Z[t][p]=s}function K(e,i,r,n){var s=n&&n.add||l;var o=n&&n.rm||f;var c=n&&n.listeners||"eventListeners";var u=n&&n.rmAll||"removeAllListeners";var h=g(s);var d="."+s+":";var v="prependListener";var w="."+v+":";var y=function(t,e,i){if(t.isRemoved){return}var r=t.callback;if(typeof r==="object"&&r.handleEvent){t.callback=function(t){return r.handleEvent(t)};t.originalDelegate=r}var n;try{t.invoke(t,e,[i])}catch(t){n=t}var s=t.options;if(s&&typeof s==="object"&&s.once){var a=t.originalDelegate?t.originalDelegate:t.callback;e[o].call(e,i.type,a,s)}return n};function x(t,r,n){r=r||e.event;if(!r){return}var s=t||r.target||e;var o=s[Z[r.type][n?p:m]];if(o){var a=[];if(o.length===1){var c=y(o[0],s,r);c&&a.push(c)}else{var u=o.slice();for(var l=0;l<u.length;l++){if(r&&r[Y]===true){break}var c=y(u[l],s,r);c&&a.push(c)}}if(a.length===1){throw a[0]}else{var f=function(t){var e=a[t];i.nativeScheduleMicroTask((function(){throw e}))};for(var l=0;l<a.length;l++){f(l)}}}}var k=function(t){return x(this,t,false)};var S=function(t){return x(this,t,true)};function _(i,r){if(!i){return false}var n=true;if(r&&r.useG!==undefined){n=r.useG}var l=r&&r.vh;var f=true;if(r&&r.chkDup!==undefined){f=r.chkDup}var y=false;if(r&&r.rt!==undefined){y=r.rt}var x=i;while(x&&!x.hasOwnProperty(s)){x=a(x)}if(!x&&i[s]){x=i}if(!x){return false}if(x[h]){return false}var _=r&&r.eventNameToString;var T={};var E=x[h]=x[s];var M=x[g(o)]=x[o];var A=x[g(c)]=x[c];var P=x[g(u)]=x[u];var I;if(r&&r.prepend){I=x[g(r.prepend)]=x[r.prepend]}function O(e,i){if(!i){return e}if(typeof e==="boolean"){return{capture:e,passive:true}}if(!e){return{passive:true}}if(typeof e==="object"&&e.passive!==false){return t(t({},e),{passive:true})}return e}var L=function(t){if(T.isExisting){return}return E.call(T.target,T.eventName,T.capture?S:k,T.options)};var j=function(t){if(!t.isRemoved){var e=Z[t.eventName];var i=void 0;if(e){i=e[t.capture?p:m]}var r=i&&t.target[i];if(r){for(var n=0;n<r.length;n++){var s=r[n];if(s===t){r.splice(n,1);t.isRemoved=true;if(t.removeAbortListener){t.removeAbortListener();t.removeAbortListener=null}if(r.length===0){t.allRemoved=true;t.target[i]=null}break}}}}if(!t.allRemoved){return}return M.call(t.target,t.eventName,t.capture?S:k,t.options)};var N=function(t){return E.call(T.target,T.eventName,t.invoke,T.options)};var R=function(t){return I.call(T.target,T.eventName,t.invoke,T.options)};var z=function(t){return M.call(t.target,t.eventName,t.invoke,t.options)};var $=n?L:N;var D=n?j:z;var U=function(t,e){var i=typeof e;return i==="function"&&t.callback===e||i==="object"&&t.originalDelegate===e};var B=(r===null||r===void 0?void 0:r.diff)||U;var q=Zone[g("UNPATCHED_EVENTS")];var V=e[g("PASSIVE_EVENTS")];function H(e){if(typeof e==="object"&&e!==null){var i=t({},e);if(e.signal){i.signal=e.signal}return i}return e}var Y=function(t,i,s,o,a,c){if(a===void 0){a=false}if(c===void 0){c=false}return function(){var u=this||e;var h=arguments[0];if(r&&r.transferEventName){h=r.transferEventName(h)}var d=arguments[1];if(!d){return t.apply(this,arguments)}if(C&&h==="uncaughtException"){return t.apply(this,arguments)}var b=false;if(typeof d!=="function"){if(!d.handleEvent){return t.apply(this,arguments)}b=true}if(l&&!l(t,d,u,arguments)){return}var v=!!V&&V.indexOf(h)!==-1;var w=H(O(arguments[2],v));var g=w===null||w===void 0?void 0:w.signal;if(g===null||g===void 0?void 0:g.aborted){return}if(q){for(var y=0;y<q.length;y++){if(h===q[y]){if(v){return t.call(u,h,d,w)}else{return t.apply(this,arguments)}}}}var x=!w?false:typeof w==="boolean"?true:w.capture;var k=w&&typeof w==="object"?w.once:false;var S=Zone.current;var E=Z[h];if(!E){J(h,_);E=Z[h]}var M=E[x?p:m];var A=u[M];var P=false;if(A){P=true;if(f){for(var y=0;y<A.length;y++){if(B(A[y],d)){return}}}}else{A=u[M]=[]}var I;var L=u.constructor["name"];var j=W[L];if(j){I=j[h]}if(!I){I=L+i+(_?_(h):h)}T.options=w;if(k){T.options.once=false}T.target=u;T.capture=x;T.eventName=h;T.isExisting=P;var N=n?G:undefined;if(N){N.taskData=T}if(g){T.options.signal=undefined}var R=S.scheduleEventTask(I,d,N,s,o);if(g){T.options.signal=g;var z=function(){return R.zone.cancelTask(R)};t.call(g,"abort",z,{once:true});R.removeAbortListener=function(){return g.removeEventListener("abort",z)}}T.target=null;if(N){N.taskData=null}if(k){T.options.once=true}if(typeof R.options!=="boolean"){R.options=w}R.target=u;R.capture=x;R.eventName=h;if(b){R.originalDelegate=d}if(!c){A.push(R)}else{A.unshift(R)}if(a){return u}}};x[s]=Y(E,d,$,D,y);if(I){x[v]=Y(I,w,R,D,y,true)}x[o]=function(){var t=this||e;var i=arguments[0];if(r&&r.transferEventName){i=r.transferEventName(i)}var n=arguments[2];var s=!n?false:typeof n==="boolean"?true:n.capture;var o=arguments[1];if(!o){return M.apply(this,arguments)}if(l&&!l(M,o,t,arguments)){return}var a=Z[i];var c;if(a){c=a[s?p:m]}var u=c&&t[c];if(u){for(var f=0;f<u.length;f++){var h=u[f];if(B(h,o)){u.splice(f,1);h.isRemoved=true;if(u.length===0){h.allRemoved=true;t[c]=null;if(!s&&typeof i==="string"){var d=b+"ON_PROPERTY"+i;t[d]=null}}h.zone.cancelTask(h);if(y){return t}return}}}return M.apply(this,arguments)};x[c]=function(){var t=this||e;var i=arguments[0];if(r&&r.transferEventName){i=r.transferEventName(i)}var n=[];var s=Q(t,_?_(i):i);for(var o=0;o<s.length;o++){var a=s[o];var c=a.originalDelegate?a.originalDelegate:a.callback;n.push(c)}return n};x[u]=function(){var t=this||e;var i=arguments[0];if(!i){var n=Object.keys(t);for(var s=0;s<n.length;s++){var a=n[s];var c=X.exec(a);var l=c&&c[1];if(l&&l!=="removeListener"){this[u].call(this,l)}}this[u].call(this,"removeListener")}else{if(r&&r.transferEventName){i=r.transferEventName(i)}var f=Z[i];if(f){var h=f[m];var d=f[p];var b=t[h];var v=t[d];if(b){var w=b.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}if(v){var w=v.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}}}if(y){return this}};F(x[s],E);F(x[o],M);if(P){F(x[u],P)}if(A){F(x[c],A)}return true}var T=[];for(var E=0;E<r.length;E++){T[E]=_(r[E],n)}return T}function Q(t,e){if(!e){var i=[];for(var r in t){var n=X.exec(r);var s=n&&n[1];if(s&&(!e||s===e)){var o=t[r];if(o){for(var a=0;a<o.length;a++){i.push(o[a])}}}}return i}var c=Z[e];if(!c){J(e);c=Z[e]}var u=t[c[m]];var l=t[c[p]];if(!u){return l?l.slice():[]}else{return l?u.concat(l):u.slice()}}function tt(t,e){var i=t["Event"];if(i&&i.prototype){e.patchMethod(i.prototype,"stopImmediatePropagation",(function(t){return function(e,i){e[Y]=true;t&&t.apply(e,i)}}))}}function et(t,e){e.patchMethod(t,"queueMicrotask",(function(t){return function(t,e){Zone.current.scheduleMicroTask("queueMicrotask",e[0])}}))}var it=g("zoneTask");function rt(t,e,i,r){var n=null;var s=null;e+=r;i+=r;var o={};function a(e){var i=e.data;i.args[0]=function(){return e.invoke.apply(this,arguments)};var r=n.apply(t,i.args);if(H(r)){i.handleId=r}else{i.handle=r;i.isRefreshable=V(r.refresh)}return e}function c(e){var i=e.data,r=i.handle,n=i.handleId;return s.call(t,r!==null&&r!==void 0?r:n)}n=$(t,e,(function(i){return function(n,s){var u;if(V(s[0])){var l={isRefreshable:false,isPeriodic:r==="Interval",delay:r==="Timeout"||r==="Interval"?s[1]||0:undefined,args:s};var f=s[0];s[0]=function t(){try{return f.apply(this,arguments)}finally{var e=l.handle,i=l.handleId,r=l.isPeriodic,n=l.isRefreshable;if(!r&&!n){if(i){delete o[i]}else if(e){e[it]=null}}}};var h=w(e,s[0],l,a,c);if(!h){return h}var d=h.data,p=d.handleId,m=d.handle,b=d.isRefreshable,v=d.isPeriodic;if(p){o[p]=h}else if(m){m[it]=h;if(b&&!v){var g=m.refresh;m.refresh=function(){var t=h.zone,e=h.state;if(e==="notScheduled"){h._state="scheduled";t._updateTaskCount(h,1)}else if(e==="running"){h._state="scheduling"}return g.call(this)}}}return(u=m!==null&&m!==void 0?m:p)!==null&&u!==void 0?u:h}else{return i.apply(t,s)}}}));s=$(t,i,(function(e){return function(i,r){var n=r[0];var s;if(H(n)){s=o[n];delete o[n]}else{s=n===null||n===void 0?void 0:n[it];if(s){n[it]=null}else{s=n}}if(s===null||s===void 0?void 0:s.type){if(s.cancelFn){s.zone.cancelTask(s)}}else{e.apply(t,r)}}}))}function nt(t,e){var i=e.getGlobalObjects(),r=i.isBrowser,n=i.isMix;if(!r&&!n||!t["customElements"]||!("customElements"in t)){return}var s=["connectedCallback","disconnectedCallback","adoptedCallback","attributeChangedCallback","formAssociatedCallback","formDisabledCallback","formResetCallback","formStateRestoreCallback"];e.patchCallbacks(e,t.customElements,"customElements","define",s)}function st(t,e){if(Zone[e.symbol("patchEventTarget")]){return}var i=e.getGlobalObjects(),r=i.eventNames,n=i.zoneSymbolEventNames,s=i.TRUE_STR,o=i.FALSE_STR,a=i.ZONE_SYMBOL_PREFIX;for(var c=0;c<r.length;c++){var u=r[c];var l=u+o;var f=u+s;var h=a+l;var d=a+f;n[u]={};n[u][o]=h;n[u][s]=d}var p=t["EventTarget"];if(!p||!p.prototype){return}e.patchEventTarget(t,e,[p&&p.prototype]);return true}function ot(t,e){e.patchEventPrototype(t,e)}function at(t,e,i){if(!i||i.length===0){return e}var r=i.filter((function(e){return e.target===t}));if(r.length===0){return e}var n=r[0].ignoreProperties;return e.filter((function(t){return n.indexOf(t)===-1}))}function ct(t,e,i,r){if(!t){return}var n=at(t,e,i);N(t,n,r)}function ut(t){return Object.getOwnPropertyNames(t).filter((function(t){return t.startsWith("on")&&t.length>2})).map((function(t){return t.substring(2)}))}function lt(t,e){if(C&&!P){return}if(Zone[t.symbol("patchEvents")]){return}var i=e["__Zone_ignore_on_properties"];var r=[];if(A){var n=window;r=r.concat(["Document","SVGElement","Element","HTMLElement","HTMLBodyElement","HTMLMediaElement","HTMLFrameSetElement","HTMLFrameElement","HTMLIFrameElement","HTMLMarqueeElement","Worker"]);var s=[];ct(n,ut(n),i?i.concat(s):i,a(n))}r=r.concat(["XMLHttpRequest","XMLHttpRequestEventTarget","IDBIndex","IDBRequest","IDBOpenDBRequest","IDBDatabase","IDBTransaction","IDBCursor","WebSocket"]);for(var o=0;o<r.length;o++){var c=e[r[o]];(c===null||c===void 0?void 0:c.prototype)&&ct(c.prototype,ut(c.prototype),i)}}function ft(t){t.__load_patch("legacy",(function(e){var i=e[t.__symbol__("legacyPatch")];if(i){i()}}));t.__load_patch("timers",(function(t){var e="set";var i="clear";rt(t,e,i,"Timeout");rt(t,e,i,"Interval");rt(t,e,i,"Immediate")}));t.__load_patch("requestAnimationFrame",(function(t){rt(t,"request","cancel","AnimationFrame");rt(t,"mozRequest","mozCancel","AnimationFrame");rt(t,"webkitRequest","webkitCancel","AnimationFrame")}));t.__load_patch("blocking",(function(t,e){var i=["alert","prompt","confirm"];for(var r=0;r<i.length;r++){var n=i[r];$(t,n,(function(i,r,n){return function(r,s){return e.current.run(i,t,s,n)}}))}}));t.__load_patch("EventTarget",(function(t,e,i){ot(t,i);st(t,i);var r=t["XMLHttpRequestEventTarget"];if(r&&r.prototype){i.patchEventTarget(t,i,[r.prototype])}}));t.__load_patch("MutationObserver",(function(t,e,i){z("MutationObserver");z("WebKitMutationObserver")}));t.__load_patch("IntersectionObserver",(function(t,e,i){z("IntersectionObserver")}));t.__load_patch("FileReader",(function(t,e,i){z("FileReader")}));t.__load_patch("on_property",(function(t,e,i){lt(i,t)}));t.__load_patch("customElements",(function(t,e,i){nt(t,i)}));t.__load_patch("XHR",(function(t,e){c(t);var i=g("xhrTask");var r=g("xhrSync");var n=g("xhrListener");var s=g("xhrScheduled");var o=g("xhrURL");var a=g("xhrErrorBeforeScheduled");function c(t){var c=t["XMLHttpRequest"];if(!c){return}var u=c.prototype;function l(t){return t[i]}var f=u[h];var p=u[d];if(!f){var m=t["XMLHttpRequestEventTarget"];if(m){var b=m.prototype;f=b[h];p=b[d]}}var v="readystatechange";var y="scheduled";function x(t){var r=t.data;var o=r.target;o[s]=false;o[a]=false;var c=o[n];if(!f){f=o[h];p=o[d]}if(c){p.call(o,v,c)}var u=o[n]=function(){if(o.readyState===o.DONE){if(!r.aborted&&o[s]&&t.state===y){var i=o[e.__symbol__("loadfalse")];if(o.status!==0&&i&&i.length>0){var n=t.invoke;t.invoke=function(){var i=o[e.__symbol__("loadfalse")];for(var s=0;s<i.length;s++){if(i[s]===t){i.splice(s,1)}}if(!r.aborted&&t.state===y){n.call(t)}};i.push(t)}else{t.invoke()}}else if(!r.aborted&&o[s]===false){o[a]=true}}};f.call(o,v,u);var l=o[i];if(!l){o[i]=t}C.apply(o,r.args);o[s]=true;return t}function k(){}function S(t){var e=t.data;e.aborted=true;return A.apply(e.target,e.args)}var _=$(u,"open",(function(){return function(t,e){t[r]=e[2]==false;t[o]=e[1];return _.apply(t,e)}}));var T="XMLHttpRequest.send";var E=g("fetchTaskAborting");var M=g("fetchTaskScheduling");var C=$(u,"send",(function(){return function(t,i){if(e.current[M]===true){return C.apply(t,i)}if(t[r]){return C.apply(t,i)}else{var n={target:t,url:t[o],isPeriodic:false,args:i,aborted:false};var s=w(T,k,n,x,S);if(t&&t[a]===true&&!n.aborted&&s.state===y){s.invoke()}}}}));var A=$(u,"abort",(function(){return function(t,i){var r=l(t);if(r&&typeof r.type=="string"){if(r.cancelFn==null||r.data&&r.data.aborted){return}r.zone.cancelTask(r)}else if(e.current[E]===true){return A.apply(t,i)}}}))}}));t.__load_patch("geolocation",(function(t){if(t["navigator"]&&t["navigator"].geolocation){T(t["navigator"].geolocation,["getCurrentPosition","watchPosition"])}}));t.__load_patch("PromiseRejectionEvent",(function(t,e){function i(e){return function(i){var r=Q(t,e);r.forEach((function(r){var n=t["PromiseRejectionEvent"];if(n){var s=new n(e,{promise:i.promise,reason:i.rejection});r.invoke(s)}}))}}if(t["PromiseRejectionEvent"]){e[g("unhandledPromiseRejectionHandler")]=i("unhandledrejection");e[g("rejectionHandledHandler")]=i("rejectionhandled")}}));t.__load_patch("queueMicrotask",(function(t,e,i){et(t,i)}))}function ht(t){t.__load_patch("ZoneAwarePromise",(function(t,e,i){var r=Object.getOwnPropertyDescriptor;var n=Object.defineProperty;function s(t){if(t&&t.toString===Object.prototype.toString){var e=t.constructor&&t.constructor.name;return(e?e:"")+": "+JSON.stringify(t)}return t?t.toString():Object.prototype.toString.call(t)}var o=i.symbol;var a=[];var c=t[o("DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION")]!==false;var u=o("Promise");var l=o("then");var f="__creationTrace__";i.onUnhandledError=function(t){if(i.showUncaughtError()){var e=t&&t.rejection;if(e){console.error("Unhandled Promise rejection:",e instanceof Error?e.message:e,"; Zone:",t.zone.name,"; Task:",t.task&&t.task.source,"; Value:",e,e instanceof Error?e.stack:undefined)}else{console.error(t)}}};i.microtaskDrainDone=function(){var t=function(){var t=a.shift();try{t.zone.runGuarded((function(){if(t.throwOriginal){throw t.rejection}throw t}))}catch(t){d(t)}};while(a.length){t()}};var h=o("unhandledPromiseRejectionHandler");function d(t){i.onUnhandledError(t);try{var r=e[h];if(typeof r==="function"){r.call(this,t)}}catch(t){}}function p(t){return t&&typeof t.then==="function"}function m(t){return t}function b(t){return D.reject(t)}var v=o("state");var w=o("value");var g=o("finally");var y=o("parentPromiseValue");var x=o("parentPromiseState");var k="Promise.then";var S=null;var _=true;var T=false;var E=0;function M(t,e){return function(i){try{I(t,e,i)}catch(e){I(t,false,e)}}}var C=function(){var t=false;return function e(i){return function(){if(t){return}t=true;i.apply(null,arguments)}}};var A="Promise resolved with itself";var P=o("currentTaskTrace");function I(t,r,o){var u=C();if(t===o){throw new TypeError(A)}if(t[v]===S){var l=null;try{if(typeof o==="object"||typeof o==="function"){l=o&&o.then}}catch(e){u((function(){I(t,false,e)}))();return t}if(r!==T&&o instanceof D&&o.hasOwnProperty(v)&&o.hasOwnProperty(w)&&o[v]!==S){L(o);I(t,o[v],o[w])}else if(r!==T&&typeof l==="function"){try{l.call(o,u(M(t,r)),u(M(t,false)))}catch(e){u((function(){I(t,false,e)}))()}}else{t[v]=r;var h=t[w];t[w]=o;if(t[g]===g){if(r===_){t[v]=t[x];t[w]=t[y]}}if(r===T&&o instanceof Error){var d=e.currentTask&&e.currentTask.data&&e.currentTask.data[f];if(d){n(o,P,{configurable:true,enumerable:false,writable:true,value:d})}}for(var p=0;p<h.length;){j(t,h[p++],h[p++],h[p++],h[p++])}if(h.length==0&&r==T){t[v]=E;var m=o;try{throw new Error("Uncaught (in promise): "+s(o)+(o&&o.stack?"\n"+o.stack:""))}catch(t){m=t}if(c){m.throwOriginal=true}m.rejection=o;m.promise=t;m.zone=e.current;m.task=e.currentTask;a.push(m);i.scheduleMicroTask()}}}return t}var O=o("rejectionHandledHandler");function L(t){if(t[v]===E){try{var i=e[O];if(i&&typeof i==="function"){i.call(this,{rejection:t[w],promise:t})}}catch(t){}t[v]=T;for(var r=0;r<a.length;r++){if(t===a[r].promise){a.splice(r,1)}}}}function j(t,e,i,r,n){L(t);var s=t[v];var o=s?typeof r==="function"?r:m:typeof n==="function"?n:b;e.scheduleMicroTask(k,(function(){try{var r=t[w];var n=!!i&&g===i[g];if(n){i[y]=r;i[x]=s}var a=e.run(o,undefined,n&&o!==b&&o!==m?[]:[r]);I(i,true,a)}catch(t){I(i,false,t)}}),i)}var N="function ZoneAwarePromise() { [native code] }";var R=function(){};var z=t.AggregateError;var D=function(){function t(e){var i=this;if(!(i instanceof t)){throw new Error("Must be an instanceof Promise.")}i[v]=S;i[w]=[];try{var r=C();e&&e(r(M(i,_)),r(M(i,T)))}catch(t){I(i,false,t)}}t.toString=function(){return N};t.resolve=function(e){if(e instanceof t){return e}return I(new this(null),_,e)};t.reject=function(t){return I(new this(null),T,t)};t.withResolvers=function(){var e={};e.promise=new t((function(t,i){e.resolve=t;e.reject=i}));return e};t.any=function(e){if(!e||typeof e[Symbol.iterator]!=="function"){return Promise.reject(new z([],"All promises were rejected"))}var i=[];var r=0;try{for(var n=0,s=e;n<s.length;n++){var o=s[n];r++;i.push(t.resolve(o))}}catch(t){return Promise.reject(new z([],"All promises were rejected"))}if(r===0){return Promise.reject(new z([],"All promises were rejected"))}var a=false;var c=[];return new t((function(t,e){for(var n=0;n<i.length;n++){i[n].then((function(e){if(a){return}a=true;t(e)}),(function(t){c.push(t);r--;if(r===0){a=true;e(new z(c,"All promises were rejected"))}}))}}))};t.race=function(t){var e;var i;var r=new this((function(t,r){e=t;i=r}));function n(t){e(t)}function s(t){i(t)}for(var o=0,a=t;o<a.length;o++){var c=a[o];if(!p(c)){c=this.resolve(c)}c.then(n,s)}return r};t.all=function(e){return t.allWithCallback(e)};t.allSettled=function(e){var i=this&&this.prototype instanceof t?this:t;return i.allWithCallback(e,{thenCallback:function(t){return{status:"fulfilled",value:t}},errorCallback:function(t){return{status:"rejected",reason:t}}})};t.allWithCallback=function(t,e){var i;var r;var n=new this((function(t,e){i=t;r=e}));var s=2;var o=0;var a=[];var c=function(t){if(!p(t)){t=u.resolve(t)}var n=o;try{t.then((function(t){a[n]=e?e.thenCallback(t):t;s--;if(s===0){i(a)}}),(function(t){if(!e){r(t)}else{a[n]=e.errorCallback(t);s--;if(s===0){i(a)}}}))}catch(t){r(t)}s++;o++};var u=this;for(var l=0,f=t;l<f.length;l++){var h=f[l];c(h)}s-=2;if(s===0){i(a)}return n};Object.defineProperty(t.prototype,Symbol.toStringTag,{get:function(){return"Promise"},enumerable:false,configurable:true});Object.defineProperty(t.prototype,Symbol.species,{get:function(){return t},enumerable:false,configurable:true});t.prototype.then=function(i,r){var n;var s=(n=this.constructor)===null||n===void 0?void 0:n[Symbol.species];if(!s||typeof s!=="function"){s=this.constructor||t}var o=new s(R);var a=e.current;if(this[v]==S){this[w].push(a,o,i,r)}else{j(this,a,o,i,r)}return o};t.prototype.catch=function(t){return this.then(null,t)};t.prototype.finally=function(i){var r;var n=(r=this.constructor)===null||r===void 0?void 0:r[Symbol.species];if(!n||typeof n!=="function"){n=t}var s=new n(R);s[g]=g;var o=e.current;if(this[v]==S){this[w].push(o,s,i,i)}else{j(this,o,s,i,i)}return s};return t}();D["resolve"]=D.resolve;D["reject"]=D.reject;D["race"]=D.race;D["all"]=D.all;var F=t[u]=t["Promise"];t["Promise"]=D;var U=o("thenPatched");function B(t){var e=t.prototype;var i=r(e,"then");if(i&&(i.writable===false||!i.configurable)){return}var n=e.then;e[l]=n;t.prototype.then=function(t,e){var i=this;var r=new D((function(t,e){n.call(i,t,e)}));return r.then(t,e)};t[U]=true}i.patchThen=B;function q(t){return function(e,i){var r=t.apply(e,i);if(r instanceof D){return r}var n=r.constructor;if(!n[U]){B(n)}return r}}if(F){B(F);$(t,"fetch",(function(t){return q(t)}))}Promise[e.__symbol__("uncaughtPromiseErrors")]=a;return D}))}function dt(t){t.__load_patch("toString",(function(t){var e=Function.prototype.toString;var i=g("OriginalDelegate");var r=g("Promise");var n=g("Error");var s=function s(){if(typeof this==="function"){var o=this[i];if(o){if(typeof o==="function"){return e.call(o)}else{return Object.prototype.toString.call(o)}}if(this===Promise){var a=t[r];if(a){return e.call(a)}}if(this===Error){var c=t[n];if(c){return e.call(c)}}}return e.call(this)};s[i]=e;Function.prototype.toString=s;var o=Object.prototype.toString;var a="[object Promise]";Object.prototype.toString=function(){if(typeof Promise==="function"&&this instanceof Promise){return a}return o.call(this)}}))}function pt(t,e,i,r,n){var s=Zone.__symbol__(r);if(e[s]){return}var o=e[s]=e[r];e[r]=function(s,a,c){if(a&&a.prototype){n.forEach((function(e){var n="".concat(i,".").concat(r,"::")+e;var s=a.prototype;try{if(s.hasOwnProperty(e)){var o=t.ObjectGetOwnPropertyDescriptor(s,e);if(o&&o.value){o.value=t.wrapWithCurrentZone(o.value,n);t._redefineProperty(a.prototype,e,o)}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],n)}}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],n)}}catch(t){}}))}return o.call(e,s,a,c)};t.attachOriginToPatched(e[r],o)}function mt(t){t.__load_patch("util",(function(t,e,i){var r=ut(t);i.patchOnProperties=N;i.patchMethod=$;i.bindArguments=_;i.patchMacroTask=D;var n=e.__symbol__("BLACK_LISTED_EVENTS");var a=e.__symbol__("UNPATCHED_EVENTS");if(t[a]){t[n]=t[a]}if(t[n]){e[n]=e[a]=t[n]}i.patchEventPrototype=tt;i.patchEventTarget=K;i.isIEOrEdge=q;i.ObjectDefineProperty=o;i.ObjectGetOwnPropertyDescriptor=s;i.ObjectCreate=c;i.ArraySlice=u;i.patchClass=z;i.wrapWithCurrentZone=v;i.filterProperties=at;i.attachOriginToPatched=F;i._redefineProperty=Object.defineProperty;i.patchCallbacks=pt;i.getGlobalObjects=function(){return{globalSources:W,zoneSymbolEventNames:Z,eventNames:r,isBrowser:A,isMix:P,isNode:C,TRUE_STR:p,FALSE_STR:m,ZONE_SYMBOL_PREFIX:b,ADD_EVENT_LISTENER_STR:l,REMOVE_EVENT_LISTENER_STR:f}}}))}function bt(t){ht(t);dt(t);mt(t)}var vt=n();bt(vt);ft(vt)}));return qa}Ha();class Ga{emit(t){}}const Za=new Ga;class Wa{getLogger(t,e,i){return new Ga}}const Xa=new Wa;class Ya{constructor(t,e,i,r){this._provider=t;this.name=e;this.version=i;this.options=r}emit(t){this._getLogger().emit(t)}_getLogger(){if(this._delegate){return this._delegate}const t=this._provider._getDelegateLogger(this.name,this.version,this.options);if(!t){return Za}this._delegate=t;return this._delegate}}class Ja{getLogger(t,e,i){var r;return(r=this._getDelegateLogger(t,e,i))!==null&&r!==void 0?r:new Ya(this,t,e,i)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Xa}_setDelegate(t){this._delegate=t}_getDelegateLogger(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getLogger(t,e,i)}}const Ka=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};const Qa=Symbol.for("io.opentelemetry.js.api.logs");const tc=Ka;function ec(t,e,i){return r=>r===t?e:i}const ic=1;class rc{constructor(){this._proxyLoggerProvider=new Ja}static getInstance(){if(!this._instance){this._instance=new rc}return this._instance}setGlobalLoggerProvider(t){if(tc[Qa]){return this.getLoggerProvider()}tc[Qa]=ec(ic,t,Xa);this._proxyLoggerProvider._setDelegate(t);return t}getLoggerProvider(){var t,e;return(e=(t=tc[Qa])===null||t===void 0?void 0:t.call(tc,ic))!==null&&e!==void 0?e:this._proxyLoggerProvider}getLogger(t,e,i){return this.getLoggerProvider().getLogger(t,e,i)}disable(){delete tc[Qa];this._proxyLoggerProvider=new Ja}}const nc=rc.getInstance();function sc(t,e,i,r){for(let n=0,s=t.length;n<s;n++){const s=t[n];if(e){s.setTracerProvider(e)}if(i){s.setMeterProvider(i)}if(r&&s.setLoggerProvider){s.setLoggerProvider(r)}if(!s.getConfig().enabled){s.enable()}}}function oc(t){t.forEach((t=>t.disable()))}function ac(t){const e=t.tracerProvider||pe.getTracerProvider();const i=t.meterProvider||ee.getMeterProvider();const r=t.loggerProvider||nc.getLoggerProvider();const n=t.instrumentations?.flat()??[];sc(n,e,i,r);return()=>{oc(n)}}let cc=console.error.bind(console);function uc(t,e,i){const r=!!t[e]&&Object.prototype.propertyIsEnumerable.call(t,e);Object.defineProperty(t,e,{configurable:true,enumerable:r,writable:true,value:i})}const lc=(t,e,i)=>{if(!t||!t[e]){cc("no original function "+String(e)+" to wrap");return}if(!i){cc("no wrapper function");cc((new Error).stack);return}const r=t[e];if(typeof r!=="function"||typeof i!=="function"){cc("original object and wrapper must be functions");return}const n=i(r,e);uc(n,"__original",r);uc(n,"__unwrap",(()=>{if(t[e]===n){uc(t,e,r)}}));uc(n,"__wrapped",true);uc(t,e,n);return n};const fc=(t,e,i)=>{if(!t){cc("must provide one or more modules to patch");cc((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){cc("must provide one or more functions to wrap on modules");return}t.forEach((t=>{e.forEach((e=>{lc(t,e,i)}))}))};const hc=(t,e)=>{if(!t||!t[e]){cc("no function to unwrap.");cc((new Error).stack);return}const i=t[e];if(!i.__unwrap){cc("no original to unwrap to -- has "+String(e)+" already been unwrapped?")}else{i.__unwrap();return}};const dc=(t,e)=>{if(!t){cc("must provide one or more modules to patch");cc((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){cc("must provide one or more functions to unwrap on modules");return}t.forEach((t=>{e.forEach((e=>{hc(t,e)}))}))};class pc{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(t,e,i){this.instrumentationName=t;this.instrumentationVersion=e;this.setConfig(i);this._diag=Yt.createComponentLogger({namespace:t});this._tracer=pe.getTracer(t,e);this._meter=ee.getMeter(t,e);this._logger=nc.getLogger(t,e);this._updateMetricInstruments()}_wrap=lc;_unwrap=hc;_massWrap=fc;_massUnwrap=dc;get meter(){return this._meter}setMeterProvider(t){this._meter=t.getMeter(this.instrumentationName,this.instrumentationVersion);this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(t){this._logger=t.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const t=this.init()??[];if(!Array.isArray(t)){return[t]}return t}_updateMetricInstruments(){return}getConfig(){return this._config}setConfig(t){this._config={enabled:true,...t}}setTracerProvider(t){this._tracer=t.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(t,e,i,r){if(!t){return}try{t(i,r)}catch(t){this._diag.error(`Error running span customization hook due to exception in handler`,{triggerName:e},t)}}}class mc extends pc{constructor(t,e,i){super(t,e,i);if(this._config.enabled){this.enable()}}}function bc(t){return typeof t==="function"&&typeof t.__original==="function"&&typeof t.__unwrap==="function"&&t.__wrapped===true}var vc;(function(t){t["EVENT_TYPE"]="event_type";t["TARGET_ELEMENT"]="target_element";t["TARGET_XPATH"]="target_xpath";t["HTTP_URL"]="http.url"})(vc||(vc={}));const wc="0.53.0";const gc="@opentelemetry/instrumentation-user-interaction";const yc="OT_ZONE_CONTEXT";const xc="Navigation:";const kc=["click"];function Sc(){return false}class _c extends mc{version=wc;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(t={}){super(gc,wc,t);this._eventNames=new Set(t?.eventNames??kc);this._shouldPreventSpanCreation=typeof t?.shouldPreventSpanCreation==="function"?t.shouldPreventSpanCreation:Sc}init(){}_checkForTimeout(t,e){const i=this._spansData.get(e);if(i){if(t.source==="setTimeout"){i.hrTimeLastTimeout=ni()}else if(t.source!=="Promise.then"&&t.source!=="setTimeout"){i.hrTimeLastTimeout=undefined}}}_allowEventName(t){return this._eventNames.has(t)}_createSpan(t,e,i){if(!(t instanceof HTMLElement)){return undefined}if(!t.getAttribute){return undefined}if(t.hasAttribute("disabled")){return undefined}if(!this._allowEventName(e)){return undefined}const r=Jr(t,true);try{const n=this.tracer.startSpan(e,{attributes:{[vc.EVENT_TYPE]:e,[vc.TARGET_ELEMENT]:t.tagName,[vc.TARGET_XPATH]:r,[vc.HTTP_URL]:window.location.href}},i?pe.setSpan(Xt.active(),i):undefined);if(this._shouldPreventSpanCreation(e,t,n)===true){return undefined}this._spansData.set(n,{taskCount:0});return n}catch(t){this._diag.error("failed to start create new user interaction span",t)}return undefined}_decrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount--;if(e.taskCount===0){this._tryToEndSpan(t,e.hrTimeLastTimeout)}}}_getCurrentSpan(t){const e=t.get(yc);if(e){return pe.getSpan(e)}return e}_incrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount++}}addPatchedListener(t,e,i,r){let n=this._wrappedListeners.get(i);if(!n){n=new Map;this._wrappedListeners.set(i,n)}let s=n.get(e);if(!s){s=new Map;n.set(e,s)}if(s.has(t)){return false}s.set(t,r);return true}removePatchedListener(t,e,i){const r=this._wrappedListeners.get(i);if(!r){return undefined}const n=r.get(e);if(!n){return undefined}const s=n.get(t);if(s){n.delete(t);if(n.size===0){r.delete(e);if(r.size===0){this._wrappedListeners.delete(i)}}}return s}_invokeListener(t,e,i){if(typeof t==="function"){return t.apply(e,i)}else{return t.handleEvent(i[0])}}_patchAddEventListener(){const t=this;return e=>function i(r,n,s){if(!n){return e.call(this,r,n,s)}const o=s&&typeof s==="object"&&s.once;const a=function(...e){let i;const s=e[0];const a=s?.target;if(s){i=t._eventsSpanMap.get(s)}if(o){t.removePatchedListener(this,r,n)}const c=t._createSpan(a,r,i);if(c){if(s){t._eventsSpanMap.set(s,c)}return Xt.with(pe.setSpan(Xt.active(),c),(()=>{const i=t._invokeListener(n,this,e);c.end();return i}))}else{return t._invokeListener(n,this,e)}};if(t.addPatchedListener(this,r,n,a)){return e.call(this,r,a,s)}}}_patchRemoveEventListener(){const t=this;return e=>function i(r,n,s){const o=t.removePatchedListener(this,r,n);if(o){return e.call(this,r,o,s)}else{return e.call(this,r,n,s)}}}_getPatchableEventTargets(){return window.EventTarget?[EventTarget.prototype]:[Node.prototype,Window.prototype]}_patchHistoryApi(){this._unpatchHistoryApi();this._wrap(history,"replaceState",this._patchHistoryMethod());this._wrap(history,"pushState",this._patchHistoryMethod());this._wrap(history,"back",this._patchHistoryMethod());this._wrap(history,"forward",this._patchHistoryMethod());this._wrap(history,"go",this._patchHistoryMethod())}_patchHistoryMethod(){const t=this;return e=>function i(...r){const n=`${location.pathname}${location.hash}${location.search}`;const s=e.apply(this,r);const o=`${location.pathname}${location.hash}${location.search}`;if(n!==o){t._updateInteractionName(o)}return s}}_unpatchHistoryApi(){if(bc(history.replaceState))this._unwrap(history,"replaceState");if(bc(history.pushState))this._unwrap(history,"pushState");if(bc(history.back))this._unwrap(history,"back");if(bc(history.forward))this._unwrap(history,"forward");if(bc(history.go))this._unwrap(history,"go")}_updateInteractionName(t){const e=pe.getSpan(Xt.active());if(e&&typeof e.updateName==="function"){e.updateName(`${xc} ${t}`)}}_patchZoneCancelTask(){const t=this;return e=>function i(r){const n=Zone.current;const s=t._getCurrentSpan(n);if(s&&t._shouldCountTask(r,n)){t._decrementTask(s)}return e.call(this,r)}}_patchZoneScheduleTask(){const t=this;return e=>function i(r){const n=Zone.current;const s=t._getCurrentSpan(n);if(s&&t._shouldCountTask(r,n)){t._incrementTask(s);t._checkForTimeout(r,s)}return e.call(this,r)}}_patchZoneRunTask(){const t=this;return e=>function i(r,n,s){const o=Array.isArray(s)&&s[0]instanceof Event?s[0]:undefined;const a=o?.target;let c;const u=this;if(a){c=t._createSpan(a,r.eventName);if(c){t._incrementTask(c);return u.run((()=>{try{return Xt.with(pe.setSpan(Xt.active(),c),(()=>{const t=Zone.current;r._zone=t;return e.call(t,r,n,s)}))}finally{t._decrementTask(c)}}))}}else{c=t._getCurrentSpan(u)}try{return e.call(u,r,n,s)}finally{if(c&&t._shouldCountTask(r,u)){t._decrementTask(c)}}}}_shouldCountTask(t,e){if(t._zone){e=t._zone}if(!e||!t.data||t.data.isPeriodic){return false}const i=this._getCurrentSpan(e);if(!i){return false}if(!this._spansData.get(i)){return false}return t.type==="macroTask"||t.type==="microTask"}_tryToEndSpan(t,e){if(t){const i=this._spansData.get(t);if(i){t.end(e);this._spansData.delete(t)}}}enable(){const t=this._getZoneWithPrototype();this._diag.debug("applying patch to",this.moduleName,this.version,"zone:",!!t);if(t){if(bc(t.prototype.runTask)){this._unwrap(t.prototype,"runTask");this._diag.debug("removing previous patch from method runTask")}if(bc(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask");this._diag.debug("removing previous patch from method scheduleTask")}if(bc(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask");this._diag.debug("removing previous patch from method cancelTask")}this._zonePatched=true;this._wrap(t.prototype,"runTask",this._patchZoneRunTask());this._wrap(t.prototype,"scheduleTask",this._patchZoneScheduleTask());this._wrap(t.prototype,"cancelTask",this._patchZoneCancelTask())}else{this._zonePatched=false;const t=this._getPatchableEventTargets();t.forEach((t=>{if(bc(t.addEventListener)){this._unwrap(t,"addEventListener");this._diag.debug("removing previous patch from method addEventListener")}if(bc(t.removeEventListener)){this._unwrap(t,"removeEventListener");this._diag.debug("removing previous patch from method removeEventListener")}this._wrap(t,"addEventListener",this._patchAddEventListener());this._wrap(t,"removeEventListener",this._patchRemoveEventListener())}))}this._patchHistoryApi()}disable(){const t=this._getZoneWithPrototype();this._diag.debug("removing patch from",this.moduleName,this.version,"zone:",!!t);if(t&&this._zonePatched){if(bc(t.prototype.runTask)){this._unwrap(t.prototype,"runTask")}if(bc(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask")}if(bc(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask")}}else{const t=this._getPatchableEventTargets();t.forEach((t=>{if(bc(t.addEventListener)){this._unwrap(t,"addEventListener")}if(bc(t.removeEventListener)){this._unwrap(t,"removeEventListener")}}))}this._unpatchHistoryApi()}_getZoneWithPrototype(){const t=window;return t.Zone}}var Tc={exports:{}};var Ec=Tc.exports;var Mc;function Cc(){if(Mc)return Tc.exports;Mc=1;(function(t,e){(function(i,r){var n="1.0.41",s="",o="?",a="function",c="undefined",u="object",l="string",f="major",h="model",d="name",p="type",m="vendor",b="version",v="architecture",w="console",g="mobile",y="tablet",x="smarttv",k="wearable",S="embedded",_=500;var T="Amazon",E="Apple",M="ASUS",C="BlackBerry",A="Browser",P="Chrome",I="Edge",O="Firefox",L="Google",j="Honor",N="Huawei",R="Lenovo",z="LG",$="Microsoft",D="Motorola",F="Nvidia",U="OnePlus",B="Opera",q="OPPO",V="Samsung",H="Sharp",G="Sony",Z="Xiaomi",W="Zebra",X="Facebook",Y="Chromium OS",J="Mac OS",K=" Browser";var Q=function(t,e){var i={};for(var r in t){if(e[r]&&e[r].length%2===0){i[r]=e[r].concat(t[r])}else{i[r]=t[r]}}return i},tt=function(t){var e={};for(var i=0;i<t.length;i++){e[t[i].toUpperCase()]=t[i]}return e},et=function(t,e){return typeof t===l?it(e).indexOf(it(t))!==-1:false},it=function(t){return t.toLowerCase()},rt=function(t){return typeof t===l?t.replace(/[^\d\.]/g,s).split(".")[0]:r},nt=function(t,e){if(typeof t===l){t=t.replace(/^\s\s*/,s);return typeof e===c?t:t.substring(0,_)}};var st=function(t,e){var i=0,n,s,o,c,l,f;while(i<e.length&&!l){var h=e[i],d=e[i+1];n=s=0;while(n<h.length&&!l){if(!h[n]){break}l=h[n++].exec(t);if(!!l){for(o=0;o<d.length;o++){f=l[++s];c=d[o];if(typeof c===u&&c.length>0){if(c.length===2){if(typeof c[1]==a){this[c[0]]=c[1].call(this,f)}else{this[c[0]]=c[1]}}else if(c.length===3){if(typeof c[1]===a&&!(c[1].exec&&c[1].test)){this[c[0]]=f?c[1].call(this,f,c[2]):r}else{this[c[0]]=f?f.replace(c[1],c[2]):r}}else if(c.length===4){this[c[0]]=f?c[3].call(this,f.replace(c[1],c[2])):r}}else{this[c]=f?f:r}}}}i+=2}},ot=function(t,e){for(var i in e){if(typeof e[i]===u&&e[i].length>0){for(var n=0;n<e[i].length;n++){if(et(e[i][n],t)){return i===o?r:i}}}else if(et(e[i],t)){return i===o?r:i}}return e.hasOwnProperty("*")?e["*"]:t};var at={"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},ct={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"};var ut={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[b,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[b,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,b],[/opios[\/ ]+([\w\.]+)/i],[b,[d,B+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[b,[d,B+" GX"]],[/\bopr\/([\w\.]+)/i],[b,[d,B]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[b,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[b,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,b],[/quark(?:pc)?\/([-\w\.]+)/i],[b,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[b,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[b,[d,"UC"+A]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[b,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[b,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[b,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[b,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[b,[d,"Smart Lenovo "+A]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+A],b],[/\bfocus\/([\w\.]+)/i],[b,[d,O+" Focus"]],[/\bopt\/([\w\.]+)/i],[b,[d,B+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[b,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[b,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[b,[d,B+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[b,[d,"MIUI"+K]],[/fxios\/([\w\.-]+)/i],[b,[d,O]],[/\bqihoobrowser\/?([\w\.]*)/i],[b,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],b],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+K],b],[/samsungbrowser\/([\w\.]+)/i],[b,[d,V+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[b,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],b],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,b],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[b,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,X],b],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,b],[/\bgsa\/([\w\.]+) .*safari\//i],[b,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[b,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[b,[d,P+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,P+" WebView"],b],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[b,[d,"Android "+A]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,b],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[b,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[b,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[b,ot,at]],[/(webkit|khtml)\/([\w\.]+)/i],[d,b],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],b],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,b],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[b,[d,O+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[d,[b,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[b,/master.|lts./,""]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[v,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[v,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[v,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[v,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[v,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[v,/ower/,s,it]],[/ sun4\w[;\)]/i],[[v,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[v,it]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[h,[m,V],[p,y]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[h,[m,V],[p,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[h,[m,E],[p,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[h,[m,E],[p,y]],[/(macintosh);/i],[h,[m,E]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[h,[m,H],[p,g]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[h,[m,j],[p,y]],[/honor([-\w ]+)[;\)]/i],[h,[m,j],[p,g]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[h,[m,N],[p,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[h,[m,N],[p,g]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[h,/_/g," "],[m,Z],[p,y]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[h,/_/g," "],[m,Z],[p,g]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[h,[m,q],[p,g]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[h,[m,ot,{OnePlus:["304","403","203"],"*":q}],[p,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[h,[m,"Vivo"],[p,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[h,[m,"Realme"],[p,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[h,[m,D],[p,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[h,[m,D],[p,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[h,[m,z],[p,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[h,[m,z],[p,g]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[h,[m,R],[p,y]],[/(nokia) (t[12][01])/i],[m,h,[p,y]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[h,/_/g," "],[p,g],[m,"Nokia"]],[/(pixel (c|tablet))\b/i],[h,[m,L],[p,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[h,[m,L],[p,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[h,[m,G],[p,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[h,"Xperia Tablet"],[m,G],[p,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[h,[m,U],[p,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[h,[m,T],[p,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[h,/(.+)/g,"Fire Phone $1"],[m,T],[p,g]],[/(playbook);[-\w\),; ]+(rim)/i],[h,m,[p,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[h,[m,C],[p,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[h,[m,M],[p,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[h,[m,M],[p,g]],[/(nexus 9)/i],[h,[m,"HTC"],[p,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[m,[h,/_/g," "],[p,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[h,[m,"TCL"],[p,y]],[/(itel) ((\w+))/i],[[m,it],h,[p,ot,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[h,[m,"Acer"],[p,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[h,[m,"Meizu"],[p,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[h,[m,"Ulefone"],[p,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[h,[m,"Energizer"],[p,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[h,[m,"Cat"],[p,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[h,[m,"Smartfren"],[p,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[h,[m,"Nothing"],[p,g]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[h,[m,"Archos"],[p,y]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[h,[m,"Archos"],[p,g]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[m,h,[p,y]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[m,h,[p,g]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[m,h,[p,y]],[/(surface duo)/i],[h,[m,$],[p,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[h,[m,"Fairphone"],[p,g]],[/(u304aa)/i],[h,[m,"AT&T"],[p,g]],[/\bsie-(\w*)/i],[h,[m,"Siemens"],[p,g]],[/\b(rct\w+) b/i],[h,[m,"RCA"],[p,y]],[/\b(venue[\d ]{2,7}) b/i],[h,[m,"Dell"],[p,y]],[/\b(q(?:mv|ta)\w+) b/i],[h,[m,"Verizon"],[p,y]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[h,[m,"Barnes & Noble"],[p,y]],[/\b(tm\d{3}\w+) b/i],[h,[m,"NuVision"],[p,y]],[/\b(k88) b/i],[h,[m,"ZTE"],[p,y]],[/\b(nx\d{3}j) b/i],[h,[m,"ZTE"],[p,g]],[/\b(gen\d{3}) b.+49h/i],[h,[m,"Swiss"],[p,g]],[/\b(zur\d{3}) b/i],[h,[m,"Swiss"],[p,y]],[/\b((zeki)?tb.*\b) b/i],[h,[m,"Zeki"],[p,y]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[m,"Dragon Touch"],h,[p,y]],[/\b(ns-?\w{0,9}) b/i],[h,[m,"Insignia"],[p,y]],[/\b((nxa|next)-?\w{0,9}) b/i],[h,[m,"NextBook"],[p,y]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[m,"Voice"],h,[p,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[m,"LvTel"],h,[p,g]],[/\b(ph-1) /i],[h,[m,"Essential"],[p,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[h,[m,"Envizen"],[p,y]],[/\b(trio[-\w\. ]+) b/i],[h,[m,"MachSpeed"],[p,y]],[/\btu_(1491) b/i],[h,[m,"Rotor"],[p,y]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[h,[m,F],[p,y]],[/(sprint) (\w+)/i],[m,h,[p,g]],[/(kin\.[onetw]{3})/i],[[h,/\./g," "],[m,$],[p,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[h,[m,W],[p,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[h,[m,W],[p,g]],[/smart-tv.+(samsung)/i],[m,[p,x]],[/hbbtv.+maple;(\d+)/i],[[h,/^/,"SmartTV"],[m,V],[p,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[m,z],[p,x]],[/(apple) ?tv/i],[m,[h,E+" TV"],[p,x]],[/crkey/i],[[h,P+"cast"],[m,L],[p,x]],[/droid.+aft(\w+)( bui|\))/i],[h,[m,T],[p,x]],[/(shield \w+ tv)/i],[h,[m,F],[p,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[h,[m,H],[p,x]],[/(bravia[\w ]+)( bui|\))/i],[h,[m,G],[p,x]],[/(mi(tv|box)-?\w+) bui/i],[h,[m,Z],[p,x]],[/Hbbtv.*(technisat) (.*);/i],[m,h,[p,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[m,nt],[h,nt],[p,x]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[h,[p,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[p,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[m,h,[p,w]],[/droid.+; (shield)( bui|\))/i],[h,[m,F],[p,w]],[/(playstation \w+)/i],[h,[m,G],[p,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[h,[m,$],[p,w]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[h,[m,V],[p,k]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[m,h,[p,k]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[h,[m,q],[p,k]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[h,[m,E],[p,k]],[/(opwwe\d{3})/i],[h,[m,U],[p,k]],[/(moto 360)/i],[h,[m,D],[p,k]],[/(smartwatch 3)/i],[h,[m,G],[p,k]],[/(g watch r)/i],[h,[m,z],[p,k]],[/droid.+; (wt63?0{2,3})\)/i],[h,[m,W],[p,k]],[/droid.+; (glass) \d/i],[h,[m,L],[p,k]],[/(pico) (4|neo3(?: link|pro)?)/i],[m,h,[p,k]],[/; (quest( \d| pro)?)/i],[h,[m,X],[p,k]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[m,[p,S]],[/(aeobc)\b/i],[h,[m,T],[p,S]],[/(homepod).+mac os/i],[h,[m,E],[p,S]],[/windows iot/i],[[p,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[h,[p,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[h,[p,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[p,y]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[p,g]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[h,[m,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[b,[d,I+"HTML"]],[/(arkweb)\/([\w\.]+)/i],[d,b],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[b,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,b],[/ladybird\//i],[[d,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[b,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,b],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[d,[b,ot,ct]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[b,ot,ct],[d,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[b,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,J],[b,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[b,d],[/(ubuntu) ([\w\.]+) like android/i],[[d,/(.+)/,"$1 Touch"],b],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[d,b],[/\(bb(10);/i],[b,[d,C]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[b,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[b,[d,O+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[b,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[b,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[b,[d,P+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,Y],b],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,b],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],b],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,b]]};var lt=function(t,e){if(typeof t===u){e=t;t=r}if(!(this instanceof lt)){return new lt(t,e).getResult()}var n=typeof i!==c&&i.navigator?i.navigator:r;var o=t||(n&&n.userAgent?n.userAgent:s);var w=n&&n.userAgentData?n.userAgentData:r;var x=e?Q(ut,e):ut;var k=n&&n.userAgent==o;this.getBrowser=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.browser);t[f]=rt(t[b]);if(k&&n&&n.brave&&typeof n.brave.isBrave==a){t[d]="Brave"}return t};this.getCPU=function(){var t={};t[v]=r;st.call(t,o,x.cpu);return t};this.getDevice=function(){var t={};t[m]=r;t[h]=r;t[p]=r;st.call(t,o,x.device);if(k&&!t[p]&&w&&w.mobile){t[p]=g}if(k&&t[h]=="Macintosh"&&n&&typeof n.standalone!==c&&n.maxTouchPoints&&n.maxTouchPoints>2){t[h]="iPad";t[p]=y}return t};this.getEngine=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.engine);return t};this.getOS=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.os);if(k&&!t[d]&&w&&w.platform&&w.platform!="Unknown"){t[d]=w.platform.replace(/chrome os/i,Y).replace(/macos/i,J)}return t};this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}};this.getUA=function(){return o};this.setUA=function(t){o=typeof t===l&&t.length>_?nt(t,_):t;return this};this.setUA(o);return this};lt.VERSION=n;lt.BROWSER=tt([d,b,f]);lt.CPU=tt([v]);lt.DEVICE=tt([h,m,p,w,g,x,y,k,S]);lt.ENGINE=lt.OS=tt([d,b]);{if(t.exports){e=t.exports=lt}e.UAParser=lt}var ft=typeof i!==c&&(i.jQuery||i.Zepto);if(ft&&!ft.ua){var ht=new lt;ft.ua=ht.getResult();ft.ua.get=function(){return ht.getUA()};ft.ua.set=function(t){ht.setUA(t);var e=ht.getResult();for(var i in e){ft.ua[i]=e[i]}}}})(typeof window==="object"?window:Ec)})(Tc,Tc.exports);return Tc.exports}var Ac=Cc();var Pc=pn(Ac);const Ic="service.name";const Oc="service.version";const Lc="eAzROSTiqNd3i+M9Jw6q5Tld0jarZc617sJB//pvb5c=";let jc=false;function Nc(){if(jc){return}jc=true;const t=window.XMLHttpRequest;if(!t){console.error("[TracingService] XMLHttpRequest not available");return}window.XMLHttpRequest=function(){const e=new t;const i=e.open;const r=e.send;let n=false;e.open=function(t,e,...r){const s=typeof e==="string"?e:e.toString();n=s.includes("collector.jaak.ai");return i.apply(this,[t,e,...r])};e.send=function(...t){if(n){this.setRequestHeader("Authorization",`Bearer ${Lc}`)}return r.apply(this,t)};return e};for(const e in t){if(t.hasOwnProperty(e)){window.XMLHttpRequest[e]=t[e]}}const e=window.fetch;window.fetch=function(t,i){const r=typeof t==="string"?t:t instanceof URL?t.href:t.url;if(r.includes("collector.jaak.ai")){const t=new Headers(i?.headers||{});t.set("Authorization",`Bearer ${Lc}`);i={...i,headers:t}}return e.call(this,t,i)};navigator.sendBeacon=function(){return false}}class Rc{provider=null;tracer=null;sessionTraceId=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;enableAutoInstrumentation;spanProcessor=null;parser;geoCache=null;geoCacheTimestamp=0;GEO_CACHE_DURATION_MS=60*60*1e3;constructor(t={}){this.collectorUrl=t.collectorUrl||"https://collector.jaak.ai/v1/traces";this.serviceName=t.serviceName||"jaak-stamps-webcomponent";this.serviceVersion=t.serviceVersion||"2.1.0";this.debug=t.debug||false;this.customerId=t.customerId;this.tenantId=t.tenantId;this.environment=t.environment||"production";this.enableAutoInstrumentation=t.enableAutoInstrumentation??false;this.parser=new Pc}initialize(){try{Nc();const t=new Da({url:this.collectorUrl,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Lc}`},useSendBeacon:false});const e={export:(e,i)=>{if(this.debug){console.log("[TracingService] 📤 Exporting",e.length,"spans to collector")}t.export(e,(t=>{if(t.code!==0){console.error("[TracingService] ❌ Export failed:",t)}i(t)}))},shutdown:async()=>t.shutdown(),forceFlush:async()=>t.forceFlush()};this.spanProcessor=new zr(e,{maxQueueSize:100,maxExportBatchSize:10,scheduledDelayMillis:5e3,exportTimeoutMillis:3e4});this.provider=new Yr({spanProcessors:[this.spanProcessor]});const i=new Ba;const r=new Ni;this.provider.register({contextManager:i,propagator:r});this.tracer=pe.getTracer(this.serviceName,this.serviceVersion);if(this.enableAutoInstrumentation){this.initializeAutoInstrumentation()}}catch(t){console.error("[TracingService] Failed to initialize:",t)}}initializeAutoInstrumentation(){try{ac({instrumentations:[new _c({eventNames:["click","submit"],shouldPreventSpanCreation:(t,e)=>e.tagName==="BUTTON"||e.tagName==="A"||e.tagName==="FORM"})]})}catch(t){console.error("[TracingService] Failed to initialize auto-instrumentation:",t)}}getDeviceInfo(){const t=this.parser.getResult();return{type:t.device.type||"desktop",vendor:t.device.vendor||"unknown",model:t.device.model||"unknown"}}getBrowserInfo(){const t=this.parser.getResult();return{name:t.browser.name||"unknown",version:t.browser.version||"unknown",major:t.browser.major||"unknown"}}getOSInfo(){const t=this.parser.getResult();return{name:t.os.name||"unknown",version:t.os.version||"unknown"}}setSessionTraceId(t){if(t&&t.length===32&&/^[a-f0-9]{32}$/i.test(t)){this.sessionTraceId=t.toLowerCase();if(this.debug){console.log("[TracingService] Session trace ID set:",this.sessionTraceId)}}else if(t){console.warn("[TracingService] Invalid trace ID format. Must be 32 hex characters:",t)}}getSessionTraceId(){return this.sessionTraceId}generateSpanId(){const t=new Uint8Array(8);crypto.getRandomValues(t);return Array.from(t).map((t=>t.toString(16).padStart(2,"0"))).join("")}async getGeoLocation(){const t=Date.now();if(this.geoCache&&t-this.geoCacheTimestamp<this.GEO_CACHE_DURATION_MS){return this.geoCache}try{const e=await fetch("https://ipapi.co/json/",{signal:AbortSignal.timeout(5e3)});if(!e.ok){return{}}const i=await e.json();this.geoCache={country:i.country_name,region:i.region,city:i.city,latitude:i.latitude,longitude:i.longitude};this.geoCacheTimestamp=t;return this.geoCache}catch(t){console.warn("[TracingService] Failed to fetch geo location:",t);return this.geoCache||{}}}startSpan(t,e){if(!this.tracer){console.warn("[TracingService] Tracer not initialized, returning no-op span");return pe.getTracer("noop").startSpan("noop")}try{let i=Xt.active();if(this.sessionTraceId&&!pe.getSpan(i)){const t={traceId:this.sessionTraceId,spanId:this.generateSpanId(),traceFlags:yt.SAMPLED,isRemote:true};const e=pe.wrapSpanContext(t);i=pe.setSpan(i,e)}const r=this.getDeviceInfo();const n=this.getBrowserInfo();const s=this.getOSInfo();const o=this.tracer.startSpan(t,{attributes:{...e,component:this.serviceName.includes("stamps")?"jaak-stamps":"jaak-visage",[Ic]:this.serviceName,[Oc]:this.serviceVersion,"deployment.environment":this.environment,"trace.id":this.sessionTraceId||"auto-generated","device.type":r.type,"device.vendor":r.vendor,"device.model":r.model,"browser.name":n.name,"browser.version":n.version,"browser.major":n.major,"os.name":s.name,"os.version":s.version,user_agent:navigator.userAgent,...this.customerId&&{"customer.id":this.customerId},...this.tenantId&&{"tenant.id":this.tenantId}}},i);this.getGeoLocation().then((t=>{if(t.country)o.setAttribute("geo.country",t.country);if(t.region)o.setAttribute("geo.region",t.region);if(t.city)o.setAttribute("geo.city",t.city)})).catch((t=>console.warn("Failed to add geo attributes:",t)));if(this.debug){console.log(`[TracingService] Started span: ${t}`,{traceId:o.spanContext().traceId,spanId:o.spanContext().spanId,sessionTraceId:this.sessionTraceId,attributes:e})}return o}catch(t){console.error("[TracingService] Failed to start span:",t);return pe.getTracer("noop").startSpan("noop")}}endSpan(t){if(!t){console.warn("[TracingService] endSpan called with null/undefined span");return}try{t.end()}catch(t){console.error("[TracingService] ❌ Failed to end span:",t)}}addSpanEvent(t,e,i){if(!t)return;try{t.addEvent(e,i);if(this.debug){console.log(`[TracingService] Added event to span: ${e}`,i)}}catch(t){console.error("[TracingService] Failed to add span event:",t)}}recordException(t,e){if(!t)return;try{t.recordException(e);t.setStatus({code:Wt.ERROR,message:e.message})}catch(t){console.error("[TracingService] Failed to record exception:",t)}}setSpanAttribute(t,e,i){if(!t)return;try{t.setAttribute(e,i);if(this.debug){console.log(`[TracingService] Set attribute: ${e} = ${i}`)}}catch(t){console.error("[TracingService] Failed to set span attribute:",t)}}async trace(t,e,i){const r=this.startSpan(t,i);try{const t=await Xt.with(pe.setSpan(Xt.active(),r),(async()=>await e()));r.setStatus({code:Wt.OK});return t}catch(t){this.recordException(r,t);throw t}finally{this.endSpan(r)}}async traceAsync(t,e,i){return this.trace(t,e,i)}async flush(){try{if(!this.spanProcessor){console.warn("[TracingService] No span processor available to flush");return}await this.spanProcessor.forceFlush()}catch(t){console.error("[TracingService] ❌ Failed to flush spans:",t);throw t}}async cleanup(){try{if(this.spanProcessor){await this.spanProcessor.forceFlush();await this.spanProcessor.shutdown()}if(this.provider){await this.provider.shutdown()}}catch(t){console.error("[TracingService] Failed to cleanup:",t)}}getCurrentTraceId(){try{const t=pe.getSpan(Xt.active());return t?.spanContext().traceId}catch{return undefined}}getCurrentSpanId(){try{const t=pe.getSpan(Xt.active());return t?.spanContext().spanId}catch{return undefined}}}var zc;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE";t[t["LOWMEMORY"]=2]="LOWMEMORY"})(zc||(zc={}));const $c=()=>In.CUMULATIVE;const Dc=t=>{switch(t){case On.COUNTER:case On.OBSERVABLE_COUNTER:case On.GAUGE:case On.HISTOGRAM:case On.OBSERVABLE_GAUGE:return In.DELTA;case On.UP_DOWN_COUNTER:case On.OBSERVABLE_UP_DOWN_COUNTER:return In.CUMULATIVE}};const Fc=t=>{switch(t){case On.COUNTER:case On.HISTOGRAM:return In.DELTA;case On.GAUGE:case On.UP_DOWN_COUNTER:case On.OBSERVABLE_UP_DOWN_COUNTER:case On.OBSERVABLE_COUNTER:case On.OBSERVABLE_GAUGE:return In.CUMULATIVE}};function Uc(){const t="cumulative".toLowerCase();if(t==="cumulative"){return $c}if(t==="delta"){return Dc}if(t==="lowmemory"){return Fc}Yt.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${t}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);return $c}function Bc(t){if(t!=null){if(t===zc.DELTA){return Dc}else if(t===zc.LOWMEMORY){return Fc}return $c}return Uc()}const qc=Object.freeze({type:$s.DEFAULT});function Vc(t){return t?.aggregationPreference??(()=>qc)}class Hc extends tn{_aggregationTemporalitySelector;_aggregationSelector;constructor(t,e){super(t);this._aggregationSelector=Vc(e);this._aggregationTemporalitySelector=Bc(e?.temporalityPreference)}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}}class Gc extends Hc{constructor(t){super(za(t??{},ua,"v1/metrics",{"Content-Type":"application/json"}),t)}}class Zc{meterProvider=null;meter=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;exportIntervalMillis;metricReader=null;captureCounter=null;errorCounter=null;modelLoadCounter=null;userInteractionCounter=null;captureLatencyHistogram=null;modelLoadLatencyHistogram=null;detectionLatencyHistogram=null;imageSizeHistogram=null;activeSessionsGauge=null;memoryUsageGauge=null;activeSessions=0;gaugeValues=new Map;constructor(t={}){this.collectorUrl=t.collectorUrl||"https://collector.jaak.ai/v1/metrics";this.serviceName=t.serviceName||"jaak-stamps-webcomponent";this.serviceVersion=t.serviceVersion||"2.1.0";this.debug=t.debug||false;this.customerId=t.customerId;this.tenantId=t.tenantId;this.environment=t.environment||"production";this.exportIntervalMillis=t.exportIntervalMillis||6e4}initialize(){try{const t=new Gc({url:this.collectorUrl,headers:{"Content-Type":"application/json"}});this.metricReader=new qs({exporter:t,exportIntervalMillis:this.exportIntervalMillis,exportTimeoutMillis:3e4});this.meterProvider=new qo({readers:[this.metricReader]});this.meter=this.meterProvider.getMeter(this.serviceName,this.serviceVersion);this.initializeMetrics();if(this.debug){console.log("[MetricsService] Initialized successfully",{collectorUrl:this.collectorUrl,serviceName:this.serviceName,serviceVersion:this.serviceVersion,environment:this.environment,customerId:this.customerId,tenantId:this.tenantId,exportIntervalMillis:this.exportIntervalMillis})}}catch(t){console.error("[MetricsService] Failed to initialize:",t)}}initializeMetrics(){if(!this.meter)return;const t=this.getBaseAttributes();try{this.captureCounter=this.meter.createCounter("jaak.captures.total",{description:"Total number of document captures",unit:"1"});this.errorCounter=this.meter.createCounter("jaak.errors.total",{description:"Total number of errors",unit:"1"});this.modelLoadCounter=this.meter.createCounter("jaak.model.loads.total",{description:"Total number of model loads",unit:"1"});this.userInteractionCounter=this.meter.createCounter("jaak.user.interactions.total",{description:"Total user interactions (clicks, etc.)",unit:"1"});this.captureLatencyHistogram=this.meter.createHistogram("jaak.capture.duration",{description:"Duration of capture operations",unit:"ms"});this.modelLoadLatencyHistogram=this.meter.createHistogram("jaak.model.load.duration",{description:"Duration of model loading",unit:"ms"});this.detectionLatencyHistogram=this.meter.createHistogram("jaak.detection.duration",{description:"Duration of detection inference",unit:"ms"});this.imageSizeHistogram=this.meter.createHistogram("jaak.image.size",{description:"Size of captured images",unit:"bytes"});this.activeSessionsGauge=this.meter.createObservableGauge("jaak.sessions.active",{description:"Number of active capture sessions",unit:"1"});this.activeSessionsGauge.addCallback((e=>{e.observe(this.activeSessions,t)}));if("memory"in performance){this.memoryUsageGauge=this.meter.createObservableGauge("jaak.memory.usage",{description:"JavaScript heap memory usage",unit:"bytes"});this.memoryUsageGauge.addCallback((e=>{const i=performance.memory;if(i){e.observe(i.usedJSHeapSize,t)}}))}if(this.debug){console.log("[MetricsService] Business metrics initialized")}}catch(t){console.error("[MetricsService] Failed to initialize metrics:",t)}}getBaseAttributes(){const t={"service.name":this.serviceName,"service.version":this.serviceVersion,"deployment.environment":this.environment};if(this.customerId){t["customer.id"]=this.customerId}if(this.tenantId){t["tenant.id"]=this.tenantId}return t}incrementCounter(t,e=1,i){try{const r=this.getBaseAttributes();const n={...r,...i};switch(t){case"captures":this.captureCounter?.add(e,n);break;case"errors":this.errorCounter?.add(e,n);break;case"model_loads":this.modelLoadCounter?.add(e,n);break;case"user_interactions":this.userInteractionCounter?.add(e,n);break;default:if(this.meter){const i=this.meter.createCounter(`jaak.${t}.total`,{description:`Total ${t}`,unit:"1"});i.add(e,n)}}if(this.debug){console.log(`[MetricsService] Counter incremented: ${t} += ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to increment counter:",t)}}recordHistogram(t,e,i){try{const r=this.getBaseAttributes();const n={...r,...i};switch(t){case"capture_duration":this.captureLatencyHistogram?.record(e,n);break;case"model_load_duration":this.modelLoadLatencyHistogram?.record(e,n);break;case"detection_duration":this.detectionLatencyHistogram?.record(e,n);break;case"image_size":this.imageSizeHistogram?.record(e,n);break;default:if(this.meter){const i=this.meter.createHistogram(`jaak.${t}`,{description:`Distribution of ${t}`,unit:"ms"});i.record(e,n)}}if(this.debug){console.log(`[MetricsService] Histogram recorded: ${t} = ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to record histogram:",t)}}setGauge(t,e,i){try{this.gaugeValues.set(t,e);if(t==="active_sessions"){this.activeSessions=e}if(this.debug){console.log(`[MetricsService] Gauge set: ${t} = ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to set gauge:",t)}}async measureDuration(t,e,i){const r=performance.now();try{const n=await e();const s=performance.now()-r;this.recordHistogram(t,s,i);return n}catch(e){const n=performance.now()-r;this.recordHistogram(t,n,{...i,error:true});throw e}}async flush(){try{if(this.metricReader){await this.metricReader.forceFlush()}if(this.debug){console.log("[MetricsService] Metrics flushed")}}catch(t){console.error("[MetricsService] Failed to flush metrics:",t)}}async cleanup(){try{if(this.metricReader){await this.metricReader.forceFlush();await this.metricReader.shutdown()}if(this.meterProvider){await this.meterProvider.shutdown()}if(this.debug){console.log("[MetricsService] Cleaned up successfully")}}catch(t){console.error("[MetricsService] Failed to cleanup:",t)}}recordCapture(t,e,i){this.incrementCounter("captures",1,{side:t,mode:e});this.recordHistogram("capture_duration",i,{side:t,mode:e})}recordError(t,e){this.incrementCounter("errors",1,{error_type:t,operation:e})}recordModelLoad(t,e,i){this.incrementCounter("model_loads",1,{model_type:t,cached:i});this.recordHistogram("model_load_duration",e,{model_type:t,cached:i})}recordDetection(t,e){this.recordHistogram("detection_duration",t,{detections_found:e})}recordImageSize(t,e){this.recordHistogram("image_size",e,{side:t})}updateActiveSessions(t){this.setGauge("active_sessions",t)}recordUserInteraction(t){this.incrementCounter("user_interactions",1,{interaction_type:t})}}class Wc{services=new Map;constructor(t){this.initializeServices(t)}initializeServices(t){const e=new n;const i=new s(e);const r=new o(e,t.preferredCamera);const a=new f(t.debug,t.useDocumentClassification,t.useDocumentDetector);let c=null;if(t.enableTelemetry!==false){c=new Rc({collectorUrl:t.telemetryCollectorUrl||"https://collector.jaak.ai/v1/traces",serviceName:"jaak-stamps-webcomponent",serviceVersion:"2.1.0",debug:t.debug,customerId:t.customerId,tenantId:t.tenantId,environment:t.environment||"production",propagateTraceHeaderCorsUrls:t.propagateTraceHeaderCorsUrls||[],enableAutoInstrumentation:true});c.initialize()}let u=null;if(t.enableMetrics!==false){u=new Zc({collectorUrl:t.metricsCollectorUrl||"https://collector.jaak.ai/v1/metrics",serviceName:"jaak-stamps-webcomponent",serviceVersion:"2.1.0",debug:t.debug,customerId:t.customerId,tenantId:t.tenantId,environment:t.environment||"production",exportIntervalMillis:t.metricsExportIntervalMillis||6e4});u.initialize()}this.services.set("eventBus",e);this.services.set("stateManager",i);this.services.set("cameraService",r);this.services.set("detectionService",a);if(c){this.services.set("tracingService",c)}if(u){this.services.set("metricsService",u)}}get(t){const e=this.services.get(t);if(!e){throw new Error(`Service ${t} not found`)}return e}getEventBus(){return this.get("eventBus")}getStateManager(){return this.get("stateManager")}getCameraService(){return this.get("cameraService")}getDetectionService(){return this.get("detectionService")}getTracingService(){try{return this.get("tracingService")}catch{return null}}getMetricsService(){try{return this.get("metricsService")}catch{return null}}updateConfig(t){}async cleanup(){this.getDetectionService().cleanup();const t=this.getMetricsService();if(t){await t.cleanup()}const e=this.getTracingService();if(e){await e.cleanup()}this.getEventBus().clear();this.services.clear()}}class Xc{apiEndpoint="/api/v1/license/validate";baseUrl;static ENVIRONMENT_URLS={dev:"https://api.dev.jaak.ai",qa:"https://api.qa.jaak.ai",sandbox:"https://api.sandbox.jaak.ai",prod:"https://services.api.jaak.ai"};constructor(t="prod"){this.baseUrl=Xc.ENVIRONMENT_URLS[t]}async validateLicense(t,e,i="jaak-stamps-web"){const r=e||this.generateTraceId();const n={license:e?`L${r}`:t,origin:"web",app_id:i,product:"kyc",metadata:{sdk_version:"2.1.0"}};const s={"Content-Type":"application/json"};s["traceparent"]=`00-${r}-${this.generateSpanId()}-01`;try{const t=await fetch(`${this.baseUrl}${this.apiEndpoint}`,{method:"POST",headers:s,body:JSON.stringify(n)});if(!t.ok){const e=await t.json().catch((()=>({})));throw{error:e.error||"license_validation_failed",error_description:e.error_description||`HTTP ${t.status}: ${t.statusText}`,status_code:t.status}}const e=await t.json();return{...e,traceId:r}}catch(t){if(t.error){throw t}throw{error:"network_error",error_description:"Failed to connect to license validation service",status_code:0}}}generateTraceId(){const t=new Uint8Array(16);crypto.getRandomValues(t);return Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("")}generateSpanId(){const t=new Uint8Array(8);crypto.getRandomValues(t);return Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("")}static extractTraceIdFromLicense(t){if(!t||typeof t!=="string"){return null}const e=t.startsWith("L")?t.slice(1):t;if(e.length===32&&/^[a-f0-9]{32}$/i.test(e)){return e.toLowerCase()}console.warn("[LicenseValidationService] Invalid license format for trace ID:",t);return null}}const Yc=":host{display:block;width:100%;height:100%;font-family:system-ui, -apple-system, sans-serif;color:#1a1a1a}.detector-container{display:flex;flex-direction:column;align-items:center;width:100%;height:100%}h1{font-size:24px;font-weight:500;color:#333;margin:0 0 24px 0}.video-container{position:relative;width:100%;height:100%;background-color:#000;border:none;border-radius:8px;overflow:hidden}video,.detection-overlay{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,.detection-overlay.mirror{transform:rotateY(180deg)}.detection-overlay{z-index:1;pointer-events:none}video{z-index:0}video::-webkit-media-controls{display:none !important}video::-webkit-media-controls-panel{display:none !important}video::-webkit-media-controls-play-button{display:none !important}video::-webkit-media-controls-start-playback-button{display:none !important}video::-webkit-media-controls-enclosure{display:none !important}.detection-box{transition:opacity 0.2s ease}.status{margin-top:16px;font-size:12px;color:#666}.overlay-mask{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10;display:block;pointer-events:none}.card-outline{position:absolute;top:var(--mask-center-y, 50%);left:var(--mask-center-x, 50%);transform:translate(-50%, -50%);width:var(--mask-width, 88%);height:var(--mask-height, 55%);border:none;border-radius:4px;background:transparent;opacity:0.8}.side{position:absolute;background:#999;transition:background-color 0.3s ease;border-radius:1px}.side-top.aligned{border-left-color:#28a745;border-top-color:#28a745}.side-right.aligned{border-right-color:#28a745;border-top-color:#28a745}.side-bottom.aligned{border-left-color:#28a745;border-bottom-color:#28a745}.side-left.aligned{border-right-color:#28a745;border-bottom-color:#28a745}.side-top{top:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-right{top:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-bottom{bottom:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.side-left{bottom:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);color:#ffffff;font-size:12px;font-weight:500;text-align:center;white-space:normal;padding:13px;max-width:300px;z-index:20;height:fit-content;width:fit-content;animation:slideInFromTopCentered 0.3s ease-out}.quality-indicator{position:absolute;top:20px;right:20px;display:flex;align-items:center;gap:8px;background:rgba(0, 0, 0, 0.8);padding:8px 12px;border-radius:20px;z-index:25;transition:all 0.3s ease}.quality-indicator.warning{background:rgba(255, 152, 0, 0.9)}.quality-indicator.good{background:rgba(76, 175, 80, 0.9)}.quality-score{color:#fff;font-size:12px;font-weight:600;min-width:30px;text-align:center}.quality-status{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:bold;color:#fff;transition:all 0.3s ease}.quality-status.ready{background:#4CAF50}.quality-status.not-ready{background:#f44336}.card-outline.quality-warning{animation:qualityWarning 1s ease-in-out infinite alternate}@keyframes qualityWarning{0%{box-shadow:0 0 0 3px rgba(255, 152, 0, 0.6)}100%{box-shadow:0 0 0 6px rgba(255, 152, 0, 0.3)}}.capture-animation{position:absolute;top:0;left:0;width:100%;height:100%;background:#fff;opacity:0;z-index:30;pointer-events:none;animation:captureFlash 0.6s ease-out}@keyframes captureFlash{0%{opacity:0}15%{opacity:0.8}30%{opacity:0}45%{opacity:0.4}60%{opacity:0}100%{opacity:0}}.card-outline.capturing{animation:pulseGreen 0.6s ease-out}@keyframes pulseGreen{0%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}}.flip-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showFlipInstruction 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.id-card-icon{width:80px;height:50px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:8px;position:relative;animation:flipCard 2s ease-in-out infinite;box-shadow:0 4px 12px rgba(0, 0, 0, 0.3)}.id-card-icon::before{content:'';position:absolute;top:8px;left:8px;width:16px;height:12px;background:rgba(255, 255, 255, 0.9);border-radius:2px}.id-card-icon::after{content:'';position:absolute;top:25px;left:8px;width:64px;height:3px;background:rgba(255, 255, 255, 0.7);border-radius:1px;box-shadow:0 6px 0 rgba(255, 255, 255, 0.7), 0 12px 0 rgba(255, 255, 255, 0.7)}.flip-text{margin-top:12px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px}@keyframes showFlipInstruction{0%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}}@keyframes flipCard{0%{transform:rotateY(0deg)}50%{transform:rotateY(180deg)}100%{transform:rotateY(360deg)}}.success-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showSuccessMessage 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.check-icon{width:80px;height:80px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:50%;position:relative;animation:bounceSuccess 0.6s ease-out;box-shadow:0 4px 16px rgba(108, 117, 125, 0.4);display:flex;align-items:center;justify-content:center}.check-icon::before{content:'';position:absolute;width:20px;height:35px;border:4px solid #fff;border-top:none;border-left:none;transform:rotate(45deg);}.success-text{margin-top:16px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;animation:fadeInUp 0.5s ease-out 0.4s both}@keyframes showSuccessMessage{0%{opacity:0;transform:translate(-50%, -50%) scale(0.5)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.9)}}@keyframes bounceSuccess{0%{transform:scale(0)}50%{transform:scale(1.1)}100%{transform:scale(1)}}@keyframes drawCheck{0%{width:0;height:0}50%{width:20px;height:0}100%{width:20px;height:35px}}@keyframes fadeInUp{0%{opacity:0;transform:translateY(20px)}100%{opacity:1;transform:translateY(0)}}.skip-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.back-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:320px}.back-capture-buttons{display:flex;gap:12px;align-items:center;justify-content:center;flex-wrap:wrap}.capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.capture-button:hover{background:#f8f9fa}.capture-button:active{background:#e9ecef;transform:translateY(1px)}.capture-button:disabled,.capture-button.primary-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}@media (max-width: 480px){.back-capture-section{bottom:16px;max-width:300px}.back-capture-buttons{flex-direction:column;gap:8px;width:100%}.capture-button,.back-capture-buttons .skip-button{width:100%;max-width:200px;padding:10px 20px;font-size:13px}.capture-button:disabled,.capture-button.primary-button:disabled,.skip-button:disabled{opacity:0.7 !important;cursor:not-allowed !important}}.skip-explanation{background:rgba(0, 0, 0, 0.5);color:#ffffff;padding:10px 16px;border-radius:8px;font-size:14px;font-weight:500;text-align:center;margin-bottom:12px;box-shadow:0 2px 8px rgba(0, 0, 0, 0.2);backdrop-filter:blur(12px);border:1px solid rgba(255, 255, 255, 0.1);animation:fadeIn 0.3s ease-in-out}@keyframes fadeIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.guide-text.performance-warning-text{animation:gentlePulse 2s ease-in-out infinite;background:rgba(255, 107, 107, 0.3);border:1px solid rgba(255, 107, 107, 0.5)}@keyframes gentlePulse{0%,100%{transform:translate(-50%, -50%) scale(1);background:rgba(255, 107, 107, 0.3)}50%{transform:translate(-50%, -50%) scale(1.02);background:rgba(255, 107, 107, 0.4)}}.skip-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.skip-button:hover{background:#f8f9fa}.skip-button:active{background:#e9ecef;transform:translateY(1px)}.skip-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}.camera-controls{position:absolute;top:16px;right:16px;z-index:25;display:flex;gap:8px;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}.camera-selector-button{height:32px;padding:0 10px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(12px);color:#ffffff;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s ease;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255, 255, 255, 0.1);white-space:nowrap;min-width:fit-content}.camera-selector-button:hover{background:rgba(0, 0, 0, 0.8);border-color:rgba(255, 255, 255, 0.2);transform:translateY(-1px)}.camera-selector-button:active{transform:translateY(0);background:rgba(0, 0, 0, 0.9)}.camera-selector-button:disabled,.camera-selector-button.loading{opacity:0.7;cursor:not-allowed;pointer-events:none}.camera-selector-button:disabled:hover,.camera-selector-button.loading:hover{transform:none;background:rgba(0, 0, 0, 0.6);border-color:rgba(255, 255, 255, 0.1)}.button-spinner{width:16px;height:16px;border:2px solid rgba(0, 0, 0, 0.2);border-top:2px solid #333333;border-radius:50%;animation:spin 1s linear infinite;display:inline-block;margin-right:8px;vertical-align:middle}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.camera-selector-dropdown{position:absolute;top:56px;right:16px;z-index:30;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;min-width:260px;max-width:300px;border:1px solid rgba(255, 255, 255, 0.1);overflow:hidden;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-8px) scale(0.95)}100%{opacity:1;transform:translateY(0) scale(1)}}@keyframes slideInFromTopCentered{0%{opacity:0;transform:translate(-50%, -50%) translateY(-8px) scale(0.95)}100%{opacity:1;transform:translate(-50%, -50%) translateY(0) scale(1)}}.camera-selector-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid rgba(255, 255, 255, 0.1)}.camera-selector-header span{font-weight:500;color:#ffffff;font-size:13px;opacity:0.9}.close-selector{width:20px;height:20px;border:none;background:none;color:rgba(255, 255, 255, 0.7);font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all 0.2s ease}.close-selector:hover{background:rgba(255, 255, 255, 0.1);color:#ffffff}.camera-list{padding:4px 0;max-height:240px;overflow-y:auto}.camera-option{width:100%;padding:8px 12px;border:none;background:none;text-align:left;cursor:pointer;transition:all 0.2s ease;display:flex;justify-content:flex-start;align-items:center;gap:8px;color:rgba(255, 255, 255, 0.9)}.camera-option:hover{background:rgba(255, 255, 255, 0.08)}.camera-option.selected{background:rgba(255, 255, 255, 0.12);color:#ffffff}.camera-label{font-size:13px;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-right:0;font-weight:400;display:flex;align-items:center;gap:6px}.camera-label .autofocus-icon{font-size:12px;color:#ffffff !important;opacity:0.8;flex-shrink:0}.selected-indicator{font-size:14px;color:#ffffff;opacity:0.9;flex-shrink:0}.device-info{padding:6px 12px;border-top:1px solid rgba(255, 255, 255, 0.1);background:rgba(255, 255, 255, 0.05)}.device-info small{color:rgba(255, 255, 255, 0.6);font-size:11px;text-transform:capitalize;font-weight:400}@media (max-width: 480px){.camera-controls{top:12px;right:12px;gap:6px}.camera-selector-button{height:36px;padding:0 12px;font-size:11px;border-radius:6px}.camera-selector-dropdown{right:12px;top:48px;min-width:240px;max-width:calc(100vw - 24px)}.camera-selector-header{padding:6px 10px}.camera-option{padding:6px 10px}.device-info{padding:4px 10px}}.watermark{position:absolute;bottom:12px;right:12px;z-index:15;pointer-events:none;opacity:0.7}.watermark img{height:24px;width:auto;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))}.component-status{position:absolute;top:16px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);display:flex;align-items:center;gap:6px;padding:6px 10px;z-index:40;height:32px;width:fit-content;animation:slideInFromTop 0.3s ease-out}.status-spinner{width:16px;height:16px;border:1px solid rgba(255, 255, 255, 0.3);border-top:1px solid #ffffff;border-radius:50%;animation:statusSpin 1s linear infinite;flex-shrink:0}.status-content{display:flex;flex-direction:column;gap:1px}.status-message{color:#ffffff;font-size:12px;font-weight:500;margin:0}.status-description{color:rgba(255, 255, 255, 0.7);font-size:10px;line-height:1.2;margin:0}@keyframes statusSpin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@media (max-width: 480px){.component-status{top:12px;left:12px;padding:4px 8px;gap:4px;height:28px;border-radius:8px}.status-spinner{width:14px;height:14px}.status-message{font-size:11px}.status-description{font-size:9px}.guide-text{font-size:11px;padding:4px 8px;border-radius:8px}}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.85);backdrop-filter:blur(4px);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:8px}.loading-spinner{width:50px;height:50px;border:3px solid rgba(255, 255, 255, 0.15);border-top:3px solid #28a745;border-radius:50%;animation:spin 1s ease-in-out infinite;margin-bottom:16px}.loading-text{color:#ffffff;font-size:14px;font-weight:500;text-align:center;opacity:0.9;margin-bottom:4px}.loading-description{color:rgba(255, 255, 255, 0.7);font-size:12px;text-align:center;opacity:0.8}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.performance-monitor{position:absolute;top:70px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromTop 0.3s ease-out;transition:all 0.3s ease}@keyframes slideInFromLeft{0%{opacity:0;transform:translateX(-20px) scale(0.95)}100%{opacity:1;transform:translateX(0) scale(1)}}.performance-expanded{padding:6px 10px}.metrics-row{display:flex;gap:8px;margin-bottom:4px}.metrics-row:last-child{margin-bottom:0}.metric-compact{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:50px}.metric-label{font-size:9px;color:rgba(255, 255, 255, 0.6);font-weight:500;text-transform:uppercase;letter-spacing:0.3px}.metric-value{font-size:10px;font-weight:600;font-family:'Monaco', 'Menlo', 'Consolas', monospace;padding:2px 4px;border-radius:3px;text-align:center;white-space:nowrap}.metric-value.good{color:#4ade80;background:rgba(74, 222, 128, 0.1);border:1px solid rgba(74, 222, 128, 0.2)}.metric-value.warning{color:#fbbf24;background:rgba(251, 191, 36, 0.1);border:1px solid rgba(251, 191, 36, 0.2)}.metric-value.danger{color:#f87171;background:rgba(248, 113, 113, 0.1);border:1px solid rgba(248, 113, 113, 0.2)}@media (max-width: 480px){.performance-monitor{top:60px;left:12px;width:fit-content}.performance-expanded{padding:4px 8px}.metrics-row{gap:6px;margin-bottom:3px}.metric-compact{min-width:45px;gap:1px}.metric-label{font-size:8px}.metric-value{font-size:9px;padding:1px 3px}}.quality-monitor{position:absolute;top:200px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromLeft 0.3s ease-out;transition:all 0.3s ease}.quality-text{padding:6px 10px;font-size:11px;color:white;font-family:'Monaco', 'Menlo', 'Consolas', monospace;line-height:1.4}.quality-fail{color:#ff9999}@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.7}}.metric-value.danger{animation:pulse 2s infinite}@media (max-width: 480px){.quality-monitor{top:160px;left:12px}.quality-text{padding:4px 8px;font-size:10px}}.manual-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.manual-capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.manual-capture-button:hover{background:#f8f9fa}.manual-capture-button:active{background:#e9ecef;transform:translateY(1px)}.manual-capture-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}@media (max-width: 480px){.manual-capture-section{bottom:16px;max-width:280px}.manual-capture-button{padding:10px 20px;font-size:13px}.manual-capture-button:disabled{opacity:0.7 !important;cursor:not-allowed !important}}.license-error-container{display:flex;align-items:center;justify-content:center;padding:40px 20px;height:100%;width:100%;background:#f5f7fa;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif}.license-error-card{background:#ffffff;border-radius:8px;box-shadow:0 2px 12px rgba(0, 0, 0, 0.1);max-width:480px;width:100%;padding:48px 32px;text-align:center}.license-error-icon{color:#dc3545;margin-bottom:24px}.license-error-title{color:#2c3e50;font-size:24px;font-weight:600;margin:0 0 16px 0}.license-error-message{color:#495057;font-size:16px;line-height:1.6;margin:0 0 24px 0}.license-error-help{color:#6c757d;font-size:14px;margin:0 0 32px 0}.license-error-help a{color:#007bff;text-decoration:none;font-weight:500}.license-error-help a:hover{text-decoration:underline}.license-error-footer{color:#adb5bd;font-size:12px;font-weight:500;padding-top:24px;border-top:1px solid #e9ecef}@media (max-width: 640px){.license-error-card{padding:32px 24px}.license-error-title{font-size:20px}.license-error-message{font-size:14px}}";const Jc=class{constructor(i){t(this,i);this.captureCompleted=e(this,"captureCompleted");this.isReady=e(this,"isReady");this.traceIdGenerated=e(this,"traceIdGenerated")}get el(){return i(this)}debug=false;alignmentTolerance=15;maskSize=90;cropMargin=20;useDocumentClassification=false;useDocumentDetector=true;preferredCamera="auto";captureDelay=1500;enableBackDocumentTimer=false;backDocumentTimerDuration=20;telemetryCollectorUrl="https://collector.jaak.ai/v1/traces";metricsCollectorUrl="https://collector.jaak.ai/v1/metrics";enableTelemetry=true;enableMetrics=true;customerId;tenantId;environment="production";propagateTraceHeaderCorsUrls;metricsExportIntervalMillis=6e4;license;licenseEnvironment="prod";traceId;appId="jaak-stamps-web";captureCompleted;isReady;traceIdGenerated;detectionBoxes=[];sideAlignment={top:false,right:false,bottom:false,left:false};isMaskReady=false;shouldMirrorVideo=true;showCameraSelector=false;isSwitchingCamera=false;hasDocumentDetected=false;cameraInfoWithAutofocus={availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null};currentStatus={message:"Preparando capturador...",description:"Configurando herramientas de captura",type:"initializing",isInitialized:false};performanceData={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0};backDocumentTimerRemaining=0;showManualCaptureButton=false;performanceDegradedMode=false;showPerformanceMessage=false;captureStateVersion=0;processingButton=null;licenseValid=true;licenseError=null;licenseValidationService=null;serviceContainer;eventBus;stateManager;cameraService;detectionService;tracingService;metricsService;videoRef;detectionContainer;videoStream;animationId;lastDetectedBox;startTime;hasScreenshotTaken=false;alignmentStartTime;alignmentTimer;backDocumentTimer;orientationTimer;performanceMetrics={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0,lastUpdateTime:0};performanceUpdateInterval;frameSkipCounter=0;BASE_FRAME_SKIP=2;MAX_FRAME_SKIP=8;consecutiveFailures=0;MAX_FAILURES=30;lastInferenceTime=0;MIN_INFERENCE_INTERVAL=50;MOBILE_MIN_INFERENCE_INTERVAL=100;performanceHistory=[];PERFORMANCE_HISTORY_SIZE=10;PERFORMANCE_THRESHOLD_MS=2e3;SLOW_FRAMES_TO_TRIGGER=2;slowFrameCount=0;processedFramesCount=0;hasAutoSwitchedToManual=false;canvasPool=[];MAX_CANVAS_POOL_SIZE=3;async componentWillLoad(){await new Promise((t=>setTimeout(t,50)));this.updateStatus("Validando licencia...","Verificando autorización de uso","initializing");await this.validateLicense();if(!this.licenseValid){return}}async componentDidLoad(){try{if(!this.licenseValid){return}this.updateStatus("Preparando capturador...","Configurando herramientas de captura","initializing");await this.initializeServices();this.updateStatus("Preparando funciones...","Configurando herramientas de trabajo","initializing");await this.setupEventListeners();this.updateStatus("Configurando cámara...","Detectando dispositivos disponibles","initializing");await this.initializeComponent();if(this.debug){this.initializePerformanceMonitor()}}catch(t){this.updateStatus("Error de inicialización",t.message,"error")}}async initializeServices(){const t=this.propagateTraceHeaderCorsUrls?this.propagateTraceHeaderCorsUrls.split(",").map((t=>t.trim())):[];const e={debug:this.debug,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,cropMargin:this.cropMargin,useDocumentClassification:this.useDocumentClassification,useDocumentDetector:this.useDocumentDetector,preferredCamera:this.preferredCamera,captureDelay:this.captureDelay,telemetryCollectorUrl:this.telemetryCollectorUrl,metricsCollectorUrl:this.metricsCollectorUrl,enableTelemetry:this.enableTelemetry,enableMetrics:this.enableMetrics,customerId:this.customerId,tenantId:this.tenantId,environment:this.environment,propagateTraceHeaderCorsUrls:t,metricsExportIntervalMillis:this.metricsExportIntervalMillis};this.serviceContainer=new Wc(e);this.eventBus=this.serviceContainer.getEventBus();this.stateManager=this.serviceContainer.getStateManager();this.cameraService=this.serviceContainer.getCameraService();this.detectionService=this.serviceContainer.getDetectionService();this.tracingService=this.serviceContainer.getTracingService();this.metricsService=this.serviceContainer.getMetricsService();if(this.tracingService&&this.traceId){this.tracingService.setSessionTraceId(this.traceId)}if(this.tracingService){const t=this.tracingService.startSpan("component.initialize",{"component.debug":this.debug,"component.useDocumentDetector":this.useDocumentDetector,"component.useDocumentClassification":this.useDocumentClassification});this.tracingService.endSpan(t)}}async validateLicense(){if(!this.license){console.error("❌ No license provided for JAAK Stamps component");this.licenseError='Este componente requiere una licencia válida. Por favor, proporcione una licencia usando el atributo "license".';this.licenseValid=false;this.updateStatus("Error de licencia","Licencia no proporcionada","error");return}try{console.log("🔑 Validating license for JAAK Stamps...");this.licenseValidationService=new Xc(this.licenseEnvironment);const t=await this.licenseValidationService.validateLicense(this.license,this.traceId,this.appId);if(t&&t.access_token){this.licenseValid=true;this.licenseError=null;console.log("✅ License validated successfully for JAAK Stamps");if(t.traceId){this.traceIdGenerated.emit({traceId:t.traceId});console.log("📋 TraceId:",t.traceId)}}else{this.licenseValid=false;this.licenseError="La licencia proporcionada no es válida. Por favor, verifique su licencia e intente nuevamente.";this.updateStatus("Error de licencia","Licencia inválida","error");console.error("❌ Invalid license for JAAK Stamps")}}catch(t){this.licenseValid=false;const e=t;this.licenseError=e.error_description||"Error al validar la licencia. Por favor, verifique su conexión e intente nuevamente.";this.updateStatus("Error de licencia","Fallo en la validación","error");console.error("❌ License validation failed for JAAK Stamps:",t)}}async setupEventListeners(){this.eventBus.on("state-changed",(()=>{this.handleStateChange()}))}async initializeComponent(){this.validateProps();if(this.debug){this.stateManager.updateCaptureState({isLoading:true});await new Promise((t=>setTimeout(t,500)))}this.updateStatus("Detectando cámaras...","Buscando dispositivos de captura","initializing");await this.cameraService.detectDeviceType();await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","initializing");await this.loadOnnxRuntime();this.initializeResizeObserver()}validateProps(){if(this.maskSize<50||this.maskSize>100){this.maskSize=90}if(this.cropMargin<0||this.cropMargin>100){this.cropMargin=0}const t=["auto","front","back"];if(!t.includes(this.preferredCamera)){this.preferredCamera="auto"}if(this.captureDelay<0||this.captureDelay>1e4){this.captureDelay=1500}}async loadOnnxRuntime(){if(!window.ort){this.updateStatus("Preparando herramientas...","Configurando funciones de captura","initializing");const t=document.createElement("script");const e=navigator.userAgent;const i=/iPad|iPhone|iPod/.test(e);if(i){t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.0/dist/ort.wasm.min.js"}else{t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.0/dist/ort.min.js"}document.head.appendChild(t);await new Promise((e=>{t.onload=()=>{if(i&&window.ort?.env){const t=window.ort;t.env.wasm.simd=false;t.env.wasm.numThreads=1;t.env.wasm.proxy=false}setTimeout((async()=>{await this.finalizeInitialization();e(undefined)}),300)}}))}else{setTimeout((async()=>{await this.finalizeInitialization()}),300)}}async finalizeInitialization(){this.stateManager.updateCaptureState({isLoading:false});const t=await this.checkCameraPermissions();if(t){this.currentStatus={message:"Listo para capturar",description:"",type:"ready",isInitialized:true}}else{this.currentStatus={message:"Permisos de cámara requeridos",description:"Por favor, otorgue permisos de cámara para continuar",type:"error",isInitialized:true}}this.emitReadyEvent()}updateStatus(t,e,i="loading"){this.currentStatus={message:t,description:e,type:i,isInitialized:this.currentStatus.isInitialized}}emitReadyEvent(){const t=!!window.ort&&this.detectionService.isModelLoaded();this.isReady.emit(t)}async checkCameraPermissions(){try{if(!navigator.permissions){try{const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()));return true}catch{return false}}const t=await navigator.permissions.query({name:"camera"});return t.state==="granted"}catch(t){return false}}handleStateChange(){}initializeResizeObserver(){if("ResizeObserver"in window&&this.detectionContainer){const t=new ResizeObserver((()=>{this.handleResize()}));t.observe(this.detectionContainer.parentElement)}window.addEventListener("orientationchange",(()=>{if(this.orientationTimer){clearTimeout(this.orientationTimer)}this.orientationTimer=window.setTimeout((()=>{this.handleResize();this.orientationTimer=undefined}),300)}))}handleResize(){if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}}triggerRerender(){this.captureStateVersion=this.captureStateVersion+1}getGuideText(t){if(t==="completed"){return"Proceso completado"}if(this.showPerformanceMessage&&t==="front"){return"Modo manual activado por rendimiento. Use el botón para capturar."}if(t==="front"){if(this.showManualCaptureButton){return"Posicione el frente de su documento en el marco y presione el botón para capturar"}return"Alinee su identificación con el marco"}else if(t==="back"){if(this.useDocumentDetector){return"Si tu documento no tiene lado trasero, da clic en el botón para continuar con el proceso"}else{return"Posicione el reverso de su documento en el marco y capture, o salte este paso"}}return"Alinee su identificación con el marco"}updateMaskDimensions(t){if(!this.videoRef)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;if(e===0||i===0)return;const r=e/i;const n=t.width/t.height;let s,o;let a=0,c=0;if(r>n){s=t.width;o=t.width/r;c=(t.height-o)/2}else{o=t.height;s=t.height*r;a=(t.width-s)/2}const u=85.6/53.98;const l=o*u;let f,h;const d=this.maskSize/100;if(l<=s){h=o*d;f=h*u}else{f=s*d;h=f/u}const p=f/t.width*100;const m=h/t.height*100;const b=a+s/2;const v=c+o/2;const w=b/t.width*100;const g=v/t.height*100;this.el.style.setProperty("--mask-width",`${p}%`);this.el.style.setProperty("--mask-height",`${m}%`);this.el.style.setProperty("--mask-center-x",`${w}%`);this.el.style.setProperty("--mask-center-y",`${g}%`);this.isMaskReady=true}isComponentReady(){if(!this.currentStatus.isInitialized){return{ready:false,message:"El componente aún se está inicializando",status:"initializing"}}if(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing"){return{ready:false,message:"El componente está cargando recursos",status:"loading"}}if(!this.serviceContainer||!this.stateManager||!this.cameraService||!this.detectionService){return{ready:false,message:"Los servicios del componente no están disponibles",status:"error"}}return{ready:true}}async getCapturedImages(){const t=this.isComponentReady();if(!t.ready){throw new Error(t.message)}const e=this.stateManager.getCaptureState();if(e.step!=="completed"){throw new Error("El proceso de captura no ha sido completado")}return this.stateManager.getCapturedImages()}async isProcessCompleted(){const t=this.isComponentReady();if(!t.ready){return false}return this.stateManager.isProcessCompleted()}async startCapture(){const t=this.tracingService?.startSpan("capture.start");const e=this.isComponentReady();if(!e.ready){this.updateStatus(e.message,"Espere a que termine la inicialización",e.status);if(t){this.tracingService?.setSpanAttribute(t,"error",true);this.tracingService?.setSpanAttribute(t,"error.message",e.message);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}try{await this.startDetection();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true}}catch(e){this.updateStatus("Error al iniciar captura",e.message,"error");if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async stopCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.exitSession();return{success:true}}catch(t){return{success:false,error:t.message}}}async resetCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.resetDetection();return{success:true}}catch(t){return{success:false,error:t.message}}}async skipBackCapture(){console.log("🟡 Botón clicked: Saltar reverso");this.processingButton="skip-back";await new Promise((t=>setTimeout(t,100)));const t=this.isComponentReady();if(!t.ready){this.processingButton=null;return{success:false,error:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();if(t.step==="back"&&e.front.fullFrame){this.completeProcess(true);return{success:true}}else{return{success:false,error:"No se puede saltar el reverso en el estado actual"}}}catch(t){return{success:false,error:t.message}}finally{this.processingButton=null}}async getStatus(){const t=this.isComponentReady();if(!t.ready){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:t.status,componentMessage:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();return{isVideoActive:t.isVideoActive,captureStep:t.step,hasImages:!!(e.front.fullFrame||e.back.fullFrame),isProcessCompleted:this.stateManager.isProcessCompleted(),isModelPreloaded:this.detectionService.isModelLoaded(),componentStatus:"ready"}}catch(t){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:"error",componentMessage:t.message}}}async preloadModel(){const t=this.tracingService?.startSpan("model.preload");const e=this.isComponentReady();if(!e.ready){this.updateStatus(e.message,"Espere a que termine la inicialización",e.status);if(t){this.tracingService?.setSpanAttribute(t,"error",true);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}if(this.detectionService.isModelLoaded()){this.updateStatus("Reconocimiento listo","","ready");if(t){this.tracingService?.setSpanAttribute(t,"cached",true);this.tracingService?.endSpan(t)}return{success:true,message:"Model already loaded"}}try{const e=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:true})}try{const t=performance.now();const e=this.tracingService?.startSpan("model.detection.load");await this.detectionService.loadModel();if(e)this.tracingService?.endSpan(e);const i=performance.now()-t;this.metricsService?.recordModelLoad("detection",i,false)}catch(t){this.metricsService?.recordError("model_load_failed","detection");this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");try{const t=performance.now();const e=this.tracingService?.startSpan("model.classification.load");await this.detectionService.loadClassificationModel();if(e)this.tracingService?.endSpan(e);const i=performance.now()-t;this.metricsService?.recordModelLoad("classification",i,false)}catch(t){this.metricsService?.recordError("model_load_failed","classification");this.switchToManualModeWithError("Error al cargar modelo de clasificación");throw t}const i=performance.now();const r=i-e;if(this.debug){this.recordOnnxPerformance(r,0)}if(t){this.tracingService?.setSpanAttribute(t,"loadTime",r)}this.updateStatus("Finalizando configuración...","Preparando herramientas para captura","loading");await new Promise((t=>setTimeout(t,300)));this.updateStatus("Reconocimiento preparado","","ready");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}this.emitReadyEvent();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true,message:"Models preloaded successfully"}}catch(e){this.updateStatus("Error de configuración","No se pudieron preparar las herramientas necesarias","error");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async getCameraInfo(){const t=this.isComponentReady();if(!t.ready){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}try{return await this.cameraService.getCameraInfo()}catch(t){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}}async setPreferredCamera(t){const e=this.isComponentReady();if(!e.ready){return{success:false,error:e.message,selectedCamera:null,availableCameras:0}}try{this.preferredCamera=t;this.serviceContainer.updateConfig({preferredCamera:t});await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();const e=this.stateManager.getCaptureState();if(e.isVideoActive){const t=this.cameraService.getSelectedCameraId();if(t){await this.cameraService.switchCamera(t)}}return{success:true,selectedCamera:this.cameraService.getSelectedCameraId(),availableCameras:this.cameraService.getAvailableCameras().length}}catch(t){return{success:false,error:t.message,selectedCamera:null,availableCameras:0}}}async setCaptureDelay(t){if(t<0||t>1e4){return{success:false,error:"Capture delay must be between 0 and 10000 milliseconds",captureDelay:this.captureDelay}}this.captureDelay=t;if(this.serviceContainer){this.serviceContainer.updateConfig({captureDelay:t})}return{success:true,captureDelay:this.captureDelay}}async getCaptureDelay(){return this.captureDelay}checkDeviceCapabilities(){const t=navigator.deviceMemory;return{canUseML:true,reason:"Dispositivo compatible con detección automática.",memoryMB:t?t*1024:null}}async startDetection(){try{const t=this.checkDeviceCapabilities();if(!t.canUseML&&this.useDocumentDetector){this.switchToManualModeWithWarning(t.reason);return}if(!this.detectionService.isModelLoaded()){const t=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");this.stateManager.updateCaptureState({isLoading:true});try{await this.detectionService.loadModel()}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";this.switchToManualModeWithWarning(`Memoria insuficiente para detección automática ${t}. Modo manual activado - funciona igual de bien!`);return}else{this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");try{await this.detectionService.loadClassificationModel()}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";this.switchToManualModeWithWarning(`Memoria insuficiente para clasificación automática ${t}. Modo manual activado para optimizar rendimiento.`);return}else{this.switchToManualModeWithError("Error al cargar modelo de clasificación");throw t}}const e=performance.now();const i=e-t;if(this.debug){this.recordOnnxPerformance(i,0)}}this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus()}catch(t){throw new Error(`Error al actualizar información de cámara: ${t.message}`)}this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");let e;try{e=await this.cameraService.setupCamera()}catch(t){throw new Error(`Error al configurar cámara: ${t.message}`)}if(this.useDocumentDetector){this.updateStatus("Analizando estabilidad...","Evaluando rendimiento del sistema","loading")}else{this.updateStatus("Captura activa","Posicione su documento y use el botón para capturar","active")}try{await this.initializeVideoStream(e)}catch(t){throw new Error(`Error al inicializar video: ${t.message}`)}if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});if(!this.useDocumentDetector){this.showManualCaptureButton=true}this.detectFrame()}catch(t){this.updateStatus("Error al iniciar","No se pudo preparar la captura","error");this.stateManager.updateCaptureState({isLoading:false})}}async initializeVideoStream(t){if(this.videoRef){this.videoRef.srcObject=t;this.videoStream=t;const e=this.cameraService.isRearCamera(t);this.shouldMirrorVideo=!e;return new Promise((t=>{this.videoRef.onloadedmetadata=async()=>{await this.videoRef.play();this.stateManager.updateCaptureState({isVideoActive:true});if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}t()}}))}else{throw new Error("Video element not available")}}async detectFrame(){try{const t=performance.now();const e=this.stateManager.getCaptureState();if(!this.videoRef||!this.detectionContainer||!this.detectionService.isModelLoaded())return;if(!this.useDocumentDetector||this.performanceDegradedMode){this.showManualCaptureButton=true;if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}else if(!this.performanceDegradedMode){this.showManualCaptureButton=false}if(e.isDetectionPaused){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter++;const i=this.getAdaptiveFrameSkip();if(this.frameSkipCounter<=i){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter=0;const r=Date.now();const n=this.cameraInfoWithAutofocus.deviceType==="mobile"||/Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);const s=this.cameraInfoWithAutofocus.deviceType==="tablet"||/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const o=n&&!s?this.MOBILE_MIN_INFERENCE_INTERVAL:this.MIN_INFERENCE_INTERVAL;if(r-this.lastInferenceTime<o){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.lastInferenceTime=r;const a=performance.now();let c;let u;let l;try{c=this.detectionService.preprocess(this.videoRef)}catch(t){this.switchToManualModeWithError("Error al procesar imagen");return}try{u=await this.detectionService.runInference(c);l=performance.now()-a}catch(t){this.switchToManualModeWithError("Error en detección automática");return}this.processedFramesCount++;if(this.debug){this.recordOnnxPerformance(0,l)}if(this.startTime&&Date.now()-this.startTime<5e3){u.forEach((t=>{const i=this.detectionService.isCardInFrame(t);const r=i?t.score*1.2:t.score;if(r>e.bestScore){this.stateManager.updateCaptureState({bestScore:r})}}))}const f=this.hasDocumentDetected;this.hasDocumentDetected=u.length>0;if(!f&&this.hasDocumentDetected&&e.step==="back"&&this.enableBackDocumentTimer){this.startBackDocumentTimer()}if(u.length===0){this.consecutiveFailures++}else{this.consecutiveFailures=0}if(this.debug){this.updateDetectionBoxes(u)}else{this.detectionBoxes=[]}this.updateMaskColor(u);const h=performance.now();const d=h-t;if(this.useDocumentDetector&&!this.hasAutoSwitchedToManual){if(d>=this.PERFORMANCE_THRESHOLD_MS){this.slowFrameCount++;if(this.slowFrameCount>=this.SLOW_FRAMES_TO_TRIGGER){this.switchToManualMode()}}else{if(this.slowFrameCount>0){this.slowFrameCount=0}}if(this.processedFramesCount===2){this.updateStatus("Captura activa","Buscando documento en el marco de captura","active")}}if(this.debug){this.recordFrameProcessing(d,u.length)}if(e.step!=="completed"){if(this.consecutiveFailures>this.MAX_FAILURES){setTimeout((()=>this.detectFrame()),200)}else{this.animationId=requestAnimationFrame((()=>this.detectFrame()))}}}catch(t){const e=this.stateManager.getCaptureState();if(e.step!=="completed"){setTimeout((()=>this.detectFrame()),100)}}}disconnectedCallback(){this.cleanup()}cleanup(){if(this.animationId){cancelAnimationFrame(this.animationId)}if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(this.orientationTimer){clearTimeout(this.orientationTimer);this.orientationTimer=undefined}this.releaseOnnxResources();if(this.performanceUpdateInterval){clearInterval(this.performanceUpdateInterval);this.performanceUpdateInterval=undefined}this.canvasPool=[];this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.serviceContainer?.cleanup()}render(){const t=this.stateManager?.getCaptureState()||{isVideoActive:false,showFlipAnimation:false,showSuccessAnimation:false,step:"front",isCapturing:false};const e=this.cameraInfoWithAutofocus;return r("div",{key:"c5af80713fb108ab73d086f2acbdd11277d7d52c",class:"detector-container"},!this.licenseValid&&this.licenseError&&r("div",{key:"99c886b52f58e667f76dce00f09828b9962b3606",class:"license-error-container"},r("div",{key:"ffd643ef41b3a4b1aa8f40075232a1d70695d566",class:"license-error-card"},r("svg",{key:"90e628f4e6e20ac8b27560833ada7486aac1c9fb",class:"license-error-icon",width:"64",height:"64",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r("path",{key:"cb442fe342c6c0ffb50dfcda42d0af43adedf143",d:"M12 22C12 22 20 18 20 12V5L12 2L4 5V12C4 18 12 22 12 22Z",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}),r("path",{key:"6b29651b70273f585d9870e71811c0cdb57ea659",d:"M12 8V12",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"}),r("circle",{key:"9ec1e61c3bc9e6f7046a49e45e7ef87880d8a443",cx:"12",cy:"16",r:"0.5",fill:"currentColor",stroke:"currentColor","stroke-width":"1"})),r("h2",{key:"56de8037a70da2c0b185029d4a9da0c935fd8c2b",class:"license-error-title"},"Licencia Requerida"),r("p",{key:"b6634818db630b62c8a5aa6152adc8e6da5f329f",class:"license-error-message"},this.licenseError),r("p",{key:"8c0b404805c2515912416b9a62d66680e6d4b411",class:"license-error-help"},"Contacte a soporte: ",r("a",{key:"1cd69e09c282353548ad9b14985054e47b6ff218",href:"mailto:support@jaak.ai"},"support@jaak.ai")),r("div",{key:"c2d13002c8f91a35b647199c77eb78b5643316df",class:"license-error-footer"},"JAAK Stamps"))),this.licenseValid&&r("div",{key:"094f1c85b06758399520cb85a461e1af755e3d45",class:"video-container"},r("video",{key:"e7973937fa0d77c9793e984d063ec29a80d464eb",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{display:t.isVideoActive?"block":"none"}}),r("div",{key:"fb86b9eb362e13902d31803c187f5d2b6c5ac664",ref:t=>this.detectionContainer=t,class:`detection-overlay ${this.shouldMirrorVideo?"mirror":""}`},this.debug&&this.detectionBoxes.map(((t,e)=>r("div",{key:e,class:"detection-box",style:{position:"absolute",left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,border:"2px solid #32406C",pointerEvents:"none",boxSizing:"border-box"}})))),this.isMaskReady&&r("div",{key:"28a8d52ace75ee2dc3f4cd31275f2feae0db31e3",class:"overlay-mask"},r("div",{key:"16c956f26a514c67ae178da5db2c0d19b53acdac",class:"card-outline"},r("div",{key:"578f111f358c0b66968b389f99235d1361ff035c",class:"side side-top"}),r("div",{key:"e7854fd3363f340fd2c832815e7c8aaf8935e5f4",class:"side side-right"}),r("div",{key:"c6f58f1c03506ec8920b914b76679730d1944b0e",class:"side side-bottom"}),r("div",{key:"a1af9d6777819d2c941ff99b985c3430d673e534",class:"side side-left"})),!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"fc9ec8cf13eb9b25140ebb9cfddd6636dc3b6e99",class:`guide-text ${this.showPerformanceMessage?"performance-warning-text":""}`},this.getGuideText(t.step)),t.step==="back"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"078ce12f5f2d24928d3f66eedac97f8c4bae3717",class:"back-capture-section"},r("div",{key:"9bf0528cc9fc691c212cf413bafdfeb999b47682",class:"back-capture-buttons"},(!this.useDocumentDetector||this.performanceDegradedMode||this.showManualCaptureButton)&&r("button",{key:"8d5613bda9e823293181f4551dfc5a49683a0e3e",class:"capture-button primary-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-back"&&r("span",{key:"19909120ab9576d4b820e528c1456f8ba5f17fb9",class:"button-spinner"}),"Capturar Reverso"),r("button",{key:"6e1cfac4e73ace6a2e59ed601e82c3f5b2770681",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button",disabled:this.processingButton!==null},this.processingButton==="skip-back"&&r("span",{key:"4aa6846d76295a428185ef3a83d15554eb2d9d00",class:"button-spinner"}),this.enableBackDocumentTimer&&this.backDocumentTimerRemaining>0?`Saltar reverso (${this.backDocumentTimerRemaining}s)`:"Saltar reverso"))),t.isVideoActive&&r("div",{key:"1c2ca195f159238c1b234e97dd3871d0a1caa3c8",class:"camera-controls"},r("button",{key:"085795c9083606fde64aeb211c242c031ebaf66a",class:`camera-selector-button ${this.isSwitchingCamera?"loading":""}`,onClick:()=>this.toggleCameraSelector(),type:"button",title:"Seleccionar cámara",disabled:this.isSwitchingCamera},this.isSwitchingCamera?r("div",{class:"button-spinner"}):"Cámaras")),this.showCameraSelector&&e.availableCameras.length>0&&r("div",{key:"e153c9e786afc0e911c32056351fa358eca45d21",class:"camera-selector-dropdown"},r("div",{key:"cb611c0d0b3170da382cb54895888d465ac4bd0a",class:"camera-selector-header"},r("span",{key:"200f7cdf43ec10163e573fbc00b077d75cc703ae"},"Seleccionar Cámara"),r("button",{key:"86cd2942c5a499053e64d2432dfbaa2bf9612777",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),r("div",{key:"1085775e191c43105ac4c645bb8fa227f1a230f5",class:"camera-list"},e.availableCameras.map((t=>r("button",{key:t.id,class:`camera-option ${e.selectedCameraId===t.id?"selected":""}`,onClick:()=>this.handleCameraSwitch(t.id),type:"button"},r("span",{class:"camera-label"},t.label||`Cámara ${e.availableCameras.indexOf(t)+1}`,t.hasAutofocus&&r("span",{class:"autofocus-icon",title:"Autofoco disponible"},"⦿")),e.selectedCameraId===t.id&&r("span",{class:"selected-indicator"},"✓"))))),r("div",{key:"b7465daa8357fce5192ba4800b03fc200e065145",class:"device-info"},r("small",{key:"2c824e7585afd324cefd071cdda380f3df5ada1b"},"Dispositivo: ",e.deviceType))),this.showManualCaptureButton&&t.step==="front"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"703f54145582191eaddcecd22a718dd72e16f977",class:"manual-capture-section"},r("button",{key:"dcbaa7e780c4bdb0703653e25146b17248a2d8c9",class:"manual-capture-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-front"&&r("span",{key:"cb989324a41f502ae740941ad75e6240051d8273",class:"button-spinner"}),"Capturar Frente"))),t.isCapturing&&r("div",{key:"c3567ccbd287c39f72cbca897e5f643c68624b5e",class:"capture-animation"}),t.showFlipAnimation&&r("div",{key:"b16f56f7fc7c710a4b41760515b2b8054d2aad4c",class:"flip-animation"},r("div",{key:"df905809f04bece3856545f8a6a1dcce89377377",class:"id-card-icon"}),r("div",{key:"daa09f264bf3708e535a3be580b86145568d4f66",class:"flip-text"},"¡Voltea tu identificación!")),t.showSuccessAnimation&&r("div",{key:"1be7277ef588b42060808b575670872a6aa08925",class:"success-animation"},r("div",{key:"ce18848121423499a4bc7b2e95586f3a01bc6ceb",class:"check-icon"}),r("div",{key:"2e2ae20c3e4bffbf3ec45f2fd7016a485ea380c1",class:"success-text"},"¡Proceso completado!")),r("div",{key:"951f37ba2b6366aa44e15c1dcf17b2ec6975131d",class:`component-status status-${this.currentStatus.type}`},(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing")&&r("div",{key:"1718aa68ed5db592183696bc212c7066f35bf789",class:"status-spinner"}),r("div",{key:"45bf0d9ee7786578b34d25623667ee8336720270",class:"status-content"},r("div",{key:"4fa2c1f9ddc62981cefbd63c19e04d14a503a406",class:"status-message"},this.currentStatus.message),this.currentStatus.description&&r("div",{key:"7f38fb0096a15467a63362979137981e84df55f9",class:"status-description"},this.currentStatus.description))),this.debug&&r("div",{key:"692e49518f3f78960b74f47741f2051e95ce9280",class:"performance-monitor"},r("div",{key:"be9f96048e16510203d8abc3b2b09ea9a0e91fe1",class:"performance-expanded"},r("div",{key:"ca19a5467a8bba02be34e3515af3f92839a4397a",class:"metrics-row"},r("div",{key:"54a6b187da25a3a6af0c8fbfc023fb16b45bb606",class:"metric-compact"},r("span",{key:"52b9bd1bbb8542011139b4556af213f64cc62c1f",class:"metric-label"},"FPS"),r("span",{key:"eff3acd45c407866e9c67205a4b4f0727b47afc8",class:`metric-value ${this.performanceData.fps<15?"warning":this.performanceData.fps<10?"danger":"good"}`},this.performanceData.fps)),r("div",{key:"fad4f7c5603ba7c2a95544d37f9d4b61c1840dca",class:"metric-compact"},r("span",{key:"e01386e6898c3f036f66795e71e65dad4d11366a",class:"metric-label"},"MEM"),r("span",{key:"71cb13b49656c869be920080f7b53ce2e709a4c0",class:`metric-value ${this.performanceData.memoryUsage>100?"warning":this.performanceData.memoryUsage>200?"danger":"good"}`},this.performanceData.memoryUsage,"MB"))),r("div",{key:"61fa2c277a2226f68d9dc036450dc086a1409b62",class:"metrics-row"},r("div",{key:"752052d1cdc68a5d65c3ec3f0b85241527d251ae",class:"metric-compact"},r("span",{key:"de5fae8f627df6347e5569d31433a96476bba22d",class:"metric-label"},"INF"),r("span",{key:"841c1a1b42e63e9fc4c56c72b54e07e47997f8be",class:`metric-value ${this.performanceData.inferenceTime>100?"warning":this.performanceData.inferenceTime>200?"danger":"good"}`},this.performanceData.inferenceTime,"ms")),r("div",{key:"194d01303155cda7b58a3bca1bd34795eac31556",class:"metric-compact"},r("span",{key:"73f023e1de8b6fbc8976bc3fe1d9655d3d5f3c92",class:"metric-label"},"FRAME"),r("span",{key:"ddb8d7fa99b83f477bd8cbfe4ca856d2baa7a493",class:`metric-value ${this.performanceData.frameProcessingTime>50?"warning":this.performanceData.frameProcessingTime>100?"danger":"good"}`},this.performanceData.frameProcessingTime,"ms"))),r("div",{key:"37eb5780cd09e3c056e7094b6b028789529112e3",class:"metrics-row"},r("div",{key:"236828977e1a634fddda1fef079c7780e469b815",class:"metric-compact"},r("span",{key:"d704dd8ba1e2080159a932c87208d2747feeb030",class:"metric-label"},"DET"),r("span",{key:"e0ceaf4cc91c00835bf92fdd3744a26958f39105",class:"metric-value good"},this.performanceData.successfulDetections,"/",this.performanceData.totalDetections)),r("div",{key:"96ad9e60657306f20efc285fd6eb5a83c3b8ee32",class:"metric-compact"},r("span",{key:"25e0ea0b4f16118b0bf7b9b974997b9bf832d2f8",class:"metric-label"},"RATE"),r("span",{key:"3f6f5370611d6fa6a927bc8ec1e03d0c262a3466",class:`metric-value ${this.performanceData.detectionRate<30?"danger":this.performanceData.detectionRate<60?"warning":"good"}`},this.performanceData.detectionRate,"%"))))),r("div",{key:"429a70ff02a2a2de127cb6cfe3426df1fdc4bbae",class:"watermark"},r("img",{key:"cc4174740e58367b2e66b6029dcca8404a3dccee",src:"https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png",alt:"Powered by Jaak"}))))}updateDetectionBoxes(t){if(!this.videoRef||!this.detectionContainer)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;const r=this.detectionContainer.parentElement;const n=r.getBoundingClientRect();const s=n.width;const o=n.height;if(e===0||i===0)return;const a=e/i;const c=s/o;let u,l;let f=0,h=0;if(a>c){u=s;l=s/a;h=(o-l)/2}else{l=o;u=o*a;f=(s-u)/2}const d=320;const p=u/d;const m=l/d;this.detectionBoxes=t.map((t=>({x:t.x*p+f,y:t.y*m+h,w:t.w*p,h:t.h*m,score:t.score})))}updateMaskColor(t){const e=this.el.shadowRoot?.querySelector(".card-outline");const i=this.el.shadowRoot?.querySelectorAll(".corner");const r=this.el.shadowRoot?.querySelector(".side-top");const n=this.el.shadowRoot?.querySelector(".side-right");const s=this.el.shadowRoot?.querySelector(".side-bottom");const o=this.el.shadowRoot?.querySelector(".side-left");let a=null;let c={top:false,right:false,bottom:false,left:false};if(t.length>0){a=t.reduce(((t,e)=>e.score>t.score?e:t));const e={INPUT_SIZE:320,ID1_ASPECT_RATIO:85.6/53.98,shouldMirrorVideo:this.shouldMirrorVideo,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,videoRef:this.videoRef};c=this.detectionService.checkSideAlignment(a,e);this.sideAlignment=c}else{this.sideAlignment={top:false,right:false,bottom:false,left:false}}r?.classList.toggle("aligned",c.top);n?.classList.toggle("aligned",c.right);s?.classList.toggle("aligned",c.bottom);o?.classList.toggle("aligned",c.left);const u=this.detectionService.areAllSidesAligned(c);const l=this.stateManager.getCaptureState();if(l.step==="back"&&this.enableBackDocumentTimer&&a){const t=c.top||c.right||c.bottom||c.left;if(t){this.startBackDocumentTimer()}}if(u&&a){e?.classList.add("perfect-match");i?.forEach((t=>t.classList.add("perfect-match")));if(!this.hasScreenshotTaken){const t=Date.now();if(!this.alignmentStartTime){this.alignmentStartTime=t}const e=t-this.alignmentStartTime;if(e>=this.captureDelay){this.lastDetectedBox=a;this.takeScreenshot().catch((()=>{}));this.hasScreenshotTaken=true;this.alignmentStartTime=undefined;setTimeout((()=>{this.hasScreenshotTaken=false}),2e3)}}}else{e?.classList.remove("perfect-match");i?.forEach((t=>t.classList.remove("perfect-match")));if(this.alignmentStartTime){this.alignmentStartTime=undefined}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}}}async takeManualScreenshot(){console.log("🔵 Botón clicked: Capturar (Frente/Reverso)");const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.manual");const i=this.stateManager?.getCaptureState();const r=i?.step==="front"?"front":"back";if(i?.step==="front"){this.processingButton="capture-front";if(e)this.tracingService?.setSpanAttribute(e,"side","front")}else if(i?.step==="back"){this.processingButton="capture-back";if(e)this.tracingService?.setSpanAttribute(e,"side","back")}this.metricsService?.recordUserInteraction("manual_capture_button");console.log("🔵 processingButton set to:",this.processingButton);await new Promise((t=>setTimeout(t,100)));if(!this.videoRef){this.processingButton=null;if(e){this.tracingService?.setSpanAttribute(e,"error","no_video_ref");this.tracingService?.endSpan(e)}return}await this.takeScreenshotWithMaskCoordinates();const n=performance.now()-t;this.metricsService?.recordCapture(r,"manual",n);if(e){this.tracingService?.setSpanAttribute(e,"success",true);this.tracingService?.endSpan(e)}}async takeScreenshotWithMaskCoordinates(){if(!this.videoRef||!this.detectionContainer)return;this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const t=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const e=t.getContext("2d",{alpha:false});e.clearRect(0,0,t.width,t.height);e.drawImage(this.videoRef,0,0,t.width,t.height);const i=this.detectionContainer.parentElement;const r=i.getBoundingClientRect();const n=parseFloat(this.el.style.getPropertyValue("--mask-width").replace("%",""))||90;const s=parseFloat(this.el.style.getPropertyValue("--mask-height").replace("%",""))||56.25;const o=parseFloat(this.el.style.getPropertyValue("--mask-center-x").replace("%",""))||50;const a=parseFloat(this.el.style.getPropertyValue("--mask-center-y").replace("%",""))||50;const c=this.videoRef.videoWidth;const u=this.videoRef.videoHeight;const l=c/u;const f=r.width/r.height;let h,d;let p=0,m=0;if(l>f){h=r.width;d=r.width/l;m=(r.height-d)/2}else{d=r.height;h=r.height*l;p=(r.width-h)/2}const b=n/100*r.width;const v=s/100*r.height;const w=o/100*r.width;const g=a/100*r.height;const y=c/h;const x=u/d;const k=(w-p)*y;const S=(g-m)*x;const _=b*y;const T=v*x;const E=Math.max(0,k-_/2-this.cropMargin);const M=Math.max(0,S-T/2-this.cropMargin);const C=Math.min(_+2*this.cropMargin,c-E);const A=Math.min(T+2*this.cropMargin,u-M);const P=this.getPooledCanvas(C,A);const I=P.getContext("2d",{alpha:false});I.clearRect(0,0,P.width,P.height);I.drawImage(this.videoRef,E,M,C,A,0,0,C,A);const O=this.stateManager.getCaptureState();if(O.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/jpeg"),cropped:P.toDataURL("image/jpeg")}});if(this.useDocumentClassification){try{const e=await this.detectionService.classifyDocument(P);if(e&&e.class==="passport"){this.completeProcess(true);this.returnCanvasToPool(t);this.returnCanvasToPool(P);this.processingButton=null;return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});this.triggerRerender();setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.triggerRerender();this.startBackDocumentTimer();this.processingButton=null}),3e3)}else if(O.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/jpeg"),cropped:P.toDataURL("image/jpeg")}});this.completeProcess(false);this.processingButton=null}this.returnCanvasToPool(t);this.returnCanvasToPool(P)}async takeScreenshot(){if(!this.videoRef||!this.lastDetectedBox)return;const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.auto");this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const i=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const r=i.getContext("2d",{alpha:false});r.clearRect(0,0,i.width,i.height);r.drawImage(this.videoRef,0,0,i.width,i.height);const n=320;const s=this.videoRef.videoWidth/n;const o=this.videoRef.videoHeight/n;const a=Math.max(0,this.lastDetectedBox.x*s-this.cropMargin);const c=Math.max(0,this.lastDetectedBox.y*o-this.cropMargin);const u=Math.min(this.lastDetectedBox.w*s+2*this.cropMargin,this.videoRef.videoWidth-a);const l=Math.min(this.lastDetectedBox.h*o+2*this.cropMargin,this.videoRef.videoHeight-c);const f=this.getPooledCanvas(u,l);const h=f.getContext("2d",{alpha:false});h.clearRect(0,0,f.width,f.height);h.drawImage(this.videoRef,a,c,u,l,0,0,u,l);const d=this.stateManager.getCaptureState();if(d.step==="front"){const r=i.toDataURL("image/jpeg");const n=f.toDataURL("image/jpeg");this.stateManager.setCapturedImages({front:{fullFrame:r,cropped:n}});const s=performance.now()-t;this.metricsService?.recordCapture("front","auto",s);this.metricsService?.recordImageSize("front",r.length);if(e){this.tracingService?.setSpanAttribute(e,"side","front")}if(this.useDocumentClassification){try{const t=await this.detectionService.classifyDocument(f);if(t&&t.class==="passport"){if(e){this.tracingService?.setSpanAttribute(e,"document.type","passport");this.tracingService?.endSpan(e)}this.completeProcess(true);return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});if(e){this.tracingService?.endSpan(e)}setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.startBackDocumentTimer()}),3e3)}else if(d.step==="back"){const r=i.toDataURL("image/jpeg");const n=f.toDataURL("image/jpeg");this.stateManager.setCapturedImages({back:{fullFrame:r,cropped:n}});const s=performance.now()-t;this.metricsService?.recordCapture("back","auto",s);this.metricsService?.recordImageSize("back",r.length);if(e){this.tracingService?.setSpanAttribute(e,"side","back");this.tracingService?.endSpan(e)}this.completeProcess(false)}this.returnCanvasToPool(i);this.returnCanvasToPool(f)}triggerCaptureAnimation(){const t=this.el.shadowRoot?.querySelector(".card-outline");t?.classList.add("capturing");setTimeout((()=>{this.stateManager.updateCaptureState({isCapturing:false});t?.classList.remove("capturing")}),600)}switchToManualMode(){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}this.stopPerformanceMonitoring();this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.showPerformanceMessage=true;setTimeout((()=>{this.showPerformanceMessage=false}),5e3)}switchToManualModeWithWarning(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.useDocumentDetector=false;this.updateStatus("Modo manual activado",t,"active");this.continueWithCameraSetup()}async continueWithCameraSetup(){try{this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus()}catch(t){throw new Error(`Error al actualizar información de cámara: ${t.message}`)}this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");let t;try{t=await this.cameraService.setupCamera()}catch(t){throw new Error(`Error al configurar cámara: ${t.message}`)}this.updateStatus("Captura manual","Posicione su documento y use el botón para capturar","active");try{await this.initializeVideoStream(t)}catch(t){throw new Error(`Error al inicializar video: ${t.message}`)}if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});this.showManualCaptureButton=true}catch(t){this.updateStatus("Error de cámara",t.message,"error");throw t}}switchToManualModeWithError(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.useDocumentDetector=false;this.updateStatus("Modo manual activado",t,"error");this.continueWithCameraSetup().catch((()=>{setTimeout((()=>{this.updateStatus("Captura manual","Use el botón para capturar","ready")}),5e3)}))}stopPerformanceMonitoring(){}releaseOnnxResources(){try{if(this.detectionService){this.detectionService.cleanup()}}catch(t){}}async completeProcess(t=false){this.stateManager.updateCaptureState({step:"completed",showSuccessAnimation:true});const e=this.stateManager.getCapturedImages();e.metadata.processCompleted=true;e.metadata.backCaptureSkipped=t;this.stateManager.setCapturedImages(e);this.stopDetection();this.updateStatus("Proceso completado",`Imágenes capturadas exitosamente`,"ready");const i={...e,timestamp:(new Date).toISOString()};if(this.tracingService){try{await this.tracingService.flush()}catch(t){console.error("[my-component] Failed to flush traces:",t)}}this.captureCompleted.emit(i);setTimeout((()=>{this.stateManager.updateCaptureState({showSuccessAnimation:false})}),3e3)}stopDetection(){if(this.animationId){cancelAnimationFrame(this.animationId);this.animationId=undefined}this.clearBackDocumentTimer();this.detectionBoxes=[]}startBackDocumentTimer(){if(!this.enableBackDocumentTimer)return;if(this.backDocumentTimer){clearInterval(this.backDocumentTimer)}this.backDocumentTimerRemaining=this.backDocumentTimerDuration;this.backDocumentTimer=window.setInterval((()=>{this.backDocumentTimerRemaining--;if(this.backDocumentTimerRemaining<=0){this.clearBackDocumentTimer();this.skipBackCapture()}}),1e3)}clearBackDocumentTimer(){if(this.backDocumentTimer){clearInterval(this.backDocumentTimer);this.backDocumentTimer=undefined}this.backDocumentTimerRemaining=0}toggleCameraSelector(){if(this.isSwitchingCamera)return;this.showCameraSelector=!this.showCameraSelector}async updateCameraInfoWithAutofocus(){try{const t=await this.cameraService.getCameraInfo();this.cameraInfoWithAutofocus=t}catch(t){}}async handleCameraSwitch(t){if(this.isSwitchingCamera)return;try{this.showCameraSelector=false;const e=this.cameraService.getSelectedCameraId();if(e===t){return}this.isSwitchingCamera=true;if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}await this.cameraService.switchCamera(t);const i=await this.cameraService.setupCamera();await this.initializeVideoStream(i);await this.updateCameraInfoWithAutofocus()}catch(t){try{const t=await this.cameraService.setupCamera();await this.initializeVideoStream(t)}catch(t){this.updateStatus("Error al cambiar cámara","No se pudo cambiar el dispositivo","error")}}finally{this.isSwitchingCamera=false}}resetDetection(){const t=this.stateManager.getCaptureState();const e=t.isVideoActive;this.stateManager.reset();if(e){this.stateManager.updateCaptureState({isVideoActive:true})}this.hasScreenshotTaken=false;this.startTime=Date.now();this.frameSkipCounter=0;this.consecutiveFailures=0;this.lastInferenceTime=0;this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.processedFramesCount=0;this.slowFrameCount=0;this.hasAutoSwitchedToManual=false;this.performanceDegradedMode=false;this.showPerformanceMessage=false;if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(e&&this.detectionService.isModelLoaded()){this.updateStatus("Captura reiniciada","Buscando documento en el marco de captura","active");this.detectFrame()}else{this.updateStatus("Listo para capturar","","ready")}}exitSession(){if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()));this.videoStream=undefined;this.stateManager.updateCaptureState({isVideoActive:false,isLoading:false})}this.isMaskReady=false;this.updateStatus("Captura finalizada","","ready");this.detectionBoxes=[];this.cleanup()}initializePerformanceMonitor(){this.performanceMetrics.lastUpdateTime=performance.now();this.performanceUpdateInterval=window.setInterval((()=>{this.updatePerformanceMetrics()}),500)}updatePerformanceMetrics(){const t=performance.now();const e=t-this.performanceMetrics.lastUpdateTime;if(e>0){this.performanceMetrics.fps=Math.round(1e3/(e/this.frameSkipCounter||1))}if("memory"in performance){const t=performance.memory;this.performanceMetrics.memoryUsage=Math.round(t.usedJSHeapSize/1048576)}if(this.performanceMetrics.totalDetections>0){this.performanceMetrics.successfulDetections=this.performanceMetrics.successfulDetections;const t=this.performanceMetrics.successfulDetections/this.performanceMetrics.totalDetections*100;this.performanceMetrics.detectionRate=Math.round(t)}this.performanceData={fps:this.performanceMetrics.fps,inferenceTime:this.performanceMetrics.inferenceTime,memoryUsage:this.performanceMetrics.memoryUsage,onnxLoadTime:this.performanceMetrics.onnxLoadTime,frameProcessingTime:this.performanceMetrics.frameProcessingTime,totalDetections:this.performanceMetrics.totalDetections,successfulDetections:this.performanceMetrics.successfulDetections,detectionRate:this.performanceMetrics.detectionRate};this.performanceMetrics.lastUpdateTime=t}recordOnnxPerformance(t,e){this.performanceMetrics.onnxLoadTime=Math.round(t);this.performanceMetrics.inferenceTime=Math.round(e)}recordFrameProcessing(t,e){this.performanceMetrics.frameProcessingTime=Math.round(t);this.performanceMetrics.totalDetections++;if(e>0){this.performanceMetrics.successfulDetections++}this.performanceHistory.push(t);if(this.performanceHistory.length>this.PERFORMANCE_HISTORY_SIZE){this.performanceHistory.shift()}}getAdaptiveFrameSkip(){const t=this.cameraInfoWithAutofocus.deviceType==="mobile"||/Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);const e=this.cameraInfoWithAutofocus.deviceType==="tablet"||/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const i=t&&!e?4:this.BASE_FRAME_SKIP;if(this.consecutiveFailures>20)return this.MAX_FRAME_SKIP;if(this.performanceMetrics.inferenceTime>200)return Math.max(6,i);if(this.performanceMetrics.memoryUsage>200)return Math.max(5,i);if(this.performanceHistory.length>0){const t=this.performanceHistory.reduce(((t,e)=>t+e),0)/this.performanceHistory.length;if(t>100)return Math.max(4,i);if(t>80)return Math.max(3,i);if(t>60)return Math.max(this.BASE_FRAME_SKIP+1,i)}if(this.performanceMetrics.memoryUsage>150)return Math.max(4,i);return i}resetMaskToWhite(){const t=this.el.shadowRoot?.querySelector(".card-outline");const e=this.el.shadowRoot?.querySelectorAll(".corner");const i=this.el.shadowRoot?.querySelector(".side-top");const r=this.el.shadowRoot?.querySelector(".side-right");const n=this.el.shadowRoot?.querySelector(".side-bottom");const s=this.el.shadowRoot?.querySelector(".side-left");t?.classList.remove("perfect-match");e?.forEach((t=>t.classList.remove("perfect-match")));i?.classList.remove("aligned");r?.classList.remove("aligned");n?.classList.remove("aligned");s?.classList.remove("aligned");this.sideAlignment={top:false,right:false,bottom:false,left:false}}getPooledCanvas(t,e){const i=this.canvasPool.findIndex((i=>i.width===t&&i.height===e));if(i!==-1){return this.canvasPool.splice(i,1)[0]}if(this.canvasPool.length>0){const i=this.canvasPool.pop();i.width=t;i.height=e;return i}const r=document.createElement("canvas");r.width=t;r.height=e;return r}returnCanvasToPool(t){if(this.canvasPool.length<this.MAX_CANVAS_POOL_SIZE){const e=t.getContext("2d");e.clearRect(0,0,t.width,t.height);this.canvasPool.push(t)}}};Jc.style=Yc;export{Jc as jaak_stamps};
7
- //# sourceMappingURL=p-e91f65fd.entry.js.map