@jaak.ai/stamps 2.5.4-dev.1 → 2.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/{index-D6NBn_qu.js → index-ucw61xdq.js} +9 -2
- package/dist/cjs/{index-D6NBn_qu.js.map → index-ucw61xdq.js.map} +1 -1
- package/dist/cjs/jaak-stamps-webcomponent.cjs.js +1 -1
- package/dist/cjs/jaak-stamps.cjs.entry.js +6 -23
- package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -1
- package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -1
- package/dist/cjs/loader.cjs.js +1 -1
- package/dist/collection/assets/powered-by-jaak.png +0 -0
- package/dist/collection/components/my-component/my-component.js +6 -5
- package/dist/collection/components/my-component/my-component.js.map +1 -1
- package/dist/collection/services/DetectionService.js +0 -18
- package/dist/collection/services/DetectionService.js.map +1 -1
- package/dist/components/jaak-stamps.js +6 -23
- package/dist/components/jaak-stamps.js.map +1 -1
- package/dist/esm/{index-BCfAsrzL.js → index-CqdAwiLj.js} +9 -3
- package/dist/esm/{index-BCfAsrzL.js.map → index-CqdAwiLj.js.map} +1 -1
- package/dist/esm/jaak-stamps-webcomponent.js +2 -2
- package/dist/esm/jaak-stamps.entry.js +6 -23
- package/dist/esm/jaak-stamps.entry.js.map +1 -1
- package/dist/esm/loader.js +2 -2
- package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +1 -1
- package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -1
- package/dist/jaak-stamps-webcomponent/{p-0f4d77b3.entry.js → p-178aea65.entry.js} +3 -3
- package/dist/jaak-stamps-webcomponent/p-178aea65.entry.js.map +1 -0
- package/dist/jaak-stamps-webcomponent/p-CqdAwiLj.js +3 -0
- package/dist/jaak-stamps-webcomponent/{p-BCfAsrzL.js.map → p-CqdAwiLj.js.map} +1 -1
- package/package.json +1 -1
- package/dist/jaak-stamps-webcomponent/p-0f4d77b3.entry.js.map +0 -1
- package/dist/jaak-stamps-webcomponent/p-BCfAsrzL.js +0 -3
|
@@ -1,7 +1,7 @@
|
|
|
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 h{debug;useDocumentClassification;useDocumentDetector;session;mobileNetSession;mobileNetClassMap;modelLoaded=false;deviceStrategy;MODEL_PATH="https://static.jaak.ai/web/component/stamps/ddmyp-v2.onnx";MODEL_PATH_FP32="https://static.jaak.ai/web/component/stamps/ddmyp-v2-fp32.onnx";MOBILENET_MODEL_PATH="https://static.jaak.ai/web/component/stamps/squeezenet_new_fp32.onnx";MOBILENET_CLASSES_PATH="https://static.jaak.ai/web/component/stamps/cdmmp-v1.json";INPUT_SIZE=320;CONFIDENCE_THRESHOLD=.6;useFloat16=true;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);this.detectFloat16Support()}catch(e){const i=e.message||"";const r=i.includes("failed to allocate a buffer")||i.includes("Out of memory")||i.includes("RangeError: Out of memory")||i.includes("no available backend found");const n=i.includes("unsupported data type")||i.includes("FLOAT16")||i.includes("float16");if(n){if(this.debug){console.log("[JAAK-DEBUG] float16 model not supported, loading fp32 model:",this.MODEL_PATH_FP32)}this.useFloat16=false;try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH_FP32,t);if(this.debug){console.log("[JAAK-DEBUG] fp32 model loaded successfully")}}catch(t){if(this.debug){console.log("[JAAK-DEBUG] fp32 model failed with default options:",t.message);console.log("[JAAK-DEBUG] Retrying fp32 model with WASM fallback options")}const e={executionProviders:["wasm"],graphOptimizationLevel:"all",logSeverityLevel:this.debug?2:4};this.session=await window.ort.InferenceSession.create(this.MODEL_PATH_FP32,e)}}else if(r){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1,enableProfiling:false,sessionLogSeverityLevel:4,sessionLogVerbosityLevel:0};this.useFloat16=false;try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH_FP32,t)}catch(t){throw new Error(`no available backend found. ERR: [wasm] RangeError: Out of memory`)}}else{throw e}}if(this.debug){console.log("[JAAK-DEBUG] Model loaded. useFloat16:",this.useFloat16)}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));if(this.useFloat16){const t=new Uint16Array(o.length);for(let e=0;e<o.length;e++){t[e]=this.float32ToFloat16(o[e])}return new window.ort.Tensor("float16",t,[1,3,this.INPUT_SIZE,this.INPUT_SIZE])}return new window.ort.Tensor("float32",o,[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 h=1;let f,d;if(l>h){f=i;d=i/l}else{d=i;f=i*l}const p=d*r;let m,b;const v=o/100;if(p<=f){b=d*v;m=b*r}else{m=f*v;b=m/r}const w=m*(i/f);const g=b*(i/d);const y=i/2;const x=i/2;const k=y-w/2;const S=y+w/2;const E=x-g/2;const A=x+g/2;let T=t.x;let _=t.x+t.w;const M=t.y;const C=t.y+t.h;if(n){const t=T;const e=_;T=i-e;_=i-t}const O=s;const I=Math.abs(M-E)<=O;const P=Math.abs(_-S)<=O;const L=Math.abs(C-A)<=O;const D=Math.abs(T-k)<=O;return{top:I&&D,right:I&&P,bottom:L&&D,left:L&&P}}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}}detectFloat16Support(){try{const t=new Uint16Array([0]);new window.ort.Tensor("float16",t,[1]);this.useFloat16=true}catch{this.useFloat16=false;if(this.debug){console.log("[JAAK-DEBUG] float16 not supported by current backend, using float32")}}}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(!h.canvasPool.has(i)){h.canvasPool.set(i,[])}const r=h.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(!h.canvasPool.has(e)){h.canvasPool.set(e,[])}const i=h.canvasPool.get(e);if(i.length<h.MAX_POOL_SIZE){i.push(t)}}static clearCanvasPools(){h.canvasPool.clear()}getPoolStats(){const t={};h.canvasPool.forEach(((e,i)=>{t[i]=e.length}));return t}}var f=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=f;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 E=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 A=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 T("debug",this._namespace,t)};t.prototype.error=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("error",this._namespace,t)};t.prototype.info=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("info",this._namespace,t)};t.prototype.warn=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("warn",this._namespace,t)};t.prototype.verbose=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("verbose",this._namespace,t)};return t}();function T(t,e,i){var r=x("diag");if(!r){return}i.unshift(e);return r[t].apply(r,E([],S(i),false))}var _;(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"})(_||(_={}));function M(t,e){if(t<_.NONE){t=_.NONE}else if(t>_.ALL){t=_.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",_.ERROR),warn:i("warn",_.WARN),info:i("info",_.INFO),debug:i("debug",_.DEBUG),verbose:i("verbose",_.VERBOSE)}}var C=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 O=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 P=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,O([],C(e),false))}}var e=this;var i=function(t,i){var r,n,s;if(i===void 0){i={logLevel:_.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=M((n=i.logLevel)!==null&&n!==void 0?n:_.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 A(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 D=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 R=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=D(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 N=Symbol("BaggageEntryMetadata");var j=P.instance();function U(t){if(t===void 0){t={}}return new R(new Map(Object.entries(t)))}function z(t){if(typeof t!=="string"){j.error("Cannot create baggage metadata from unknown type: "+typeof t);t=""}return{__TYPE__:N,toString:function(){return t}}}function $(t){return Symbol.for(t)}var B=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 F=new B;var G=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 q=function(){function t(){}return t}();var H=function(t){G(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.add=function(t,e){};return e}(q);var J=function(t){G(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.add=function(t,e){};return e}(q);var K=function(t){G(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.record=function(t,e){};return e}(q);var Z=function(t){G(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.record=function(t,e){};return e}(q);var W=function(){function t(){}t.prototype.addCallback=function(t){};t.prototype.removeCallback=function(t){};return t}();var X=function(t){G(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(W);var Y=function(t){G(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(W);var Q=function(t){G(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(W);var tt=new V;var et=new H;var it=new K;var rt=new Z;var nt=new J;var st=new X;var ot=new Y;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 ht={set:function(t,e,i){if(t==null){return}t[e]=i}};var ft=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 F};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],ft(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,P.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,P.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 Et=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 At=$("OpenTelemetry Context Key SPAN");function Tt(t){return t.getValue(At)||undefined}function _t(){return Tt(gt.getInstance().active())}function Mt(t,e){return t.setValue(At,e)}function Ct(t){return t.deleteValue(At)}function Ot(t,e){return Mt(t,new Et(e))}function It(t){var e;return(e=Tt(t))===null||e===void 0?void 0:e.spanContext()}var Pt=/^([0-9a-f]{32})$/i;var Lt=/^[0-9a-f]{16}$/i;function Dt(t){return Pt.test(t)&&t!==kt}function Rt(t){return Lt.test(t)&&t!==xt}function Nt(t){return Dt(t.traceId)&&Rt(t.spanId)}function jt(t){return new Et(t)}var Ut=gt.getInstance();var zt=function(){function t(){}t.prototype.startSpan=function(t,e,i){if(i===void 0){i=Ut.active()}var r=Boolean(e===null||e===void 0?void 0:e.root);if(r){return new Et}var n=i&&It(i);if($t(n)&&Nt(n)){return new Et(n)}else{return new Et}};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:Ut.active();var c=this.startSpan(t,n,a);var u=Mt(a,c);return Ut.with(u,o,undefined,c)};return t}();function $t(t){return typeof t==="object"&&typeof t["spanId"]==="string"&&typeof t["traceId"]==="string"&&typeof t["traceFlags"]==="number"}var Bt=new zt;var Ft=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 Bt}this._delegate=t;return this._delegate};return t}();var Gt=function(){function t(){}t.prototype.getTracer=function(t,e,i){return new zt};return t}();var Vt=new Gt;var qt=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 Ft(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 Ht;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(Ht||(Ht={}));var Jt;(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"})(Jt||(Jt={}));var Kt;(function(t){t[t["UNSET"]=0]="UNSET";t[t["OK"]=1]="OK";t[t["ERROR"]=2]="ERROR"})(Kt||(Kt={}));var Zt=gt.getInstance();var Wt=P.instance();var Xt=function(){function t(){}t.prototype.getMeter=function(t,e,i){return tt};return t}();var Yt=new Xt;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,P.instance())};t.prototype.getMeterProvider=function(){return x(Qt)||Yt};t.prototype.getMeter=function(t,e,i){return this.getMeterProvider().getMeter(t,e,i)};t.prototype.disable=function(){k(Qt,P.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=$("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=U;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,P.instance())};t.prototype.inject=function(t,e,i){if(i===void 0){i=ht}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,P.instance())};t.prototype._getGlobalPropagator=function(){return x(ce)||ue};return t}();var he=le.getInstance();var fe="trace";var de=function(){function t(){this._proxyTracerProvider=new qt;this.wrapSpanContext=jt;this.isSpanContextValid=Nt;this.deleteSpan=Ct;this.getSpan=Tt;this.getActiveSpan=_t;this.getSpanContext=It;this.setSpan=Mt;this.setSpanContext=Ot}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalTracerProvider=function(t){var e=y(fe,this._proxyTracerProvider,P.instance());if(e){this._proxyTracerProvider.setDelegate(t)}return e};t.prototype.getTracerProvider=function(){return x(fe)||this._proxyTracerProvider};t.prototype.getTracer=function(t,e){return this.getTracerProvider().getTracer(t,e)};t.prototype.disable=function(){k(fe,P.instance());this._proxyTracerProvider=new qt};return t}();var pe=de.getInstance();const me=$("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 Ee=8192;function Ae(t){return t.reduce(((t,e)=>{const i=`${t}${t!==""?ye:""}${e}`;return i.length>Ee?t:i}),"")}function Te(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 _e(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=z(e.join(ge))}return{key:n,value:s,metadata:o}}class Me{inject(t,e,i){const r=he.getBaggage(t);if(!r||ve(t))return;const n=Te(r).filter((t=>t.length<=Se)).slice(0,ke);const s=Ae(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=_e(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 he.setBaggage(t,he.createBaggage(s))}fields(){return[xe]}}function Ce(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(!Oe(i)){Wt.warn(`Invalid attribute key: ${i}`);continue}const r=t[i];if(!Ie(r)){Wt.warn(`Invalid attribute value set for key: ${i}`);continue}if(Array.isArray(r)){e[i]=r.slice()}else{e[i]=r}}return e}function Oe(t){return typeof t==="string"&&t!==""}function Ie(t){if(t==null){return true}if(Array.isArray(t)){return Pe(t)}return Le(typeof t)}function Pe(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 De(){return t=>{Wt.error(Re(t))}}function Re(t){if(typeof t==="string"){return t}else{return JSON.stringify(Ne(t))}}function Ne(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 je=De();function Ue(t){try{je(t)}catch{}}function ze(t){return undefined}const $e=performance;const Be="2.2.0";const Fe="exception.message";const Ge="exception.stacktrace";const Ve="exception.type";const qe="service.name";const He="telemetry.sdk.language";const Je="webjs";const Ke="telemetry.sdk.name";const Ze="telemetry.sdk.version";const We="process.runtime.name";const Xe={[Ke]:"opentelemetry",[We]:"browser",[He]:Je,[Ze]:Be};const Ye=9;const Qe=6;const ti=Math.pow(10,Qe);const ei=Math.pow(10,Ye);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=$e.timeOrigin;if(typeof t!=="number"){const e=$e;t=e.timing&&e.timing.fetchStart}return t}function ni(t){const e=ii(ri());const i=ii(typeof t==="number"?t:$e.now());return ui(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 Array.isArray(t)&&t.length===2&&typeof t[0]==="number"&&typeof t[1]==="number"}function ci(t){return ai(t)||typeof t==="number"||t instanceof Date}function ui(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 li;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(li||(li={}));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){Wt.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){Wt.warn(`Failed to extract with ${r.constructor.name}. Err: ${t.message}`)}return t}),t)}fields(){return this._fields.slice()}}const fi="[_0-9a-z-*/]";const di=`[a-z]${fi}{0,255}`;const pi=`[a-z0-9]${fi}{0,240}@[a-z]${fi}{0,13}`;const mi=new RegExp(`^(?:${di}|${pi})$`);const bi=/^[ -~]{0,255}[!-~]$/;const vi=/,|=/;function wi(t){return mi.test(t)}function gi(t){return bi.test(t)&&!vi.test(t)}const yi=32;const xi=512;const ki=",";const Si="=";class Ei{_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+Si+this.get(e));return t}),[]).join(ki)}_parse(t){if(t.length>xi)return;this._internalState=t.split(ki).reverse().reduce(((t,e)=>{const i=e.trim();const r=i.indexOf(Si);if(r!==-1){const n=i.slice(0,r);const s=i.slice(r+1,e.length);if(wi(n)&&gi(s)){t.set(n,s)}}return t}),new Map);if(this._internalState.size>yi){this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,yi))}}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const t=new Ei;t._internalState=new Map(this._internalState);return t}}const Ai="traceparent";const Ti="tracestate";const _i="00";const Mi="(?!ff)[\\da-f]{2}";const Ci="(?![0]{32})[\\da-f]{32}";const Oi="(?![0]{16})[\\da-f]{16}";const Ii="[\\da-f]{2}";const Pi=new RegExp(`^\\s?(${Mi})-(${Ci})-(${Oi})-(${Ii})(-.*)?\\s?$`);function Li(t){const e=Pi.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 Di{inject(t,e,i){const r=pe.getSpanContext(t);if(!r||ve(t)||!Nt(r))return;const n=`${_i}-${r.traceId}-${r.spanId}-0${Number(r.traceFlags||yt.NONE).toString(16)}`;i.set(e,Ai,n);if(r.traceState){i.set(e,Ti,r.traceState.serialize())}}extract(t,e,i){const r=i.get(e,Ai);if(!r)return t;const n=Array.isArray(r)?r[0]:r;if(typeof n!=="string")return t;const s=Li(n);if(!s)return t;s.isRemote=true;const o=i.get(e,Ti);if(o){const t=Array.isArray(o)?o.join(","):o;s.traceState=new Ei(typeof t==="string"?t:undefined)}return pe.setSpanContext(t,s)}fields(){return[Ai,Ti]}}const Ri="[object Object]";const Ni="[object Null]";const ji="[object Undefined]";const Ui=Function.prototype;const zi=Ui.toString;const $i=zi.call(Object);const Bi=Object.getPrototypeOf;const Fi=Object.prototype;const Gi=Fi.hasOwnProperty;const Vi=Symbol?Symbol.toStringTag:undefined;const qi=Fi.toString;function Hi(t){if(!Ji(t)||Ki(t)!==Ri){return false}const e=Bi(t);if(e===null){return true}const i=Gi.call(e,"constructor")&&e.constructor;return typeof i=="function"&&i instanceof i&&zi.call(i)===$i}function Ji(t){return t!=null&&typeof t=="object"}function Ki(t){if(t==null){return t===undefined?ji:Ni}return Vi&&Vi in Object(t)?Zi(t):Wi(t)}function Zi(t){const e=Gi.call(t,Vi),i=t[Vi];let r=false;try{t[Vi]=undefined;r=true}catch{}const n=qi.call(t);if(r){if(e){t[Vi]=i}else{delete t[Vi]}}return n}function Wi(t){return qi.call(t)}const Xi=20;function Yi(...t){let e=t.shift();const i=new WeakMap;while(t.length>0){e=tr(e,t.shift(),0,i)}return e}function Qi(t){if(ir(t)){return t.slice()}return t}function tr(t,e,i=0,r){let n;if(i>Xi){return undefined}i++;if(sr(t)||sr(e)||rr(e)){n=Qi(e)}else if(ir(t)){n=t.slice();if(ir(e)){for(let t=0,i=e.length;t<i;t++){n.push(Qi(e[t]))}}else if(nr(e)){const t=Object.keys(e);for(let i=0,r=t.length;i<r;i++){const r=t[i];n[r]=Qi(e[r])}}}else if(nr(t)){if(nr(e)){if(!or(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(sr(c)){if(typeof c==="undefined"){delete n[a]}else{n[a]=c}}else{const s=n[a];const o=c;if(er(t,a,r)||er(e,a,r)){delete n[a]}else{if(nr(s)&&nr(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]=tr(n[a],c,i,r)}}}}else{n=e}}return n}function er(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 ir(t){return Array.isArray(t)}function rr(t){return typeof t==="function"}function nr(t){return!sr(t)&&!ir(t)&&!rr(t)&&typeof t==="object"}function sr(t){return typeof t==="string"||typeof t==="number"||typeof t==="boolean"||typeof t==="undefined"||t instanceof Date||t instanceof RegExp||t===null}function or(t,e){if(!Hi(t)||!Hi(e)){return false}return true}class ar{_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 cr{_callback;_that;_isCalled=false;_deferred=new ar;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 ur(){return"unknown_service"}const lr=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";let hr=class t{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(e,i){const r=new t({},i);r._rawAttributes=pr(e);r._asyncAttributesPending=e.filter((([t,e])=>lr(e))).length>0;return r}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(lr(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=pr(this._rawAttributes);this._schemaUrl=mr(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,lr(i)?await i:i]}this._asyncAttributesPending=false}get attributes(){if(this.asyncAttributesPending){Wt.error("Accessing resource attributes before async attributes settled")}if(this._memoizedAttributes){return this._memoizedAttributes}const t={};for(const[e,i]of this._rawAttributes){if(lr(i)){Wt.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(e){if(e==null)return this;const i=br(this,e);const r=i?{schemaUrl:i}:undefined;return t.FromAttributeList([...e.getRawAttributes(),...this.getRawAttributes()],r)}};function fr(t,e){return hr.FromAttributeList(Object.entries(t),e)}function dr(){return fr({[qe]:ur(),[He]:Xe[He],[Ke]:Xe[Ke],[Ze]:Xe[Ze]})}function pr(t){return t.map((([t,e])=>{if(lr(e)){return[t,e.catch((e=>{Wt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function mr(t){if(typeof t==="string"||t===undefined){return t}Wt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t);return undefined}function br(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}Wt.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 vr="exception";class wr{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:Kt.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=$e.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){Wt.warn(`Invalid attribute key: ${t}`);return this}if(!Ie(e)){Wt.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){Wt.warn("No events allowed.");this._droppedEventsCount++;return this}if(r!==undefined&&this.events.length>=r){if(this._droppedEventsCount===0){Wt.debug("Dropping extra events.")}this.events.shift();this._droppedEventsCount++}if(ci(e)){if(!ci(i)){i=e}e=undefined}const n=Ce(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"){Wt.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()){Wt.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){Wt.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){Wt.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`)}this._spanProcessor.onEnd(this)}_getTime(t){if(typeof t==="number"&&t<=$e.now()){return ni(t+this._performanceOffset)}if(typeof t==="number"){return ii(t)}if(t instanceof Date){return ii(t.getTime())}if(ai(t)){return t}if(this._startTimeProvided){return ii(Date.now())}const e=$e.now()-this._performanceStartTime;return ui(this.startTime,ii(e))}isRecording(){return this._ended===false}recordException(t,e){const i={};if(typeof t==="string"){i[Fe]=t}else if(t){if(t.code){i[Ve]=t.code.toString()}else if(t.name){i[Ve]=t.name}if(t.message){i[Fe]=t.message}if(t.stack){i[Ge]=t.stack}}if(i[Ve]||i[Fe]){this.addEvent(vr,i,e)}else{Wt.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}}`);Wt.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){Wt.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 gr;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(gr||(gr={}));class yr{shouldSample(){return{decision:gr.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class xr{shouldSample(){return{decision:gr.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class kr{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(t){this._root=t.root;if(!this._root){Ue(new Error("ParentBasedSampler must have a root sampler configured"));this._root=new xr}this._remoteParentSampled=t.remoteParentSampled??new xr;this._remoteParentNotSampled=t.remoteParentNotSampled??new yr;this._localParentSampled=t.localParentSampled??new xr;this._localParentNotSampled=t.localParentNotSampled??new yr}shouldSample(t,e,i,r,n,s){const o=pe.getSpanContext(t);if(!o||!Nt(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 Sr{_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:Dt(e)&&this._accumulate(e)<this._upperBound?gr.RECORD_AND_SAMPLED:gr.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 Er;(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"})(Er||(Er={}));const Ar=1;function Tr(){return{sampler:_r(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function _r(){const t=Er.ParentBasedAlwaysOn;switch(t){case Er.AlwaysOn:return new xr;case Er.AlwaysOff:return new yr;case Er.ParentBasedAlwaysOn:return new kr({root:new xr});case Er.ParentBasedAlwaysOff:return new kr({root:new yr});case Er.TraceIdRatio:return new Sr(Mr());case Er.ParentBasedTraceIdRatio:return new kr({root:new Sr(Mr())});default:Wt.error(`OTEL_TRACES_SAMPLER value "${t}" invalid, defaulting to "${Er.ParentBasedAlwaysOn}".`);return new kr({root:new xr})}}function Mr(){{Wt.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${Ar}.`);return Ar}}const Cr=128;const Or=Infinity;function Ir(t){const e={sampler:_r()};const i=Tr();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 Pr(t){const e=Object.assign({},t.spanLimits);e.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??ze()??ze()??Cr;e.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??ze()??ze()??Or;return Object.assign({},t,{spanLimits:e})}class Lr{_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 cr(this._shutdown,this);if(this._maxExportBatchSize>this._maxQueueSize){Wt.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){Wt.debug("maxQueueSize reached, dropping spans")}this._droppedSpansCount++;return}if(this._droppedSpansCount>0){Wt.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);Zt.with(be(Zt.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===li.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=>{Ue(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;Ue(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 Dr extends Lr{_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=>{Ue(t)}))}};this._pageHideListener=()=>{this.forceFlush().catch((t=>{Ue(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 Rr=8;const Nr=16;class jr{generateTraceId=zr(Nr);generateSpanId=zr(Rr)}const Ur=Array(32);function zr(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 $r{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(t,e,i,r){const n=Ir(e);this._sampler=n.sampler;this._generalLimits=n.generalLimits;this._spanLimits=n.spanLimits;this._idGenerator=e.idGenerator||new jr;this._resource=i;this._spanProcessor=r;this.instrumentationScope=t}startSpan(t,e={},i=Zt.active()){if(e.root){i=pe.deleteSpan(i)}const r=pe.getSpan(i);if(ve(i)){Wt.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??Jt.INTERNAL;const l=(e.links??[]).map((t=>({context:t.context,attributes:Ce(t.attributes)})));const h=Ce(e.attributes);const f=this._sampler.shouldSample(i,a,t,u,h,l);c=f.traceState??c;const d=f.decision===Ht.RECORD_AND_SAMPLED?yt.SAMPLED:yt.NONE;const p={traceId:a,spanId:s,traceFlags:d,traceState:c};if(f.decision===Ht.NOT_RECORD){Wt.debug("Recording is off, propagating context in a non-recording span");const t=pe.wrapSpanContext(p);return t}const m=Ce(Object.assign(h,f.attributes));const b=new wr({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??Zt.active();const c=this.startSpan(t,n,a);const u=pe.setSpan(a,c);return Zt.with(u,o,undefined,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class Br{_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=>{Ue(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 Fr;(function(t){t[t["resolved"]=0]="resolved";t[t["timeout"]=1]="timeout";t[t["error"]=2]="error";t[t["unresolved"]=3]="unresolved"})(Fr||(Fr={}));class Gr{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(t={}){const e=Yi({},Tr(),Pr(t));this._resource=e.resource??dr();this._config=Object.assign({},e,{resource:this._resource});const i=[];if(t.spanProcessors?.length){i.push(...t.spanProcessors)}this._activeSpanProcessor=new Br(i)}getTracer(t,e,i){const r=`${t}@${e||""}:${i?.schemaUrl||""}`;if(!this._tracers.has(r)){this._tracers.set(r,new $r({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=Fr.timeout}),t);e.forceFlush().then((()=>{clearTimeout(n);if(r!==Fr.timeout){r=Fr.resolved;i(r)}})).catch((t=>{clearTimeout(n);r=Fr.error;i(t)}))}))));return new Promise(((t,i)=>{Promise.all(e).then((e=>{const r=e.filter((t=>t!==Fr.resolved));if(r.length>0){i(r)}else{t()}})).catch((t=>i([t])))}))}shutdown(){return this._activeSpanProcessor.shutdown()}}class Vr{_enabled=false;_currentContext=F;_bindFunction(t=F,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=F;this._enabled=false;return this}enable(){if(this._enabled){return this}this._enabled=true;this._currentContext=F;return this}with(t,e,i,...r){const n=this._currentContext;this._currentContext=t||F;try{return e.call(i,...r)}finally{this._currentContext=n}}}function qr(t){if(t===null){return}if(t===undefined){const t=new Vr;t.enable();Zt.setGlobalContextManager(t);return}t.enable();Zt.setGlobalContextManager(t)}function Hr(t){if(t===null){return}if(t===undefined){he.setGlobalPropagator(new hi({propagators:[new Di,new Me]}));return}he.setGlobalPropagator(t)}class Jr extends Gr{constructor(t={}){super(t)}register(t={}){pe.setGlobalTracerProvider(this);Hr(t.propagator);qr(t.contextManager)}}function Kr(t,e){if(t.nodeType===Node.DOCUMENT_NODE){return"/"}const i=Wr(t,e);if(e&&i.indexOf("@id")>0){return i}let r="";if(t.parentNode){r+=Kr(t.parentNode,false)}r+=i;return r}function Zr(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 Wr(t,e){const i=t.nodeType;const r=Zr(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 Xr{_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 Yr extends Error{code;name="OTLPExporterError";data;constructor(t,e,i){super(t);this.data=i;this.code=e}}function Qr(t){if(Number.isFinite(t)&&t>0){return t}throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${t}')`)}function tn(t){if(t==null){return undefined}return async()=>t}function en(t,e,i){return{timeoutMillis:Qr(t.timeoutMillis??e.timeoutMillis??i.timeoutMillis),concurrencyLimit:t.concurrencyLimit??e.concurrencyLimit??i.concurrencyLimit,compression:t.compression??e.compression??i.compression}}function rn(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class nn{_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 sn(t){return new nn(t.concurrencyLimit)}function on(t){return Object.prototype.hasOwnProperty.call(t,"partialSuccess")}function an(){return{handleResponse(t){if(t==null||!on(t)||t.partialSuccess==null||Object.keys(t.partialSuccess).length===0){return}Wt.warn("Received Partial Success response:",JSON.stringify(t.partialSuccess))}}}class cn{_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=Wt.createComponentLogger({namespace:"OTLPExportDelegate"})}export(t,e){this._diagLogger.debug("items to be sent",t);if(this._promiseQueue.hasReachedLimit()){e({code:li.FAILED,error:new Error("Concurrent export limit reached")});return}const i=this._serializer.serializeRequest(t);if(i==null){e({code:li.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:li.SUCCESS});return}else if(t.status==="failure"&&t.error){e({code:li.FAILED,error:t.error});return}else if(t.status==="retryable"){e({code:li.FAILED,error:new Yr("Export failed with retryable status")})}else{e({code:li.FAILED,error:new Yr("Export failed with unknown error")})}}),(t=>e({code:li.FAILED,error:t}))))}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started");await this.forceFlush();this._transport.shutdown()}}function un(t,e){return new cn(t.transport,t.serializer,an(),t.promiseHandler,e.timeout)}function ln(t,e,i){return un({transport:i,serializer:e,promiseHandler:sn(t)},{timeout:t.timeoutMillis})}function hn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t["default"]:t}function fn(t){if(t>=48&&t<=57){return t-48}if(t>=97&&t<=102){return t-87}return t-55}function dn(t){const e=new Uint8Array(t.length/2);let i=0;for(let r=0;r<t.length;r+=2){const n=fn(t.charCodeAt(r));const s=fn(t.charCodeAt(r+1));e[i++]=n<<4|s}return e}function pn(t){const e=BigInt(1e9);return BigInt(Math.trunc(t[0]))*e+BigInt(Math.trunc(t[1]))}function mn(t){const e=Number(BigInt.asUintN(32,t));const i=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:i}}function bn(t){const e=pn(t);return mn(e)}function vn(t){const e=pn(t);return e.toString()}const wn=typeof BigInt!=="undefined"?vn:oi;function gn(t){return t}function yn(t){if(t===undefined)return undefined;return dn(t)}const xn={encodeHrTime:bn,encodeSpanContext:dn,encodeOptionalSpanContext:yn};function kn(t){if(t===undefined){return xn}const e=t.useLongBits??true;const i=t.useHex??false;return{encodeHrTime:e?bn:wn,encodeSpanContext:i?gn:dn,encodeOptionalSpanContext:i?gn:yn}}function Sn(t){const e={attributes:An(t.attributes),droppedAttributesCount:0};const i=t.schemaUrl;if(i&&i!=="")e.schemaUrl=i;return e}function En(t){return{name:t.name,version:t.version}}function An(t){return Object.keys(t).map((e=>Tn(e,t[e])))}function Tn(t,e){return{key:t,value:_n(e)}}function _n(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(_n)}};if(e==="object"&&t!=null)return{kvlistValue:{values:Object.entries(t).map((([t,e])=>Tn(t,e)))}};return{}}var Mn;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(Mn||(Mn={}));var Cn;(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"})(Cn||(Cn={}));var On;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(On||(On={}));var In;(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"})(In||(In={}));function Pn(t,e){const i=kn(e);const r=Sn(t.resource);return{resource:r,schemaUrl:r.schemaUrl,scopeMetrics:Ln(t.scopeMetrics,i)}}function Ln(t,e){return Array.from(t.map((t=>({scope:En(t.scope),metrics:t.metrics.map((t=>Dn(t,e))),schemaUrl:t.scope.schemaUrl}))))}function Dn(t,e){const i={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit};const r=zn(t.aggregationTemporality);switch(t.dataPointType){case On.SUM:i.sum={aggregationTemporality:r,isMonotonic:t.isMonotonic,dataPoints:Nn(t,e)};break;case On.GAUGE:i.gauge={dataPoints:Nn(t,e)};break;case On.HISTOGRAM:i.histogram={aggregationTemporality:r,dataPoints:jn(t,e)};break;case On.EXPONENTIAL_HISTOGRAM:i.exponentialHistogram={aggregationTemporality:r,dataPoints:Un(t,e)};break}return i}function Rn(t,e,i){const r={attributes:An(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 Nn(t,e){return t.dataPoints.map((i=>Rn(i,t.descriptor.valueType,e)))}function jn(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:An(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 Un(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:An(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 zn(t){switch(t){case Mn.DELTA:return In.AGGREGATION_TEMPORALITY_DELTA;case Mn.CUMULATIVE:return In.AGGREGATION_TEMPORALITY_CUMULATIVE}}function $n(t,e){return{resourceMetrics:t.map((t=>Pn(t,e)))}}const Bn=256;const Fn=512;function Gn(t,e){let i=t&255|Bn;if(e){i|=Fn}return i}function Vn(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:An(t.attributes),droppedAttributesCount:t.droppedAttributesCount,events:t.events.map((t=>Hn(t,e))),droppedEventsCount:t.droppedEventsCount,status:{code:r.code,message:r.message},links:t.links.map((t=>qn(t,e))),droppedLinksCount:t.droppedLinksCount,flags:Gn(i.traceFlags,t.parentSpanContext?.isRemote)}}function qn(t,e){return{attributes:t.attributes?An(t.attributes):[],spanId:e.encodeSpanContext(t.context.spanId),traceId:e.encodeSpanContext(t.context.traceId),traceState:t.context.traceState?.serialize(),droppedAttributesCount:t.droppedAttributesCount||0,flags:Gn(t.context.traceFlags,t.context.isRemote)}}function Hn(t,e){return{attributes:t.attributes?An(t.attributes):[],name:t.name,timeUnixNano:e.encodeHrTime(t.time),droppedAttributesCount:t.droppedAttributesCount||0}}function Jn(t,e){const i=kn(e);return{resourceSpans:Zn(t,i)}}function Kn(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 Zn(t,e){const i=Kn(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=>Vn(t,e)));o.push({scope:En(t[0].instrumentationScope),spans:i,schemaUrl:t[0].instrumentationScope.schemaUrl})}c=a.next()}const u=Sn(t);const l={resource:u,scopeSpans:o,schemaUrl:u.schemaUrl};r.push(l);s=n.next()}return r}const Wn={serializeRequest:t=>{const e=$n([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 Xn={serializeRequest:t=>{const e=Jn(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 Yn=5;const Qn=1e3;const ts=5e3;const es=1.5;const is=.2;function rs(){return Math.random()*(2*is)-is}class ns{_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=Yn;let s=Qn;while(r.status==="retryable"&&n>0){n--;const e=Math.max(Math.min(s,ts)+rs(),0);s=s*es;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 ss(t){return new ns(t.transport)}function os(t){const e=[429,502,503,504];return e.includes(t)}function as(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 cs{_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){Wt.debug("XHR success");r({status:"success"})}else if(n.status&&os(n.status)){r({status:"retryable",retryInMillis:as(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 us(t){return new cs(t)}class ls{_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}))){Wt.debug("SendBeacon success");i({status:"success"})}else{i({status:"failure",error:new Error("SendBeacon failed")})}}))}shutdown(){}}function hs(t){return new ls(t)}class fs{_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){Wt.debug("response success");return{status:"success"}}else if(os(n.status)){const t=n.headers.get("Retry-After");const e=as(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 ds(t){return new fs(t)}function ps(t,e){return ln(t,e,ss({transport:us(t)}))}function ms(t,e){return ln(t,e,ss({transport:ds(t)}))}function bs(t,e){return ln(t,e,ss({transport:hs({url:t.url,headers:t.headers})}))}function vs(t){const e={};Object.entries(t??{}).forEach((([t,i])=>{if(typeof i!=="undefined"){e[t]=String(i)}else{Wt.warn(`Header "${t}" has invalid value (${i}) and will be ignored`)}}));return e}function ws(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,vs(await t()))}return Object.assign(n,r)}}function gs(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 ys(t,e,i){return{...en(t,e,i),headers:ws(t.headers,e.headers,i.headers),url:gs(t.url)??e.url??i.url}}function xs(t,e){return{...rn(),headers:async()=>t,url:"http://localhost:4318/"+e}}function ks(t){if(typeof t.headers==="function"){return t.headers}return tn(t.headers)}function Ss(t,e,i){return ys({url:t.url,timeoutMillis:t.timeoutMillis,headers:ks(t),concurrencyLimit:t.concurrencyLimit},{},xs(i,e))}function Es(t,e,i,r){const n=As(t.headers);const s=Ss(t,i,r);return n(s,e)}function As(t){if(!t&&typeof navigator.sendBeacon==="function"){return bs}else if(typeof globalThis.fetch!=="undefined"){return ms}else{return ps}}class Ts extends Xr{constructor(t={}){super(Es(t,Xn,"v1/traces",{"Content-Type":"application/json"}))}}function _s(t){return typeof t==="object"&&t!==null&&"addEventListener"in t&&typeof t.addEventListener==="function"&&"removeEventListener"in t&&typeof t.removeEventListener==="function"}const Ms="OT_ZONE_CONTEXT";class Cs{_enabled=false;_zoneCounter=0;_activeContextFromZone(t){return t&&t.get(Ms)||F}_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:{[Ms]: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 F}const t=this._getActiveZone();const e=this._activeContextFromZone(t);if(e){return e}return F}bind(t,e){if(t===undefined){t=this.active()}if(typeof e==="function"){return this._bindFunction(t,e)}else if(_s(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 Os={};var Is;function Ps(){if(Is)return Os;Is=1;var t=Os&&Os.__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)};
|
|
1
|
+
import{r as t,c as e,g as i,h as r,a as n}from"./p-CqdAwiLj.js";class s{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 o{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 a{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(a.deviceEnumerationCache&&t-a.deviceEnumerationCache.timestamp<a.CACHE_DURATION){this.availableCameras=a.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[]}a.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(a.cameraCapabilitiesCache.has(t)){const e=a.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"));a.cameraCapabilitiesCache.set(t,s);return s}catch(e){a.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&&a.cameraCapabilitiesCache.has(this.selectedCameraId+"_caps")){e=JSON.parse(a.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){a.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(){a.cameraCapabilitiesCache.clear();a.deviceEnumerationCache=null}invalidateDeviceCache(){a.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 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: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 u{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 l{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 h{static createStrategy(){const t=navigator;const e=navigator.userAgent;const i=/iPad|iPhone|iPod/.test(e);if(i){return new l}const r=t.deviceMemory||t.hardwareConcurrency||4;const n=r<=4;if(n){return new c}else{return new u}}}class f{debug;useDocumentClassification;useDocumentDetector;session;mobileNetSession;mobileNetClassMap;modelLoaded=false;deviceStrategy;MODEL_PATH="https://static.jaak.ai/web/component/stamps/ddmyp-v2.onnx";MODEL_PATH_FP32="https://static.jaak.ai/web/component/stamps/ddmyp-v2-fp32.onnx";MOBILENET_MODEL_PATH="https://static.jaak.ai/web/component/stamps/squeezenet_new_fp32.onnx";MOBILENET_CLASSES_PATH="https://static.jaak.ai/web/component/stamps/cdmmp-v1.json";INPUT_SIZE=320;CONFIDENCE_THRESHOLD=.6;useFloat16=true;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=h.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);this.detectFloat16Support()}catch(e){const i=e.message||"";const r=i.includes("failed to allocate a buffer")||i.includes("Out of memory")||i.includes("RangeError: Out of memory")||i.includes("no available backend found");const n=i.includes("unsupported data type")||i.includes("FLOAT16")||i.includes("float16");if(n){this.useFloat16=false;try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH_FP32,t)}catch(t){const e={executionProviders:["wasm"],graphOptimizationLevel:"all",logSeverityLevel:this.debug?2:4};this.session=await window.ort.InferenceSession.create(this.MODEL_PATH_FP32,e)}}else if(r){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1,enableProfiling:false,sessionLogSeverityLevel:4,sessionLogVerbosityLevel:0};this.useFloat16=false;try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH_FP32,t)}catch(t){throw new Error(`no available backend found. ERR: [wasm] RangeError: Out of memory`)}}else{throw e}}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));if(this.useFloat16){const t=new Uint16Array(o.length);for(let e=0;e<o.length;e++){t[e]=this.float32ToFloat16(o[e])}return new window.ort.Tensor("float16",t,[1,3,this.INPUT_SIZE,this.INPUT_SIZE])}return new window.ort.Tensor("float32",o,[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 h=1;let f,d;if(l>h){f=i;d=i/l}else{d=i;f=i*l}const p=d*r;let m,b;const v=o/100;if(p<=f){b=d*v;m=b*r}else{m=f*v;b=m/r}const w=m*(i/f);const g=b*(i/d);const y=i/2;const x=i/2;const k=y-w/2;const S=y+w/2;const E=x-g/2;const T=x+g/2;let _=t.x;let A=t.x+t.w;const M=t.y;const C=t.y+t.h;if(n){const t=_;const e=A;_=i-e;A=i-t}const O=s;const I=Math.abs(M-E)<=O;const P=Math.abs(A-S)<=O;const L=Math.abs(C-T)<=O;const D=Math.abs(_-k)<=O;return{top:I&&D,right:I&&P,bottom:L&&D,left:L&&P}}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}}detectFloat16Support(){try{const t=new Uint16Array([0]);new window.ort.Tensor("float16",t,[1]);this.useFloat16=true}catch{this.useFloat16=false}}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 d=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};var p="1.9.0";var m=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function b(t){var e=new Set([t]);var i=new Set;var r=t.match(m);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(m);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 v=b(p);var w=p.split(".")[0];var g=Symbol.for("opentelemetry.js.api."+w);var y=d;function x(t,e,i,r){var n;if(r===void 0){r=false}var s=y[g]=(n=y[g])!==null&&n!==void 0?n:{version:p};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!==p){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+p);i.error(o.stack||o.message);return false}s[t]=e;i.debug("@opentelemetry/api: Registered a global for "+t+" v"+p+".");return true}function k(t){var e,i;var r=(e=y[g])===null||e===void 0?void 0:e.version;if(!r||!v(r)){return}return(i=y[g])===null||i===void 0?void 0:i[t]}function S(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+p+".");var i=y[g];if(i){delete i[t]}}var E=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 T=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 _=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 A("debug",this._namespace,t)};t.prototype.error=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return A("error",this._namespace,t)};t.prototype.info=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return A("info",this._namespace,t)};t.prototype.warn=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return A("warn",this._namespace,t)};t.prototype.verbose=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return A("verbose",this._namespace,t)};return t}();function A(t,e,i){var r=k("diag");if(!r){return}i.unshift(e);return r[t].apply(r,T([],E(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 O=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 I=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 P="diag";var L=function(){function t(){function t(t){return function(){var e=[];for(var i=0;i<arguments.length;i++){e[i]=arguments[i]}var r=k("diag");if(!r)return;return r[t].apply(r,I([],O(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=k("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 x("diag",c,e,true)};e.setLogger=i;e.disable=function(){S(P,e)};e.createComponentLogger=function(t){return new _(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 D=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 R=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=D(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=R(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 j=Symbol("BaggageEntryMetadata");var z=L.instance();function $(t){if(t===void 0){t={}}return new N(new Map(Object.entries(t)))}function U(t){if(typeof t!=="string"){z.error("Cannot create baggage metadata from unknown type: "+typeof t);t=""}return{__TYPE__:j,toString:function(){return t}}}function B(t){return Symbol.for(t)}var F=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 G=new F;var V=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 q=function(){function t(){}t.prototype.createGauge=function(t,e){return rt};t.prototype.createHistogram=function(t,e){return nt};t.prototype.createCounter=function(t,e){return it};t.prototype.createUpDownCounter=function(t,e){return st};t.prototype.createObservableGauge=function(t,e){return at};t.prototype.createObservableCounter=function(t,e){return ot};t.prototype.createObservableUpDownCounter=function(t,e){return ct};t.prototype.addBatchObservableCallback=function(t,e){};t.prototype.removeBatchObservableCallback=function(t){};return t}();var H=function(){function t(){}return t}();var J=function(t){V(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.add=function(t,e){};return e}(H);var K=function(t){V(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){V(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.record=function(t,e){};return e}(H);var W=function(t){V(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.record=function(t,e){};return e}(H);var X=function(){function t(){}t.prototype.addCallback=function(t){};t.prototype.removeCallback=function(t){};return t}();var Y=function(t){V(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var Q=function(t){V(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var tt=function(t){V(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var et=new q;var it=new J;var rt=new Z;var nt=new W;var st=new K;var ot=new Y;var at=new Q;var ct=new tt;function ut(){return et}var lt;(function(t){t[t["INT"]=0]="INT";t[t["DOUBLE"]=1]="DOUBLE"})(lt||(lt={}));var ht={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 dt=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 pt=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 mt=function(){function t(){}t.prototype.active=function(){return G};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,pt([i],dt(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 bt=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 vt=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 wt="context";var gt=new mt;var yt=function(){function t(){}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalContextManager=function(t){return x(wt,t,L.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,vt([t,e,i],bt(n),false))};t.prototype.bind=function(t,e){return this._getContextManager().bind(t,e)};t.prototype._getContextManager=function(){return k(wt)||gt};t.prototype.disable=function(){this._getContextManager().disable();S(wt,L.instance())};return t}();var xt;(function(t){t[t["NONE"]=0]="NONE";t[t["SAMPLED"]=1]="SAMPLED"})(xt||(xt={}));var kt="0000000000000000";var St="00000000000000000000000000000000";var Et={traceId:St,spanId:kt,traceFlags:xt.NONE};var Tt=function(){function t(t){if(t===void 0){t=Et}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 _t=B("OpenTelemetry Context Key SPAN");function At(t){return t.getValue(_t)||undefined}function Mt(){return At(yt.getInstance().active())}function Ct(t,e){return t.setValue(_t,e)}function Ot(t){return t.deleteValue(_t)}function It(t,e){return Ct(t,new Tt(e))}function Pt(t){var e;return(e=At(t))===null||e===void 0?void 0:e.spanContext()}var Lt=/^([0-9a-f]{32})$/i;var Dt=/^[0-9a-f]{16}$/i;function Rt(t){return Lt.test(t)&&t!==St}function Nt(t){return Dt.test(t)&&t!==kt}function jt(t){return Rt(t.traceId)&&Nt(t.spanId)}function zt(t){return new Tt(t)}var $t=yt.getInstance();var Ut=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 Tt}var n=i&&Pt(i);if(Bt(n)&&jt(n)){return new Tt(n)}else{return new Tt}};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 Bt(t){return typeof t==="object"&&typeof t["spanId"]==="string"&&typeof t["traceId"]==="string"&&typeof t["traceFlags"]==="number"}var Ft=new Ut;var Gt=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 Ft}this._delegate=t;return this._delegate};return t}();var Vt=function(){function t(){}t.prototype.getTracer=function(t,e,i){return new Ut};return t}();var qt=new Vt;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 Gt(this,t,e,i)};t.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:qt};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 Jt;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(Jt||(Jt={}));var Kt;(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"})(Kt||(Kt={}));var Zt;(function(t){t[t["UNSET"]=0]="UNSET";t[t["OK"]=1]="OK";t[t["ERROR"]=2]="ERROR"})(Zt||(Zt={}));var Wt=yt.getInstance();var Xt=L.instance();var Yt=function(){function t(){}t.prototype.getMeter=function(t,e,i){return et};return t}();var Qt=new Yt;var te="metrics";var ee=function(){function t(){}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalMeterProvider=function(t){return x(te,t,L.instance())};t.prototype.getMeterProvider=function(){return k(te)||Qt};t.prototype.getMeter=function(t,e,i){return this.getMeterProvider().getMeter(t,e,i)};t.prototype.disable=function(){S(te,L.instance())};return t}();var ie=ee.getInstance();var re=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 ne=B("OpenTelemetry Baggage Key");function se(t){return t.getValue(ne)||undefined}function oe(){return se(yt.getInstance().active())}function ae(t,e){return t.setValue(ne,e)}function ce(t){return t.deleteValue(ne)}var ue="propagation";var le=new re;var he=function(){function t(){this.createBaggage=$;this.getBaggage=se;this.getActiveBaggage=oe;this.setBaggage=ae;this.deleteBaggage=ce}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalPropagator=function(t){return x(ue,t,L.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=ht}return this._getGlobalPropagator().extract(t,e,i)};t.prototype.fields=function(){return this._getGlobalPropagator().fields()};t.prototype.disable=function(){S(ue,L.instance())};t.prototype._getGlobalPropagator=function(){return k(ue)||le};return t}();var fe=he.getInstance();var de="trace";var pe=function(){function t(){this._proxyTracerProvider=new Ht;this.wrapSpanContext=zt;this.isSpanContextValid=jt;this.deleteSpan=Ot;this.getSpan=At;this.getActiveSpan=Mt;this.getSpanContext=Pt;this.setSpan=Ct;this.setSpanContext=It}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalTracerProvider=function(t){var e=x(de,this._proxyTracerProvider,L.instance());if(e){this._proxyTracerProvider.setDelegate(t)}return e};t.prototype.getTracerProvider=function(){return k(de)||this._proxyTracerProvider};t.prototype.getTracer=function(t,e){return this.getTracerProvider().getTracer(t,e)};t.prototype.disable=function(){S(de,L.instance());this._proxyTracerProvider=new Ht};return t}();var me=pe.getInstance();const be=B("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function ve(t){return t.setValue(be,true)}function we(t){return t.getValue(be)===true}const ge="=";const ye=";";const xe=",";const ke="baggage";const Se=180;const Ee=4096;const Te=8192;function _e(t){return t.reduce(((t,e)=>{const i=`${t}${t!==""?xe:""}${e}`;return i.length>Te?t:i}),"")}function Ae(t){return t.getAllEntries().map((([t,e])=>{let i=`${encodeURIComponent(t)}=${encodeURIComponent(e.value)}`;if(e.metadata!==undefined){i+=ye+e.metadata.toString()}return i}))}function Me(t){const e=t.split(ye);if(e.length<=0)return;const i=e.shift();if(!i)return;const r=i.indexOf(ge);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=U(e.join(ye))}return{key:n,value:s,metadata:o}}class Ce{inject(t,e,i){const r=fe.getBaggage(t);if(!r||we(t))return;const n=Ae(r).filter((t=>t.length<=Ee)).slice(0,Se);const s=_e(n);if(s.length>0){i.set(e,ke,s)}}extract(t,e,i){const r=i.get(e,ke);const n=Array.isArray(r)?r.join(xe):r;if(!n)return t;const s={};if(n.length===0){return t}const o=n.split(xe);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[ke]}}function Oe(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(!Ie(i)){Xt.warn(`Invalid attribute key: ${i}`);continue}const r=t[i];if(!Pe(r)){Xt.warn(`Invalid attribute value set for key: ${i}`);continue}if(Array.isArray(r)){e[i]=r.slice()}else{e[i]=r}}return e}function Ie(t){return typeof t==="string"&&t!==""}function Pe(t){if(t==null){return true}if(Array.isArray(t)){return Le(t)}return De(typeof t)}function Le(t){let e;for(const i of t){if(i==null)continue;const t=typeof i;if(t===e){continue}if(!e){if(De(t)){e=t;continue}return false}return false}return true}function De(t){switch(t){case"number":case"boolean":case"string":return true}return false}function Re(){return t=>{Xt.error(Ne(t))}}function Ne(t){if(typeof t==="string"){return t}else{return JSON.stringify(je(t))}}function je(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=Re();function $e(t){try{ze(t)}catch{}}function Ue(t){return undefined}const Be=performance;const Fe="2.2.0";const Ge="exception.message";const Ve="exception.stacktrace";const qe="exception.type";const He="service.name";const Je="telemetry.sdk.language";const Ke="webjs";const Ze="telemetry.sdk.name";const We="telemetry.sdk.version";const Xe="process.runtime.name";const Ye={[Ze]:"opentelemetry",[Xe]:"browser",[Je]:Ke,[We]:Fe};const Qe=9;const ti=6;const ei=Math.pow(10,ti);const ii=Math.pow(10,Qe);function ri(t){const e=t/1e3;const i=Math.trunc(e);const r=Math.round(t%1e3*ei);return[i,r]}function ni(){let t=Be.timeOrigin;if(typeof t!=="number"){const e=Be;t=e.timing&&e.timing.fetchStart}return t}function si(t){const e=ri(ni());const i=ri(typeof t==="number"?t:Be.now());return li(e,i)}function oi(t,e){let i=e[0]-t[0];let r=e[1]-t[1];if(r<0){i-=1;r+=ii}return[i,r]}function ai(t){return t[0]*ii+t[1]}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]>=ii){i[1]-=ii;i[0]+=1}return i}var hi;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(hi||(hi={}));class fi{_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){Xt.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){Xt.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 Ei="=";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+Ei+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(Ei);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 _i="traceparent";const Ai="tracestate";const Mi="00";const Ci="(?!ff)[\\da-f]{2}";const Oi="(?![0]{32})[\\da-f]{32}";const Ii="(?![0]{16})[\\da-f]{16}";const Pi="[\\da-f]{2}";const Li=new RegExp(`^\\s?(${Ci})-(${Oi})-(${Ii})-(${Pi})(-.*)?\\s?$`);function Di(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 Ri{inject(t,e,i){const r=me.getSpanContext(t);if(!r||we(t)||!jt(r))return;const n=`${Mi}-${r.traceId}-${r.spanId}-0${Number(r.traceFlags||xt.NONE).toString(16)}`;i.set(e,_i,n);if(r.traceState){i.set(e,Ai,r.traceState.serialize())}}extract(t,e,i){const r=i.get(e,_i);if(!r)return t;const n=Array.isArray(r)?r[0]:r;if(typeof n!=="string")return t;const s=Di(n);if(!s)return t;s.isRemote=true;const o=i.get(e,Ai);if(o){const t=Array.isArray(o)?o.join(","):o;s.traceState=new Ti(typeof t==="string"?t:undefined)}return me.setSpanContext(t,s)}fields(){return[_i,Ai]}}const Ni="[object Object]";const ji="[object Null]";const zi="[object Undefined]";const $i=Function.prototype;const Ui=$i.toString;const Bi=Ui.call(Object);const Fi=Object.getPrototypeOf;const Gi=Object.prototype;const Vi=Gi.hasOwnProperty;const qi=Symbol?Symbol.toStringTag:undefined;const Hi=Gi.toString;function Ji(t){if(!Ki(t)||Zi(t)!==Ni){return false}const e=Fi(t);if(e===null){return true}const i=Vi.call(e,"constructor")&&e.constructor;return typeof i=="function"&&i instanceof i&&Ui.call(i)===Bi}function Ki(t){return t!=null&&typeof t=="object"}function Zi(t){if(t==null){return t===undefined?zi:ji}return qi&&qi in Object(t)?Wi(t):Xi(t)}function Wi(t){const e=Vi.call(t,qi),i=t[qi];let r=false;try{t[qi]=undefined;r=true}catch{}const n=Hi.call(t);if(r){if(e){t[qi]=i}else{delete t[qi]}}return n}function Xi(t){return Hi.call(t)}const Yi=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>Yi){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(!Ji(t)||!Ji(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(){return"unknown_service"}const hr=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";let fr=class t{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(e,i){const r=new t({},i);r._rawAttributes=mr(e);r._asyncAttributesPending=e.filter((([t,e])=>hr(e))).length>0;return r}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(hr(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=mr(this._rawAttributes);this._schemaUrl=br(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,hr(i)?await i:i]}this._asyncAttributesPending=false}get attributes(){if(this.asyncAttributesPending){Xt.error("Accessing resource attributes before async attributes settled")}if(this._memoizedAttributes){return this._memoizedAttributes}const t={};for(const[e,i]of this._rawAttributes){if(hr(i)){Xt.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(e){if(e==null)return this;const i=vr(this,e);const r=i?{schemaUrl:i}:undefined;return t.FromAttributeList([...e.getRawAttributes(),...this.getRawAttributes()],r)}};function dr(t,e){return fr.FromAttributeList(Object.entries(t),e)}function pr(){return dr({[He]:lr(),[Je]:Ye[Je],[Ze]:Ye[Ze],[We]:Ye[We]})}function mr(t){return t.map((([t,e])=>{if(hr(e)){return[t,e.catch((e=>{Xt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function br(t){if(typeof t==="string"||t===undefined){return t}Xt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t);return undefined}function vr(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}Xt.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 wr="exception";class gr{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:Zt.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=Be.now();this._performanceOffset=e-(this._performanceStartTime+ni());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){Xt.warn(`Invalid attribute key: ${t}`);return this}if(!Pe(e)){Xt.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){Xt.warn("No events allowed.");this._droppedEventsCount++;return this}if(r!==undefined&&this.events.length>=r){if(this._droppedEventsCount===0){Xt.debug("Dropping extra events.")}this.events.shift();this._droppedEventsCount++}if(ui(e)){if(!ui(i)){i=e}e=undefined}const n=Oe(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"){Xt.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()){Xt.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=oi(this.startTime,this.endTime);if(this._duration[0]<0){Xt.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){Xt.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`)}this._spanProcessor.onEnd(this)}_getTime(t){if(typeof t==="number"&&t<=Be.now()){return si(t+this._performanceOffset)}if(typeof t==="number"){return ri(t)}if(t instanceof Date){return ri(t.getTime())}if(ci(t)){return t}if(this._startTimeProvided){return ri(Date.now())}const e=Be.now()-this._performanceStartTime;return li(this.startTime,ri(e))}isRecording(){return this._ended===false}recordException(t,e){const i={};if(typeof t==="string"){i[Ge]=t}else if(t){if(t.code){i[qe]=t.code.toString()}else if(t.name){i[qe]=t.name}if(t.message){i[Ge]=t.message}if(t.stack){i[Ve]=t.stack}}if(i[qe]||i[Ge]){this.addEvent(wr,i,e)}else{Xt.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}}`);Xt.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){Xt.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 yr;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(yr||(yr={}));class xr{shouldSample(){return{decision:yr.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class kr{shouldSample(){return{decision:yr.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class Sr{_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 kr}this._remoteParentSampled=t.remoteParentSampled??new kr;this._remoteParentNotSampled=t.remoteParentNotSampled??new xr;this._localParentSampled=t.localParentSampled??new kr;this._localParentNotSampled=t.localParentNotSampled??new xr}shouldSample(t,e,i,r,n,s){const o=me.getSpanContext(t);if(!o||!jt(o)){return this._root.shouldSample(t,e,i,r,n,s)}if(o.isRemote){if(o.traceFlags&xt.SAMPLED){return this._remoteParentSampled.shouldSample(t,e,i,r,n,s)}return this._remoteParentNotSampled.shouldSample(t,e,i,r,n,s)}if(o.traceFlags&xt.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:Rt(e)&&this._accumulate(e)<this._upperBound?yr.RECORD_AND_SAMPLED:yr.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 Tr;(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"})(Tr||(Tr={}));const _r=1;function Ar(){return{sampler:Mr(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function Mr(){const t=Tr.ParentBasedAlwaysOn;switch(t){case Tr.AlwaysOn:return new kr;case Tr.AlwaysOff:return new xr;case Tr.ParentBasedAlwaysOn:return new Sr({root:new kr});case Tr.ParentBasedAlwaysOff:return new Sr({root:new xr});case Tr.TraceIdRatio:return new Er(Cr());case Tr.ParentBasedTraceIdRatio:return new Sr({root:new Er(Cr())});default:Xt.error(`OTEL_TRACES_SAMPLER value "${t}" invalid, defaulting to "${Tr.ParentBasedAlwaysOn}".`);return new Sr({root:new kr})}}function Cr(){{Xt.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${_r}.`);return _r}}const Or=128;const Ir=Infinity;function Pr(t){const e={sampler:Mr()};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 Lr(t){const e=Object.assign({},t.spanLimits);e.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??Ue()??Ue()??Or;e.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??Ue()??Ue()??Ir;return Object.assign({},t,{spanLimits:e})}class Dr{_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){Xt.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&xt.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){Xt.debug("maxQueueSize reached, dropping spans")}this._droppedSpansCount++;return}if(this._droppedSpansCount>0){Xt.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);Wt.with(ve(Wt.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===hi.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 Rr extends Dr{_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 Nr=8;const jr=16;class zr{generateTraceId=Ur(jr);generateSpanId=Ur(Nr)}const $r=Array(32);function Ur(t){return function e(){for(let e=0;e<t*2;e++){$r[e]=Math.floor(Math.random()*16)+48;if($r[e]>=58){$r[e]+=39}}return String.fromCharCode.apply(null,$r.slice(0,t*2))}}class Br{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(t,e,i,r){const n=Pr(e);this._sampler=n.sampler;this._generalLimits=n.generalLimits;this._spanLimits=n.spanLimits;this._idGenerator=e.idGenerator||new zr;this._resource=i;this._spanProcessor=r;this.instrumentationScope=t}startSpan(t,e={},i=Wt.active()){if(e.root){i=me.deleteSpan(i)}const r=me.getSpan(i);if(we(i)){Xt.debug("Instrumentation suppressed, returning Noop Span");const t=me.wrapSpanContext(Et);return t}const n=r?.spanContext();const s=this._idGenerator.generateSpanId();let o;let a;let c;if(!n||!me.isSpanContextValid(n)){a=this._idGenerator.generateTraceId()}else{a=n.traceId;c=n.traceState;o=n}const u=e.kind??Kt.INTERNAL;const l=(e.links??[]).map((t=>({context:t.context,attributes:Oe(t.attributes)})));const h=Oe(e.attributes);const f=this._sampler.shouldSample(i,a,t,u,h,l);c=f.traceState??c;const d=f.decision===Jt.RECORD_AND_SAMPLED?xt.SAMPLED:xt.NONE;const p={traceId:a,spanId:s,traceFlags:d,traceState:c};if(f.decision===Jt.NOT_RECORD){Xt.debug("Recording is off, propagating context in a non-recording span");const t=me.wrapSpanContext(p);return t}const m=Oe(Object.assign(h,f.attributes));const b=new gr({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??Wt.active();const c=this.startSpan(t,n,a);const u=me.setSpan(a,c);return Wt.with(u,o,undefined,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class Fr{_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 Gr;(function(t){t[t["resolved"]=0]="resolved";t[t["timeout"]=1]="timeout";t[t["error"]=2]="error";t[t["unresolved"]=3]="unresolved"})(Gr||(Gr={}));class Vr{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(t={}){const e=Qi({},Ar(),Lr(t));this._resource=e.resource??pr();this._config=Object.assign({},e,{resource:this._resource});const i=[];if(t.spanProcessors?.length){i.push(...t.spanProcessors)}this._activeSpanProcessor=new Fr(i)}getTracer(t,e,i){const r=`${t}@${e||""}:${i?.schemaUrl||""}`;if(!this._tracers.has(r)){this._tracers.set(r,new Br({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=Gr.timeout}),t);e.forceFlush().then((()=>{clearTimeout(n);if(r!==Gr.timeout){r=Gr.resolved;i(r)}})).catch((t=>{clearTimeout(n);r=Gr.error;i(t)}))}))));return new Promise(((t,i)=>{Promise.all(e).then((e=>{const r=e.filter((t=>t!==Gr.resolved));if(r.length>0){i(r)}else{t()}})).catch((t=>i([t])))}))}shutdown(){return this._activeSpanProcessor.shutdown()}}class qr{_enabled=false;_currentContext=G;_bindFunction(t=G,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=G;this._enabled=false;return this}enable(){if(this._enabled){return this}this._enabled=true;this._currentContext=G;return this}with(t,e,i,...r){const n=this._currentContext;this._currentContext=t||G;try{return e.call(i,...r)}finally{this._currentContext=n}}}function Hr(t){if(t===null){return}if(t===undefined){const t=new qr;t.enable();Wt.setGlobalContextManager(t);return}t.enable();Wt.setGlobalContextManager(t)}function Jr(t){if(t===null){return}if(t===undefined){fe.setGlobalPropagator(new fi({propagators:[new Ri,new Ce]}));return}fe.setGlobalPropagator(t)}class Kr extends Vr{constructor(t={}){super(t)}register(t={}){me.setGlobalTracerProvider(this);Jr(t.propagator);Hr(t.contextManager)}}function Zr(t,e){if(t.nodeType===Node.DOCUMENT_NODE){return"/"}const i=Xr(t,e);if(e&&i.indexOf("@id")>0){return i}let r="";if(t.parentNode){r+=Zr(t.parentNode,false)}r+=i;return r}function Wr(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 Xr(t,e){const i=t.nodeType;const r=Wr(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 Yr{_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 Qr extends Error{code;name="OTLPExporterError";data;constructor(t,e,i){super(t);this.data=i;this.code=e}}function tn(t){if(Number.isFinite(t)&&t>0){return t}throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${t}')`)}function en(t){if(t==null){return undefined}return async()=>t}function rn(t,e,i){return{timeoutMillis:tn(t.timeoutMillis??e.timeoutMillis??i.timeoutMillis),concurrencyLimit:t.concurrencyLimit??e.concurrencyLimit??i.concurrencyLimit,compression:t.compression??e.compression??i.compression}}function nn(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class sn{_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 on(t){return new sn(t.concurrencyLimit)}function an(t){return Object.prototype.hasOwnProperty.call(t,"partialSuccess")}function cn(){return{handleResponse(t){if(t==null||!an(t)||t.partialSuccess==null||Object.keys(t.partialSuccess).length===0){return}Xt.warn("Received Partial Success response:",JSON.stringify(t.partialSuccess))}}}class un{_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=Xt.createComponentLogger({namespace:"OTLPExportDelegate"})}export(t,e){this._diagLogger.debug("items to be sent",t);if(this._promiseQueue.hasReachedLimit()){e({code:hi.FAILED,error:new Error("Concurrent export limit reached")});return}const i=this._serializer.serializeRequest(t);if(i==null){e({code:hi.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:hi.SUCCESS});return}else if(t.status==="failure"&&t.error){e({code:hi.FAILED,error:t.error});return}else if(t.status==="retryable"){e({code:hi.FAILED,error:new Qr("Export failed with retryable status")})}else{e({code:hi.FAILED,error:new Qr("Export failed with unknown error")})}}),(t=>e({code:hi.FAILED,error:t}))))}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started");await this.forceFlush();this._transport.shutdown()}}function ln(t,e){return new un(t.transport,t.serializer,cn(),t.promiseHandler,e.timeout)}function hn(t,e,i){return ln({transport:i,serializer:e,promiseHandler:on(t)},{timeout:t.timeoutMillis})}function fn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t["default"]:t}function dn(t){if(t>=48&&t<=57){return t-48}if(t>=97&&t<=102){return t-87}return t-55}function pn(t){const e=new Uint8Array(t.length/2);let i=0;for(let r=0;r<t.length;r+=2){const n=dn(t.charCodeAt(r));const s=dn(t.charCodeAt(r+1));e[i++]=n<<4|s}return e}function mn(t){const e=BigInt(1e9);return BigInt(Math.trunc(t[0]))*e+BigInt(Math.trunc(t[1]))}function bn(t){const e=Number(BigInt.asUintN(32,t));const i=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:i}}function vn(t){const e=mn(t);return bn(e)}function wn(t){const e=mn(t);return e.toString()}const gn=typeof BigInt!=="undefined"?wn:ai;function yn(t){return t}function xn(t){if(t===undefined)return undefined;return pn(t)}const kn={encodeHrTime:vn,encodeSpanContext:pn,encodeOptionalSpanContext:xn};function Sn(t){if(t===undefined){return kn}const e=t.useLongBits??true;const i=t.useHex??false;return{encodeHrTime:e?vn:gn,encodeSpanContext:i?yn:pn,encodeOptionalSpanContext:i?yn:xn}}function En(t){const e={attributes:_n(t.attributes),droppedAttributesCount:0};const i=t.schemaUrl;if(i&&i!=="")e.schemaUrl=i;return e}function Tn(t){return{name:t.name,version:t.version}}function _n(t){return Object.keys(t).map((e=>An(e,t[e])))}function An(t,e){return{key:t,value:Mn(e)}}function Mn(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(Mn)}};if(e==="object"&&t!=null)return{kvlistValue:{values:Object.entries(t).map((([t,e])=>An(t,e)))}};return{}}var Cn;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(Cn||(Cn={}));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 In;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(In||(In={}));var Pn;(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"})(Pn||(Pn={}));function Ln(t,e){const i=Sn(e);const r=En(t.resource);return{resource:r,schemaUrl:r.schemaUrl,scopeMetrics:Dn(t.scopeMetrics,i)}}function Dn(t,e){return Array.from(t.map((t=>({scope:Tn(t.scope),metrics:t.metrics.map((t=>Rn(t,e))),schemaUrl:t.scope.schemaUrl}))))}function Rn(t,e){const i={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit};const r=Un(t.aggregationTemporality);switch(t.dataPointType){case In.SUM:i.sum={aggregationTemporality:r,isMonotonic:t.isMonotonic,dataPoints:jn(t,e)};break;case In.GAUGE:i.gauge={dataPoints:jn(t,e)};break;case In.HISTOGRAM:i.histogram={aggregationTemporality:r,dataPoints:zn(t,e)};break;case In.EXPONENTIAL_HISTOGRAM:i.exponentialHistogram={aggregationTemporality:r,dataPoints:$n(t,e)};break}return i}function Nn(t,e,i){const r={attributes:_n(t.attributes),startTimeUnixNano:i.encodeHrTime(t.startTime),timeUnixNano:i.encodeHrTime(t.endTime)};switch(e){case lt.INT:r.asInt=t.value;break;case lt.DOUBLE:r.asDouble=t.value;break}return r}function jn(t,e){return t.dataPoints.map((i=>Nn(i,t.descriptor.valueType,e)))}function zn(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:_n(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 $n(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:_n(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 Un(t){switch(t){case Cn.DELTA:return Pn.AGGREGATION_TEMPORALITY_DELTA;case Cn.CUMULATIVE:return Pn.AGGREGATION_TEMPORALITY_CUMULATIVE}}function Bn(t,e){return{resourceMetrics:t.map((t=>Ln(t,e)))}}const Fn=256;const Gn=512;function Vn(t,e){let i=t&255|Fn;if(e){i|=Gn}return i}function qn(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:_n(t.attributes),droppedAttributesCount:t.droppedAttributesCount,events:t.events.map((t=>Jn(t,e))),droppedEventsCount:t.droppedEventsCount,status:{code:r.code,message:r.message},links:t.links.map((t=>Hn(t,e))),droppedLinksCount:t.droppedLinksCount,flags:Vn(i.traceFlags,t.parentSpanContext?.isRemote)}}function Hn(t,e){return{attributes:t.attributes?_n(t.attributes):[],spanId:e.encodeSpanContext(t.context.spanId),traceId:e.encodeSpanContext(t.context.traceId),traceState:t.context.traceState?.serialize(),droppedAttributesCount:t.droppedAttributesCount||0,flags:Vn(t.context.traceFlags,t.context.isRemote)}}function Jn(t,e){return{attributes:t.attributes?_n(t.attributes):[],name:t.name,timeUnixNano:e.encodeHrTime(t.time),droppedAttributesCount:t.droppedAttributesCount||0}}function Kn(t,e){const i=Sn(e);return{resourceSpans:Wn(t,i)}}function Zn(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 Wn(t,e){const i=Zn(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=>qn(t,e)));o.push({scope:Tn(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 Xn={serializeRequest:t=>{const e=Bn([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 Yn={serializeRequest:t=>{const e=Kn(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 Qn=5;const ts=1e3;const es=5e3;const is=1.5;const rs=.2;function ns(){return Math.random()*(2*rs)-rs}class ss{_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=Qn;let s=ts;while(r.status==="retryable"&&n>0){n--;const e=Math.max(Math.min(s,es)+ns(),0);s=s*is;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 os(t){return new ss(t.transport)}function as(t){const e=[429,502,503,504];return e.includes(t)}function cs(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 us{_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){Xt.debug("XHR success");r({status:"success"})}else if(n.status&&as(n.status)){r({status:"retryable",retryInMillis:cs(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 ls(t){return new us(t)}class hs{_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}))){Xt.debug("SendBeacon success");i({status:"success"})}else{i({status:"failure",error:new Error("SendBeacon failed")})}}))}shutdown(){}}function fs(t){return new hs(t)}class ds{_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){Xt.debug("response success");return{status:"success"}}else if(as(n.status)){const t=n.headers.get("Retry-After");const e=cs(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 ps(t){return new ds(t)}function ms(t,e){return hn(t,e,os({transport:ls(t)}))}function bs(t,e){return hn(t,e,os({transport:ps(t)}))}function vs(t,e){return hn(t,e,os({transport:fs({url:t.url,headers:t.headers})}))}function ws(t){const e={};Object.entries(t??{}).forEach((([t,i])=>{if(typeof i!=="undefined"){e[t]=String(i)}else{Xt.warn(`Header "${t}" has invalid value (${i}) and will be ignored`)}}));return e}function gs(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,ws(await t()))}return Object.assign(n,r)}}function ys(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 xs(t,e,i){return{...rn(t,e,i),headers:gs(t.headers,e.headers,i.headers),url:ys(t.url)??e.url??i.url}}function ks(t,e){return{...nn(),headers:async()=>t,url:"http://localhost:4318/"+e}}function Ss(t){if(typeof t.headers==="function"){return t.headers}return en(t.headers)}function Es(t,e,i){return xs({url:t.url,timeoutMillis:t.timeoutMillis,headers:Ss(t),concurrencyLimit:t.concurrencyLimit},{},ks(i,e))}function Ts(t,e,i,r){const n=_s(t.headers);const s=Es(t,i,r);return n(s,e)}function _s(t){if(!t&&typeof navigator.sendBeacon==="function"){return vs}else if(typeof globalThis.fetch!=="undefined"){return bs}else{return ms}}class As extends Yr{constructor(t={}){super(Ts(t,Yn,"v1/traces",{"Content-Type":"application/json"}))}}function Ms(t){return typeof t==="object"&&t!==null&&"addEventListener"in t&&typeof t.addEventListener==="function"&&"removeEventListener"in t&&typeof t.removeEventListener==="function"}const Cs="OT_ZONE_CONTEXT";class Os{_enabled=false;_zoneCounter=0;_activeContextFromZone(t){return t&&t.get(Cs)||G}_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:{[Cs]: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 G}const t=this._getActiveZone();const e=this._activeContextFromZone(t);if(e){return e}return G}bind(t,e){if(t===undefined){t=this.active()}if(typeof e==="function"){return this._bindFunction(t,e)}else if(Ms(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 Is={};var Ps;function Ls(){if(Ps)return Is;Ps=1;var t=Is&&Is.__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
2
|
/**
|
|
3
3
|
* @license Angular v<unknown>
|
|
4
4
|
* (c) 2010-2025 Google LLC. https://angular.io/
|
|
5
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"]!==M["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 O.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(M.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);M[s]=o(e,t,C);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){O={parent:O,zone:this};try{return this._zoneDelegate.invoke(this,t,e,i,r)}finally{O=O.parent}};t.prototype.runGuarded=function(t,e,i,r){if(e===void 0){e=null}O={parent:O,zone:this};try{try{return this._zoneDelegate.invoke(this,t,e,i,r)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{O=O.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===_||n===T)){return}var h=t.state!=k;h&&r._transitionTo(k,x);var f=I;I=r;O={parent:O,zone:this};try{if(n==T&&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!==E){if(n==_||c||l&&d===y){h&&r._transitionTo(x,k,y)}else{var p=r._zoneDelegates;this._updateTaskCount(r,-1);h&&r._transitionTo(g,k,g);if(l){r._zoneDelegates=p}}}O=O.parent;I=f}};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(E,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(A,t,e,i,r,undefined))};t.prototype.scheduleMacroTask=function(t,e,i,r,n){return this.scheduleTask(new c(T,t,e,i,r,n))};t.prototype.scheduleEventTask=function(t,e,i,r,n){return this.scheduleTask(new c(_,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(E,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==A){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===_&&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}P++;try{t.runCount++;return t.zone.runTask(t,e,i)}finally{if(P==1){v()}P--}};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 h=i("then");var f=[];var d=false;var p;function m(t){if(!p){if(e[l]){p=e[l].resolve(0)}}if(p){var i=p[h];if(!i){i=p["then"]}i.call(p,t)}else{e[u](t,0)}}function b(t){if(P===0&&f.length===0){m(v)}t&&f.push(t)}function v(){if(!d){d=true;while(f.length){var t=f;f=[];for(var e=0;e<t.length;e++){var i=t[e];try{i.zone.runTask(i,null,null)}catch(t){C.onUnhandledError(t)}}}C.microtaskDrainDone();d=false}}var w={name:"NO ZONE"};var g="notScheduled",y="scheduling",x="scheduled",k="running",S="canceling",E="unknown";var A="microTask",T="macroTask",_="eventTask";var M={};var C={symbol:i,currentZoneFrame:function(){return O},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 O={parent:null,zone:new s(null,null)};var I=null;var P=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 h="removeEventListener";var f=i(l);var d=i(h);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 E(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 A(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(!T(a)){return"continue"}t[n]=function(t){var e=function(){return t.apply(this,E(arguments,i+"."+n))};$(e,t);return e}(o)}};for(var n=0;n<e.length;n++){r(n)}}function T(t){if(!t){return true}if(t.writable===false){return false}return!(typeof t.get==="function"&&typeof t.set==="undefined")}var _=typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope;var M=!("nw"in k)&&typeof k.process!=="undefined"&&k.process.toString()==="[object process]";var C=!M&&!_&&!!(y&&x["HTMLElement"]);var O=typeof k.process!=="undefined"&&k.process.toString()==="[object process]"&&!_&&!!(y&&x["HTMLElement"]);var I={};var P=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(C&&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[P]&&typeof n==="string"){t.returnValue=n}else if(n!=undefined&&!n){t.preventDefault()}}return n};function D(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 h=I[l];if(!h){h=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[h];if(typeof r==="function"){i.removeEventListener(l,L)}u===null||u===void 0?void 0:u.call(i,null);i[h]=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[h];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 R(t,e,i){if(e){for(var r=0;r<e.length;r++){D(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++){D(t,n[o],i)}}}var N=g("originalInstance");function j(t){var e=k[t];if(!e)return;k[g(t)]=e;k[t]=function(){var i=E(arguments,t);switch(i.length){case 0:this[N]=new e;break;case 1:this[N]=new e(i[0]);break;case 2:this[N]=new e(i[0],i[1]);break;case 3:this[N]=new e(i[0],i[1],i[2]);break;case 4:this[N]=new e(i[0],i[1],i[2],i[3]);break;default:throw new Error("Arg list too long.")}};$(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[N][e].apply(this[N],arguments)}}else{o(k[t].prototype,e,{set:function(i){if(typeof i==="function"){this[N][e]=v(i,t+"."+e);$(this[N][e],i)}else{this[N][e]=i}},get:function(){return this[N][e]}})}})(r)}for(r in e){if(r!=="prototype"&&e.hasOwnProperty(r)){k[t][r]=e[r]}}}function U(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(T(c)){var u=i(o,n,e);r[e]=function(){return u(this,arguments)};$(r[e],o)}}return o}function z(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=U(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 $(t,e){t[g("OriginalDelegate")]=e}var B=false;var F=false;function G(){if(B){return F}B=true;try{var t=x.navigator.userAgent;if(t.indexOf("MSIE ")!==-1||t.indexOf("Trident/")!==-1||t.indexOf("Edge/")!==-1){F=true}}catch(t){}return F}function V(t){return typeof t==="function"}function q(t){return typeof t==="number"}var H={useG:true};var J={};var K={};var Z=new RegExp("^"+b+"(\\w+)(true|false)$");var W=g("propagationStopped");function X(t,e){var i=(e?e(t):t)+m;var r=(e?e(t):t)+p;var n=b+i;var s=b+r;J[t]={};J[t][m]=n;J[t][p]=s}function Y(e,i,r,n){var s=n&&n.add||l;var o=n&&n.rm||h;var c=n&&n.listeners||"eventListeners";var u=n&&n.rmAll||"removeAllListeners";var f=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[J[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[W]===true){break}var c=y(u[l],s,r);c&&a.push(c)}}if(a.length===1){throw a[0]}else{var h=function(t){var e=a[t];i.nativeScheduleMicroTask((function(){throw e}))};for(var l=0;l<a.length;l++){h(l)}}}}var k=function(t){return x(this,t,false)};var S=function(t){return x(this,t,true)};function E(i,r){if(!i){return false}var n=true;if(r&&r.useG!==undefined){n=r.useG}var l=r&&r.vh;var h=true;if(r&&r.chkDup!==undefined){h=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[f]){return false}var E=r&&r.eventNameToString;var A={};var T=x[f]=x[s];var _=x[g(o)]=x[o];var C=x[g(c)]=x[c];var O=x[g(u)]=x[u];var I;if(r&&r.prepend){I=x[g(r.prepend)]=x[r.prepend]}function P(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(A.isExisting){return}return T.call(A.target,A.eventName,A.capture?S:k,A.options)};var D=function(t){if(!t.isRemoved){var e=J[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 _.call(t.target,t.eventName,t.capture?S:k,t.options)};var R=function(t){return T.call(A.target,A.eventName,t.invoke,A.options)};var N=function(t){return I.call(A.target,A.eventName,t.invoke,A.options)};var j=function(t){return _.call(t.target,t.eventName,t.invoke,t.options)};var U=n?L:R;var z=n?D:j;var B=function(t,e){var i=typeof e;return i==="function"&&t.callback===e||i==="object"&&t.originalDelegate===e};var F=(r===null||r===void 0?void 0:r.diff)||B;var G=Zone[g("UNPATCHED_EVENTS")];var V=e[g("PASSIVE_EVENTS")];function q(e){if(typeof e==="object"&&e!==null){var i=t({},e);if(e.signal){i.signal=e.signal}return i}return e}var W=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 f=arguments[0];if(r&&r.transferEventName){f=r.transferEventName(f)}var d=arguments[1];if(!d){return t.apply(this,arguments)}if(M&&f==="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(f)!==-1;var w=q(P(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(G){for(var y=0;y<G.length;y++){if(f===G[y]){if(v){return t.call(u,f,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 T=J[f];if(!T){X(f,E);T=J[f]}var _=T[x?p:m];var C=u[_];var O=false;if(C){O=true;if(h){for(var y=0;y<C.length;y++){if(F(C[y],d)){return}}}}else{C=u[_]=[]}var I;var L=u.constructor["name"];var D=K[L];if(D){I=D[f]}if(!I){I=L+i+(E?E(f):f)}A.options=w;if(k){A.options.once=false}A.target=u;A.capture=x;A.eventName=f;A.isExisting=O;var R=n?H:undefined;if(R){R.taskData=A}if(g){A.options.signal=undefined}var N=S.scheduleEventTask(I,d,R,s,o);if(g){A.options.signal=g;var j=function(){return N.zone.cancelTask(N)};t.call(g,"abort",j,{once:true});N.removeAbortListener=function(){return g.removeEventListener("abort",j)}}A.target=null;if(R){R.taskData=null}if(k){A.options.once=true}if(typeof N.options!=="boolean"){N.options=w}N.target=u;N.capture=x;N.eventName=f;if(b){N.originalDelegate=d}if(!c){C.push(N)}else{C.unshift(N)}if(a){return u}}};x[s]=W(T,d,U,z,y);if(I){x[v]=W(I,w,N,z,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 _.apply(this,arguments)}if(l&&!l(_,o,t,arguments)){return}var a=J[i];var c;if(a){c=a[s?p:m]}var u=c&&t[c];if(u){for(var h=0;h<u.length;h++){var f=u[h];if(F(f,o)){u.splice(h,1);f.isRemoved=true;if(u.length===0){f.allRemoved=true;t[c]=null;if(!s&&typeof i==="string"){var d=b+"ON_PROPERTY"+i;t[d]=null}}f.zone.cancelTask(f);if(y){return t}return}}}return _.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,E?E(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=Z.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 h=J[i];if(h){var f=h[m];var d=h[p];var b=t[f];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}};$(x[s],T);$(x[o],_);if(O){$(x[u],O)}if(C){$(x[c],C)}return true}var A=[];for(var T=0;T<r.length;T++){A[T]=E(r[T],n)}return A}function Q(t,e){if(!e){var i=[];for(var r in t){var n=Z.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=J[e];if(!c){X(e);c=J[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[W]=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(q(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=U(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 h=s[0];s[0]=function t(){try{return h.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 f=w(e,s[0],l,a,c);if(!f){return f}var d=f.data,p=d.handleId,m=d.handle,b=d.isRefreshable,v=d.isPeriodic;if(p){o[p]=f}else if(m){m[it]=f;if(b&&!v){var g=m.refresh;m.refresh=function(){var t=f.zone,e=f.state;if(e==="notScheduled"){f._state="scheduled";t._updateTaskCount(f,1)}else if(e==="running"){f._state="scheduling"}return g.call(this)}}}return(u=m!==null&&m!==void 0?m:p)!==null&&u!==void 0?u:f}else{return i.apply(t,s)}}}));s=U(t,i,(function(e){return function(i,r){var n=r[0];var s;if(q(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 h=u+s;var f=a+l;var d=a+h;n[u]={};n[u][o]=f;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);R(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(M&&!O){return}if(Zone[t.symbol("patchEvents")]){return}var i=e["__Zone_ignore_on_properties"];var r=[];if(C){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 ht(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];U(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){j("MutationObserver");j("WebKitMutationObserver")}));t.__load_patch("IntersectionObserver",(function(t,e,i){j("IntersectionObserver")}));t.__load_patch("FileReader",(function(t,e,i){j("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 h=u[f];var p=u[d];if(!h){var m=t["XMLHttpRequestEventTarget"];if(m){var b=m.prototype;h=b[f];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(!h){h=o[f];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}}};h.call(o,v,u);var l=o[i];if(!l){o[i]=t}M.apply(o,r.args);o[s]=true;return t}function k(){}function S(t){var e=t.data;e.aborted=true;return C.apply(e.target,e.args)}var E=U(u,"open",(function(){return function(t,e){t[r]=e[2]==false;t[o]=e[1];return E.apply(t,e)}}));var A="XMLHttpRequest.send";var T=g("fetchTaskAborting");var _=g("fetchTaskScheduling");var M=U(u,"send",(function(){return function(t,i){if(e.current[_]===true){return M.apply(t,i)}if(t[r]){return M.apply(t,i)}else{var n={target:t,url:t[o],isPeriodic:false,args:i,aborted:false};var s=w(A,k,n,x,S);if(t&&t[a]===true&&!n.aborted&&s.state===y){s.invoke()}}}}));var C=U(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[T]===true){return C.apply(t,i)}}}))}}));t.__load_patch("geolocation",(function(t){if(t["navigator"]&&t["navigator"].geolocation){A(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 ft(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 h="__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 f=o("unhandledPromiseRejectionHandler");function d(t){i.onUnhandledError(t);try{var r=e[f];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 z.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 E=true;var A=false;var T=0;function _(t,e){return function(i){try{I(t,e,i)}catch(e){I(t,false,e)}}}var M=function(){var t=false;return function e(i){return function(){if(t){return}t=true;i.apply(null,arguments)}}};var C="Promise resolved with itself";var O=o("currentTaskTrace");function I(t,r,o){var u=M();if(t===o){throw new TypeError(C)}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!==A&&o instanceof z&&o.hasOwnProperty(v)&&o.hasOwnProperty(w)&&o[v]!==S){L(o);I(t,o[v],o[w])}else if(r!==A&&typeof l==="function"){try{l.call(o,u(_(t,r)),u(_(t,false)))}catch(e){u((function(){I(t,false,e)}))()}}else{t[v]=r;var f=t[w];t[w]=o;if(t[g]===g){if(r===E){t[v]=t[x];t[w]=t[y]}}if(r===A&&o instanceof Error){var d=e.currentTask&&e.currentTask.data&&e.currentTask.data[h];if(d){n(o,O,{configurable:true,enumerable:false,writable:true,value:d})}}for(var p=0;p<f.length;){D(t,f[p++],f[p++],f[p++],f[p++])}if(f.length==0&&r==A){t[v]=T;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 P=o("rejectionHandledHandler");function L(t){if(t[v]===T){try{var i=e[P];if(i&&typeof i==="function"){i.call(this,{rejection:t[w],promise:t})}}catch(t){}t[v]=A;for(var r=0;r<a.length;r++){if(t===a[r].promise){a.splice(r,1)}}}}function D(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 R="function ZoneAwarePromise() { [native code] }";var N=function(){};var j=t.AggregateError;var z=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=M();e&&e(r(_(i,E)),r(_(i,A)))}catch(t){I(i,false,t)}}t.toString=function(){return R};t.resolve=function(e){if(e instanceof t){return e}return I(new this(null),E,e)};t.reject=function(t){return I(new this(null),A,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 j([],"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 j([],"All promises were rejected"))}if(r===0){return Promise.reject(new j([],"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 j(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,h=t;l<h.length;l++){var f=h[l];c(f)}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(N);var a=e.current;if(this[v]==S){this[w].push(a,o,i,r)}else{D(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(N);s[g]=g;var o=e.current;if(this[v]==S){this[w].push(o,s,i,i)}else{D(this,o,s,i,i)}return s};return t}();z["resolve"]=z.resolve;z["reject"]=z.reject;z["race"]=z.race;z["all"]=z.all;var $=t[u]=t["Promise"];t["Promise"]=z;var B=o("thenPatched");function F(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 z((function(t,e){n.call(i,t,e)}));return r.then(t,e)};t[B]=true}i.patchThen=F;function G(t){return function(e,i){var r=t.apply(e,i);if(r instanceof z){return r}var n=r.constructor;if(!n[B]){F(n)}return r}}if($){F($);U(t,"fetch",(function(t){return G(t)}))}Promise[e.__symbol__("uncaughtPromiseErrors")]=a;return z}))}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=R;i.patchMethod=U;i.bindArguments=E;i.patchMacroTask=z;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=Y;i.isIEOrEdge=G;i.ObjectDefineProperty=o;i.ObjectGetOwnPropertyDescriptor=s;i.ObjectCreate=c;i.ArraySlice=u;i.patchClass=j;i.wrapWithCurrentZone=v;i.filterProperties=at;i.attachOriginToPatched=$;i._redefineProperty=Object.defineProperty;i.patchCallbacks=pt;i.getGlobalObjects=function(){return{globalSources:K,zoneSymbolEventNames:J,eventNames:r,isBrowser:C,isMix:O,isNode:M,TRUE_STR:p,FALSE_STR:m,ZONE_SYMBOL_PREFIX:b,ADD_EVENT_LISTENER_STR:l,REMOVE_EVENT_LISTENER_STR:h}}}))}function bt(t){ft(t);dt(t);mt(t)}var vt=n();bt(vt);ht(vt)}));return Os}Ps();class Ls{emit(t){}}const Ds=new Ls;class Rs{getLogger(t,e,i){return new Ls}}const Ns=new Rs;class js{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 Ds}this._delegate=t;return this._delegate}}class Us{getLogger(t,e,i){var r;return(r=this._getDelegateLogger(t,e,i))!==null&&r!==void 0?r:new js(this,t,e,i)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Ns}_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 zs=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};const $s=Symbol.for("io.opentelemetry.js.api.logs");const Bs=zs;function Fs(t,e,i){return r=>r===t?e:i}const Gs=1;class Vs{constructor(){this._proxyLoggerProvider=new Us}static getInstance(){if(!this._instance){this._instance=new Vs}return this._instance}setGlobalLoggerProvider(t){if(Bs[$s]){return this.getLoggerProvider()}Bs[$s]=Fs(Gs,t,Ns);this._proxyLoggerProvider._setDelegate(t);return t}getLoggerProvider(){var t,e;return(e=(t=Bs[$s])===null||t===void 0?void 0:t.call(Bs,Gs))!==null&&e!==void 0?e:this._proxyLoggerProvider}getLogger(t,e,i){return this.getLoggerProvider().getLogger(t,e,i)}disable(){delete Bs[$s];this._proxyLoggerProvider=new Us}}const qs=Vs.getInstance();function Hs(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 Js(t){t.forEach((t=>t.disable()))}function Ks(t){const e=t.tracerProvider||pe.getTracerProvider();const i=t.meterProvider||ee.getMeterProvider();const r=t.loggerProvider||qs.getLoggerProvider();const n=t.instrumentations?.flat()??[];Hs(n,e,i,r);return()=>{Js(n)}}let Zs=console.error.bind(console);function Ws(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 Xs=(t,e,i)=>{if(!t||!t[e]){Zs("no original function "+String(e)+" to wrap");return}if(!i){Zs("no wrapper function");Zs((new Error).stack);return}const r=t[e];if(typeof r!=="function"||typeof i!=="function"){Zs("original object and wrapper must be functions");return}const n=i(r,e);Ws(n,"__original",r);Ws(n,"__unwrap",(()=>{if(t[e]===n){Ws(t,e,r)}}));Ws(n,"__wrapped",true);Ws(t,e,n);return n};const Ys=(t,e,i)=>{if(!t){Zs("must provide one or more modules to patch");Zs((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Zs("must provide one or more functions to wrap on modules");return}t.forEach((t=>{e.forEach((e=>{Xs(t,e,i)}))}))};const Qs=(t,e)=>{if(!t||!t[e]){Zs("no function to unwrap.");Zs((new Error).stack);return}const i=t[e];if(!i.__unwrap){Zs("no original to unwrap to -- has "+String(e)+" already been unwrapped?")}else{i.__unwrap();return}};const to=(t,e)=>{if(!t){Zs("must provide one or more modules to patch");Zs((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Zs("must provide one or more functions to unwrap on modules");return}t.forEach((t=>{e.forEach((e=>{Qs(t,e)}))}))};class eo{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(t,e,i){this.instrumentationName=t;this.instrumentationVersion=e;this.setConfig(i);this._diag=Wt.createComponentLogger({namespace:t});this._tracer=pe.getTracer(t,e);this._meter=ee.getMeter(t,e);this._logger=qs.getLogger(t,e);this._updateMetricInstruments()}_wrap=Xs;_unwrap=Qs;_massWrap=Ys;_massUnwrap=to;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 io extends eo{constructor(t,e,i){super(t,e,i);if(this._config.enabled){this.enable()}}}function ro(t){return typeof t==="function"&&typeof t.__original==="function"&&typeof t.__unwrap==="function"&&t.__wrapped===true}var no;(function(t){t["EVENT_TYPE"]="event_type";t["TARGET_ELEMENT"]="target_element";t["TARGET_XPATH"]="target_xpath";t["HTTP_URL"]="http.url"})(no||(no={}));const so="0.53.0";const oo="@opentelemetry/instrumentation-user-interaction";const ao="OT_ZONE_CONTEXT";const co="Navigation:";const uo=["click"];function lo(){return false}class ho extends io{version=so;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(t={}){super(oo,so,t);this._eventNames=new Set(t?.eventNames??uo);this._shouldPreventSpanCreation=typeof t?.shouldPreventSpanCreation==="function"?t.shouldPreventSpanCreation:lo}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=Kr(t,true);try{const n=this.tracer.startSpan(e,{attributes:{[no.EVENT_TYPE]:e,[no.TARGET_ELEMENT]:t.tagName,[no.TARGET_XPATH]:r,[no.HTTP_URL]:window.location.href}},i?pe.setSpan(Zt.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(ao);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 Zt.with(pe.setSpan(Zt.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(ro(history.replaceState))this._unwrap(history,"replaceState");if(ro(history.pushState))this._unwrap(history,"pushState");if(ro(history.back))this._unwrap(history,"back");if(ro(history.forward))this._unwrap(history,"forward");if(ro(history.go))this._unwrap(history,"go")}_updateInteractionName(t){const e=pe.getSpan(Zt.active());if(e&&typeof e.updateName==="function"){e.updateName(`${co} ${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 Zt.with(pe.setSpan(Zt.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(ro(t.prototype.runTask)){this._unwrap(t.prototype,"runTask");this._diag.debug("removing previous patch from method runTask")}if(ro(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask");this._diag.debug("removing previous patch from method scheduleTask")}if(ro(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(ro(t.addEventListener)){this._unwrap(t,"addEventListener");this._diag.debug("removing previous patch from method addEventListener")}if(ro(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(ro(t.prototype.runTask)){this._unwrap(t.prototype,"runTask")}if(ro(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask")}if(ro(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask")}}else{const t=this._getPatchableEventTargets();t.forEach((t=>{if(ro(t.addEventListener)){this._unwrap(t,"addEventListener")}if(ro(t.removeEventListener)){this._unwrap(t,"removeEventListener")}}))}this._unpatchHistoryApi()}_getZoneWithPrototype(){const t=window;return t.Zone}}var fo={exports:{}};var po=fo.exports;var mo;function bo(){if(mo)return fo.exports;mo=1;(function(t,e){(function(i,r){var n="1.0.41",s="",o="?",a="function",c="undefined",u="object",l="string",h="major",f="model",d="name",p="type",m="vendor",b="version",v="architecture",w="console",g="mobile",y="tablet",x="smarttv",k="wearable",S="embedded",E=500;var A="Amazon",T="Apple",_="ASUS",M="BlackBerry",C="Browser",O="Chrome",I="Edge",P="Firefox",L="Google",D="Honor",R="Huawei",N="Lenovo",j="LG",U="Microsoft",z="Motorola",$="Nvidia",B="OnePlus",F="Opera",G="OPPO",V="Samsung",q="Sharp",H="Sony",J="Xiaomi",K="Zebra",Z="Facebook",W="Chromium OS",X="Mac OS",Y=" 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,E)}};var st=function(t,e){var i=0,n,s,o,c,l,h;while(i<e.length&&!l){var f=e[i],d=e[i+1];n=s=0;while(n<f.length&&!l){if(!f[n]){break}l=f[n++].exec(t);if(!!l){for(o=0;o<d.length;o++){h=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,h)}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]]=h?c[1].call(this,h,c[2]):r}else{this[c[0]]=h?h.replace(c[1],c[2]):r}}else if(c.length===4){this[c[0]]=h?c[3].call(this,h.replace(c[1],c[2])):r}}else{this[c]=h?h: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,F+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[b,[d,F+" GX"]],[/\bopr\/([\w\.]+)/i],[b,[d,F]],[/\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"+C]],[/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 "+C]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+C],b],[/\bfocus\/([\w\.]+)/i],[b,[d,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[b,[d,F+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[b,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[b,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[b,[d,F+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[b,[d,"MIUI"+Y]],[/fxios\/([\w\.-]+)/i],[b,[d,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[b,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],b],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+Y],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,Z],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,O+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,O+" WebView"],b],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[b,[d,"Android "+C]],[/(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,P+" 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],[f,[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],[f,[m,V],[p,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[f,[m,T],[p,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[f,[m,T],[p,y]],[/(macintosh);/i],[f,[m,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[f,[m,q],[p,g]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[f,[m,D],[p,y]],[/honor([-\w ]+)[;\)]/i],[f,[m,D],[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],[f,[m,R],[p,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[f,[m,R],[p,g]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[f,/_/g," "],[m,J],[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],[[f,/_/g," "],[m,J],[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],[f,[m,G],[p,g]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[f,[m,ot,{OnePlus:["304","403","203"],"*":G}],[p,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[f,[m,"Vivo"],[p,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[f,[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],[f,[m,z],[p,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[f,[m,z],[p,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[f,[m,j],[p,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[f,[m,j],[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],[f,[m,N],[p,y]],[/(nokia) (t[12][01])/i],[m,f,[p,y]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[f,/_/g," "],[p,g],[m,"Nokia"]],[/(pixel (c|tablet))\b/i],[f,[m,L],[p,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[f,[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],[f,[m,H],[p,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[f,"Xperia Tablet"],[m,H],[p,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[f,[m,B],[p,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[f,[m,A],[p,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[f,/(.+)/g,"Fire Phone $1"],[m,A],[p,g]],[/(playbook);[-\w\),; ]+(rim)/i],[f,m,[p,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[f,[m,M],[p,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[f,[m,_],[p,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[f,[m,_],[p,g]],[/(nexus 9)/i],[f,[m,"HTC"],[p,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[m,[f,/_/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],[f,[m,"TCL"],[p,y]],[/(itel) ((\w+))/i],[[m,it],f,[p,ot,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[f,[m,"Acer"],[p,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[f,[m,"Meizu"],[p,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[f,[m,"Ulefone"],[p,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[f,[m,"Energizer"],[p,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[f,[m,"Cat"],[p,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[f,[m,"Smartfren"],[p,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[f,[m,"Nothing"],[p,g]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[f,[m,"Archos"],[p,y]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[f,[m,"Archos"],[p,g]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[m,f,[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,f,[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,f,[p,y]],[/(surface duo)/i],[f,[m,U],[p,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[f,[m,"Fairphone"],[p,g]],[/(u304aa)/i],[f,[m,"AT&T"],[p,g]],[/\bsie-(\w*)/i],[f,[m,"Siemens"],[p,g]],[/\b(rct\w+) b/i],[f,[m,"RCA"],[p,y]],[/\b(venue[\d ]{2,7}) b/i],[f,[m,"Dell"],[p,y]],[/\b(q(?:mv|ta)\w+) b/i],[f,[m,"Verizon"],[p,y]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[f,[m,"Barnes & Noble"],[p,y]],[/\b(tm\d{3}\w+) b/i],[f,[m,"NuVision"],[p,y]],[/\b(k88) b/i],[f,[m,"ZTE"],[p,y]],[/\b(nx\d{3}j) b/i],[f,[m,"ZTE"],[p,g]],[/\b(gen\d{3}) b.+49h/i],[f,[m,"Swiss"],[p,g]],[/\b(zur\d{3}) b/i],[f,[m,"Swiss"],[p,y]],[/\b((zeki)?tb.*\b) b/i],[f,[m,"Zeki"],[p,y]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[m,"Dragon Touch"],f,[p,y]],[/\b(ns-?\w{0,9}) b/i],[f,[m,"Insignia"],[p,y]],[/\b((nxa|next)-?\w{0,9}) b/i],[f,[m,"NextBook"],[p,y]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[m,"Voice"],f,[p,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[m,"LvTel"],f,[p,g]],[/\b(ph-1) /i],[f,[m,"Essential"],[p,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[f,[m,"Envizen"],[p,y]],[/\b(trio[-\w\. ]+) b/i],[f,[m,"MachSpeed"],[p,y]],[/\btu_(1491) b/i],[f,[m,"Rotor"],[p,y]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[f,[m,$],[p,y]],[/(sprint) (\w+)/i],[m,f,[p,g]],[/(kin\.[onetw]{3})/i],[[f,/\./g," "],[m,U],[p,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[f,[m,K],[p,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[f,[m,K],[p,g]],[/smart-tv.+(samsung)/i],[m,[p,x]],[/hbbtv.+maple;(\d+)/i],[[f,/^/,"SmartTV"],[m,V],[p,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[m,j],[p,x]],[/(apple) ?tv/i],[m,[f,T+" TV"],[p,x]],[/crkey/i],[[f,O+"cast"],[m,L],[p,x]],[/droid.+aft(\w+)( bui|\))/i],[f,[m,A],[p,x]],[/(shield \w+ tv)/i],[f,[m,$],[p,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[f,[m,q],[p,x]],[/(bravia[\w ]+)( bui|\))/i],[f,[m,H],[p,x]],[/(mi(tv|box)-?\w+) bui/i],[f,[m,J],[p,x]],[/Hbbtv.*(technisat) (.*);/i],[m,f,[p,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[m,nt],[f,nt],[p,x]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[f,[p,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[p,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[m,f,[p,w]],[/droid.+; (shield)( bui|\))/i],[f,[m,$],[p,w]],[/(playstation \w+)/i],[f,[m,H],[p,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[f,[m,U],[p,w]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[f,[m,V],[p,k]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[m,f,[p,k]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[f,[m,G],[p,k]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[f,[m,T],[p,k]],[/(opwwe\d{3})/i],[f,[m,B],[p,k]],[/(moto 360)/i],[f,[m,z],[p,k]],[/(smartwatch 3)/i],[f,[m,H],[p,k]],[/(g watch r)/i],[f,[m,j],[p,k]],[/droid.+; (wt63?0{2,3})\)/i],[f,[m,K],[p,k]],[/droid.+; (glass) \d/i],[f,[m,L],[p,k]],[/(pico) (4|neo3(?: link|pro)?)/i],[m,f,[p,k]],[/; (quest( \d| pro)?)/i],[f,[m,Z],[p,k]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[m,[p,S]],[/(aeobc)\b/i],[f,[m,A],[p,S]],[/(homepod).+mac os/i],[f,[m,T],[p,S]],[/windows iot/i],[[p,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[f,[p,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[f,[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],[f,[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,X],[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,M]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[b,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[b,[d,P+" 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,O+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,W],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[h]=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[f]=r;t[p]=r;st.call(t,o,x.device);if(k&&!t[p]&&w&&w.mobile){t[p]=g}if(k&&t[f]=="Macintosh"&&n&&typeof n.standalone!==c&&n.maxTouchPoints&&n.maxTouchPoints>2){t[f]="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,W).replace(/macos/i,X)}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>E?nt(t,E):t;return this};this.setUA(o);return this};lt.VERSION=n;lt.BROWSER=tt([d,b,h]);lt.CPU=tt([v]);lt.DEVICE=tt([f,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 ht=typeof i!==c&&(i.jQuery||i.Zepto);if(ht&&!ht.ua){var ft=new lt;ht.ua=ft.getResult();ht.ua.get=function(){return ft.getUA()};ht.ua.set=function(t){ft.setUA(t);var e=ft.getResult();for(var i in e){ht.ua[i]=e[i]}}}})(typeof window==="object"?window:po)})(fo,fo.exports);return fo.exports}var vo=bo();var wo=hn(vo);const go="service.name";const yo="service.version";const xo="eAzROSTiqNd3i+M9Jw6q5Tld0jarZc617sJB//pvb5c=";let ko=false;function So(){if(ko){return}ko=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 ${xo}`)}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 ${xo}`);i={...i,headers:t}}return e.call(this,t,i)};navigator.sendBeacon=function(){return false}}class Eo{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 wo}initialize(){try{So();const t=new Ts({url:this.collectorUrl,headers:{"Content-Type":"application/json",Authorization:`Bearer ${xo}`},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 Dr(e,{maxQueueSize:100,maxExportBatchSize:10,scheduledDelayMillis:5e3,exportTimeoutMillis:3e4});this.provider=new Jr({spanProcessors:[this.spanProcessor]});const i=new Cs;const r=new Di;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{Ks({instrumentations:[new ho({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=Zt.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",[go]:this.serviceName,[yo]: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:Kt.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 Zt.with(pe.setSpan(Zt.active(),r),(async()=>await e()));r.setStatus({code:Kt.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(Zt.active());return t?.spanContext().traceId}catch{return undefined}}getCurrentSpanId(){try{const t=pe.getSpan(Zt.active());return t?.spanContext().spanId}catch{return undefined}}}var Ao;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(Ao||(Ao={}));var To;(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"})(To||(To={}));var _o;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(_o||(_o={}));function Mo(t){let e=Object.keys(t);if(e.length===0)return"";e=e.sort();return JSON.stringify(e.map((e=>[e,t[e]])))}function Co(t){return`${t.name}:${t.version??""}:${t.schemaUrl??""}`}class Oo extends Error{constructor(t){super(t);Object.setPrototypeOf(this,Oo.prototype)}}function Io(t,e){let i;const r=new Promise((function t(r,n){i=setTimeout((function t(){n(new Oo("Operation timed out."))}),e)}));return Promise.race([t,r]).then((t=>{clearTimeout(i);return t}),(t=>{clearTimeout(i);throw t}))}function Po(t,e){if(t.size!==e.size){return false}for(const i of t){if(!e.has(i)){return false}}return true}function Lo(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 Do(t,e){return t.toLowerCase()===e.toLowerCase()}var Ro;(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"})(Ro||(Ro={}));class No{kind=Ro.DROP;createAccumulation(){return undefined}merge(t,e){return undefined}diff(t,e){return undefined}toMetricData(t,e,i,r){return undefined}}function jo(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 Uo{startTime;_boundaries;_recordMinMax;_current;constructor(t,e,i=true,r=jo(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=Lo(this._boundaries,t);this._current.buckets.counts[e]+=1}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class zo{kind=Ro.HISTOGRAM;_boundaries;_recordMinMax;constructor(t,e){this._boundaries=t;this._recordMinMax=e}createAccumulation(t){return new Uo(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 Uo(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 Uo(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:_o.HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===To.GAUGE||t.type===To.UP_DOWN_COUNTER||t.type===To.OBSERVABLE_GAUGE||t.type===To.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 $o{backing;indexBase;indexStart;indexEnd;constructor(t=new Bo,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 $o(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 Bo{_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 Bo([...this._counts])}}const Fo=52;const Go=2146435072;const Vo=1048575;const qo=1023;const Ho=-1023+1;const Jo=qo;const Ko=Math.pow(2,-1022);function Zo(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=(i&Go)>>20;return r-qo}function Wo(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&Vo)*Math.pow(2,32);return n+r}function Xo(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 Yo(t){t--;t|=t>>1;t|=t>>2;t|=t>>4;t|=t>>8;t|=t>>16;t++;return t}class Qo extends Error{}class ta{_shift;constructor(t){this._shift=-t}mapToIndex(t){if(t<Ko){return this._minNormalLowerBoundaryIndex()}const e=Zo(t);const i=this._rightShift(Wo(t)-1,Fo);return e+i>>this._shift}lowerBoundary(t){const e=this._minNormalLowerBoundaryIndex();if(t<e){throw new Qo(`underflow: ${t} is < minimum lower boundary: ${e}`)}const i=this._maxNormalLowerBoundaryIndex();if(t>i){throw new Qo(`overflow: ${t} is > maximum lower boundary: ${i}`)}return Xo(1,t<<this._shift)}get scale(){if(this._shift===0){return 0}return-this._shift}_minNormalLowerBoundaryIndex(){let t=Ho>>this._shift;if(this._shift<2){t--}return t}_maxNormalLowerBoundaryIndex(){return Jo>>this._shift}_rightShift(t,e){return Math.floor(t*Math.pow(2,-e))}}class ea{_scale;_scaleFactor;_inverseFactor;constructor(t){this._scale=t;this._scaleFactor=Xo(Math.LOG2E,t);this._inverseFactor=Xo(Math.LN2,-t)}mapToIndex(t){if(t<=Ko){return this._minNormalLowerBoundaryIndex()-1}if(Wo(t)===0){const e=Zo(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 Qo(`overflow: ${t} is > maximum lower boundary: ${e}`)}const i=this._minNormalLowerBoundaryIndex();if(t<=i){if(t===i){return Ko}else if(t===i-1){return Math.exp((t+(1<<this._scale))/this._scaleFactor)/2}throw new Qo(`overflow: ${t} is < minimum lower boundary: ${i}`)}return Math.exp(t*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Ho<<this._scale}_maxNormalLowerBoundaryIndex(){return(Jo+1<<this._scale)-1}}const ia=-10;const ra=20;const na=Array.from({length:31},((t,e)=>{if(e>10){return new ea(e-10)}return new ta(e-10)}));function sa(t){if(t>ra||t<ia){throw new Qo(`expected scale >= ${ia} && <= ${ra}, got: ${t}`)}return na[t+10]}class oa{static combine(t,e){return new oa(Math.min(t.low,e.low),Math.max(t.high,e.high))}low;high;constructor(t,e){this.low=t;this.high=e}}const aa=20;const ca=160;const ua=2;class la{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(t,e=ca,i=true,r=0,n=0,s=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new $o,u=new $o,l=sa(aa)){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<ua){Wt.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${ua}`);this._maxSize=ua}}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 la(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=Yo(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=sa(e)}_minScale(t){const e=Math.min(this.scale,t.scale);const i=oa.combine(this._highLowAtScale(this.positive,this.scale,e),this._highLowAtScale(t.positive,t.scale,e));const r=oa.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 oa(0,-1)}const r=e-i;return new oa(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 ha{kind=Ro.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(t,e){this._maxSize=t;this._recordMinMax=e}createAccumulation(t){return new la(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:_o.EXPONENTIAL_HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===To.GAUGE||t.type===To.UP_DOWN_COUNTER||t.type===To.OBSERVABLE_GAUGE||t.type===To.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}}}))}}}const fa=$("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function da(t){return t.setValue(fa,true)}function pa(){return t=>{Wt.error(ma(t))}}function ma(t){if(typeof t==="string"){return t}else{return JSON.stringify(ba(t))}}function ba(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 va=pa();function wa(t){try{va(t)}catch{}}const ga="2.6.0";const ya="process.runtime.name";const xa={[Ke]:"opentelemetry",[ya]:"browser",[He]:Je,[Ze]:ga};const ka=6;const Sa=Math.pow(10,ka);function Ea(t){const e=t/1e3;const i=Math.trunc(e);const r=Math.round(t%1e3*Sa);return[i,r]}function Aa(t){return t[0]*1e6+t[1]/1e3}var Ta;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(Ta||(Ta={}));function _a(t,e){return new Promise((i=>{Zt.with(da(Zt.active()),(()=>{t.export(e,i)}))}))}const Ma={_export:_a};class Ca{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=Ea(Date.now())}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Oa{kind=Ro.LAST_VALUE;createAccumulation(t){return new Ca(t)}merge(t,e){const i=Aa(e.sampleTime)>=Aa(t.sampleTime)?e:t;return new Ca(t.startTime,i.toPointValue(),i.sampleTime)}diff(t,e){const i=Aa(e.sampleTime)>=Aa(t.sampleTime)?e:t;return new Ca(e.startTime,i.toPointValue(),i.sampleTime)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:_o.GAUGE,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()})))}}}class Ia{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 Pa{kind=Ro.SUM;monotonic;constructor(t){this.monotonic=t}createAccumulation(t){return new Ia(t,this.monotonic)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();if(e.reset){return new Ia(e.startTime,this.monotonic,r,e.reset)}return new Ia(t.startTime,this.monotonic,i+r)}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();if(this.monotonic&&i>r){return new Ia(e.startTime,this.monotonic,r,true)}return new Ia(e.startTime,this.monotonic,r-i)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:_o.SUM,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()}))),isMonotonic:this.monotonic}}}class La{static DEFAULT_INSTANCE=new No;createAggregator(t){return La.DEFAULT_INSTANCE}}class Da{static MONOTONIC_INSTANCE=new Pa(true);static NON_MONOTONIC_INSTANCE=new Pa(false);createAggregator(t){switch(t.type){case To.COUNTER:case To.OBSERVABLE_COUNTER:case To.HISTOGRAM:{return Da.MONOTONIC_INSTANCE}default:{return Da.NON_MONOTONIC_INSTANCE}}}}class Ra{static DEFAULT_INSTANCE=new Oa;createAggregator(t){return Ra.DEFAULT_INSTANCE}}class Na{static DEFAULT_INSTANCE=new zo([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],true);createAggregator(t){return Na.DEFAULT_INSTANCE}}class ja{_boundaries;_recordMinMax;constructor(t,e=true){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);this._recordMinMax=e}createAggregator(t){return new zo(this._boundaries,this._recordMinMax)}}class Ua{_maxSize;_recordMinMax;constructor(t=160,e=true){this._maxSize=t;this._recordMinMax=e}createAggregator(t){return new ha(this._maxSize,this._recordMinMax)}}class za{_resolve(t){switch(t.type){case To.COUNTER:case To.UP_DOWN_COUNTER:case To.OBSERVABLE_COUNTER:case To.OBSERVABLE_UP_DOWN_COUNTER:{return Ba}case To.GAUGE:case To.OBSERVABLE_GAUGE:{return Fa}case To.HISTOGRAM:{if(t.advice.explicitBucketBoundaries){return new ja(t.advice.explicitBucketBoundaries)}return Ga}}Wt.warn(`Unable to recognize instrument type: ${t.type}`);return $a}createAggregator(t){return this._resolve(t).createAggregator(t)}}const $a=new La;const Ba=new Da;const Fa=new Ra;const Ga=new Na;const Va=new za;var qa;(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"})(qa||(qa={}));function Ha(t){switch(t.type){case qa.DEFAULT:return Va;case qa.DROP:return $a;case qa.SUM:return Ba;case qa.LAST_VALUE:return Fa;case qa.EXPONENTIAL_HISTOGRAM:{const e=t;return new Ua(e.options?.maxSize,e.options?.recordMinMax)}case qa.EXPLICIT_BUCKET_HISTOGRAM:{const e=t;if(e.options==null){return Ga}else{return new ja(e.options?.boundaries,e.options?.recordMinMax)}}default:throw new Error("Unsupported Aggregation")}}const Ja=t=>({type:qa.DEFAULT});const Ka=t=>Ao.CUMULATIVE;class Za{_shutdown=false;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(t){this._aggregationSelector=t?.aggregationSelector??Ja;this._aggregationTemporalitySelector=t?.aggregationTemporalitySelector??Ka;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(i.flatMap((t=>t.errors)));const n=e.resourceMetrics.resource;const s=e.resourceMetrics.scopeMetrics.concat(i.flatMap((t=>t.resourceMetrics.scopeMetrics)));return{resourceMetrics:{resource:n,scopeMetrics:s},errors:r}}async shutdown(t){if(this._shutdown){Wt.error("Cannot call shutdown twice.");return}if(t?.timeoutMillis==null){await this.onShutdown()}else{await Io(this.onShutdown(),t.timeoutMillis)}this._shutdown=true}async forceFlush(t){if(this._shutdown){Wt.warn("Cannot forceFlush on already shutdown MetricReader.");return}if(t?.timeoutMillis==null){await this.onForceFlush();return}await Io(this.onForceFlush(),t.timeoutMillis)}}class Wa extends Za{_interval;_exporter;_exportInterval;_exportTimeout;constructor(t){const{exporter:e,exportIntervalMillis:i=6e4,metricProducers:r}=t;let{exportTimeoutMillis:n=3e4}=t;super({aggregationSelector:e.selectAggregation?.bind(e),aggregationTemporalitySelector:e.selectAggregationTemporality?.bind(e),metricProducers:r});if(i<=0){throw Error("exportIntervalMillis must be greater than 0")}if(n<=0){throw Error("exportTimeoutMillis must be greater than 0")}if(i<n){if("exportIntervalMillis"in t&&"exportTimeoutMillis"in t){throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis")}else{Wt.info(`Timeout of ${n} exceeds the interval of ${i}. Clamping timeout to interval duration.`);n=i}}this._exportInterval=i;this._exportTimeout=n;this._exporter=e}async _runOnce(){try{await Io(this._doRun(),this._exportTimeout)}catch(t){if(t instanceof Oo){Wt.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);return}wa(t)}}async _doRun(){const{resourceMetrics:t,errors:e}=await this.collect({timeoutMillis:this._exportTimeout});if(e.length>0){Wt.error("PeriodicExportingMetricReader: metrics collection errors",...e)}if(t.resource.asyncAttributesPending){try{await(t.resource.waitForAsyncAttributes?.())}catch(t){Wt.debug("Error while resolving async portion of resource: ",t);wa(t)}}if(t.scopeMetrics.length===0){return}const i=await Ma._export(this._exporter,t);if(i.code!==Ta.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()}}let Xa;function Ya(){if(Xa===undefined){try{const t=globalThis.process.argv0;Xa=t?`unknown_service:${t}`:"unknown_service"}catch{Xa="unknown_service"}}return Xa}const Qa=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";class tc{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,e){const i=new tc({},e);i._rawAttributes=rc(t);i._asyncAttributesPending=t.filter((([t,e])=>Qa(e))).length>0;return i}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(Qa(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=rc(this._rawAttributes);this._schemaUrl=nc(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,Qa(i)?await i:i]}this._asyncAttributesPending=false}get attributes(){if(this.asyncAttributesPending){Wt.error("Accessing resource attributes before async attributes settled")}if(this._memoizedAttributes){return this._memoizedAttributes}const t={};for(const[e,i]of this._rawAttributes){if(Qa(i)){Wt.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=sc(this,t);const i=e?{schemaUrl:e}:undefined;return tc.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],i)}}function ec(t,e){return tc.FromAttributeList(Object.entries(t),e)}function ic(){return ec({[qe]:Ya(),[He]:xa[He],[Ke]:xa[Ke],[Ze]:xa[Ze]})}function rc(t){return t.map((([t,e])=>{if(Qa(e)){return[t,e.catch((e=>{Wt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function nc(t){if(typeof t==="string"||t===undefined){return t}Wt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t);return undefined}function sc(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}Wt.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',i,r);return undefined}class oc{_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 ac(t,e,i){if(!hc(t)){Wt.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 cc(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 uc(t,e){return Do(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}const lc=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function hc(t){return lc.test(t)}class fc{_writableMetricStorage;_descriptor;constructor(t,e){this._writableMetricStorage=t;this._descriptor=e}_record(t,e={},i=Zt.active()){if(typeof t!=="number"){Wt.warn(`non-number value provided to metric ${this._descriptor.name}: ${t}`);return}if(this._descriptor.valueType===ut.INT&&!Number.isInteger(t)){Wt.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,Ea(Date.now()))}}class dc extends fc{add(t,e,i){this._record(t,e,i)}}class pc extends fc{add(t,e,i){if(t<0){Wt.warn(`negative value provided to counter ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class mc extends fc{record(t,e,i){this._record(t,e,i)}}class bc extends fc{record(t,e,i){if(t<0){Wt.warn(`negative value provided to histogram ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class vc{_metricStorages;_descriptor;_observableRegistry;constructor(t,e,i){this._descriptor=t;this._metricStorages=e;this._observableRegistry=i}addCallback(t){this._observableRegistry.addCallback(t,this)}removeCallback(t){this._observableRegistry.removeCallback(t,this)}}class wc extends vc{}class gc extends vc{}class yc extends vc{}function xc(t){return t instanceof vc}class kc{_meterSharedState;constructor(t){this._meterSharedState=t}createGauge(t,e){const i=ac(t,To.GAUGE,e);const r=this._meterSharedState.registerMetricStorage(i);return new mc(r,i)}createHistogram(t,e){const i=ac(t,To.HISTOGRAM,e);const r=this._meterSharedState.registerMetricStorage(i);return new bc(r,i)}createCounter(t,e){const i=ac(t,To.COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new pc(r,i)}createUpDownCounter(t,e){const i=ac(t,To.UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new dc(r,i)}createObservableGauge(t,e){const i=ac(t,To.OBSERVABLE_GAUGE,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new gc(i,r,this._meterSharedState.observableRegistry)}createObservableCounter(t,e){const i=ac(t,To.OBSERVABLE_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new wc(i,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(t,e){const i=ac(t,To.OBSERVABLE_UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new yc(i,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.addBatchCallback(t,e)}removeBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.removeBatchCallback(t,e)}}class Sc{_instrumentDescriptor;constructor(t){this._instrumentDescriptor=t}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(t){this._instrumentDescriptor=ac(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:t,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class Ec{_valueMap=new Map;_keyMap=new Map;_hash;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 Ac extends Ec{constructor(){super(Mo)}}class Tc{_activeCollectionStorage=new Ac;_cumulativeMemoStorage=new Ac;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":true};_overflowHashCode;_aggregator;constructor(t,e){this._aggregator=t;this._cardinalityLimit=(e??2e3)-1;this._overflowHashCode=Mo(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 Ac;return t}}class _c{_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===Ao.CUMULATIVE){s=_c.merge(e.accumulations,n,this._aggregator)}else{s=_c.calibrateStartTime(e.accumulations,n,i)}}else{o=t.selectAggregationTemporality(e.type)}this._reportHistory.set(t,{accumulations:s,collectionTime:r,aggregationTemporality:o});const a=Mc(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 Ac;const i=this._unreportedAccumulations.get(t);this._unreportedAccumulations.set(t,[]);if(i===undefined){return e}for(const t of i){e=_c.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 Mc(t){return Array.from(t.entries())}class Cc extends Sc{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(t,e,i,r,n){super(t);this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new Tc(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new _c(e,r);this._attributesProcessor=i}record(t,e){const i=new Ac;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 Oc(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 Ic(t,e){return`\t- use valueType '${t.valueType}' on instrument creation or use an instrument name other than '${e.name}'`}function Pc(t,e){return`\t- use unit '${t.unit}' on instrument creation or use an instrument name other than '${e.name}'`}function Lc(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 Dc(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 Rc(t,e){if(t.valueType!==e.valueType){return Ic(t,e)}if(t.unit!==e.unit){return Pc(t,e)}if(t.type!==e.type){return Lc(t,e)}if(t.description!==e.description){return Dc(t,e)}return""}class Nc{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new Nc}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(uc(e,t)){if(e.description!==t.description){if(t.description.length>e.description.length){r.updateDescription(t.description)}Wt.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",Oc(e,t),"The longer description will be used.\nTo resolve the conflict:",Rc(e,t))}i=r}else{Wt.warn("A view or instrument with the name ",t.name," has already been registered and is incompatible with another registered view.\n","Details:\n",Oc(e,t),"To resolve the conflict:\n",Rc(e,t))}}return i}}class jc{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,i,r){this._backingStorages.forEach((n=>{n.record(t,e,i,r)}))}}class Uc{_buffer=new Ac;_instrumentName;_valueType;constructor(t,e){this._instrumentName=t;this._valueType=e}observe(t,e={}){if(typeof t!=="number"){Wt.warn(`non-number value provided to metric ${this._instrumentName}: ${t}`);return}if(this._valueType===ut.INT&&!Number.isInteger(t)){Wt.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 zc{_buffer=new Map;observe(t,e,i={}){if(!xc(t)){return}let r=this._buffer.get(t);if(r==null){r=new Ac;this._buffer.set(t,r)}if(typeof e!=="number"){Wt.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}if(t._descriptor.valueType===ut.INT&&!Number.isInteger(e)){Wt.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 $c{_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(xc));if(i.size===0){Wt.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(xc));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 Promise.allSettled([...i,...r]);const s=n.filter((t=>t.status==="rejected")).map((t=>t.reason));return s}_observeCallbacks(t,e){return this._callbacks.map((async({callback:i,instrument:r})=>{const n=new Uc(r._descriptor.name,r._descriptor.valueType);let s=Promise.resolve(i(n));if(e!=null){s=Io(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 zc;let s=Promise.resolve(i(n));if(e!=null){s=Io(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&&Po(i.instruments,e)))}}class Bc extends Sc{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(t,e,i,r,n){super(t);this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new Tc(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new _c(e,r);this._attributesProcessor=i}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 Fc{process(t,e){return t}}class Gc{_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 Vc(){return Hc}function qc(t){return new Gc(t)}const Hc=new Fc;class Jc{metricStorageRegistry=new Nc;observableRegistry=new $c;meter;_meterProviderSharedState;_instrumentationScope;constructor(t,e){this.meter=new kc(this);this._meterProviderSharedState=t;this._instrumentationScope=e}registerMetricStorage(t){const e=this._registerMetricStorage(t,Bc);if(e.length===1){return e[0]}return new jc(e)}registerAsyncMetricStorage(t){const e=this._registerMetricStorage(t,Cc);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.forEach((i=>{const r=i.collect(t,e);if(r!=null){s.push(r)}}));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=cc(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,Vc(),[i],o);this.metricStorageRegistry.registerForCollector(i,a);return a}));r=r.concat(n)}return r}}class Kc{viewRegistry=new oc;metricCollectors=[];meterSharedStates=new Map;resource;constructor(t){this.resource=t}getMeterSharedState(t){const e=Co(t);let i=this.meterSharedStates.get(e);if(i==null){i=new Jc(this,t);this.meterSharedStates.set(e,i)}return i}selectAggregations(t){const e=[];for(const i of this.metricCollectors){e.push([i,Ha(i.selectAggregation(t))])}return e}}class Zc{_sharedState;_metricReader;constructor(t,e){this._sharedState=t;this._metricReader=e}async collect(t){const e=Ea(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 Wc=/[\^$\\.+?()[\]{}|]/g;class Xc{_matchAll;_regexp;constructor(t){if(t==="*"){this._matchAll=true;this._regexp=/.*/}else{this._matchAll=false;this._regexp=new RegExp(Xc.escapePattern(t))}}match(t){if(this._matchAll){return true}return this._regexp.test(t)}static escapePattern(t){return`^${t.replace(Wc,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}}class Yc{_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 Qc{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new Xc(t?.name??"*");this._type=t?.type;this._unitFilter=new Yc(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class tu{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new Yc(t?.name);this._versionFilter=new Yc(t?.version);this._schemaUrlFilter=new Yc(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function eu(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}function iu(t){if(eu(t)){throw new Error("Cannot create view with no selector arguments supplied")}if(t.name!=null&&(t?.instrumentName==null||Xc.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 ru{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){iu(t);if(t.attributesProcessors!=null){this.attributesProcessor=qc(t.attributesProcessors)}else{this.attributesProcessor=Vc()}this.name=t.name;this.description=t.description;this.aggregation=Ha(t.aggregation??{type:qa.DEFAULT});this.instrumentSelector=new Qc({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit});this.meterSelector=new tu({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl});this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}}class nu{_sharedState;_shutdown=false;constructor(t){this._sharedState=new Kc(t?.resource??ic());if(t?.views!=null&&t.views.length>0){for(const e of t.views){this._sharedState.viewRegistry.addView(new ru(e))}}if(t?.readers!=null&&t.readers.length>0){for(const e of t.readers){const t=new Zc(this._sharedState,e);e.setMetricProducer(t);this._sharedState.metricCollectors.push(t)}}}getMeter(t,e="",i={}){if(this._shutdown){Wt.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){Wt.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){Wt.warn("invalid attempt to force flush after MeterProvider shutdown");return}await Promise.all(this._sharedState.metricCollectors.map((e=>e.forceFlush(t))))}}var su;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(su||(su={}));var ou;(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"})(ou||(ou={}));var au;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(au||(au={}));var cu;(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"})(cu||(cu={}));var uu;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE";t[t["LOWMEMORY"]=2]="LOWMEMORY"})(uu||(uu={}));const lu=()=>su.CUMULATIVE;const hu=t=>{switch(t){case ou.COUNTER:case ou.OBSERVABLE_COUNTER:case ou.GAUGE:case ou.HISTOGRAM:case ou.OBSERVABLE_GAUGE:return su.DELTA;case ou.UP_DOWN_COUNTER:case ou.OBSERVABLE_UP_DOWN_COUNTER:return su.CUMULATIVE}};const fu=t=>{switch(t){case ou.COUNTER:case ou.HISTOGRAM:return su.DELTA;case ou.GAUGE:case ou.UP_DOWN_COUNTER:case ou.OBSERVABLE_UP_DOWN_COUNTER:case ou.OBSERVABLE_COUNTER:case ou.OBSERVABLE_GAUGE:return su.CUMULATIVE}};function du(){const t="cumulative".toLowerCase();if(t==="cumulative"){return lu}if(t==="delta"){return hu}if(t==="lowmemory"){return fu}Wt.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${t}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);return lu}function pu(t){if(t!=null){if(t===uu.DELTA){return hu}else if(t===uu.LOWMEMORY){return fu}return lu}return du()}const mu=Object.freeze({type:cu.DEFAULT});function bu(t){return t?.aggregationPreference??(()=>mu)}class vu extends Xr{_aggregationTemporalitySelector;_aggregationSelector;constructor(t,e){super(t);this._aggregationSelector=bu(e);this._aggregationTemporalitySelector=pu(e?.temporalityPreference)}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}}class wu extends vu{constructor(t){super(Es(t??{},Wn,"v1/metrics",{"Content-Type":"application/json"}),t)}}class gu{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 wu({url:this.collectorUrl,headers:{"Content-Type":"application/json"}});this.metricReader=new Wa({exporter:t,exportIntervalMillis:this.exportIntervalMillis,exportTimeoutMillis:3e4});this.meterProvider=new nu({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 yu{services=new Map;cleanedUp=false;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 h(t.debug,t.useDocumentClassification,t.useDocumentDetector);let c=null;if(t.enableTelemetry!==false){c=new Eo({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 gu({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(){if(this.cleanedUp){return}this.cleanedUp=true;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 xu{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=xu.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 ku=":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 Su=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;classificationDisabled=false;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;_manualModeLoggedOnce=false;VIDEO_DIAGNOSTIC_EVENTS=["loadstart","loadedmetadata","loadeddata","canplay","playing","pause","stalled","suspend","abort","emptied"];canvasPool=[];MAX_CANVAS_POOL_SIZE=3;async componentWillLoad(){if(this.debug){console.log("[JAAK-DEBUG] componentWillLoad() - Props at initialization:");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector,"(type:",typeof this.useDocumentDetector,")");console.log("[JAAK-DEBUG] useDocumentClassification:",this.useDocumentClassification);console.log("[JAAK-DEBUG] debug:",this.debug);console.log("[JAAK-DEBUG] license:",this.license?this.license.substring(0,8)+"...":"EMPTY");console.log("[JAAK-DEBUG] licenseEnvironment:",this.licenseEnvironment);console.log("[JAAK-DEBUG] alignmentTolerance:",this.alignmentTolerance);console.log("[JAAK-DEBUG] maskSize:",this.maskSize);console.log("[JAAK-DEBUG] captureDelay:",this.captureDelay);console.log("[JAAK-DEBUG] preferredCamera:",this.preferredCamera);console.log("[JAAK-DEBUG] appId:",this.appId)}await new Promise((t=>setTimeout(t,50)));if(this.debug){console.log("[JAAK-DEBUG] Props AFTER 50ms wait:");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector,"(type:",typeof this.useDocumentDetector,")")}this.updateStatus("Validando licencia...","Verificando autorización de uso","initializing");await this.validateLicense();if(!this.licenseValid){if(this.debug){console.error("[JAAK-DEBUG] License validation FAILED. Stopping initialization.")}return}if(this.debug){console.log("[JAAK-DEBUG] License validation OK")}}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 yu(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 xu(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/dist/ort.wasm.min.js"}else{t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web/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 h,f;const d=this.maskSize/100;if(l<=s){f=o*d;h=f*u}else{h=s*d;f=h/u}const p=h/t.width*100;const m=f/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}}debugLog(t,e){if(!this.debug){return}if(typeof e==="undefined"){console.log(`[jaak-stamps][diag] ${t}`);return}console.log(`[jaak-stamps][diag] ${t}`,e)}debugWarn(t,e){if(!this.debug){return}if(typeof e==="undefined"){console.warn(`[jaak-stamps][diag] ${t}`);return}console.warn(`[jaak-stamps][diag] ${t}`,e)}summarizeId(t){if(!t){return null}return t.length<=8?t:`${t.slice(0,8)}...`}getCameraDevicesSnapshot(){return this.cameraService.getAvailableCameras().map((t=>({label:t.label||"(sin label)",deviceId:this.summarizeId(t.deviceId),groupId:this.summarizeId(t.groupId),kind:t.kind})))}sanitizeTrackSettings(t){if(!t){return null}return{...t,deviceId:this.summarizeId(t.deviceId),groupId:this.summarizeId(t.groupId)}}sanitizeTrackConstraints(t){if(!t){return null}const e=t.getConstraints?t.getConstraints():{};const i={...e};if(typeof i.deviceId==="string"){i.deviceId=this.summarizeId(i.deviceId)}return i}getStreamSnapshot(t){if(!t){return{hasStream:false}}const e=t.getVideoTracks()[0];if(!e){return{hasStream:true,streamActive:t.active,trackCount:t.getTracks().length,hasVideoTrack:false}}return{hasStream:true,streamActive:t.active,trackCount:t.getTracks().length,trackLabel:e.label||"(sin label)",trackEnabled:e.enabled,trackMuted:e.muted,trackReadyState:e.readyState,settings:this.sanitizeTrackSettings(e.getSettings?e.getSettings():undefined),constraints:this.sanitizeTrackConstraints(e)}}getVideoElementSnapshot(){if(!this.videoRef){return{hasVideoRef:false}}const t=this.el.ownerDocument?.defaultView?.getComputedStyle(this.videoRef);return{hasVideoRef:true,isConnected:this.videoRef.isConnected,readyState:this.videoRef.readyState,networkState:this.videoRef.networkState,paused:this.videoRef.paused,muted:this.videoRef.muted,autoplay:this.videoRef.autoplay,playsInline:this.videoRef.playsInline,currentTime:Number.isFinite(this.videoRef.currentTime)?Number(this.videoRef.currentTime.toFixed(3)):this.videoRef.currentTime,videoWidth:this.videoRef.videoWidth,videoHeight:this.videoRef.videoHeight,clientWidth:this.videoRef.clientWidth,clientHeight:this.videoRef.clientHeight,hasSrcObject:!!this.videoRef.srcObject,display:t?.display??"unknown",visibility:t?.visibility??"unknown"}}attachVideoDiagnosticListeners(){if(!this.debug||!this.videoRef){return()=>undefined}const t=this.videoRef;const e=this.VIDEO_DIAGNOSTIC_EVENTS.map((e=>{const i=()=>{this.debugLog(`video event "${e}"`,this.getVideoElementSnapshot())};t.addEventListener(e,i);return{eventName:e,handler:i}}));return()=>{e.forEach((({eventName:e,handler:i})=>{t.removeEventListener(e,i)}))}}async startDetection(){try{if(this.debug){console.log("[JAAK-DEBUG] startDetection() called");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector);console.log("[JAAK-DEBUG] useDocumentClassification:",this.useDocumentClassification)}const t=this.checkDeviceCapabilities();if(this.debug){console.log("[JAAK-DEBUG] Device capabilities:",JSON.stringify(t))}if(!t.canUseML&&this.useDocumentDetector){if(this.debug){console.warn("[JAAK-DEBUG] MANUAL MODE: Device cannot use ML. Reason:",t.reason)}this.switchToManualModeWithWarning(t.reason);return}if(!this.detectionService.isModelLoaded()){const t=performance.now();if(this.debug){console.log("[JAAK-DEBUG] Loading detection model...")}this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");this.stateManager.updateCaptureState({isLoading:true});try{await this.detectionService.loadModel();if(this.debug){console.log("[JAAK-DEBUG] Detection model loaded successfully in",(performance.now()-t).toFixed(0),"ms")}}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";if(this.debug){console.warn("[JAAK-DEBUG] MANUAL MODE: Out of memory loading detection model.",t)}this.switchToManualModeWithWarning(`Memoria insuficiente para detección automática ${t}. Modo manual activado - funciona igual de bien!`);return}else{if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Error loading detection model:",t.message)}this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");if(this.debug){console.log("[JAAK-DEBUG] Loading classification model...")}try{await this.detectionService.loadClassificationModel();if(this.debug){console.log("[JAAK-DEBUG] Classification model loaded successfully")}}catch(t){if(this.debug){console.warn("[JAAK-DEBUG] Classification model failed to load, disabling classification. Error:",t.message)}this.classificationDisabled=true}const e=performance.now();const i=e-t;if(this.debug){console.log("[JAAK-DEBUG] All models loaded in",i.toFixed(0),"ms");this.recordOnnxPerformance(i,0)}}else{if(this.debug){console.log("[JAAK-DEBUG] Models already loaded, skipping load")}}this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices();this.debugLog("step 2/5 enumerateDevices()",{cameras:this.getCameraDevicesSnapshot(),selectedCameraId:this.summarizeId(this.cameraService.getSelectedCameraId()||undefined)})}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus();this.debugLog("step 2/5 updateCameraInfoWithAutofocus()",{cameraInfo:this.cameraInfoWithAutofocus})}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();this.debugLog("step 3/5 setupCamera() resolved",{stream:this.getStreamSnapshot(e),videoRef:this.getVideoElementSnapshot()})}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{this.debugLog("step 4/5 initializeVideoStream() start",{stream:this.getStreamSnapshot(e),videoRef:this.getVideoElementSnapshot()});await this.initializeVideoStream(e);this.debugLog("step 4/5 initializeVideoStream() completed",{stream:this.getStreamSnapshot(e),videoRef:this.getVideoElementSnapshot()})}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.debugLog("step 5/5 capture loop ready",{videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(this.videoStream),useDocumentDetector:this.useDocumentDetector});this.detectFrame()}catch(t){this.debugWarn("startDetection() failed",{error:t instanceof Error?t.message:String(t),videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(this.videoStream)});console.error("[jaak-stamps] Error al preparar captura:",t);this.updateStatus("Error al iniciar","No se pudo preparar la captura","error");this.stateManager.updateCaptureState({isLoading:false})}}async initializeVideoStream(t){if(!this.videoRef){throw new Error("Video element not available")}const e=this.attachVideoDiagnosticListeners();this.debugLog("initializeVideoStream() pre-assign",{stream:this.getStreamSnapshot(t),videoRef:this.getVideoElementSnapshot()});this.videoRef.srcObject=t;this.videoStream=t;this.debugLog("initializeVideoStream() post-srcObject assignment",{stream:this.getStreamSnapshot(t),videoRef:this.getVideoElementSnapshot()});const i=this.cameraService.isRearCamera(t);this.shouldMirrorVideo=!i;const r=1e4;const n=t.getVideoTracks()[0];const s=performance.now();const o=[];const a=t=>{o.push({at:Math.round(performance.now()-s),event:t,state:n?.readyState})};const c=()=>a("mute");const u=()=>a("unmute");const l=()=>a("ended");if(n){n.addEventListener("mute",c);n.addEventListener("unmute",u);n.addEventListener("ended",l)}const h=()=>{if(!n)return;n.removeEventListener("mute",c);n.removeEventListener("unmute",u);n.removeEventListener("ended",l)};const f=()=>{const e=n?.getSettings?.();const i=this.videoRef?getComputedStyle(this.videoRef):null;return{reason:"VIDEO_METADATA_TIMEOUT",waitedMs:Math.round(performance.now()-s),stream:{videoTrackCount:t.getVideoTracks().length,audioTrackCount:t.getAudioTracks().length},track:n?{readyState:n.readyState,muted:n.muted,enabled:n.enabled,label:n.label,kind:n.kind,settings:e?{width:e.width,height:e.height,frameRate:e.frameRate,deviceId:e.deviceId,facingMode:e.facingMode}:null}:null,video:this.videoRef?{readyState:this.videoRef.readyState,networkState:this.videoRef.networkState,error:this.videoRef.error?{code:this.videoRef.error.code,message:this.videoRef.error.message}:null,paused:this.videoRef.paused,offsetWidth:this.videoRef.offsetWidth,offsetHeight:this.videoRef.offsetHeight,videoWidth:this.videoRef.videoWidth,videoHeight:this.videoRef.videoHeight,display:i?.display,visibility:i?.visibility}:null,document:{visibilityState:document.visibilityState,hasFocus:document.hasFocus()},trackEvents:o,userAgent:navigator.userAgent}};const d=async()=>{try{await this.videoRef.play()}catch(t){console.error("[jaak-stamps] video.play() failed (likely autoplay policy):",t);throw t}this.stateManager.updateCaptureState({isVideoActive:true});if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.debugLog("initializeVideoStream() finalized after play()",{stream:this.getStreamSnapshot(t),videoRef:this.getVideoElementSnapshot()})};if(this.videoRef.readyState>=1){this.debugLog("video metadata already available, skipping event wait",this.getVideoElementSnapshot());h();await d();e();return}return new Promise(((i,n)=>{let s=false;const o=()=>{this.videoRef.onloadedmetadata=null;this.videoRef.onerror=null;e()};const a=setTimeout((()=>{if(s)return;s=true;const e=f();this.debugWarn(`initializeVideoStream() timeout after ${r}ms`,{videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(t)});console.error("[jaak-stamps] Video metadata timeout diagnostics (json):",JSON.stringify(e));o();h();n(new Error(`Video metadata load timeout after ${r}ms`))}),r);this.videoRef.onloadedmetadata=async()=>{if(s)return;s=true;clearTimeout(a);this.debugLog("initializeVideoStream() onloadedmetadata fired",{videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(t)});h();try{await d();o();i()}catch(t){o();n(t)}};this.videoRef.onerror=e=>{if(s)return;s=true;clearTimeout(a);this.debugWarn("initializeVideoStream() video element emitted error",{event:e,videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(t)});o();h();n(new Error(`Video element error: ${e}`))}}))}async detectFrame(){try{const t=performance.now();const e=this.stateManager.getCaptureState();if(!this.videoRef||!this.detectionContainer||!this.detectionService.isModelLoaded()){if(this.debug){console.log("[JAAK-DEBUG] detectFrame() skipped: videoRef=",!!this.videoRef,"detectionContainer=",!!this.detectionContainer,"modelLoaded=",this.detectionService.isModelLoaded())}return}if(!this.useDocumentDetector||this.performanceDegradedMode){if(this.debug&&!this._manualModeLoggedOnce){console.warn("[JAAK-DEBUG] detectFrame() in MANUAL MODE: useDocumentDetector=",this.useDocumentDetector,"performanceDegradedMode=",this.performanceDegradedMode);this._manualModeLoggedOnce=true}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){if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Preprocess error:",t.message)}this.switchToManualModeWithError("Error al procesar imagen");return}try{u=await this.detectionService.runInference(c);l=performance.now()-a}catch(t){if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Inference error:",t.message)}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 h=this.hasDocumentDetected;this.hasDocumentDetected=u.length>0;if(!h&&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 f=performance.now();const d=f-t;if(this.useDocumentDetector&&!this.hasAutoSwitchedToManual){if(this.debug){console.log(`[JAAK-DEBUG] Frame #${this.processedFramesCount} time: ${d.toFixed(0)}ms (threshold: ${this.PERFORMANCE_THRESHOLD_MS}ms) | inference: ${l.toFixed(0)}ms | slowFrames: ${this.slowFrameCount}/${this.SLOW_FRAMES_TO_TRIGGER}`)}if(d>=this.PERFORMANCE_THRESHOLD_MS){this.slowFrameCount++;if(this.debug){console.warn(`[JAAK-DEBUG] SLOW FRAME detected: ${d.toFixed(0)}ms >= ${this.PERFORMANCE_THRESHOLD_MS}ms | slowFrameCount: ${this.slowFrameCount}/${this.SLOW_FRAMES_TO_TRIGGER}`)}if(this.slowFrameCount>=this.SLOW_FRAMES_TO_TRIGGER){if(this.debug){console.error(`[JAAK-DEBUG] MANUAL MODE: Performance degraded. ${this.slowFrameCount} slow frames (>= ${this.PERFORMANCE_THRESHOLD_MS}ms) exceeded threshold of ${this.SLOW_FRAMES_TO_TRIGGER}`)}this.switchToManualMode()}}else{if(this.slowFrameCount>0){if(this.debug){console.log(`[JAAK-DEBUG] Fast frame, resetting slowFrameCount from ${this.slowFrameCount} to 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:"958fb0a94dcab5e15b2da9b2f6e1219d85e1f03a",class:"detector-container"},!this.licenseValid&&this.licenseError&&r("div",{key:"b455ba5f14b5415d2b49c8ace3ead469cd2a7acc",class:"license-error-container"},r("div",{key:"4c1e7f980319cf125b5186e26158c37a7a97842c",class:"license-error-card"},r("svg",{key:"4c411ef193d03c543fe9298bc3aa077dcaf6b7ea",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:"24f0eb292901ee9cef24afdc2161bc69f6a51cd0",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:"e5e61abf14d9422633d1c3de9efb7d1a909c941c",d:"M12 8V12",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"}),r("circle",{key:"f5612a5748a26d33fbfa9a60ea084614f53197f9",cx:"12",cy:"16",r:"0.5",fill:"currentColor",stroke:"currentColor","stroke-width":"1"})),r("h2",{key:"5ba51ab22b3dc341a5a59661a5f4f87d6dcc4f96",class:"license-error-title"},"Licencia Requerida"),r("p",{key:"d162830f9b888ff9d179abd4d532287c3edd2b44",class:"license-error-message"},this.licenseError),r("p",{key:"8ac80117990849f03c4cac091a9642160b49c109",class:"license-error-help"},"Contacte a soporte: ",r("a",{key:"df4b871006f2d4e5f95be43b4a2c3699288d3773",href:"mailto:support@jaak.ai"},"support@jaak.ai")),r("div",{key:"aa1aacb0dc56c76cce5d6bdac373f2e64d7b3f18",class:"license-error-footer"},"JAAK Stamps"))),this.licenseValid&&r("div",{key:"0a5a3ad11c511d0d8f1b33a4a2fff32aede47277",class:"video-container"},r("video",{key:"db9c667c035c27aec76625385bb7b1ec0624736e",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{opacity:t.isVideoActive?"1":"0",visibility:t.isVideoActive?"visible":"hidden"}}),r("div",{key:"424765f58b596d8459ae903245ee8e0717eaf14a",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:"26b11d2375ac441dbd8b5eaec4f5976df4d1f0aa",class:"overlay-mask"},r("div",{key:"51d95dab401719ed84533a76e58ce00c12d4f72a",class:"card-outline"},r("div",{key:"d2b87cb68858e74340611a46ea7e3efc1691f46e",class:"side side-top"}),r("div",{key:"55ff7658fcc123535c9710133ef4d8973bca1d2e",class:"side side-right"}),r("div",{key:"0dfa4f296ff756afa2003eb4fb368d208128c47e",class:"side side-bottom"}),r("div",{key:"9aefe3fef283ee27cbe412d27a1a873cd871eb1a",class:"side side-left"})),!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"ae93e17580fe8d6efa460857011ebf36d4b162b6",class:`guide-text ${this.showPerformanceMessage?"performance-warning-text":""}`},this.getGuideText(t.step)),t.step==="back"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"a9835585d26c8819ffb12e5a278d19c89d17ec6a",class:"back-capture-section"},r("div",{key:"7563c10750eb649c337379bcd1966ebbe4c0a7be",class:"back-capture-buttons"},(!this.useDocumentDetector||this.performanceDegradedMode||this.showManualCaptureButton)&&r("button",{key:"0c44faf4123197765b0bad30f5674ce7b1cc4f00",class:"capture-button primary-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-back"&&r("span",{key:"efed4645446e3ac5189dcc909998bda49771e61d",class:"button-spinner"}),"Capturar Reverso"),r("button",{key:"7f21e533d151507cb8aefeb232e2e6924ec4a935",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button",disabled:this.processingButton!==null},this.processingButton==="skip-back"&&r("span",{key:"2634e6953b71e30b658dc632d853124f5ce5bb91",class:"button-spinner"}),this.enableBackDocumentTimer&&this.backDocumentTimerRemaining>0?`Saltar reverso (${this.backDocumentTimerRemaining}s)`:"Saltar reverso"))),t.isVideoActive&&r("div",{key:"ed8cf74950d02b58d4c8628663ec692d964757f0",class:"camera-controls"},r("button",{key:"d309850ed774ac08e63e1eb1ea0019f7c80d3db6",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:"4a70996d233bffbeac7badc52537d94453db30d3",class:"camera-selector-dropdown"},r("div",{key:"7f893af0afeff55fe63e4971d0afc24516d2b6a6",class:"camera-selector-header"},r("span",{key:"d20382742b5ee5d90f678988d0d2c1c964f615d6"},"Seleccionar Cámara"),r("button",{key:"1542d189db50740dd10e2ea843f7c5dccc5e24f2",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),r("div",{key:"e7907a23b4c7571c455f906333ccbd8e4172d3c9",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:"8615ca9b81f57bbf5d52d40fd827b79a637f5e4f",class:"device-info"},r("small",{key:"6f07c1bfb1a2b3824ccdfae4ebca11b0fa0297fe"},"Dispositivo: ",e.deviceType))),this.showManualCaptureButton&&t.step==="front"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"c1c18723517003f2bcb9f68c527a13c4e6f30095",class:"manual-capture-section"},r("button",{key:"94d21c348697cd28ecb44a5144e1e105f10e377c",class:"manual-capture-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-front"&&r("span",{key:"74333b317328ad70da763e5d127635f3b6dc13d1",class:"button-spinner"}),"Capturar Frente"))),t.isCapturing&&r("div",{key:"6761b16e393c5d496c5fde729b6b36580cfede0c",class:"capture-animation"}),t.showFlipAnimation&&r("div",{key:"7556dddec2de2c134f9b09fbd38569366c35da48",class:"flip-animation"},r("div",{key:"baa3cd8993ef761ebfb94ccda6d66896959f32ee",class:"id-card-icon"}),r("div",{key:"3c5027ada509290b9abbf599849dbd19e50113af",class:"flip-text"},"¡Voltea tu identificación!")),t.showSuccessAnimation&&r("div",{key:"1826a908ea94637428d9e800668d9ee02f0f03de",class:"success-animation"},r("div",{key:"60d8e894ceed0c5198edb67a1e3e0fa24b9aaa3b",class:"check-icon"}),r("div",{key:"106d6ccec79f64b94273baeb8984f23e71987076",class:"success-text"},"¡Proceso completado!")),r("div",{key:"804e4fe62de056dca22964283282e32336f8eb00",class:`component-status status-${this.currentStatus.type}`},(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing")&&r("div",{key:"108d6cab9eb7826cbe396806652a6b096ce0736d",class:"status-spinner"}),r("div",{key:"4abe0717c6b66b2bf44eb2da513fb6c22af31725",class:"status-content"},r("div",{key:"77fb79d89df1f9e25c3c4962235b0605c7b6237f",class:"status-message"},this.currentStatus.message),this.currentStatus.description&&r("div",{key:"2b24b09eabbbbbedd1270ebbf72f32f19ee063cb",class:"status-description"},this.currentStatus.description))),this.debug&&r("div",{key:"7c6bf594cdb26334bfe62ee09d860b19399b4fd2",class:"performance-monitor"},r("div",{key:"06f2b94e8a08e8afe94a2947d928a4c3c1ec260f",class:"performance-expanded"},r("div",{key:"c9302538e10e53e81a5685226c89a293ffd1608b",class:"metrics-row"},r("div",{key:"7499bee1d362bf9910b401c2f85961847facc9f8",class:"metric-compact"},r("span",{key:"f005aab118350af46520ece3615544976b5d533f",class:"metric-label"},"FPS"),r("span",{key:"69102a7df1fdc559883f807a8d26ae9268e56b01",class:`metric-value ${this.performanceData.fps<15?"warning":this.performanceData.fps<10?"danger":"good"}`},this.performanceData.fps)),r("div",{key:"0a63031beb60eeeb19cd50637f506661cdb1da16",class:"metric-compact"},r("span",{key:"0231014ed6f077d780252c3b822a269148675d2f",class:"metric-label"},"MEM"),r("span",{key:"859eda6914fdab077635f983fd4ca01daaf47ce7",class:`metric-value ${this.performanceData.memoryUsage>100?"warning":this.performanceData.memoryUsage>200?"danger":"good"}`},this.performanceData.memoryUsage,"MB"))),r("div",{key:"102218bc7cf2d29c3c8ef7f91febf924ecb418a3",class:"metrics-row"},r("div",{key:"205e50b3dbc43c541b76c21ef8e19a3defe065ce",class:"metric-compact"},r("span",{key:"42eace007731c4642040e33f3e20462d7e150494",class:"metric-label"},"INF"),r("span",{key:"ff2d169c660011b24fa3340479d91befc9c2d06c",class:`metric-value ${this.performanceData.inferenceTime>100?"warning":this.performanceData.inferenceTime>200?"danger":"good"}`},this.performanceData.inferenceTime,"ms")),r("div",{key:"ec3ec57e442b3aefb38acf774873b0b181731523",class:"metric-compact"},r("span",{key:"27d6d74dcdffbdafb4382c40b60f032b20dc5ade",class:"metric-label"},"FRAME"),r("span",{key:"e55795508f97a27c0b03736de2e5960560970378",class:`metric-value ${this.performanceData.frameProcessingTime>50?"warning":this.performanceData.frameProcessingTime>100?"danger":"good"}`},this.performanceData.frameProcessingTime,"ms"))),r("div",{key:"60e80821ed57f1a724409e26a232fa2792886011",class:"metrics-row"},r("div",{key:"7deb1504fb3705affaab105782ed7107d6e1a501",class:"metric-compact"},r("span",{key:"0658ce3204ce120557caa248505def48a8a205dd",class:"metric-label"},"DET"),r("span",{key:"6b14fafc3903912380edda27e5024e1221917db7",class:"metric-value good"},this.performanceData.successfulDetections,"/",this.performanceData.totalDetections)),r("div",{key:"ec602c3b4d7d8ab0ffbf165d98e8b2e7d7d0b0ec",class:"metric-compact"},r("span",{key:"9615ae1d383d383f116d2953f05ddb252336f7be",class:"metric-label"},"RATE"),r("span",{key:"eca7277e9185b9ff4232e556e707a3f1ce80365f",class:`metric-value ${this.performanceData.detectionRate<30?"danger":this.performanceData.detectionRate<60?"warning":"good"}`},this.performanceData.detectionRate,"%"))))),r("div",{key:"3b6b9368797965d5795c9752d2b4a08a9934b441",class:"watermark"},r("img",{key:"b40ffaeb6f88d1a744bffeb64ac11d4f19be6220",src:"https://static.jaak.ai/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 h=0,f=0;if(a>c){u=s;l=s/a;f=(o-l)/2}else{l=o;u=o*a;h=(s-u)/2}const d=320;const p=u/d;const m=l/d;this.detectionBoxes=t.map((t=>({x:t.x*p+h,y:t.y*m+f,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 h=r.width/r.height;let f,d;let p=0,m=0;if(l>h){f=r.width;d=r.width/l;m=(r.height-d)/2}else{d=r.height;f=r.height*l;p=(r.width-f)/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/f;const x=u/d;const k=(w-p)*y;const S=(g-m)*x;const E=b*y;const A=v*x;const T=Math.max(0,k-E/2-this.cropMargin);const _=Math.max(0,S-A/2-this.cropMargin);const M=Math.min(E+2*this.cropMargin,c-T);const C=Math.min(A+2*this.cropMargin,u-_);const O=this.getPooledCanvas(M,C);const I=O.getContext("2d",{alpha:false});I.clearRect(0,0,O.width,O.height);I.drawImage(this.videoRef,T,_,M,C,0,0,M,C);const P=this.stateManager.getCaptureState();if(P.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/jpeg"),cropped:O.toDataURL("image/jpeg")}});if(this.useDocumentClassification&&!this.classificationDisabled){try{const e=await this.detectionService.classifyDocument(O);if(e&&e.class==="passport"){this.completeProcess(true);this.returnCanvasToPool(t);this.returnCanvasToPool(O);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(P.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/jpeg"),cropped:O.toDataURL("image/jpeg")}});this.completeProcess(false);this.processingButton=null}this.returnCanvasToPool(t);this.returnCanvasToPool(O)}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 h=this.getPooledCanvas(u,l);const f=h.getContext("2d",{alpha:false});f.clearRect(0,0,h.width,h.height);f.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=h.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&&!this.classificationDisabled){try{const t=await this.detectionService.classifyDocument(h);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=h.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(h)}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}if(this.debug){console.warn("[JAAK-DEBUG] switchToManualMode() called - PERFORMANCE DEGRADED");console.warn("[JAAK-DEBUG] Cause: Slow frames exceeded threshold");console.warn("[JAAK-DEBUG] slowFrameCount:",this.slowFrameCount,"| threshold:",this.PERFORMANCE_THRESHOLD_MS,"ms | trigger:",this.SLOW_FRAMES_TO_TRIGGER)}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}if(this.debug){console.warn("[JAAK-DEBUG] switchToManualModeWithWarning() called");console.warn("[JAAK-DEBUG] Cause:",t);console.warn("[JAAK-DEBUG] deviceMemory:",navigator.deviceMemory,"| hardwareConcurrency:",navigator.hardwareConcurrency)}this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;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}if(this.debug){console.error("[JAAK-DEBUG] switchToManualModeWithError() called");console.error("[JAAK-DEBUG] Cause:",t);console.error("[JAAK-DEBUG] deviceMemory:",navigator.deviceMemory,"| hardwareConcurrency:",navigator.hardwareConcurrency)}this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;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)}}};Su.style=ku;export{Su as jaak_stamps};
|
|
7
|
-
//# sourceMappingURL=p-
|
|
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"]!==M["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 O.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(M.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);M[s]=o(e,t,C);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){O={parent:O,zone:this};try{return this._zoneDelegate.invoke(this,t,e,i,r)}finally{O=O.parent}};t.prototype.runGuarded=function(t,e,i,r){if(e===void 0){e=null}O={parent:O,zone:this};try{try{return this._zoneDelegate.invoke(this,t,e,i,r)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{O=O.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===A||n===_)){return}var h=t.state!=k;h&&r._transitionTo(k,x);var f=I;I=r;O={parent:O,zone:this};try{if(n==_&&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!==E){if(n==A||c||l&&d===y){h&&r._transitionTo(x,k,y)}else{var p=r._zoneDelegates;this._updateTaskCount(r,-1);h&&r._transitionTo(g,k,g);if(l){r._zoneDelegates=p}}}O=O.parent;I=f}};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(E,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(_,t,e,i,r,n))};t.prototype.scheduleEventTask=function(t,e,i,r,n){return this.scheduleTask(new c(A,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(E,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===A&&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}P++;try{t.runCount++;return t.zone.runTask(t,e,i)}finally{if(P==1){v()}P--}};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 h=i("then");var f=[];var d=false;var p;function m(t){if(!p){if(e[l]){p=e[l].resolve(0)}}if(p){var i=p[h];if(!i){i=p["then"]}i.call(p,t)}else{e[u](t,0)}}function b(t){if(P===0&&f.length===0){m(v)}t&&f.push(t)}function v(){if(!d){d=true;while(f.length){var t=f;f=[];for(var e=0;e<t.length;e++){var i=t[e];try{i.zone.runTask(i,null,null)}catch(t){C.onUnhandledError(t)}}}C.microtaskDrainDone();d=false}}var w={name:"NO ZONE"};var g="notScheduled",y="scheduling",x="scheduled",k="running",S="canceling",E="unknown";var T="microTask",_="macroTask",A="eventTask";var M={};var C={symbol:i,currentZoneFrame:function(){return O},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 O={parent:null,zone:new s(null,null)};var I=null;var P=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 h="removeEventListener";var f=i(l);var d=i(h);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 E(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(!_(a)){return"continue"}t[n]=function(t){var e=function(){return t.apply(this,E(arguments,i+"."+n))};U(e,t);return e}(o)}};for(var n=0;n<e.length;n++){r(n)}}function _(t){if(!t){return true}if(t.writable===false){return false}return!(typeof t.get==="function"&&typeof t.set==="undefined")}var A=typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope;var M=!("nw"in k)&&typeof k.process!=="undefined"&&k.process.toString()==="[object process]";var C=!M&&!A&&!!(y&&x["HTMLElement"]);var O=typeof k.process!=="undefined"&&k.process.toString()==="[object process]"&&!A&&!!(y&&x["HTMLElement"]);var I={};var P=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(C&&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[P]&&typeof n==="string"){t.returnValue=n}else if(n!=undefined&&!n){t.preventDefault()}}return n};function D(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 h=I[l];if(!h){h=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[h];if(typeof r==="function"){i.removeEventListener(l,L)}u===null||u===void 0?void 0:u.call(i,null);i[h]=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[h];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 R(t,e,i){if(e){for(var r=0;r<e.length;r++){D(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++){D(t,n[o],i)}}}var N=g("originalInstance");function j(t){var e=k[t];if(!e)return;k[g(t)]=e;k[t]=function(){var i=E(arguments,t);switch(i.length){case 0:this[N]=new e;break;case 1:this[N]=new e(i[0]);break;case 2:this[N]=new e(i[0],i[1]);break;case 3:this[N]=new e(i[0],i[1],i[2]);break;case 4:this[N]=new e(i[0],i[1],i[2],i[3]);break;default:throw new Error("Arg list too long.")}};U(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[N][e].apply(this[N],arguments)}}else{o(k[t].prototype,e,{set:function(i){if(typeof i==="function"){this[N][e]=v(i,t+"."+e);U(this[N][e],i)}else{this[N][e]=i}},get:function(){return this[N][e]}})}})(r)}for(r in e){if(r!=="prototype"&&e.hasOwnProperty(r)){k[t][r]=e[r]}}}function z(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(_(c)){var u=i(o,n,e);r[e]=function(){return u(this,arguments)};U(r[e],o)}}return o}function $(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=z(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 U(t,e){t[g("OriginalDelegate")]=e}var B=false;var F=false;function G(){if(B){return F}B=true;try{var t=x.navigator.userAgent;if(t.indexOf("MSIE ")!==-1||t.indexOf("Trident/")!==-1||t.indexOf("Edge/")!==-1){F=true}}catch(t){}return F}function V(t){return typeof t==="function"}function q(t){return typeof t==="number"}var H={useG:true};var J={};var K={};var Z=new RegExp("^"+b+"(\\w+)(true|false)$");var W=g("propagationStopped");function X(t,e){var i=(e?e(t):t)+m;var r=(e?e(t):t)+p;var n=b+i;var s=b+r;J[t]={};J[t][m]=n;J[t][p]=s}function Y(e,i,r,n){var s=n&&n.add||l;var o=n&&n.rm||h;var c=n&&n.listeners||"eventListeners";var u=n&&n.rmAll||"removeAllListeners";var f=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[J[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[W]===true){break}var c=y(u[l],s,r);c&&a.push(c)}}if(a.length===1){throw a[0]}else{var h=function(t){var e=a[t];i.nativeScheduleMicroTask((function(){throw e}))};for(var l=0;l<a.length;l++){h(l)}}}}var k=function(t){return x(this,t,false)};var S=function(t){return x(this,t,true)};function E(i,r){if(!i){return false}var n=true;if(r&&r.useG!==undefined){n=r.useG}var l=r&&r.vh;var h=true;if(r&&r.chkDup!==undefined){h=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[f]){return false}var E=r&&r.eventNameToString;var T={};var _=x[f]=x[s];var A=x[g(o)]=x[o];var C=x[g(c)]=x[c];var O=x[g(u)]=x[u];var I;if(r&&r.prepend){I=x[g(r.prepend)]=x[r.prepend]}function P(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 _.call(T.target,T.eventName,T.capture?S:k,T.options)};var D=function(t){if(!t.isRemoved){var e=J[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 A.call(t.target,t.eventName,t.capture?S:k,t.options)};var R=function(t){return _.call(T.target,T.eventName,t.invoke,T.options)};var N=function(t){return I.call(T.target,T.eventName,t.invoke,T.options)};var j=function(t){return A.call(t.target,t.eventName,t.invoke,t.options)};var z=n?L:R;var $=n?D:j;var B=function(t,e){var i=typeof e;return i==="function"&&t.callback===e||i==="object"&&t.originalDelegate===e};var F=(r===null||r===void 0?void 0:r.diff)||B;var G=Zone[g("UNPATCHED_EVENTS")];var V=e[g("PASSIVE_EVENTS")];function q(e){if(typeof e==="object"&&e!==null){var i=t({},e);if(e.signal){i.signal=e.signal}return i}return e}var W=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 f=arguments[0];if(r&&r.transferEventName){f=r.transferEventName(f)}var d=arguments[1];if(!d){return t.apply(this,arguments)}if(M&&f==="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(f)!==-1;var w=q(P(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(G){for(var y=0;y<G.length;y++){if(f===G[y]){if(v){return t.call(u,f,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 _=J[f];if(!_){X(f,E);_=J[f]}var A=_[x?p:m];var C=u[A];var O=false;if(C){O=true;if(h){for(var y=0;y<C.length;y++){if(F(C[y],d)){return}}}}else{C=u[A]=[]}var I;var L=u.constructor["name"];var D=K[L];if(D){I=D[f]}if(!I){I=L+i+(E?E(f):f)}T.options=w;if(k){T.options.once=false}T.target=u;T.capture=x;T.eventName=f;T.isExisting=O;var R=n?H:undefined;if(R){R.taskData=T}if(g){T.options.signal=undefined}var N=S.scheduleEventTask(I,d,R,s,o);if(g){T.options.signal=g;var j=function(){return N.zone.cancelTask(N)};t.call(g,"abort",j,{once:true});N.removeAbortListener=function(){return g.removeEventListener("abort",j)}}T.target=null;if(R){R.taskData=null}if(k){T.options.once=true}if(typeof N.options!=="boolean"){N.options=w}N.target=u;N.capture=x;N.eventName=f;if(b){N.originalDelegate=d}if(!c){C.push(N)}else{C.unshift(N)}if(a){return u}}};x[s]=W(_,d,z,$,y);if(I){x[v]=W(I,w,N,$,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 A.apply(this,arguments)}if(l&&!l(A,o,t,arguments)){return}var a=J[i];var c;if(a){c=a[s?p:m]}var u=c&&t[c];if(u){for(var h=0;h<u.length;h++){var f=u[h];if(F(f,o)){u.splice(h,1);f.isRemoved=true;if(u.length===0){f.allRemoved=true;t[c]=null;if(!s&&typeof i==="string"){var d=b+"ON_PROPERTY"+i;t[d]=null}}f.zone.cancelTask(f);if(y){return t}return}}}return A.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,E?E(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=Z.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 h=J[i];if(h){var f=h[m];var d=h[p];var b=t[f];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}};U(x[s],_);U(x[o],A);if(O){U(x[u],O)}if(C){U(x[c],C)}return true}var T=[];for(var _=0;_<r.length;_++){T[_]=E(r[_],n)}return T}function Q(t,e){if(!e){var i=[];for(var r in t){var n=Z.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=J[e];if(!c){X(e);c=J[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[W]=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(q(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=z(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 h=s[0];s[0]=function t(){try{return h.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 f=w(e,s[0],l,a,c);if(!f){return f}var d=f.data,p=d.handleId,m=d.handle,b=d.isRefreshable,v=d.isPeriodic;if(p){o[p]=f}else if(m){m[it]=f;if(b&&!v){var g=m.refresh;m.refresh=function(){var t=f.zone,e=f.state;if(e==="notScheduled"){f._state="scheduled";t._updateTaskCount(f,1)}else if(e==="running"){f._state="scheduling"}return g.call(this)}}}return(u=m!==null&&m!==void 0?m:p)!==null&&u!==void 0?u:f}else{return i.apply(t,s)}}}));s=z(t,i,(function(e){return function(i,r){var n=r[0];var s;if(q(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 h=u+s;var f=a+l;var d=a+h;n[u]={};n[u][o]=f;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);R(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(M&&!O){return}if(Zone[t.symbol("patchEvents")]){return}var i=e["__Zone_ignore_on_properties"];var r=[];if(C){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 ht(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];z(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){j("MutationObserver");j("WebKitMutationObserver")}));t.__load_patch("IntersectionObserver",(function(t,e,i){j("IntersectionObserver")}));t.__load_patch("FileReader",(function(t,e,i){j("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 h=u[f];var p=u[d];if(!h){var m=t["XMLHttpRequestEventTarget"];if(m){var b=m.prototype;h=b[f];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(!h){h=o[f];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}}};h.call(o,v,u);var l=o[i];if(!l){o[i]=t}M.apply(o,r.args);o[s]=true;return t}function k(){}function S(t){var e=t.data;e.aborted=true;return C.apply(e.target,e.args)}var E=z(u,"open",(function(){return function(t,e){t[r]=e[2]==false;t[o]=e[1];return E.apply(t,e)}}));var T="XMLHttpRequest.send";var _=g("fetchTaskAborting");var A=g("fetchTaskScheduling");var M=z(u,"send",(function(){return function(t,i){if(e.current[A]===true){return M.apply(t,i)}if(t[r]){return M.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 C=z(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[_]===true){return C.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 ft(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 h="__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 f=o("unhandledPromiseRejectionHandler");function d(t){i.onUnhandledError(t);try{var r=e[f];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 $.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 E=true;var T=false;var _=0;function A(t,e){return function(i){try{I(t,e,i)}catch(e){I(t,false,e)}}}var M=function(){var t=false;return function e(i){return function(){if(t){return}t=true;i.apply(null,arguments)}}};var C="Promise resolved with itself";var O=o("currentTaskTrace");function I(t,r,o){var u=M();if(t===o){throw new TypeError(C)}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 $&&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(A(t,r)),u(A(t,false)))}catch(e){u((function(){I(t,false,e)}))()}}else{t[v]=r;var f=t[w];t[w]=o;if(t[g]===g){if(r===E){t[v]=t[x];t[w]=t[y]}}if(r===T&&o instanceof Error){var d=e.currentTask&&e.currentTask.data&&e.currentTask.data[h];if(d){n(o,O,{configurable:true,enumerable:false,writable:true,value:d})}}for(var p=0;p<f.length;){D(t,f[p++],f[p++],f[p++],f[p++])}if(f.length==0&&r==T){t[v]=_;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 P=o("rejectionHandledHandler");function L(t){if(t[v]===_){try{var i=e[P];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 D(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 R="function ZoneAwarePromise() { [native code] }";var N=function(){};var j=t.AggregateError;var $=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=M();e&&e(r(A(i,E)),r(A(i,T)))}catch(t){I(i,false,t)}}t.toString=function(){return R};t.resolve=function(e){if(e instanceof t){return e}return I(new this(null),E,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 j([],"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 j([],"All promises were rejected"))}if(r===0){return Promise.reject(new j([],"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 j(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,h=t;l<h.length;l++){var f=h[l];c(f)}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(N);var a=e.current;if(this[v]==S){this[w].push(a,o,i,r)}else{D(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(N);s[g]=g;var o=e.current;if(this[v]==S){this[w].push(o,s,i,i)}else{D(this,o,s,i,i)}return s};return t}();$["resolve"]=$.resolve;$["reject"]=$.reject;$["race"]=$.race;$["all"]=$.all;var U=t[u]=t["Promise"];t["Promise"]=$;var B=o("thenPatched");function F(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 $((function(t,e){n.call(i,t,e)}));return r.then(t,e)};t[B]=true}i.patchThen=F;function G(t){return function(e,i){var r=t.apply(e,i);if(r instanceof $){return r}var n=r.constructor;if(!n[B]){F(n)}return r}}if(U){F(U);z(t,"fetch",(function(t){return G(t)}))}Promise[e.__symbol__("uncaughtPromiseErrors")]=a;return $}))}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=R;i.patchMethod=z;i.bindArguments=E;i.patchMacroTask=$;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=Y;i.isIEOrEdge=G;i.ObjectDefineProperty=o;i.ObjectGetOwnPropertyDescriptor=s;i.ObjectCreate=c;i.ArraySlice=u;i.patchClass=j;i.wrapWithCurrentZone=v;i.filterProperties=at;i.attachOriginToPatched=U;i._redefineProperty=Object.defineProperty;i.patchCallbacks=pt;i.getGlobalObjects=function(){return{globalSources:K,zoneSymbolEventNames:J,eventNames:r,isBrowser:C,isMix:O,isNode:M,TRUE_STR:p,FALSE_STR:m,ZONE_SYMBOL_PREFIX:b,ADD_EVENT_LISTENER_STR:l,REMOVE_EVENT_LISTENER_STR:h}}}))}function bt(t){ft(t);dt(t);mt(t)}var vt=n();bt(vt);ht(vt)}));return Is}Ls();class Ds{emit(t){}}const Rs=new Ds;class Ns{getLogger(t,e,i){return new Ds}}const js=new Ns;class zs{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 Rs}this._delegate=t;return this._delegate}}class $s{getLogger(t,e,i){var r;return(r=this._getDelegateLogger(t,e,i))!==null&&r!==void 0?r:new zs(this,t,e,i)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:js}_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 Us=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};const Bs=Symbol.for("io.opentelemetry.js.api.logs");const Fs=Us;function Gs(t,e,i){return r=>r===t?e:i}const Vs=1;class qs{constructor(){this._proxyLoggerProvider=new $s}static getInstance(){if(!this._instance){this._instance=new qs}return this._instance}setGlobalLoggerProvider(t){if(Fs[Bs]){return this.getLoggerProvider()}Fs[Bs]=Gs(Vs,t,js);this._proxyLoggerProvider._setDelegate(t);return t}getLoggerProvider(){var t,e;return(e=(t=Fs[Bs])===null||t===void 0?void 0:t.call(Fs,Vs))!==null&&e!==void 0?e:this._proxyLoggerProvider}getLogger(t,e,i){return this.getLoggerProvider().getLogger(t,e,i)}disable(){delete Fs[Bs];this._proxyLoggerProvider=new $s}}const Hs=qs.getInstance();function Js(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 Ks(t){t.forEach((t=>t.disable()))}function Zs(t){const e=t.tracerProvider||me.getTracerProvider();const i=t.meterProvider||ie.getMeterProvider();const r=t.loggerProvider||Hs.getLoggerProvider();const n=t.instrumentations?.flat()??[];Js(n,e,i,r);return()=>{Ks(n)}}let Ws=console.error.bind(console);function Xs(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 Ys=(t,e,i)=>{if(!t||!t[e]){Ws("no original function "+String(e)+" to wrap");return}if(!i){Ws("no wrapper function");Ws((new Error).stack);return}const r=t[e];if(typeof r!=="function"||typeof i!=="function"){Ws("original object and wrapper must be functions");return}const n=i(r,e);Xs(n,"__original",r);Xs(n,"__unwrap",(()=>{if(t[e]===n){Xs(t,e,r)}}));Xs(n,"__wrapped",true);Xs(t,e,n);return n};const Qs=(t,e,i)=>{if(!t){Ws("must provide one or more modules to patch");Ws((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Ws("must provide one or more functions to wrap on modules");return}t.forEach((t=>{e.forEach((e=>{Ys(t,e,i)}))}))};const to=(t,e)=>{if(!t||!t[e]){Ws("no function to unwrap.");Ws((new Error).stack);return}const i=t[e];if(!i.__unwrap){Ws("no original to unwrap to -- has "+String(e)+" already been unwrapped?")}else{i.__unwrap();return}};const eo=(t,e)=>{if(!t){Ws("must provide one or more modules to patch");Ws((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Ws("must provide one or more functions to unwrap on modules");return}t.forEach((t=>{e.forEach((e=>{to(t,e)}))}))};class io{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(t,e,i){this.instrumentationName=t;this.instrumentationVersion=e;this.setConfig(i);this._diag=Xt.createComponentLogger({namespace:t});this._tracer=me.getTracer(t,e);this._meter=ie.getMeter(t,e);this._logger=Hs.getLogger(t,e);this._updateMetricInstruments()}_wrap=Ys;_unwrap=to;_massWrap=Qs;_massUnwrap=eo;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 ro extends io{constructor(t,e,i){super(t,e,i);if(this._config.enabled){this.enable()}}}function no(t){return typeof t==="function"&&typeof t.__original==="function"&&typeof t.__unwrap==="function"&&t.__wrapped===true}var so;(function(t){t["EVENT_TYPE"]="event_type";t["TARGET_ELEMENT"]="target_element";t["TARGET_XPATH"]="target_xpath";t["HTTP_URL"]="http.url"})(so||(so={}));const oo="0.53.0";const ao="@opentelemetry/instrumentation-user-interaction";const co="OT_ZONE_CONTEXT";const uo="Navigation:";const lo=["click"];function ho(){return false}class fo extends ro{version=oo;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(t={}){super(ao,oo,t);this._eventNames=new Set(t?.eventNames??lo);this._shouldPreventSpanCreation=typeof t?.shouldPreventSpanCreation==="function"?t.shouldPreventSpanCreation:ho}init(){}_checkForTimeout(t,e){const i=this._spansData.get(e);if(i){if(t.source==="setTimeout"){i.hrTimeLastTimeout=si()}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=Zr(t,true);try{const n=this.tracer.startSpan(e,{attributes:{[so.EVENT_TYPE]:e,[so.TARGET_ELEMENT]:t.tagName,[so.TARGET_XPATH]:r,[so.HTTP_URL]:window.location.href}},i?me.setSpan(Wt.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(co);if(e){return me.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 Wt.with(me.setSpan(Wt.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(no(history.replaceState))this._unwrap(history,"replaceState");if(no(history.pushState))this._unwrap(history,"pushState");if(no(history.back))this._unwrap(history,"back");if(no(history.forward))this._unwrap(history,"forward");if(no(history.go))this._unwrap(history,"go")}_updateInteractionName(t){const e=me.getSpan(Wt.active());if(e&&typeof e.updateName==="function"){e.updateName(`${uo} ${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 Wt.with(me.setSpan(Wt.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(no(t.prototype.runTask)){this._unwrap(t.prototype,"runTask");this._diag.debug("removing previous patch from method runTask")}if(no(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask");this._diag.debug("removing previous patch from method scheduleTask")}if(no(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(no(t.addEventListener)){this._unwrap(t,"addEventListener");this._diag.debug("removing previous patch from method addEventListener")}if(no(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(no(t.prototype.runTask)){this._unwrap(t.prototype,"runTask")}if(no(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask")}if(no(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask")}}else{const t=this._getPatchableEventTargets();t.forEach((t=>{if(no(t.addEventListener)){this._unwrap(t,"addEventListener")}if(no(t.removeEventListener)){this._unwrap(t,"removeEventListener")}}))}this._unpatchHistoryApi()}_getZoneWithPrototype(){const t=window;return t.Zone}}var po={exports:{}};var mo=po.exports;var bo;function vo(){if(bo)return po.exports;bo=1;(function(t,e){(function(i,r){var n="1.0.41",s="",o="?",a="function",c="undefined",u="object",l="string",h="major",f="model",d="name",p="type",m="vendor",b="version",v="architecture",w="console",g="mobile",y="tablet",x="smarttv",k="wearable",S="embedded",E=500;var T="Amazon",_="Apple",A="ASUS",M="BlackBerry",C="Browser",O="Chrome",I="Edge",P="Firefox",L="Google",D="Honor",R="Huawei",N="Lenovo",j="LG",z="Microsoft",$="Motorola",U="Nvidia",B="OnePlus",F="Opera",G="OPPO",V="Samsung",q="Sharp",H="Sony",J="Xiaomi",K="Zebra",Z="Facebook",W="Chromium OS",X="Mac OS",Y=" 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,E)}};var st=function(t,e){var i=0,n,s,o,c,l,h;while(i<e.length&&!l){var f=e[i],d=e[i+1];n=s=0;while(n<f.length&&!l){if(!f[n]){break}l=f[n++].exec(t);if(!!l){for(o=0;o<d.length;o++){h=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,h)}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]]=h?c[1].call(this,h,c[2]):r}else{this[c[0]]=h?h.replace(c[1],c[2]):r}}else if(c.length===4){this[c[0]]=h?c[3].call(this,h.replace(c[1],c[2])):r}}else{this[c]=h?h: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,F+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[b,[d,F+" GX"]],[/\bopr\/([\w\.]+)/i],[b,[d,F]],[/\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"+C]],[/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 "+C]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+C],b],[/\bfocus\/([\w\.]+)/i],[b,[d,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[b,[d,F+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[b,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[b,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[b,[d,F+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[b,[d,"MIUI"+Y]],[/fxios\/([\w\.-]+)/i],[b,[d,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[b,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],b],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+Y],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,Z],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,O+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,O+" WebView"],b],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[b,[d,"Android "+C]],[/(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,P+" 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],[f,[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],[f,[m,V],[p,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[f,[m,_],[p,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[f,[m,_],[p,y]],[/(macintosh);/i],[f,[m,_]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[f,[m,q],[p,g]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[f,[m,D],[p,y]],[/honor([-\w ]+)[;\)]/i],[f,[m,D],[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],[f,[m,R],[p,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[f,[m,R],[p,g]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[f,/_/g," "],[m,J],[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],[[f,/_/g," "],[m,J],[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],[f,[m,G],[p,g]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[f,[m,ot,{OnePlus:["304","403","203"],"*":G}],[p,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[f,[m,"Vivo"],[p,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[f,[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],[f,[m,$],[p,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[f,[m,$],[p,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[f,[m,j],[p,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[f,[m,j],[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],[f,[m,N],[p,y]],[/(nokia) (t[12][01])/i],[m,f,[p,y]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[f,/_/g," "],[p,g],[m,"Nokia"]],[/(pixel (c|tablet))\b/i],[f,[m,L],[p,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[f,[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],[f,[m,H],[p,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[f,"Xperia Tablet"],[m,H],[p,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[f,[m,B],[p,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[f,[m,T],[p,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[f,/(.+)/g,"Fire Phone $1"],[m,T],[p,g]],[/(playbook);[-\w\),; ]+(rim)/i],[f,m,[p,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[f,[m,M],[p,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[f,[m,A],[p,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[f,[m,A],[p,g]],[/(nexus 9)/i],[f,[m,"HTC"],[p,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[m,[f,/_/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],[f,[m,"TCL"],[p,y]],[/(itel) ((\w+))/i],[[m,it],f,[p,ot,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[f,[m,"Acer"],[p,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[f,[m,"Meizu"],[p,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[f,[m,"Ulefone"],[p,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[f,[m,"Energizer"],[p,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[f,[m,"Cat"],[p,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[f,[m,"Smartfren"],[p,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[f,[m,"Nothing"],[p,g]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[f,[m,"Archos"],[p,y]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[f,[m,"Archos"],[p,g]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[m,f,[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,f,[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,f,[p,y]],[/(surface duo)/i],[f,[m,z],[p,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[f,[m,"Fairphone"],[p,g]],[/(u304aa)/i],[f,[m,"AT&T"],[p,g]],[/\bsie-(\w*)/i],[f,[m,"Siemens"],[p,g]],[/\b(rct\w+) b/i],[f,[m,"RCA"],[p,y]],[/\b(venue[\d ]{2,7}) b/i],[f,[m,"Dell"],[p,y]],[/\b(q(?:mv|ta)\w+) b/i],[f,[m,"Verizon"],[p,y]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[f,[m,"Barnes & Noble"],[p,y]],[/\b(tm\d{3}\w+) b/i],[f,[m,"NuVision"],[p,y]],[/\b(k88) b/i],[f,[m,"ZTE"],[p,y]],[/\b(nx\d{3}j) b/i],[f,[m,"ZTE"],[p,g]],[/\b(gen\d{3}) b.+49h/i],[f,[m,"Swiss"],[p,g]],[/\b(zur\d{3}) b/i],[f,[m,"Swiss"],[p,y]],[/\b((zeki)?tb.*\b) b/i],[f,[m,"Zeki"],[p,y]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[m,"Dragon Touch"],f,[p,y]],[/\b(ns-?\w{0,9}) b/i],[f,[m,"Insignia"],[p,y]],[/\b((nxa|next)-?\w{0,9}) b/i],[f,[m,"NextBook"],[p,y]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[m,"Voice"],f,[p,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[m,"LvTel"],f,[p,g]],[/\b(ph-1) /i],[f,[m,"Essential"],[p,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[f,[m,"Envizen"],[p,y]],[/\b(trio[-\w\. ]+) b/i],[f,[m,"MachSpeed"],[p,y]],[/\btu_(1491) b/i],[f,[m,"Rotor"],[p,y]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[f,[m,U],[p,y]],[/(sprint) (\w+)/i],[m,f,[p,g]],[/(kin\.[onetw]{3})/i],[[f,/\./g," "],[m,z],[p,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[f,[m,K],[p,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[f,[m,K],[p,g]],[/smart-tv.+(samsung)/i],[m,[p,x]],[/hbbtv.+maple;(\d+)/i],[[f,/^/,"SmartTV"],[m,V],[p,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[m,j],[p,x]],[/(apple) ?tv/i],[m,[f,_+" TV"],[p,x]],[/crkey/i],[[f,O+"cast"],[m,L],[p,x]],[/droid.+aft(\w+)( bui|\))/i],[f,[m,T],[p,x]],[/(shield \w+ tv)/i],[f,[m,U],[p,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[f,[m,q],[p,x]],[/(bravia[\w ]+)( bui|\))/i],[f,[m,H],[p,x]],[/(mi(tv|box)-?\w+) bui/i],[f,[m,J],[p,x]],[/Hbbtv.*(technisat) (.*);/i],[m,f,[p,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[m,nt],[f,nt],[p,x]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[f,[p,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[p,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[m,f,[p,w]],[/droid.+; (shield)( bui|\))/i],[f,[m,U],[p,w]],[/(playstation \w+)/i],[f,[m,H],[p,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[f,[m,z],[p,w]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[f,[m,V],[p,k]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[m,f,[p,k]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[f,[m,G],[p,k]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[f,[m,_],[p,k]],[/(opwwe\d{3})/i],[f,[m,B],[p,k]],[/(moto 360)/i],[f,[m,$],[p,k]],[/(smartwatch 3)/i],[f,[m,H],[p,k]],[/(g watch r)/i],[f,[m,j],[p,k]],[/droid.+; (wt63?0{2,3})\)/i],[f,[m,K],[p,k]],[/droid.+; (glass) \d/i],[f,[m,L],[p,k]],[/(pico) (4|neo3(?: link|pro)?)/i],[m,f,[p,k]],[/; (quest( \d| pro)?)/i],[f,[m,Z],[p,k]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[m,[p,S]],[/(aeobc)\b/i],[f,[m,T],[p,S]],[/(homepod).+mac os/i],[f,[m,_],[p,S]],[/windows iot/i],[[p,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[f,[p,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[f,[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],[f,[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,X],[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,M]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[b,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[b,[d,P+" 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,O+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,W],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[h]=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[f]=r;t[p]=r;st.call(t,o,x.device);if(k&&!t[p]&&w&&w.mobile){t[p]=g}if(k&&t[f]=="Macintosh"&&n&&typeof n.standalone!==c&&n.maxTouchPoints&&n.maxTouchPoints>2){t[f]="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,W).replace(/macos/i,X)}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>E?nt(t,E):t;return this};this.setUA(o);return this};lt.VERSION=n;lt.BROWSER=tt([d,b,h]);lt.CPU=tt([v]);lt.DEVICE=tt([f,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 ht=typeof i!==c&&(i.jQuery||i.Zepto);if(ht&&!ht.ua){var ft=new lt;ht.ua=ft.getResult();ht.ua.get=function(){return ft.getUA()};ht.ua.set=function(t){ft.setUA(t);var e=ft.getResult();for(var i in e){ht.ua[i]=e[i]}}}})(typeof window==="object"?window:mo)})(po,po.exports);return po.exports}var wo=vo();var go=fn(wo);const yo="service.name";const xo="service.version";const ko="eAzROSTiqNd3i+M9Jw6q5Tld0jarZc617sJB//pvb5c=";let So=false;function Eo(){if(So){return}So=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 ${ko}`)}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 ${ko}`);i={...i,headers:t}}return e.call(this,t,i)};navigator.sendBeacon=function(){return false}}class To{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 go}initialize(){try{Eo();const t=new As({url:this.collectorUrl,headers:{"Content-Type":"application/json",Authorization:`Bearer ${ko}`},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 Rr(e,{maxQueueSize:100,maxExportBatchSize:10,scheduledDelayMillis:5e3,exportTimeoutMillis:3e4});this.provider=new Kr({spanProcessors:[this.spanProcessor]});const i=new Os;const r=new Ri;this.provider.register({contextManager:i,propagator:r});this.tracer=me.getTracer(this.serviceName,this.serviceVersion);if(this.enableAutoInstrumentation){this.initializeAutoInstrumentation()}}catch(t){console.error("[TracingService] Failed to initialize:",t)}}initializeAutoInstrumentation(){try{Zs({instrumentations:[new fo({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 me.getTracer("noop").startSpan("noop")}try{let i=Wt.active();if(this.sessionTraceId&&!me.getSpan(i)){const t={traceId:this.sessionTraceId,spanId:this.generateSpanId(),traceFlags:xt.SAMPLED,isRemote:true};const e=me.wrapSpanContext(t);i=me.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",[yo]:this.serviceName,[xo]: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 me.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:Zt.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 Wt.with(me.setSpan(Wt.active(),r),(async()=>await e()));r.setStatus({code:Zt.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=me.getSpan(Wt.active());return t?.spanContext().traceId}catch{return undefined}}getCurrentSpanId(){try{const t=me.getSpan(Wt.active());return t?.spanContext().spanId}catch{return undefined}}}var _o;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(_o||(_o={}));var Ao;(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"})(Ao||(Ao={}));var Mo;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(Mo||(Mo={}));function Co(t){let e=Object.keys(t);if(e.length===0)return"";e=e.sort();return JSON.stringify(e.map((e=>[e,t[e]])))}function Oo(t){return`${t.name}:${t.version??""}:${t.schemaUrl??""}`}class Io extends Error{constructor(t){super(t);Object.setPrototypeOf(this,Io.prototype)}}function Po(t,e){let i;const r=new Promise((function t(r,n){i=setTimeout((function t(){n(new Io("Operation timed out."))}),e)}));return Promise.race([t,r]).then((t=>{clearTimeout(i);return t}),(t=>{clearTimeout(i);throw t}))}function Lo(t,e){if(t.size!==e.size){return false}for(const i of t){if(!e.has(i)){return false}}return true}function Do(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 Ro(t,e){return t.toLowerCase()===e.toLowerCase()}var No;(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"})(No||(No={}));class jo{kind=No.DROP;createAccumulation(){return undefined}merge(t,e){return undefined}diff(t,e){return undefined}toMetricData(t,e,i,r){return undefined}}function zo(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 $o{startTime;_boundaries;_recordMinMax;_current;constructor(t,e,i=true,r=zo(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=Do(this._boundaries,t);this._current.buckets.counts[e]+=1}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Uo{kind=No.HISTOGRAM;_boundaries;_recordMinMax;constructor(t,e){this._boundaries=t;this._recordMinMax=e}createAccumulation(t){return new $o(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 $o(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 $o(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:Mo.HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===Ao.GAUGE||t.type===Ao.UP_DOWN_COUNTER||t.type===Ao.OBSERVABLE_GAUGE||t.type===Ao.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 Bo{backing;indexBase;indexStart;indexEnd;constructor(t=new Fo,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 Bo(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 Fo{_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 Fo([...this._counts])}}const Go=52;const Vo=2146435072;const qo=1048575;const Ho=1023;const Jo=-1023+1;const Ko=Ho;const Zo=Math.pow(2,-1022);function Wo(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=(i&Vo)>>20;return r-Ho}function Xo(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&qo)*Math.pow(2,32);return n+r}function Yo(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 Qo(t){t--;t|=t>>1;t|=t>>2;t|=t>>4;t|=t>>8;t|=t>>16;t++;return t}class ta extends Error{}class ea{_shift;constructor(t){this._shift=-t}mapToIndex(t){if(t<Zo){return this._minNormalLowerBoundaryIndex()}const e=Wo(t);const i=this._rightShift(Xo(t)-1,Go);return e+i>>this._shift}lowerBoundary(t){const e=this._minNormalLowerBoundaryIndex();if(t<e){throw new ta(`underflow: ${t} is < minimum lower boundary: ${e}`)}const i=this._maxNormalLowerBoundaryIndex();if(t>i){throw new ta(`overflow: ${t} is > maximum lower boundary: ${i}`)}return Yo(1,t<<this._shift)}get scale(){if(this._shift===0){return 0}return-this._shift}_minNormalLowerBoundaryIndex(){let t=Jo>>this._shift;if(this._shift<2){t--}return t}_maxNormalLowerBoundaryIndex(){return Ko>>this._shift}_rightShift(t,e){return Math.floor(t*Math.pow(2,-e))}}class ia{_scale;_scaleFactor;_inverseFactor;constructor(t){this._scale=t;this._scaleFactor=Yo(Math.LOG2E,t);this._inverseFactor=Yo(Math.LN2,-t)}mapToIndex(t){if(t<=Zo){return this._minNormalLowerBoundaryIndex()-1}if(Xo(t)===0){const e=Wo(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 ta(`overflow: ${t} is > maximum lower boundary: ${e}`)}const i=this._minNormalLowerBoundaryIndex();if(t<=i){if(t===i){return Zo}else if(t===i-1){return Math.exp((t+(1<<this._scale))/this._scaleFactor)/2}throw new ta(`overflow: ${t} is < minimum lower boundary: ${i}`)}return Math.exp(t*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Jo<<this._scale}_maxNormalLowerBoundaryIndex(){return(Ko+1<<this._scale)-1}}const ra=-10;const na=20;const sa=Array.from({length:31},((t,e)=>{if(e>10){return new ia(e-10)}return new ea(e-10)}));function oa(t){if(t>na||t<ra){throw new ta(`expected scale >= ${ra} && <= ${na}, got: ${t}`)}return sa[t+10]}class aa{static combine(t,e){return new aa(Math.min(t.low,e.low),Math.max(t.high,e.high))}low;high;constructor(t,e){this.low=t;this.high=e}}const ca=20;const ua=160;const la=2;class ha{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(t,e=ua,i=true,r=0,n=0,s=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new Bo,u=new Bo,l=oa(ca)){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<la){Xt.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${la}`);this._maxSize=la}}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 ha(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=Qo(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=oa(e)}_minScale(t){const e=Math.min(this.scale,t.scale);const i=aa.combine(this._highLowAtScale(this.positive,this.scale,e),this._highLowAtScale(t.positive,t.scale,e));const r=aa.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 aa(0,-1)}const r=e-i;return new aa(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 fa{kind=No.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(t,e){this._maxSize=t;this._recordMinMax=e}createAccumulation(t){return new ha(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:Mo.EXPONENTIAL_HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===Ao.GAUGE||t.type===Ao.UP_DOWN_COUNTER||t.type===Ao.OBSERVABLE_GAUGE||t.type===Ao.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}}}))}}}const da=B("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function pa(t){return t.setValue(da,true)}function ma(){return t=>{Xt.error(ba(t))}}function ba(t){if(typeof t==="string"){return t}else{return JSON.stringify(va(t))}}function va(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 wa=ma();function ga(t){try{wa(t)}catch{}}const ya="2.6.0";const xa="process.runtime.name";const ka={[Ze]:"opentelemetry",[xa]:"browser",[Je]:Ke,[We]:ya};const Sa=6;const Ea=Math.pow(10,Sa);function Ta(t){const e=t/1e3;const i=Math.trunc(e);const r=Math.round(t%1e3*Ea);return[i,r]}function _a(t){return t[0]*1e6+t[1]/1e3}var Aa;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(Aa||(Aa={}));function Ma(t,e){return new Promise((i=>{Wt.with(pa(Wt.active()),(()=>{t.export(e,i)}))}))}const Ca={_export:Ma};class Oa{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=Ta(Date.now())}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Ia{kind=No.LAST_VALUE;createAccumulation(t){return new Oa(t)}merge(t,e){const i=_a(e.sampleTime)>=_a(t.sampleTime)?e:t;return new Oa(t.startTime,i.toPointValue(),i.sampleTime)}diff(t,e){const i=_a(e.sampleTime)>=_a(t.sampleTime)?e:t;return new Oa(e.startTime,i.toPointValue(),i.sampleTime)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:Mo.GAUGE,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()})))}}}class Pa{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 La{kind=No.SUM;monotonic;constructor(t){this.monotonic=t}createAccumulation(t){return new Pa(t,this.monotonic)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();if(e.reset){return new Pa(e.startTime,this.monotonic,r,e.reset)}return new Pa(t.startTime,this.monotonic,i+r)}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();if(this.monotonic&&i>r){return new Pa(e.startTime,this.monotonic,r,true)}return new Pa(e.startTime,this.monotonic,r-i)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:Mo.SUM,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()}))),isMonotonic:this.monotonic}}}class Da{static DEFAULT_INSTANCE=new jo;createAggregator(t){return Da.DEFAULT_INSTANCE}}class Ra{static MONOTONIC_INSTANCE=new La(true);static NON_MONOTONIC_INSTANCE=new La(false);createAggregator(t){switch(t.type){case Ao.COUNTER:case Ao.OBSERVABLE_COUNTER:case Ao.HISTOGRAM:{return Ra.MONOTONIC_INSTANCE}default:{return Ra.NON_MONOTONIC_INSTANCE}}}}class Na{static DEFAULT_INSTANCE=new Ia;createAggregator(t){return Na.DEFAULT_INSTANCE}}class ja{static DEFAULT_INSTANCE=new Uo([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],true);createAggregator(t){return ja.DEFAULT_INSTANCE}}class za{_boundaries;_recordMinMax;constructor(t,e=true){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);this._recordMinMax=e}createAggregator(t){return new Uo(this._boundaries,this._recordMinMax)}}class $a{_maxSize;_recordMinMax;constructor(t=160,e=true){this._maxSize=t;this._recordMinMax=e}createAggregator(t){return new fa(this._maxSize,this._recordMinMax)}}class Ua{_resolve(t){switch(t.type){case Ao.COUNTER:case Ao.UP_DOWN_COUNTER:case Ao.OBSERVABLE_COUNTER:case Ao.OBSERVABLE_UP_DOWN_COUNTER:{return Fa}case Ao.GAUGE:case Ao.OBSERVABLE_GAUGE:{return Ga}case Ao.HISTOGRAM:{if(t.advice.explicitBucketBoundaries){return new za(t.advice.explicitBucketBoundaries)}return Va}}Xt.warn(`Unable to recognize instrument type: ${t.type}`);return Ba}createAggregator(t){return this._resolve(t).createAggregator(t)}}const Ba=new Da;const Fa=new Ra;const Ga=new Na;const Va=new ja;const qa=new Ua;var Ha;(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"})(Ha||(Ha={}));function Ja(t){switch(t.type){case Ha.DEFAULT:return qa;case Ha.DROP:return Ba;case Ha.SUM:return Fa;case Ha.LAST_VALUE:return Ga;case Ha.EXPONENTIAL_HISTOGRAM:{const e=t;return new $a(e.options?.maxSize,e.options?.recordMinMax)}case Ha.EXPLICIT_BUCKET_HISTOGRAM:{const e=t;if(e.options==null){return Va}else{return new za(e.options?.boundaries,e.options?.recordMinMax)}}default:throw new Error("Unsupported Aggregation")}}const Ka=t=>({type:Ha.DEFAULT});const Za=t=>_o.CUMULATIVE;class Wa{_shutdown=false;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(t){this._aggregationSelector=t?.aggregationSelector??Ka;this._aggregationTemporalitySelector=t?.aggregationTemporalitySelector??Za;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(i.flatMap((t=>t.errors)));const n=e.resourceMetrics.resource;const s=e.resourceMetrics.scopeMetrics.concat(i.flatMap((t=>t.resourceMetrics.scopeMetrics)));return{resourceMetrics:{resource:n,scopeMetrics:s},errors:r}}async shutdown(t){if(this._shutdown){Xt.error("Cannot call shutdown twice.");return}if(t?.timeoutMillis==null){await this.onShutdown()}else{await Po(this.onShutdown(),t.timeoutMillis)}this._shutdown=true}async forceFlush(t){if(this._shutdown){Xt.warn("Cannot forceFlush on already shutdown MetricReader.");return}if(t?.timeoutMillis==null){await this.onForceFlush();return}await Po(this.onForceFlush(),t.timeoutMillis)}}class Xa extends Wa{_interval;_exporter;_exportInterval;_exportTimeout;constructor(t){const{exporter:e,exportIntervalMillis:i=6e4,metricProducers:r}=t;let{exportTimeoutMillis:n=3e4}=t;super({aggregationSelector:e.selectAggregation?.bind(e),aggregationTemporalitySelector:e.selectAggregationTemporality?.bind(e),metricProducers:r});if(i<=0){throw Error("exportIntervalMillis must be greater than 0")}if(n<=0){throw Error("exportTimeoutMillis must be greater than 0")}if(i<n){if("exportIntervalMillis"in t&&"exportTimeoutMillis"in t){throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis")}else{Xt.info(`Timeout of ${n} exceeds the interval of ${i}. Clamping timeout to interval duration.`);n=i}}this._exportInterval=i;this._exportTimeout=n;this._exporter=e}async _runOnce(){try{await Po(this._doRun(),this._exportTimeout)}catch(t){if(t instanceof Io){Xt.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);return}ga(t)}}async _doRun(){const{resourceMetrics:t,errors:e}=await this.collect({timeoutMillis:this._exportTimeout});if(e.length>0){Xt.error("PeriodicExportingMetricReader: metrics collection errors",...e)}if(t.resource.asyncAttributesPending){try{await(t.resource.waitForAsyncAttributes?.())}catch(t){Xt.debug("Error while resolving async portion of resource: ",t);ga(t)}}if(t.scopeMetrics.length===0){return}const i=await Ca._export(this._exporter,t);if(i.code!==Aa.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()}}let Ya;function Qa(){if(Ya===undefined){try{const t=globalThis.process.argv0;Ya=t?`unknown_service:${t}`:"unknown_service"}catch{Ya="unknown_service"}}return Ya}const tc=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";class ec{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,e){const i=new ec({},e);i._rawAttributes=nc(t);i._asyncAttributesPending=t.filter((([t,e])=>tc(e))).length>0;return i}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(tc(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=nc(this._rawAttributes);this._schemaUrl=sc(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,tc(i)?await i:i]}this._asyncAttributesPending=false}get attributes(){if(this.asyncAttributesPending){Xt.error("Accessing resource attributes before async attributes settled")}if(this._memoizedAttributes){return this._memoizedAttributes}const t={};for(const[e,i]of this._rawAttributes){if(tc(i)){Xt.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=oc(this,t);const i=e?{schemaUrl:e}:undefined;return ec.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],i)}}function ic(t,e){return ec.FromAttributeList(Object.entries(t),e)}function rc(){return ic({[He]:Qa(),[Je]:ka[Je],[Ze]:ka[Ze],[We]:ka[We]})}function nc(t){return t.map((([t,e])=>{if(tc(e)){return[t,e.catch((e=>{Xt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function sc(t){if(typeof t==="string"||t===undefined){return t}Xt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t);return undefined}function oc(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}Xt.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',i,r);return undefined}class ac{_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 cc(t,e,i){if(!fc(t)){Xt.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??lt.DOUBLE,advice:i?.advice??{}}}function uc(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 lc(t,e){return Ro(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}const hc=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function fc(t){return hc.test(t)}class dc{_writableMetricStorage;_descriptor;constructor(t,e){this._writableMetricStorage=t;this._descriptor=e}_record(t,e={},i=Wt.active()){if(typeof t!=="number"){Xt.warn(`non-number value provided to metric ${this._descriptor.name}: ${t}`);return}if(this._descriptor.valueType===lt.INT&&!Number.isInteger(t)){Xt.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,Ta(Date.now()))}}class pc extends dc{add(t,e,i){this._record(t,e,i)}}class mc extends dc{add(t,e,i){if(t<0){Xt.warn(`negative value provided to counter ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class bc extends dc{record(t,e,i){this._record(t,e,i)}}class vc extends dc{record(t,e,i){if(t<0){Xt.warn(`negative value provided to histogram ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class wc{_metricStorages;_descriptor;_observableRegistry;constructor(t,e,i){this._descriptor=t;this._metricStorages=e;this._observableRegistry=i}addCallback(t){this._observableRegistry.addCallback(t,this)}removeCallback(t){this._observableRegistry.removeCallback(t,this)}}class gc extends wc{}class yc extends wc{}class xc extends wc{}function kc(t){return t instanceof wc}class Sc{_meterSharedState;constructor(t){this._meterSharedState=t}createGauge(t,e){const i=cc(t,Ao.GAUGE,e);const r=this._meterSharedState.registerMetricStorage(i);return new bc(r,i)}createHistogram(t,e){const i=cc(t,Ao.HISTOGRAM,e);const r=this._meterSharedState.registerMetricStorage(i);return new vc(r,i)}createCounter(t,e){const i=cc(t,Ao.COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new mc(r,i)}createUpDownCounter(t,e){const i=cc(t,Ao.UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new pc(r,i)}createObservableGauge(t,e){const i=cc(t,Ao.OBSERVABLE_GAUGE,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new yc(i,r,this._meterSharedState.observableRegistry)}createObservableCounter(t,e){const i=cc(t,Ao.OBSERVABLE_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new gc(i,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(t,e){const i=cc(t,Ao.OBSERVABLE_UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new xc(i,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.addBatchCallback(t,e)}removeBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.removeBatchCallback(t,e)}}class Ec{_instrumentDescriptor;constructor(t){this._instrumentDescriptor=t}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(t){this._instrumentDescriptor=cc(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:t,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class Tc{_valueMap=new Map;_keyMap=new Map;_hash;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 _c extends Tc{constructor(){super(Co)}}class Ac{_activeCollectionStorage=new _c;_cumulativeMemoStorage=new _c;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":true};_overflowHashCode;_aggregator;constructor(t,e){this._aggregator=t;this._cardinalityLimit=(e??2e3)-1;this._overflowHashCode=Co(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 _c;return t}}class Mc{_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===_o.CUMULATIVE){s=Mc.merge(e.accumulations,n,this._aggregator)}else{s=Mc.calibrateStartTime(e.accumulations,n,i)}}else{o=t.selectAggregationTemporality(e.type)}this._reportHistory.set(t,{accumulations:s,collectionTime:r,aggregationTemporality:o});const a=Cc(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 _c;const i=this._unreportedAccumulations.get(t);this._unreportedAccumulations.set(t,[]);if(i===undefined){return e}for(const t of i){e=Mc.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 Cc(t){return Array.from(t.entries())}class Oc extends Ec{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(t,e,i,r,n){super(t);this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new Ac(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new Mc(e,r);this._attributesProcessor=i}record(t,e){const i=new _c;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 Ic(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 Pc(t,e){return`\t- use valueType '${t.valueType}' on instrument creation or use an instrument name other than '${e.name}'`}function Lc(t,e){return`\t- use unit '${t.unit}' on instrument creation or use an instrument name other than '${e.name}'`}function Dc(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 Rc(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 Nc(t,e){if(t.valueType!==e.valueType){return Pc(t,e)}if(t.unit!==e.unit){return Lc(t,e)}if(t.type!==e.type){return Dc(t,e)}if(t.description!==e.description){return Rc(t,e)}return""}class jc{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new jc}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(lc(e,t)){if(e.description!==t.description){if(t.description.length>e.description.length){r.updateDescription(t.description)}Xt.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",Ic(e,t),"The longer description will be used.\nTo resolve the conflict:",Nc(e,t))}i=r}else{Xt.warn("A view or instrument with the name ",t.name," has already been registered and is incompatible with another registered view.\n","Details:\n",Ic(e,t),"To resolve the conflict:\n",Nc(e,t))}}return i}}class zc{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,i,r){this._backingStorages.forEach((n=>{n.record(t,e,i,r)}))}}class $c{_buffer=new _c;_instrumentName;_valueType;constructor(t,e){this._instrumentName=t;this._valueType=e}observe(t,e={}){if(typeof t!=="number"){Xt.warn(`non-number value provided to metric ${this._instrumentName}: ${t}`);return}if(this._valueType===lt.INT&&!Number.isInteger(t)){Xt.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 Uc{_buffer=new Map;observe(t,e,i={}){if(!kc(t)){return}let r=this._buffer.get(t);if(r==null){r=new _c;this._buffer.set(t,r)}if(typeof e!=="number"){Xt.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}if(t._descriptor.valueType===lt.INT&&!Number.isInteger(e)){Xt.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 Bc{_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(kc));if(i.size===0){Xt.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(kc));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 Promise.allSettled([...i,...r]);const s=n.filter((t=>t.status==="rejected")).map((t=>t.reason));return s}_observeCallbacks(t,e){return this._callbacks.map((async({callback:i,instrument:r})=>{const n=new $c(r._descriptor.name,r._descriptor.valueType);let s=Promise.resolve(i(n));if(e!=null){s=Po(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 Uc;let s=Promise.resolve(i(n));if(e!=null){s=Po(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&&Lo(i.instruments,e)))}}class Fc extends Ec{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(t,e,i,r,n){super(t);this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new Ac(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new Mc(e,r);this._attributesProcessor=i}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 Gc{process(t,e){return t}}class Vc{_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 qc(){return Jc}function Hc(t){return new Vc(t)}const Jc=new Gc;class Kc{metricStorageRegistry=new jc;observableRegistry=new Bc;meter;_meterProviderSharedState;_instrumentationScope;constructor(t,e){this.meter=new Sc(this);this._meterProviderSharedState=t;this._instrumentationScope=e}registerMetricStorage(t){const e=this._registerMetricStorage(t,Fc);if(e.length===1){return e[0]}return new zc(e)}registerAsyncMetricStorage(t){const e=this._registerMetricStorage(t,Oc);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.forEach((i=>{const r=i.collect(t,e);if(r!=null){s.push(r)}}));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=uc(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,qc(),[i],o);this.metricStorageRegistry.registerForCollector(i,a);return a}));r=r.concat(n)}return r}}class Zc{viewRegistry=new ac;metricCollectors=[];meterSharedStates=new Map;resource;constructor(t){this.resource=t}getMeterSharedState(t){const e=Oo(t);let i=this.meterSharedStates.get(e);if(i==null){i=new Kc(this,t);this.meterSharedStates.set(e,i)}return i}selectAggregations(t){const e=[];for(const i of this.metricCollectors){e.push([i,Ja(i.selectAggregation(t))])}return e}}class Wc{_sharedState;_metricReader;constructor(t,e){this._sharedState=t;this._metricReader=e}async collect(t){const e=Ta(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 Xc=/[\^$\\.+?()[\]{}|]/g;class Yc{_matchAll;_regexp;constructor(t){if(t==="*"){this._matchAll=true;this._regexp=/.*/}else{this._matchAll=false;this._regexp=new RegExp(Yc.escapePattern(t))}}match(t){if(this._matchAll){return true}return this._regexp.test(t)}static escapePattern(t){return`^${t.replace(Xc,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}}class Qc{_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 tu{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new Yc(t?.name??"*");this._type=t?.type;this._unitFilter=new Qc(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class eu{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new Qc(t?.name);this._versionFilter=new Qc(t?.version);this._schemaUrlFilter=new Qc(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function iu(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}function ru(t){if(iu(t)){throw new Error("Cannot create view with no selector arguments supplied")}if(t.name!=null&&(t?.instrumentName==null||Yc.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 nu{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){ru(t);if(t.attributesProcessors!=null){this.attributesProcessor=Hc(t.attributesProcessors)}else{this.attributesProcessor=qc()}this.name=t.name;this.description=t.description;this.aggregation=Ja(t.aggregation??{type:Ha.DEFAULT});this.instrumentSelector=new tu({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit});this.meterSelector=new eu({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl});this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}}class su{_sharedState;_shutdown=false;constructor(t){this._sharedState=new Zc(t?.resource??rc());if(t?.views!=null&&t.views.length>0){for(const e of t.views){this._sharedState.viewRegistry.addView(new nu(e))}}if(t?.readers!=null&&t.readers.length>0){for(const e of t.readers){const t=new Wc(this._sharedState,e);e.setMetricProducer(t);this._sharedState.metricCollectors.push(t)}}}getMeter(t,e="",i={}){if(this._shutdown){Xt.warn("A shutdown MeterProvider cannot provide a Meter");return ut()}return this._sharedState.getMeterSharedState({name:t,version:e,schemaUrl:i.schemaUrl}).meter}async shutdown(t){if(this._shutdown){Xt.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){Xt.warn("invalid attempt to force flush after MeterProvider shutdown");return}await Promise.all(this._sharedState.metricCollectors.map((e=>e.forceFlush(t))))}}var ou;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(ou||(ou={}));var au;(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"})(au||(au={}));var cu;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(cu||(cu={}));var uu;(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"})(uu||(uu={}));var lu;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE";t[t["LOWMEMORY"]=2]="LOWMEMORY"})(lu||(lu={}));const hu=()=>ou.CUMULATIVE;const fu=t=>{switch(t){case au.COUNTER:case au.OBSERVABLE_COUNTER:case au.GAUGE:case au.HISTOGRAM:case au.OBSERVABLE_GAUGE:return ou.DELTA;case au.UP_DOWN_COUNTER:case au.OBSERVABLE_UP_DOWN_COUNTER:return ou.CUMULATIVE}};const du=t=>{switch(t){case au.COUNTER:case au.HISTOGRAM:return ou.DELTA;case au.GAUGE:case au.UP_DOWN_COUNTER:case au.OBSERVABLE_UP_DOWN_COUNTER:case au.OBSERVABLE_COUNTER:case au.OBSERVABLE_GAUGE:return ou.CUMULATIVE}};function pu(){const t="cumulative".toLowerCase();if(t==="cumulative"){return hu}if(t==="delta"){return fu}if(t==="lowmemory"){return du}Xt.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${t}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);return hu}function mu(t){if(t!=null){if(t===lu.DELTA){return fu}else if(t===lu.LOWMEMORY){return du}return hu}return pu()}const bu=Object.freeze({type:uu.DEFAULT});function vu(t){return t?.aggregationPreference??(()=>bu)}class wu extends Yr{_aggregationTemporalitySelector;_aggregationSelector;constructor(t,e){super(t);this._aggregationSelector=vu(e);this._aggregationTemporalitySelector=mu(e?.temporalityPreference)}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}}class gu extends wu{constructor(t){super(Ts(t??{},Xn,"v1/metrics",{"Content-Type":"application/json"}),t)}}class yu{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 gu({url:this.collectorUrl,headers:{"Content-Type":"application/json"}});this.metricReader=new Xa({exporter:t,exportIntervalMillis:this.exportIntervalMillis,exportTimeoutMillis:3e4});this.meterProvider=new su({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 xu{services=new Map;cleanedUp=false;constructor(t){this.initializeServices(t)}initializeServices(t){const e=new s;const i=new o(e);const r=new a(e,t.preferredCamera);const n=new f(t.debug,t.useDocumentClassification,t.useDocumentDetector);let c=null;if(t.enableTelemetry!==false){c=new To({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 yu({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",n);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(){if(this.cleanedUp){return}this.cleanedUp=true;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 ku{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=ku.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 Su=":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 Eu=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;classificationDisabled=false;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;_manualModeLoggedOnce=false;VIDEO_DIAGNOSTIC_EVENTS=["loadstart","loadedmetadata","loadeddata","canplay","playing","pause","stalled","suspend","abort","emptied"];canvasPool=[];MAX_CANVAS_POOL_SIZE=3;async componentWillLoad(){if(this.debug){console.log("[JAAK-DEBUG] componentWillLoad() - Props at initialization:");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector,"(type:",typeof this.useDocumentDetector,")");console.log("[JAAK-DEBUG] useDocumentClassification:",this.useDocumentClassification);console.log("[JAAK-DEBUG] debug:",this.debug);console.log("[JAAK-DEBUG] license:",this.license?this.license.substring(0,8)+"...":"EMPTY");console.log("[JAAK-DEBUG] licenseEnvironment:",this.licenseEnvironment);console.log("[JAAK-DEBUG] alignmentTolerance:",this.alignmentTolerance);console.log("[JAAK-DEBUG] maskSize:",this.maskSize);console.log("[JAAK-DEBUG] captureDelay:",this.captureDelay);console.log("[JAAK-DEBUG] preferredCamera:",this.preferredCamera);console.log("[JAAK-DEBUG] appId:",this.appId)}await new Promise((t=>setTimeout(t,50)));if(this.debug){console.log("[JAAK-DEBUG] Props AFTER 50ms wait:");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector,"(type:",typeof this.useDocumentDetector,")")}this.updateStatus("Validando licencia...","Verificando autorización de uso","initializing");await this.validateLicense();if(!this.licenseValid){if(this.debug){console.error("[JAAK-DEBUG] License validation FAILED. Stopping initialization.")}return}if(this.debug){console.log("[JAAK-DEBUG] License validation OK")}}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 xu(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 ku(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/dist/ort.wasm.min.js"}else{t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web/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 h,f;const d=this.maskSize/100;if(l<=s){f=o*d;h=f*u}else{h=s*d;f=h/u}const p=h/t.width*100;const m=f/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}}debugLog(t,e){if(!this.debug){return}if(typeof e==="undefined"){console.log(`[jaak-stamps][diag] ${t}`);return}console.log(`[jaak-stamps][diag] ${t}`,e)}debugWarn(t,e){if(!this.debug){return}if(typeof e==="undefined"){console.warn(`[jaak-stamps][diag] ${t}`);return}console.warn(`[jaak-stamps][diag] ${t}`,e)}summarizeId(t){if(!t){return null}return t.length<=8?t:`${t.slice(0,8)}...`}getCameraDevicesSnapshot(){return this.cameraService.getAvailableCameras().map((t=>({label:t.label||"(sin label)",deviceId:this.summarizeId(t.deviceId),groupId:this.summarizeId(t.groupId),kind:t.kind})))}sanitizeTrackSettings(t){if(!t){return null}return{...t,deviceId:this.summarizeId(t.deviceId),groupId:this.summarizeId(t.groupId)}}sanitizeTrackConstraints(t){if(!t){return null}const e=t.getConstraints?t.getConstraints():{};const i={...e};if(typeof i.deviceId==="string"){i.deviceId=this.summarizeId(i.deviceId)}return i}getStreamSnapshot(t){if(!t){return{hasStream:false}}const e=t.getVideoTracks()[0];if(!e){return{hasStream:true,streamActive:t.active,trackCount:t.getTracks().length,hasVideoTrack:false}}return{hasStream:true,streamActive:t.active,trackCount:t.getTracks().length,trackLabel:e.label||"(sin label)",trackEnabled:e.enabled,trackMuted:e.muted,trackReadyState:e.readyState,settings:this.sanitizeTrackSettings(e.getSettings?e.getSettings():undefined),constraints:this.sanitizeTrackConstraints(e)}}getVideoElementSnapshot(){if(!this.videoRef){return{hasVideoRef:false}}const t=this.el.ownerDocument?.defaultView?.getComputedStyle(this.videoRef);return{hasVideoRef:true,isConnected:this.videoRef.isConnected,readyState:this.videoRef.readyState,networkState:this.videoRef.networkState,paused:this.videoRef.paused,muted:this.videoRef.muted,autoplay:this.videoRef.autoplay,playsInline:this.videoRef.playsInline,currentTime:Number.isFinite(this.videoRef.currentTime)?Number(this.videoRef.currentTime.toFixed(3)):this.videoRef.currentTime,videoWidth:this.videoRef.videoWidth,videoHeight:this.videoRef.videoHeight,clientWidth:this.videoRef.clientWidth,clientHeight:this.videoRef.clientHeight,hasSrcObject:!!this.videoRef.srcObject,display:t?.display??"unknown",visibility:t?.visibility??"unknown"}}attachVideoDiagnosticListeners(){if(!this.debug||!this.videoRef){return()=>undefined}const t=this.videoRef;const e=this.VIDEO_DIAGNOSTIC_EVENTS.map((e=>{const i=()=>{this.debugLog(`video event "${e}"`,this.getVideoElementSnapshot())};t.addEventListener(e,i);return{eventName:e,handler:i}}));return()=>{e.forEach((({eventName:e,handler:i})=>{t.removeEventListener(e,i)}))}}async startDetection(){try{if(this.debug){console.log("[JAAK-DEBUG] startDetection() called");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector);console.log("[JAAK-DEBUG] useDocumentClassification:",this.useDocumentClassification)}const t=this.checkDeviceCapabilities();if(this.debug){console.log("[JAAK-DEBUG] Device capabilities:",JSON.stringify(t))}if(!t.canUseML&&this.useDocumentDetector){if(this.debug){console.warn("[JAAK-DEBUG] MANUAL MODE: Device cannot use ML. Reason:",t.reason)}this.switchToManualModeWithWarning(t.reason);return}if(!this.detectionService.isModelLoaded()){const t=performance.now();if(this.debug){console.log("[JAAK-DEBUG] Loading detection model...")}this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");this.stateManager.updateCaptureState({isLoading:true});try{await this.detectionService.loadModel();if(this.debug){console.log("[JAAK-DEBUG] Detection model loaded successfully in",(performance.now()-t).toFixed(0),"ms")}}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";if(this.debug){console.warn("[JAAK-DEBUG] MANUAL MODE: Out of memory loading detection model.",t)}this.switchToManualModeWithWarning(`Memoria insuficiente para detección automática ${t}. Modo manual activado - funciona igual de bien!`);return}else{if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Error loading detection model:",t.message)}this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");if(this.debug){console.log("[JAAK-DEBUG] Loading classification model...")}try{await this.detectionService.loadClassificationModel();if(this.debug){console.log("[JAAK-DEBUG] Classification model loaded successfully")}}catch(t){if(this.debug){console.warn("[JAAK-DEBUG] Classification model failed to load, disabling classification. Error:",t.message)}this.classificationDisabled=true}const e=performance.now();const i=e-t;if(this.debug){console.log("[JAAK-DEBUG] All models loaded in",i.toFixed(0),"ms");this.recordOnnxPerformance(i,0)}}else{if(this.debug){console.log("[JAAK-DEBUG] Models already loaded, skipping load")}}this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices();this.debugLog("step 2/5 enumerateDevices()",{cameras:this.getCameraDevicesSnapshot(),selectedCameraId:this.summarizeId(this.cameraService.getSelectedCameraId()||undefined)})}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus();this.debugLog("step 2/5 updateCameraInfoWithAutofocus()",{cameraInfo:this.cameraInfoWithAutofocus})}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();this.debugLog("step 3/5 setupCamera() resolved",{stream:this.getStreamSnapshot(e),videoRef:this.getVideoElementSnapshot()})}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{this.debugLog("step 4/5 initializeVideoStream() start",{stream:this.getStreamSnapshot(e),videoRef:this.getVideoElementSnapshot()});await this.initializeVideoStream(e);this.debugLog("step 4/5 initializeVideoStream() completed",{stream:this.getStreamSnapshot(e),videoRef:this.getVideoElementSnapshot()})}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.debugLog("step 5/5 capture loop ready",{videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(this.videoStream),useDocumentDetector:this.useDocumentDetector});this.detectFrame()}catch(t){this.debugWarn("startDetection() failed",{error:t instanceof Error?t.message:String(t),videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(this.videoStream)});console.error("[jaak-stamps] Error al preparar captura:",t);this.updateStatus("Error al iniciar","No se pudo preparar la captura","error");this.stateManager.updateCaptureState({isLoading:false})}}async initializeVideoStream(t){if(!this.videoRef){throw new Error("Video element not available")}const e=this.attachVideoDiagnosticListeners();this.debugLog("initializeVideoStream() pre-assign",{stream:this.getStreamSnapshot(t),videoRef:this.getVideoElementSnapshot()});this.videoRef.srcObject=t;this.videoStream=t;this.debugLog("initializeVideoStream() post-srcObject assignment",{stream:this.getStreamSnapshot(t),videoRef:this.getVideoElementSnapshot()});const i=this.cameraService.isRearCamera(t);this.shouldMirrorVideo=!i;const r=1e4;const n=t.getVideoTracks()[0];const s=performance.now();const o=[];const a=t=>{o.push({at:Math.round(performance.now()-s),event:t,state:n?.readyState})};const c=()=>a("mute");const u=()=>a("unmute");const l=()=>a("ended");if(n){n.addEventListener("mute",c);n.addEventListener("unmute",u);n.addEventListener("ended",l)}const h=()=>{if(!n)return;n.removeEventListener("mute",c);n.removeEventListener("unmute",u);n.removeEventListener("ended",l)};const f=()=>{const e=n?.getSettings?.();const i=this.videoRef?getComputedStyle(this.videoRef):null;return{reason:"VIDEO_METADATA_TIMEOUT",waitedMs:Math.round(performance.now()-s),stream:{videoTrackCount:t.getVideoTracks().length,audioTrackCount:t.getAudioTracks().length},track:n?{readyState:n.readyState,muted:n.muted,enabled:n.enabled,label:n.label,kind:n.kind,settings:e?{width:e.width,height:e.height,frameRate:e.frameRate,deviceId:e.deviceId,facingMode:e.facingMode}:null}:null,video:this.videoRef?{readyState:this.videoRef.readyState,networkState:this.videoRef.networkState,error:this.videoRef.error?{code:this.videoRef.error.code,message:this.videoRef.error.message}:null,paused:this.videoRef.paused,offsetWidth:this.videoRef.offsetWidth,offsetHeight:this.videoRef.offsetHeight,videoWidth:this.videoRef.videoWidth,videoHeight:this.videoRef.videoHeight,display:i?.display,visibility:i?.visibility}:null,document:{visibilityState:document.visibilityState,hasFocus:document.hasFocus()},trackEvents:o,userAgent:navigator.userAgent}};const d=async()=>{try{await this.videoRef.play()}catch(t){console.error("[jaak-stamps] video.play() failed (likely autoplay policy):",t);throw t}this.stateManager.updateCaptureState({isVideoActive:true});if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.debugLog("initializeVideoStream() finalized after play()",{stream:this.getStreamSnapshot(t),videoRef:this.getVideoElementSnapshot()})};if(this.videoRef.readyState>=1){this.debugLog("video metadata already available, skipping event wait",this.getVideoElementSnapshot());h();await d();e();return}return new Promise(((i,n)=>{let s=false;const o=()=>{this.videoRef.onloadedmetadata=null;this.videoRef.onerror=null;e()};const a=setTimeout((()=>{if(s)return;s=true;const e=f();this.debugWarn(`initializeVideoStream() timeout after ${r}ms`,{videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(t)});console.error("[jaak-stamps] Video metadata timeout diagnostics (json):",JSON.stringify(e));o();h();n(new Error(`Video metadata load timeout after ${r}ms`))}),r);this.videoRef.onloadedmetadata=async()=>{if(s)return;s=true;clearTimeout(a);this.debugLog("initializeVideoStream() onloadedmetadata fired",{videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(t)});h();try{await d();o();i()}catch(t){o();n(t)}};this.videoRef.onerror=e=>{if(s)return;s=true;clearTimeout(a);this.debugWarn("initializeVideoStream() video element emitted error",{event:e,videoRef:this.getVideoElementSnapshot(),stream:this.getStreamSnapshot(t)});o();h();n(new Error(`Video element error: ${e}`))}}))}async detectFrame(){try{const t=performance.now();const e=this.stateManager.getCaptureState();if(!this.videoRef||!this.detectionContainer||!this.detectionService.isModelLoaded()){if(this.debug){console.log("[JAAK-DEBUG] detectFrame() skipped: videoRef=",!!this.videoRef,"detectionContainer=",!!this.detectionContainer,"modelLoaded=",this.detectionService.isModelLoaded())}return}if(!this.useDocumentDetector||this.performanceDegradedMode){if(this.debug&&!this._manualModeLoggedOnce){console.warn("[JAAK-DEBUG] detectFrame() in MANUAL MODE: useDocumentDetector=",this.useDocumentDetector,"performanceDegradedMode=",this.performanceDegradedMode);this._manualModeLoggedOnce=true}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){if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Preprocess error:",t.message)}this.switchToManualModeWithError("Error al procesar imagen");return}try{u=await this.detectionService.runInference(c);l=performance.now()-a}catch(t){if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Inference error:",t.message)}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 h=this.hasDocumentDetected;this.hasDocumentDetected=u.length>0;if(!h&&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 f=performance.now();const d=f-t;if(this.useDocumentDetector&&!this.hasAutoSwitchedToManual){if(this.debug){console.log(`[JAAK-DEBUG] Frame #${this.processedFramesCount} time: ${d.toFixed(0)}ms (threshold: ${this.PERFORMANCE_THRESHOLD_MS}ms) | inference: ${l.toFixed(0)}ms | slowFrames: ${this.slowFrameCount}/${this.SLOW_FRAMES_TO_TRIGGER}`)}if(d>=this.PERFORMANCE_THRESHOLD_MS){this.slowFrameCount++;if(this.debug){console.warn(`[JAAK-DEBUG] SLOW FRAME detected: ${d.toFixed(0)}ms >= ${this.PERFORMANCE_THRESHOLD_MS}ms | slowFrameCount: ${this.slowFrameCount}/${this.SLOW_FRAMES_TO_TRIGGER}`)}if(this.slowFrameCount>=this.SLOW_FRAMES_TO_TRIGGER){if(this.debug){console.error(`[JAAK-DEBUG] MANUAL MODE: Performance degraded. ${this.slowFrameCount} slow frames (>= ${this.PERFORMANCE_THRESHOLD_MS}ms) exceeded threshold of ${this.SLOW_FRAMES_TO_TRIGGER}`)}this.switchToManualMode()}}else{if(this.slowFrameCount>0){if(this.debug){console.log(`[JAAK-DEBUG] Fast frame, resetting slowFrameCount from ${this.slowFrameCount} to 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:"20689d87a0b2f3ec851837a57f97b4bb79ecf10a",class:"detector-container"},!this.licenseValid&&this.licenseError&&r("div",{key:"3dccc3f6fd3ed0db2c2e7034d5cb0940625bade1",class:"license-error-container"},r("div",{key:"5f39d0762dc5fea0f5d5402cd61f696090e96865",class:"license-error-card"},r("svg",{key:"34d8290684decfe194328eba1b4af1b582f02518",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:"2cc8b54522b550f127c1b05a6f8069b78156f84a",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:"b3c7918292661cfc92fbc0d3ec237acb80364fa5",d:"M12 8V12",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"}),r("circle",{key:"86a258f69cdf26588436cba2056bdf7c92d08244",cx:"12",cy:"16",r:"0.5",fill:"currentColor",stroke:"currentColor","stroke-width":"1"})),r("h2",{key:"06e4fbde528663e485ae9a3b04945e6c95595ab2",class:"license-error-title"},"Licencia Requerida"),r("p",{key:"7466b075c8cf31d67535512e4bdaa1473e89ed47",class:"license-error-message"},this.licenseError),r("p",{key:"ba4d06029ef7e896e51ad5c6e2dd72a9a162ef08",class:"license-error-help"},"Contacte a soporte: ",r("a",{key:"177832433d66cf581743d8774a055405fa1f83fc",href:"mailto:support@jaak.ai"},"support@jaak.ai")),r("div",{key:"ce1b33ae5289689c3e07cbb2a68f4411aa3ed2d2",class:"license-error-footer"},"JAAK Stamps"))),this.licenseValid&&r("div",{key:"394ee2b3c487c9673c1df3b483900720beb42ea5",class:"video-container"},r("video",{key:"50ba3fb80f05ed35bdc58f9d75538d083cd7af32",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{opacity:t.isVideoActive?"1":"0",visibility:t.isVideoActive?"visible":"hidden"}}),r("div",{key:"a4ff51674115afeeb2c36aedbbbdf3769bf0af96",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:"6c4e710e25971692bd933486f05a231b56150e5a",class:"overlay-mask"},r("div",{key:"d7ec408535cd68a5a9c12e51061f3fd61745b566",class:"card-outline"},r("div",{key:"0e4c6066cf35cdb13843e54500db8e94603203fa",class:"side side-top"}),r("div",{key:"0c61ebf0940a01b09d509675d021051ac433ba1b",class:"side side-right"}),r("div",{key:"e1c113fa666ba1ab0b77bac98ac4b08d99bea3af",class:"side side-bottom"}),r("div",{key:"666527c49665fe1d9d04a5d3620686b7471b8d44",class:"side side-left"})),!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"71eae3c5e89eeaffd95bc32d7ed9139a5b741cc6",class:`guide-text ${this.showPerformanceMessage?"performance-warning-text":""}`},this.getGuideText(t.step)),t.step==="back"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"b4d6abc22c58eabd5afb6f440701f5b909bf949e",class:"back-capture-section"},r("div",{key:"6d4bf99ff92829efb64d6dbc7d2d14c16b7c691c",class:"back-capture-buttons"},(!this.useDocumentDetector||this.performanceDegradedMode||this.showManualCaptureButton)&&r("button",{key:"f8965079e936e32722b5eb1f8dfb63a84160aa5d",class:"capture-button primary-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-back"&&r("span",{key:"7defab9f244899e188659fd07bf114897737bd48",class:"button-spinner"}),"Capturar Reverso"),r("button",{key:"d5a501876ce24f25d21df5e8d47183e80be602f3",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button",disabled:this.processingButton!==null},this.processingButton==="skip-back"&&r("span",{key:"54e08bed19e50abdd5f5faf9e0a21d8c2cb6a368",class:"button-spinner"}),this.enableBackDocumentTimer&&this.backDocumentTimerRemaining>0?`Saltar reverso (${this.backDocumentTimerRemaining}s)`:"Saltar reverso"))),t.isVideoActive&&r("div",{key:"85998cae72d19792d41f94b3fa08fd7054e25c5e",class:"camera-controls"},r("button",{key:"fe0471dad8bdc5b45327da52af8b47f94fe2531a",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:"de26a8eda76aeec8e7095f793750b2336e2ff6c6",class:"camera-selector-dropdown"},r("div",{key:"9b4085d7be39ab227a33d02b55dd46e96a68d330",class:"camera-selector-header"},r("span",{key:"84104fb85d91ccd258c78365cad2e66b62d787b0"},"Seleccionar Cámara"),r("button",{key:"ad1d2b52e64ab8f0028e2cb083f495c2b432c054",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),r("div",{key:"e9f56e92ed01afac36ad0986dc78bfc816e60520",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:"6fa215b5f99d33272cd96a27b2295c95113bc257",class:"device-info"},r("small",{key:"f8399e02a4f2a288c09df9065e138ab8def9be5f"},"Dispositivo: ",e.deviceType))),this.showManualCaptureButton&&t.step==="front"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"4a169ae520fd5ca67716f0fe190889ace448044e",class:"manual-capture-section"},r("button",{key:"7d7808f0d1017f6eb4c701a8582152905a228e85",class:"manual-capture-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-front"&&r("span",{key:"89ee5a34898a8ba78777177001fa4406531dac3e",class:"button-spinner"}),"Capturar Frente"))),t.isCapturing&&r("div",{key:"0711e1cb5619acbade20f63f6d46bdfdf827ed12",class:"capture-animation"}),t.showFlipAnimation&&r("div",{key:"720c0b1dcdb85646b4973ae15abeaef0f3a91a95",class:"flip-animation"},r("div",{key:"a31a9500ee6f2f35f762e2f5135219ed869c6188",class:"id-card-icon"}),r("div",{key:"7237f4284d4a5b8fb471d8a568a9c3dd2eae6409",class:"flip-text"},"¡Voltea tu identificación!")),t.showSuccessAnimation&&r("div",{key:"94a28257187330f5aaca2302840300460f288f71",class:"success-animation"},r("div",{key:"ef9d9072507faac3ae29c31b87c9439f67576c14",class:"check-icon"}),r("div",{key:"7f1c077a2b3b67ebba5d12c9b69ff943b74936e9",class:"success-text"},"¡Proceso completado!")),r("div",{key:"b9cae83d9d9717728a27bd969293fe28702befe3",class:`component-status status-${this.currentStatus.type}`},(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing")&&r("div",{key:"59382426b18de9f04dcfb179acd9a49b68af45ed",class:"status-spinner"}),r("div",{key:"baa1972a55d439a95b3f91f38f91d9f35eecd7bd",class:"status-content"},r("div",{key:"3fac24107d04a2b0abcbe6a3a0bff6d395c096b6",class:"status-message"},this.currentStatus.message),this.currentStatus.description&&r("div",{key:"196c12a4fc3e8f213b17bdd366da9e61c594a0b1",class:"status-description"},this.currentStatus.description))),this.debug&&r("div",{key:"d5c36522d3bd46f434b19e8323a30f441d69c67c",class:"performance-monitor"},r("div",{key:"ccc8ae6b27be8d5d89e2722319cfc66a92c3a32f",class:"performance-expanded"},r("div",{key:"d7bed7384567663fafe4fa49dd24da4bdd05c9a3",class:"metrics-row"},r("div",{key:"a4409744d7d9e8a6288caf077ba5ebdc6aaa5371",class:"metric-compact"},r("span",{key:"939e03d6aa0138c2b0c1cce16bebf158b9b74bd6",class:"metric-label"},"FPS"),r("span",{key:"76c20f96b11725d41493b627e7a6b0fb0d594d60",class:`metric-value ${this.performanceData.fps<15?"warning":this.performanceData.fps<10?"danger":"good"}`},this.performanceData.fps)),r("div",{key:"fafe6b165149f1f590a0b7e26b4001b09a5c70c5",class:"metric-compact"},r("span",{key:"a7e99f9c05aced0cb951297ce3a6011500445421",class:"metric-label"},"MEM"),r("span",{key:"68bd733671a9664c4533e0b24b04ad0422053f77",class:`metric-value ${this.performanceData.memoryUsage>100?"warning":this.performanceData.memoryUsage>200?"danger":"good"}`},this.performanceData.memoryUsage,"MB"))),r("div",{key:"a53f1ac37527de249425529aff022858c8d924c5",class:"metrics-row"},r("div",{key:"2213e3646b22056999d29107bb32e43c61dd202f",class:"metric-compact"},r("span",{key:"31d84002498094f88f71858a91828f42b7157d23",class:"metric-label"},"INF"),r("span",{key:"f0ed4e90a338a05bd5193992e7f004df9d31239a",class:`metric-value ${this.performanceData.inferenceTime>100?"warning":this.performanceData.inferenceTime>200?"danger":"good"}`},this.performanceData.inferenceTime,"ms")),r("div",{key:"1288cf2f5a119f146886c08f8b7f036425ead78e",class:"metric-compact"},r("span",{key:"db75cca343f7c6ea588e9b62da04fc5d444604a6",class:"metric-label"},"FRAME"),r("span",{key:"40aee793f30a9cf175be6372981ce7b7be82ed07",class:`metric-value ${this.performanceData.frameProcessingTime>50?"warning":this.performanceData.frameProcessingTime>100?"danger":"good"}`},this.performanceData.frameProcessingTime,"ms"))),r("div",{key:"d193a9b4c56c6a712213a779dbc6ee161b82e828",class:"metrics-row"},r("div",{key:"89d060083973e1931232aac0d0c0f813b8aab7ef",class:"metric-compact"},r("span",{key:"35808d7a448e3f4c6dc27b2b325adf628b9aee16",class:"metric-label"},"DET"),r("span",{key:"b60da4f5a4d56e738a65fd0bc480626d4839a048",class:"metric-value good"},this.performanceData.successfulDetections,"/",this.performanceData.totalDetections)),r("div",{key:"da779be083f58be8e914d062379b565fdbf7333d",class:"metric-compact"},r("span",{key:"44645db15818eab212bc5b966213dda67f461d14",class:"metric-label"},"RATE"),r("span",{key:"39209bdf5a5fa7c74718492218ff4fa404e94879",class:`metric-value ${this.performanceData.detectionRate<30?"danger":this.performanceData.detectionRate<60?"warning":"good"}`},this.performanceData.detectionRate,"%"))))),r("div",{key:"bb0fb66ffefa86eb6e4b72215acb930c81cb6b01",class:"watermark"},r("img",{key:"93a1812ab9a1c91c4a81cdc939ef8410170dd6b9",src:"https://static.jaak.ai/commons/powered-by-jaak.png",alt:"Powered by Jaak",onError:t=>{t.target.src=n("/assets/powered-by-jaak.png")}}))))}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 h=0,f=0;if(a>c){u=s;l=s/a;f=(o-l)/2}else{l=o;u=o*a;h=(s-u)/2}const d=320;const p=u/d;const m=l/d;this.detectionBoxes=t.map((t=>({x:t.x*p+h,y:t.y*m+f,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 h=r.width/r.height;let f,d;let p=0,m=0;if(l>h){f=r.width;d=r.width/l;m=(r.height-d)/2}else{d=r.height;f=r.height*l;p=(r.width-f)/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/f;const x=u/d;const k=(w-p)*y;const S=(g-m)*x;const E=b*y;const T=v*x;const _=Math.max(0,k-E/2-this.cropMargin);const A=Math.max(0,S-T/2-this.cropMargin);const M=Math.min(E+2*this.cropMargin,c-_);const C=Math.min(T+2*this.cropMargin,u-A);const O=this.getPooledCanvas(M,C);const I=O.getContext("2d",{alpha:false});I.clearRect(0,0,O.width,O.height);I.drawImage(this.videoRef,_,A,M,C,0,0,M,C);const P=this.stateManager.getCaptureState();if(P.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/jpeg"),cropped:O.toDataURL("image/jpeg")}});if(this.useDocumentClassification&&!this.classificationDisabled){try{const e=await this.detectionService.classifyDocument(O);if(e&&e.class==="passport"){this.completeProcess(true);this.returnCanvasToPool(t);this.returnCanvasToPool(O);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(P.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/jpeg"),cropped:O.toDataURL("image/jpeg")}});this.completeProcess(false);this.processingButton=null}this.returnCanvasToPool(t);this.returnCanvasToPool(O)}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 h=this.getPooledCanvas(u,l);const f=h.getContext("2d",{alpha:false});f.clearRect(0,0,h.width,h.height);f.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=h.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&&!this.classificationDisabled){try{const t=await this.detectionService.classifyDocument(h);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=h.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(h)}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}if(this.debug){console.warn("[JAAK-DEBUG] switchToManualMode() called - PERFORMANCE DEGRADED");console.warn("[JAAK-DEBUG] Cause: Slow frames exceeded threshold");console.warn("[JAAK-DEBUG] slowFrameCount:",this.slowFrameCount,"| threshold:",this.PERFORMANCE_THRESHOLD_MS,"ms | trigger:",this.SLOW_FRAMES_TO_TRIGGER)}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}if(this.debug){console.warn("[JAAK-DEBUG] switchToManualModeWithWarning() called");console.warn("[JAAK-DEBUG] Cause:",t);console.warn("[JAAK-DEBUG] deviceMemory:",navigator.deviceMemory,"| hardwareConcurrency:",navigator.hardwareConcurrency)}this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;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}if(this.debug){console.error("[JAAK-DEBUG] switchToManualModeWithError() called");console.error("[JAAK-DEBUG] Cause:",t);console.error("[JAAK-DEBUG] deviceMemory:",navigator.deviceMemory,"| hardwareConcurrency:",navigator.hardwareConcurrency)}this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;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)}}static get assetsDirs(){return["../../assets"]}};Eu.style=Su;export{Eu as jaak_stamps};
|
|
7
|
+
//# sourceMappingURL=p-178aea65.entry.js.map
|