@jaak.ai/stamps 2.1.0 → 2.2.0-dev.1

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.
Files changed (57) hide show
  1. package/README.md +42 -9
  2. package/dist/cjs/{index-Ga0t6BMe.js → index-D6NBn_qu.js} +30 -5
  3. package/dist/cjs/index-D6NBn_qu.js.map +1 -0
  4. package/dist/cjs/jaak-stamps-webcomponent.cjs.js +2 -2
  5. package/dist/cjs/jaak-stamps.cjs.entry.js +20082 -11
  6. package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -1
  7. package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -1
  8. package/dist/cjs/loader.cjs.js +2 -2
  9. package/dist/collection/components/my-component/my-component.css +82 -2
  10. package/dist/collection/components/my-component/my-component.js +475 -9
  11. package/dist/collection/components/my-component/my-component.js.map +1 -1
  12. package/dist/collection/services/LicenseValidationService.js +111 -0
  13. package/dist/collection/services/LicenseValidationService.js.map +1 -0
  14. package/dist/collection/services/MetricsService.js +350 -0
  15. package/dist/collection/services/MetricsService.js.map +1 -0
  16. package/dist/collection/services/ServiceContainer.js +66 -1
  17. package/dist/collection/services/ServiceContainer.js.map +1 -1
  18. package/dist/collection/services/TracingService.js +442 -0
  19. package/dist/collection/services/TracingService.js.map +1 -0
  20. package/dist/collection/services/interfaces/ILicenseValidationService.js +2 -0
  21. package/dist/collection/services/interfaces/ILicenseValidationService.js.map +1 -0
  22. package/dist/collection/services/interfaces/IMetricsService.js +2 -0
  23. package/dist/collection/services/interfaces/IMetricsService.js.map +1 -0
  24. package/dist/collection/services/interfaces/ITracingService.js +2 -0
  25. package/dist/collection/services/interfaces/ITracingService.js.map +1 -0
  26. package/dist/components/index.js +28 -3
  27. package/dist/components/index.js.map +1 -1
  28. package/dist/components/jaak-stamps.js +20096 -10
  29. package/dist/components/jaak-stamps.js.map +1 -1
  30. package/dist/esm/{index-Drbzcuq-.js → index-BCfAsrzL.js} +30 -5
  31. package/dist/esm/index-BCfAsrzL.js.map +1 -0
  32. package/dist/esm/jaak-stamps-webcomponent.js +3 -3
  33. package/dist/esm/jaak-stamps.entry.js +20082 -11
  34. package/dist/esm/jaak-stamps.entry.js.map +1 -1
  35. package/dist/esm/loader.js +3 -3
  36. package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +1 -1
  37. package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -1
  38. package/dist/jaak-stamps-webcomponent/p-8c49893d.entry.js +7 -0
  39. package/dist/jaak-stamps-webcomponent/p-8c49893d.entry.js.map +1 -0
  40. package/dist/jaak-stamps-webcomponent/p-BCfAsrzL.js +3 -0
  41. package/dist/jaak-stamps-webcomponent/p-BCfAsrzL.js.map +1 -0
  42. package/dist/types/components/my-component/my-component.d.ts +23 -0
  43. package/dist/types/components.d.ts +76 -0
  44. package/dist/types/services/LicenseValidationService.d.ts +59 -0
  45. package/dist/types/services/MetricsService.d.ts +74 -0
  46. package/dist/types/services/ServiceContainer.d.ts +14 -1
  47. package/dist/types/services/TracingService.d.ts +67 -0
  48. package/dist/types/services/interfaces/ILicenseValidationService.d.ts +4 -0
  49. package/dist/types/services/interfaces/IMetricsService.d.ts +70 -0
  50. package/dist/types/services/interfaces/ITracingService.d.ts +59 -0
  51. package/package.json +18 -2
  52. package/dist/cjs/index-Ga0t6BMe.js.map +0 -1
  53. package/dist/esm/index-Drbzcuq-.js.map +0 -1
  54. package/dist/jaak-stamps-webcomponent/p-Drbzcuq-.js +0 -3
  55. package/dist/jaak-stamps-webcomponent/p-Drbzcuq-.js.map +0 -1
  56. package/dist/jaak-stamps-webcomponent/p-c06e5d7b.entry.js +0 -2
  57. package/dist/jaak-stamps-webcomponent/p-c06e5d7b.entry.js.map +0 -1
@@ -0,0 +1,7 @@
1
+ import{r as t,c as e,g as i,h as n}from"./p-BCfAsrzL.js";class r{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=n=>{e(n);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 n=i.filter((t=>t.kind==="videoinput"));this.availableCameras=n.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 n=i.getVideoTracks()[0];if(n){const t=n.getSettings();const e=t.deviceId;if(e){const t=await navigator.mediaDevices.enumerateDevices();const n=t.find((t=>t.deviceId===e));if(n&&this.isVirtualCamera(n)){console.log(`Virtual camera detected in active stream: ${n.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 n=i.getVideoTracks()[0];if(n){const t=n.getSettings();const e=t.deviceId;if(e){const t=await navigator.mediaDevices.enumerateDevices();const n=t.find((t=>t.deviceId===e));if(n&&this.isVirtualCamera(n)){console.log(`Virtual camera detected in fallback stream: ${n.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 n=i.getCapabilities();e.getTracks().forEach((t=>t.stop()));const r=n.focusMode&&Array.isArray(n.focusMode)&&n.focusMode.length>0;const s=r&&(n.focusMode.includes("continuous")||n.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 n=i.getVideoTracks()[0];e=n.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=Math.min(e.width.max,1920);const n=Math.min(e.height.max,1080);const r=/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;if(r){i.width={ideal:Math.min(t,1280)};i.height={ideal:Math.min(n,720)}}else{i.width={ideal:t};i.height={ideal:n}}}const n=e;if(n.focusMode&&Array.isArray(n.focusMode)){if(n.focusMode.includes("continuous")){i.focusMode="continuous"}else if(n.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={width:{ideal:e?1280:1920},height:{ideal:e?720:1080}};if(this.selectedCameraId){i.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){const t=this.deviceType==="desktop"?{ideal:this.preferredCameraFacing}:{exact:this.preferredCameraFacing};i.facingMode=t}else{if(this.preferredCamera==="front"){i.facingMode="user"}else if(this.preferredCamera==="back"){i.facingMode="environment"}else{i.facingMode=this.deviceType==="mobile"||this.deviceType==="tablet"?"environment":"user"}}return i}}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 n=i&&(i.effectiveType==="slow-2g"||i.effectiveType==="2g");return{estimatedRAM:e,isLowMemory:true,isSlowConnection:n}}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 n=i&&(i.effectiveType==="slow-2g"||i.effectiveType==="2g");return{estimatedRAM:e,isLowMemory:false,isSlowConnection:n}}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{static createStrategy(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=e<=4;if(i){return new a}else{return new c}}}class f{debug;useDocumentClassification;useDocumentDetector;session;mobileNetSession;mobileNetClassMap;modelLoaded=false;deviceStrategy;MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v2.onnx";MOBILENET_MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/squeezenet_new_fp32.onnx";MOBILENET_CLASSES_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";INPUT_SIZE=320;CONFIDENCE_THRESHOLD=.6;preprocessCanvas;preprocessCtx;captureCanvas;static canvasPool=new Map;static MAX_POOL_SIZE=5;constructor(t=false,e=false,i=true){this.debug=t;this.useDocumentClassification=e;this.useDocumentDetector=i;this.deviceStrategy=u.createStrategy();this.initializeCanvasPool()}async loadModel(){if(this.modelLoaded||this.session){return}if(!this.useDocumentDetector){this.modelLoaded=true;return}try{const t=this.deviceStrategy.getSessionOptions(this.debug);try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH,t)}catch(t){const e=t.message.includes("failed to allocate a buffer")||t.message.includes("Out of memory")||t.message.includes("RangeError: Out of memory")||t.message.includes("no available backend found");if(e){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1,enableProfiling:false,sessionLogSeverityLevel:4,sessionLogVerbosityLevel:0};try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH,t)}catch(t){throw new Error(`no available backend found. ERR: [wasm] RangeError: Out of memory`)}}else{throw t}}this.modelLoaded=true}catch(t){throw t}}async loadClassificationModel(){if(!this.useDocumentClassification){return}try{try{const t=await fetch(this.MOBILENET_CLASSES_PATH);if(t.ok){this.mobileNetClassMap=await t.json()}}catch(t){this.mobileNetClassMap={0:"document",1:"id_card",2:"passport",3:"license",4:"other"}}const t=this.deviceStrategy.getSessionOptions(this.debug);try{this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,t)}catch(t){const e=t.message.includes("failed to allocate a buffer")||t.message.includes("Out of memory")||t.message.includes("RangeError: Out of memory")||t.message.includes("no available backend found");if(e){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1,enableProfiling:false,sessionLogSeverityLevel:4,sessionLogVerbosityLevel:0};try{this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,t)}catch(t){throw new Error(`no available backend found. ERR: [wasm] RangeError: Out of memory`)}}else{throw t}}}catch(t){throw t}}isModelLoaded(){if(!this.useDocumentDetector){return this.modelLoaded}return this.modelLoaded&&!!this.session}preprocess(t){if(!this.preprocessCanvas||!this.preprocessCtx){this.initializeCanvasPool()}this.preprocessCtx.clearRect(0,0,this.INPUT_SIZE,this.INPUT_SIZE);this.preprocessCtx.drawImage(t,0,0,this.INPUT_SIZE,this.INPUT_SIZE);const e=this.preprocessCtx.getImageData(0,0,this.INPUT_SIZE,this.INPUT_SIZE);const[i,n,r]=[[],[],[]];const{data:s}=e;for(let t=0;t<s.length;t+=4){i.push(s[t]/255);n.push(s[t+1]/255);r.push(s[t+2]/255)}const o=new Float32Array(i.concat(n,r));const a=new Uint16Array(o.length);for(let t=0;t<o.length;t++){a[t]=this.float32ToFloat16(o[t])}return new window.ort.Tensor("float16",a,[1,3,this.INPUT_SIZE,this.INPUT_SIZE])}async runInference(t){if(!this.useDocumentDetector){return[]}if(!this.session){throw new Error("Detection model not loaded")}const e={[this.session.inputNames[0]]:t};const i=await this.session.run(e);const n=i[this.session.outputNames[0]].data;const r=[];for(let t=0;t<n.length;t+=6){const[e,i,s,o,a,c]=n.slice(t,t+6);if(a>this.CONFIDENCE_THRESHOLD){r.push({x:e,y:i,w:s-e,h:o-i,score:a,classId:c})}}return r}async classifyDocument(t){if(!this.mobileNetSession||!this.mobileNetClassMap){return null}try{const e=this.preprocessMobileNet(t);const i={[this.mobileNetSession.inputNames[0]]:e};const n=await this.mobileNetSession.run(i);const r=n[Object.keys(n)[0]].data;const s=r.reduce(((t,e,i,n)=>e>n[t]?i:t),0);const o=r[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:n,shouldMirrorVideo:r,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 f=c/u;const h=1;let l,d;if(f>h){l=i;d=i/f}else{d=i;l=i*f}const p=d*n;let m,b;const v=o/100;if(p<=l){b=d*v;m=b*n}else{m=l*v;b=m/n}const w=m*(i/l);const g=b*(i/d);const y=i/2;const x=i/2;const k=y-w/2;const S=y+w/2;const _=x-g/2;const T=x+g/2;let E=t.x;let C=t.x+t.w;const M=t.y;const A=t.y+t.h;if(r){const t=E;const e=C;E=i-e;C=i-t}const P=s;const O=Math.abs(M-_)<=P;const I=Math.abs(C-S)<=P;const L=Math.abs(A-T)<=P;const R=Math.abs(E-k)<=P;return{top:O&&R,right:O&&I,bottom:L&&R,left:L&&I}}isCardInFrame(t){const e=t.x+t.w/2;const i=t.y+t.h/2;const n=this.INPUT_SIZE/2;const r=this.INPUT_SIZE/2;const s=40;const o=30;const a=Math.abs(e-n)<s&&Math.abs(i-r)<o;const c=t.w>150&&t.w<300&&t.h>90&&t.h<200;return a&&c}areAllSidesAligned(t){return t.top&&t.right&&t.bottom&&t.left}cleanup(){this.cleanupCanvasPool();if(this.session){this.session.release?.();this.session=undefined}if(this.mobileNetSession){this.mobileNetSession.release?.();this.mobileNetSession=undefined}this.mobileNetClassMap=undefined;this.modelLoaded=false}initializeCanvasPool(){this.preprocessCanvas=document.createElement("canvas");this.preprocessCanvas.width=this.INPUT_SIZE;this.preprocessCanvas.height=this.INPUT_SIZE;this.preprocessCtx=this.preprocessCanvas.getContext("2d",{alpha:false,willReadFrequently:true});this.captureCanvas=document.createElement("canvas")}cleanupCanvasPool(){if(this.preprocessCanvas){this.preprocessCtx=undefined;this.preprocessCanvas=undefined}if(this.captureCanvas){this.captureCanvas=undefined}}float32ToFloat16(t){const e=new ArrayBuffer(4);const i=new DataView(e);i.setFloat32(0,t,true);const n=i.getUint32(0,true);const r=n>>31&1;const s=n>>23&255;const o=n&8388607;let a=s-127+15;if(s===0){a=0}else if(s===255){a=31}else if(a>=31){a=31;return r<<15|a<<10}else if(a<=0){return r<<15}return r<<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 n=i.getImageData(0,0,224,224);const r=n.data;const s=224*224;const o=new Float32Array(3*s);for(let t=0;t<s;t++){o[t]=r[t*4+0]/255;o[s+t]=r[t*4+1]/255;o[2*s+t]=r[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 n=f.canvasPool.get(i);let r=n.pop();if(!r){r=document.createElement("canvas");r.width=t;r.height=e}else{const i=r.getContext("2d");i.clearRect(0,0,t,e)}return r}returnCanvas(t){const e=`${t.width}x${t.height}`;if(!f.canvasPool.has(e)){f.canvasPool.set(e,[])}const i=f.canvasPool.get(e);if(i.length<f.MAX_POOL_SIZE){i.push(t)}}static clearCanvasPools(){f.canvasPool.clear()}getPoolStats(){const t={};f.canvasPool.forEach(((e,i)=>{t[i]=e.length}));return t}}var h=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};var l="1.9.0";var d=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function p(t){var e=new Set([t]);var i=new Set;var n=t.match(d);if(!n){return function(){return false}}var r={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(r.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(n){if(e.has(n)){return true}if(i.has(n)){return false}var a=n.match(d);if(!a){return s(n)}var c={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(c.prerelease!=null){return s(n)}if(r.major!==c.major){return s(n)}if(r.major===0){if(r.minor===c.minor&&r.patch<=c.patch){return o(n)}return s(n)}if(r.minor<=c.minor){return o(n)}return s(n)}}var m=p(l);var b=l.split(".")[0];var v=Symbol.for("opentelemetry.js.api."+b);var w=h;function g(t,e,i,n){var r;if(n===void 0){n=false}var s=w[v]=(r=w[v])!==null&&r!==void 0?r:{version:l};if(!n&&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!==l){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+l);i.error(o.stack||o.message);return false}s[t]=e;i.debug("@opentelemetry/api: Registered a global for "+t+" v"+l+".");return true}function y(t){var e,i;var n=(e=w[v])===null||e===void 0?void 0:e.version;if(!n||!m(n)){return}return(i=w[v])===null||i===void 0?void 0:i[t]}function x(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+l+".");var i=w[v];if(i){delete i[t]}}var k=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var n=i.call(t),r,s=[],o;try{while((e===void 0||e-- >0)&&!(r=n.next()).done)s.push(r.value)}catch(t){o={error:t}}finally{try{if(r&&!r.done&&(i=n["return"]))i.call(n)}finally{if(o)throw o.error}}return s};var S=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++){if(s||!(n in e)){if(!s)s=Array.prototype.slice.call(e,0,n);s[n]=e[n]}}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 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 n=y("diag");if(!n){return}i.unshift(e);return n[t].apply(n,S([],k(i),false))}var E;(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"})(E||(E={}));function C(t,e){if(t<E.NONE){t=E.NONE}else if(t>E.ALL){t=E.ALL}e=e||{};function i(i,n){var r=e[i];if(typeof r==="function"&&t>=n){return r.bind(e)}return function(){}}return{error:i("error",E.ERROR),warn:i("warn",E.WARN),info:i("info",E.INFO),debug:i("debug",E.DEBUG),verbose:i("verbose",E.VERBOSE)}}var M=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var n=i.call(t),r,s=[],o;try{while((e===void 0||e-- >0)&&!(r=n.next()).done)s.push(r.value)}catch(t){o={error:t}}finally{try{if(r&&!r.done&&(i=n["return"]))i.call(n)}finally{if(o)throw o.error}}return s};var A=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++){if(s||!(n in e)){if(!s)s=Array.prototype.slice.call(e,0,n);s[n]=e[n]}}return t.concat(s||Array.prototype.slice.call(e))};var P="diag";var O=function(){function t(){function t(t){return function(){var e=[];for(var i=0;i<arguments.length;i++){e[i]=arguments[i]}var n=y("diag");if(!n)return;return n[t].apply(n,A([],M(e),false))}}var e=this;var i=function(t,i){var n,r,s;if(i===void 0){i={logLevel:E.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((n=o.stack)!==null&&n!==void 0?n:o.message);return false}if(typeof i==="number"){i={logLevel:i}}var a=y("diag");var c=C((r=i.logLevel)!==null&&r!==void 0?r:E.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 g("diag",c,e,true)};e.setLogger=i;e.disable=function(){x(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 I=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var n=i.call(t),r,s=[],o;try{while((e===void 0||e-- >0)&&!(r=n.next()).done)s.push(r.value)}catch(t){o={error:t}}finally{try{if(r&&!r.done&&(i=n["return"]))i.call(n)}finally{if(o)throw o.error}}return s};var L=undefined&&undefined.__values||function(t){var e=typeof Symbol==="function"&&Symbol.iterator,i=e&&t[e],n=0;if(i)return i.call(t);if(t&&typeof t.length==="number")return{next:function(){if(t&&n>=t.length)t=void 0;return{value:t&&t[n++],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=I(t,2),i=e[0],n=e[1];return[i,n]}))};t.prototype.setEntry=function(e,i){var n=new t(this._entries);n._entries.set(e,i);return n};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 n=[];for(var r=0;r<arguments.length;r++){n[r]=arguments[r]}var s=new t(this._entries);try{for(var o=L(n),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 N=O.instance();function z(t){if(t===void 0){t={}}return new R(new Map(Object.entries(t)))}function $(t){if(typeof t!=="string"){N.error("Cannot create baggage metadata from unknown type: "+typeof t);t=""}return{__TYPE__:j,toString:function(){return t}}}function D(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,n){var r=new t(i._currentContext);r._currentContext.set(e,n);return r};i.deleteValue=function(e){var n=new t(i._currentContext);n._currentContext.delete(e);return n}}return t}();var U=new F;var B=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 n(){this.constructor=e}e.prototype=i===null?Object.create(i):(n.prototype=i.prototype,new n)}}();var q=function(){function t(){}t.prototype.createGauge=function(t,e){return et};t.prototype.createHistogram=function(t,e){return it};t.prototype.createCounter=function(t,e){return tt};t.prototype.createUpDownCounter=function(t,e){return nt};t.prototype.createObservableGauge=function(t,e){return st};t.prototype.createObservableCounter=function(t,e){return rt};t.prototype.createObservableUpDownCounter=function(t,e){return ot};t.prototype.addBatchObservableCallback=function(t,e){};t.prototype.removeBatchObservableCallback=function(t){};return t}();var H=function(){function t(){}return t}();var V=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.add=function(t,e){};return e}(H);var G=function(t){B(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){B(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){B(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){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var J=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var K=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var Q=new q;var tt=new V;var et=new Z;var it=new W;var nt=new G;var rt=new Y;var st=new J;var ot=new K;function at(){return Q}var ct;(function(t){t[t["INT"]=0]="INT";t[t["DOUBLE"]=1]="DOUBLE"})(ct||(ct={}));var ut={get:function(t,e){if(t==null){return undefined}return t[e]},keys:function(t){if(t==null){return[]}return Object.keys(t)}};var ft={set:function(t,e,i){if(t==null){return}t[e]=i}};var ht=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var n=i.call(t),r,s=[],o;try{while((e===void 0||e-- >0)&&!(r=n.next()).done)s.push(r.value)}catch(t){o={error:t}}finally{try{if(r&&!r.done&&(i=n["return"]))i.call(n)}finally{if(o)throw o.error}}return s};var lt=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++){if(s||!(n in e)){if(!s)s=Array.prototype.slice.call(e,0,n);s[n]=e[n]}}return t.concat(s||Array.prototype.slice.call(e))};var dt=function(){function t(){}t.prototype.active=function(){return U};t.prototype.with=function(t,e,i){var n=[];for(var r=3;r<arguments.length;r++){n[r-3]=arguments[r]}return e.call.apply(e,lt([i],ht(n),false))};t.prototype.bind=function(t,e){return e};t.prototype.enable=function(){return this};t.prototype.disable=function(){return this};return t}();var pt=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var n=i.call(t),r,s=[],o;try{while((e===void 0||e-- >0)&&!(r=n.next()).done)s.push(r.value)}catch(t){o={error:t}}finally{try{if(r&&!r.done&&(i=n["return"]))i.call(n)}finally{if(o)throw o.error}}return s};var mt=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++){if(s||!(n in e)){if(!s)s=Array.prototype.slice.call(e,0,n);s[n]=e[n]}}return t.concat(s||Array.prototype.slice.call(e))};var bt="context";var vt=new dt;var wt=function(){function t(){}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalContextManager=function(t){return g(bt,t,O.instance())};t.prototype.active=function(){return this._getContextManager().active()};t.prototype.with=function(t,e,i){var n;var r=[];for(var s=3;s<arguments.length;s++){r[s-3]=arguments[s]}return(n=this._getContextManager()).with.apply(n,mt([t,e,i],pt(r),false))};t.prototype.bind=function(t,e){return this._getContextManager().bind(t,e)};t.prototype._getContextManager=function(){return y(bt)||vt};t.prototype.disable=function(){this._getContextManager().disable();x(bt,O.instance())};return t}();var gt;(function(t){t[t["NONE"]=0]="NONE";t[t["SAMPLED"]=1]="SAMPLED"})(gt||(gt={}));var yt="0000000000000000";var xt="00000000000000000000000000000000";var kt={traceId:xt,spanId:yt,traceFlags:gt.NONE};var St=function(){function t(t){if(t===void 0){t=kt}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=D("OpenTelemetry Context Key SPAN");function Tt(t){return t.getValue(_t)||undefined}function Et(){return Tt(wt.getInstance().active())}function Ct(t,e){return t.setValue(_t,e)}function Mt(t){return t.deleteValue(_t)}function At(t,e){return Ct(t,new St(e))}function Pt(t){var e;return(e=Tt(t))===null||e===void 0?void 0:e.spanContext()}var Ot=/^([0-9a-f]{32})$/i;var It=/^[0-9a-f]{16}$/i;function Lt(t){return Ot.test(t)&&t!==xt}function Rt(t){return It.test(t)&&t!==yt}function jt(t){return Lt(t.traceId)&&Rt(t.spanId)}function Nt(t){return new St(t)}var zt=wt.getInstance();var $t=function(){function t(){}t.prototype.startSpan=function(t,e,i){if(i===void 0){i=zt.active()}var n=Boolean(e===null||e===void 0?void 0:e.root);if(n){return new St}var r=i&&Pt(i);if(Dt(r)&&jt(r)){return new St(r)}else{return new St}};t.prototype.startActiveSpan=function(t,e,i,n){var r;var s;var o;if(arguments.length<2){return}else if(arguments.length===2){o=e}else if(arguments.length===3){r=e;o=i}else{r=e;s=i;o=n}var a=s!==null&&s!==void 0?s:zt.active();var c=this.startSpan(t,r,a);var u=Ct(a,c);return zt.with(u,o,undefined,c)};return t}();function Dt(t){return typeof t==="object"&&typeof t["spanId"]==="string"&&typeof t["traceId"]==="string"&&typeof t["traceFlags"]==="number"}var Ft=new $t;var Ut=function(){function t(t,e,i,n){this._provider=t;this.name=e;this.version=i;this.options=n}t.prototype.startSpan=function(t,e,i){return this._getTracer().startSpan(t,e,i)};t.prototype.startActiveSpan=function(t,e,i,n){var r=this._getTracer();return Reflect.apply(r.startActiveSpan,r,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 Bt=function(){function t(){}t.prototype.getTracer=function(t,e,i){return new $t};return t}();var qt=new Bt;var Ht=function(){function t(){}t.prototype.getTracer=function(t,e,i){var n;return(n=this.getDelegateTracer(t,e,i))!==null&&n!==void 0?n:new Ut(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 n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(t,e,i)};return t}();var Vt;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(Vt||(Vt={}));var Gt;(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"})(Gt||(Gt={}));var Zt;(function(t){t[t["UNSET"]=0]="UNSET";t[t["OK"]=1]="OK";t[t["ERROR"]=2]="ERROR"})(Zt||(Zt={}));var Wt=wt.getInstance();var Xt=O.instance();var Yt=function(){function t(){}t.prototype.getMeter=function(t,e,i){return Q};return t}();var Jt=new Yt;var Kt="metrics";var Qt=function(){function t(){}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalMeterProvider=function(t){return g(Kt,t,O.instance())};t.prototype.getMeterProvider=function(){return y(Kt)||Jt};t.prototype.getMeter=function(t,e,i){return this.getMeterProvider().getMeter(t,e,i)};t.prototype.disable=function(){x(Kt,O.instance())};return t}();var te=Qt.getInstance();var ee=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 ie=D("OpenTelemetry Baggage Key");function ne(t){return t.getValue(ie)||undefined}function re(){return ne(wt.getInstance().active())}function se(t,e){return t.setValue(ie,e)}function oe(t){return t.deleteValue(ie)}var ae="propagation";var ce=new ee;var ue=function(){function t(){this.createBaggage=z;this.getBaggage=ne;this.getActiveBaggage=re;this.setBaggage=se;this.deleteBaggage=oe}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalPropagator=function(t){return g(ae,t,O.instance())};t.prototype.inject=function(t,e,i){if(i===void 0){i=ft}return this._getGlobalPropagator().inject(t,e,i)};t.prototype.extract=function(t,e,i){if(i===void 0){i=ut}return this._getGlobalPropagator().extract(t,e,i)};t.prototype.fields=function(){return this._getGlobalPropagator().fields()};t.prototype.disable=function(){x(ae,O.instance())};t.prototype._getGlobalPropagator=function(){return y(ae)||ce};return t}();var fe=ue.getInstance();var he="trace";var le=function(){function t(){this._proxyTracerProvider=new Ht;this.wrapSpanContext=Nt;this.isSpanContextValid=jt;this.deleteSpan=Mt;this.getSpan=Tt;this.getActiveSpan=Et;this.getSpanContext=Pt;this.setSpan=Ct;this.setSpanContext=At}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalTracerProvider=function(t){var e=g(he,this._proxyTracerProvider,O.instance());if(e){this._proxyTracerProvider.setDelegate(t)}return e};t.prototype.getTracerProvider=function(){return y(he)||this._proxyTracerProvider};t.prototype.getTracer=function(t,e){return this.getTracerProvider().getTracer(t,e)};t.prototype.disable=function(){x(he,O.instance());this._proxyTracerProvider=new Ht};return t}();var de=le.getInstance();const pe=D("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function me(t){return t.setValue(pe,true)}function be(t){return t.getValue(pe)===true}const ve="=";const we=";";const ge=",";const ye="baggage";const xe=180;const ke=4096;const Se=8192;function _e(t){return t.reduce(((t,e)=>{const i=`${t}${t!==""?ge:""}${e}`;return i.length>Se?t:i}),"")}function Te(t){return t.getAllEntries().map((([t,e])=>{let i=`${encodeURIComponent(t)}=${encodeURIComponent(e.value)}`;if(e.metadata!==undefined){i+=we+e.metadata.toString()}return i}))}function Ee(t){const e=t.split(we);if(e.length<=0)return;const i=e.shift();if(!i)return;const n=i.indexOf(ve);if(n<=0)return;const r=decodeURIComponent(i.substring(0,n).trim());const s=decodeURIComponent(i.substring(n+1).trim());let o;if(e.length>0){o=$(e.join(we))}return{key:r,value:s,metadata:o}}class Ce{inject(t,e,i){const n=fe.getBaggage(t);if(!n||be(t))return;const r=Te(n).filter((t=>t.length<=ke)).slice(0,xe);const s=_e(r);if(s.length>0){i.set(e,ye,s)}}extract(t,e,i){const n=i.get(e,ye);const r=Array.isArray(n)?n.join(ge):n;if(!r)return t;const s={};if(r.length===0){return t}const o=r.split(ge);o.forEach((t=>{const e=Ee(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[ye]}}function Me(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(!Ae(i)){Xt.warn(`Invalid attribute key: ${i}`);continue}const n=t[i];if(!Pe(n)){Xt.warn(`Invalid attribute value set for key: ${i}`);continue}if(Array.isArray(n)){e[i]=n.slice()}else{e[i]=n}}return e}function Ae(t){return typeof t==="string"&&t!==""}function Pe(t){if(t==null){return true}if(Array.isArray(t)){return Oe(t)}return Ie(typeof t)}function Oe(t){let e;for(const i of t){if(i==null)continue;const t=typeof i;if(t===e){continue}if(!e){if(Ie(t)){e=t;continue}return false}return false}return true}function Ie(t){switch(t){case"number":case"boolean":case"string":return true}return false}function Le(){return t=>{Xt.error(Re(t))}}function Re(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 n=i[t];if(n){e[t]=String(n)}}));i=Object.getPrototypeOf(i)}return e}let Ne=Le();function ze(t){try{Ne(t)}catch{}}function $e(t){return undefined}const De=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};const Fe=performance;const Ue="2.2.0";const Be="error.type";const qe="exception.message";const He="exception.stacktrace";const Ve="exception.type";const Ge="http.request.method";const Ze="http.request.method_original";const We="http.response.status_code";const Xe="server.address";const Ye="server.port";const Je="service.name";const Ke="telemetry.sdk.language";const Qe="webjs";const ti="telemetry.sdk.name";const ei="telemetry.sdk.version";const ii="url.full";const ni="user_agent.original";const ri="process.runtime.name";const si={[ti]:"opentelemetry",[ri]:"browser",[Ke]:Qe,[ei]:Ue};const oi=9;const ai=6;const ci=Math.pow(10,ai);const ui=Math.pow(10,oi);function fi(t){const e=t/1e3;const i=Math.trunc(e);const n=Math.round(t%1e3*ci);return[i,n]}function hi(){let t=Fe.timeOrigin;if(typeof t!=="number"){const e=Fe;t=e.timing&&e.timing.fetchStart}return t}function li(t){const e=fi(hi());const i=fi(typeof t==="number"?t:Fe.now());return gi(e,i)}function di(t){if(vi(t)){return t}else if(typeof t==="number"){if(t<hi()){return li(t)}else{return fi(t)}}else if(t instanceof Date){return fi(t.getTime())}else{throw TypeError("Invalid input type")}}function pi(t,e){let i=e[0]-t[0];let n=e[1]-t[1];if(n<0){i-=1;n+=ui}return[i,n]}function mi(t){return t[0]*ui+t[1]}function bi(t){return t[0]*1e6+t[1]/1e3}function vi(t){return Array.isArray(t)&&t.length===2&&typeof t[0]==="number"&&typeof t[1]==="number"}function wi(t){return vi(t)||typeof t==="number"||t instanceof Date}function gi(t,e){const i=[t[0]+e[0],t[1]+e[1]];if(i[1]>=ui){i[1]-=ui;i[0]+=1}return i}var yi;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(yi||(yi={}));class xi{_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 n of this._propagators){try{n.inject(t,e,i)}catch(t){Xt.warn(`Failed to inject with ${n.constructor.name}. Err: ${t.message}`)}}}extract(t,e,i){return this._propagators.reduce(((t,n)=>{try{return n.extract(t,e,i)}catch(t){Xt.warn(`Failed to extract with ${n.constructor.name}. Err: ${t.message}`)}return t}),t)}fields(){return this._fields.slice()}}const ki="[_0-9a-z-*/]";const Si=`[a-z]${ki}{0,255}`;const _i=`[a-z0-9]${ki}{0,240}@[a-z]${ki}{0,13}`;const Ti=new RegExp(`^(?:${Si}|${_i})$`);const Ei=/^[ -~]{0,255}[!-~]$/;const Ci=/,|=/;function Mi(t){return Ti.test(t)}function Ai(t){return Ei.test(t)&&!Ci.test(t)}const Pi=32;const Oi=512;const Ii=",";const Li="=";class Ri{_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+Li+this.get(e));return t}),[]).join(Ii)}_parse(t){if(t.length>Oi)return;this._internalState=t.split(Ii).reverse().reduce(((t,e)=>{const i=e.trim();const n=i.indexOf(Li);if(n!==-1){const r=i.slice(0,n);const s=i.slice(n+1,e.length);if(Mi(r)&&Ai(s)){t.set(r,s)}}return t}),new Map);if(this._internalState.size>Pi){this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Pi))}}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const t=new Ri;t._internalState=new Map(this._internalState);return t}}const ji="traceparent";const Ni="tracestate";const zi="00";const $i="(?!ff)[\\da-f]{2}";const Di="(?![0]{32})[\\da-f]{32}";const Fi="(?![0]{16})[\\da-f]{16}";const Ui="[\\da-f]{2}";const Bi=new RegExp(`^\\s?(${$i})-(${Di})-(${Fi})-(${Ui})(-.*)?\\s?$`);function qi(t){const e=Bi.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 Hi{inject(t,e,i){const n=de.getSpanContext(t);if(!n||be(t)||!jt(n))return;const r=`${zi}-${n.traceId}-${n.spanId}-0${Number(n.traceFlags||gt.NONE).toString(16)}`;i.set(e,ji,r);if(n.traceState){i.set(e,Ni,n.traceState.serialize())}}extract(t,e,i){const n=i.get(e,ji);if(!n)return t;const r=Array.isArray(n)?n[0]:n;if(typeof r!=="string")return t;const s=qi(r);if(!s)return t;s.isRemote=true;const o=i.get(e,Ni);if(o){const t=Array.isArray(o)?o.join(","):o;s.traceState=new Ri(typeof t==="string"?t:undefined)}return de.setSpanContext(t,s)}fields(){return[ji,Ni]}}const Vi="[object Object]";const Gi="[object Null]";const Zi="[object Undefined]";const Wi=Function.prototype;const Xi=Wi.toString;const Yi=Xi.call(Object);const Ji=Object.getPrototypeOf;const Ki=Object.prototype;const Qi=Ki.hasOwnProperty;const tn=Symbol?Symbol.toStringTag:undefined;const en=Ki.toString;function nn(t){if(!rn(t)||sn(t)!==Vi){return false}const e=Ji(t);if(e===null){return true}const i=Qi.call(e,"constructor")&&e.constructor;return typeof i=="function"&&i instanceof i&&Xi.call(i)===Yi}function rn(t){return t!=null&&typeof t=="object"}function sn(t){if(t==null){return t===undefined?Zi:Gi}return tn&&tn in Object(t)?on(t):an(t)}function on(t){const e=Qi.call(t,tn),i=t[tn];let n=false;try{t[tn]=undefined;n=true}catch{}const r=en.call(t);if(n){if(e){t[tn]=i}else{delete t[tn]}}return r}function an(t){return en.call(t)}const cn=20;function un(...t){let e=t.shift();const i=new WeakMap;while(t.length>0){e=hn(e,t.shift(),0,i)}return e}function fn(t){if(dn(t)){return t.slice()}return t}function hn(t,e,i=0,n){let r;if(i>cn){return undefined}i++;if(bn(t)||bn(e)||pn(e)){r=fn(e)}else if(dn(t)){r=t.slice();if(dn(e)){for(let t=0,i=e.length;t<i;t++){r.push(fn(e[t]))}}else if(mn(e)){const t=Object.keys(e);for(let i=0,n=t.length;i<n;i++){const n=t[i];r[n]=fn(e[n])}}}else if(mn(t)){if(mn(e)){if(!vn(t,e)){return e}r=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(bn(c)){if(typeof c==="undefined"){delete r[a]}else{r[a]=c}}else{const s=r[a];const o=c;if(ln(t,a,n)||ln(e,a,n)){delete r[a]}else{if(mn(s)&&mn(o)){const i=n.get(s)||[];const r=n.get(o)||[];i.push({obj:t,key:a});r.push({obj:e,key:a});n.set(s,i);n.set(o,r)}r[a]=hn(r[a],c,i,n)}}}}else{r=e}}return r}function ln(t,e,i){const n=i.get(t[e])||[];for(let i=0,r=n.length;i<r;i++){const r=n[i];if(r.key===e&&r.obj===t){return true}}return false}function dn(t){return Array.isArray(t)}function pn(t){return typeof t==="function"}function mn(t){return!bn(t)&&!dn(t)&&!pn(t)&&typeof t==="object"}function bn(t){return typeof t==="string"||typeof t==="number"||typeof t==="boolean"||typeof t==="undefined"||t instanceof Date||t instanceof RegExp||t===null}function vn(t,e){if(!nn(t)||!nn(e)){return false}return true}function wn(t,e){if(typeof e==="string"){return t===e}else{return!!t.match(e)}}function gn(t,e){if(!e){return false}for(const i of e){if(wn(t,i)){return true}}return false}class yn{_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 xn{_callback;_that;_isCalled=false;_deferred=new yn;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 kn(t,e){return new Promise((i=>{Wt.with(me(Wt.active()),(()=>{t.export(e,(t=>{i(t)}))}))}))}const Sn={_export:kn};function _n(){return"unknown_service"}const Tn=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";class En{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,e){const i=new En({},e);i._rawAttributes=An(t);i._asyncAttributesPending=t.filter((([t,e])=>Tn(e))).length>0;return i}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(Tn(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=An(this._rawAttributes);this._schemaUrl=Pn(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,Tn(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(Tn(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=On(this,t);const i=e?{schemaUrl:e}:undefined;return En.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],i)}}function Cn(t,e){return En.FromAttributeList(Object.entries(t),e)}function Mn(){return Cn({[Je]:_n(),[Ke]:si[Ke],[ti]:si[ti],[ei]:si[ei]})}function An(t){return t.map((([t,e])=>{if(Tn(e)){return[t,e.catch((e=>{Xt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function Pn(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 On(t,e){const i=t?.schemaUrl;const n=e?.schemaUrl;const r=i===undefined||i==="";const s=n===undefined||n==="";if(r){return n}if(s){return i}if(i===n){return i}Xt.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',i,n);return undefined}const In="exception";class Ln{_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=Fe.now();this._performanceOffset=e-(this._performanceStartTime+hi());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:n}=this._spanLimits;if(n===0){Xt.warn("No events allowed.");this._droppedEventsCount++;return this}if(n!==undefined&&this.events.length>=n){if(this._droppedEventsCount===0){Xt.debug("Dropping extra events.")}this.events.shift();this._droppedEventsCount++}if(wi(e)){if(!wi(i)){i=e}e=undefined}const r=Me(e);this.events.push({name:t,attributes:r,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=pi(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<=Fe.now()){return li(t+this._performanceOffset)}if(typeof t==="number"){return fi(t)}if(t instanceof Date){return fi(t.getTime())}if(vi(t)){return t}if(this._startTimeProvided){return fi(Date.now())}const e=Fe.now()-this._performanceStartTime;return gi(this.startTime,fi(e))}isRecording(){return this._ended===false}recordException(t,e){const i={};if(typeof t==="string"){i[qe]=t}else if(t){if(t.code){i[Ve]=t.code.toString()}else if(t.name){i[Ve]=t.name}if(t.message){i[qe]=t.message}if(t.stack){i[He]=t.stack}}if(i[Ve]||i[qe]){this.addEvent(In,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 Rn;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(Rn||(Rn={}));class jn{shouldSample(){return{decision:Rn.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class Nn{shouldSample(){return{decision:Rn.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class zn{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(t){this._root=t.root;if(!this._root){ze(new Error("ParentBasedSampler must have a root sampler configured"));this._root=new Nn}this._remoteParentSampled=t.remoteParentSampled??new Nn;this._remoteParentNotSampled=t.remoteParentNotSampled??new jn;this._localParentSampled=t.localParentSampled??new Nn;this._localParentNotSampled=t.localParentNotSampled??new jn}shouldSample(t,e,i,n,r,s){const o=de.getSpanContext(t);if(!o||!jt(o)){return this._root.shouldSample(t,e,i,n,r,s)}if(o.isRemote){if(o.traceFlags&gt.SAMPLED){return this._remoteParentSampled.shouldSample(t,e,i,n,r,s)}return this._remoteParentNotSampled.shouldSample(t,e,i,n,r,s)}if(o.traceFlags&gt.SAMPLED){return this._localParentSampled.shouldSample(t,e,i,n,r,s)}return this._localParentNotSampled.shouldSample(t,e,i,n,r,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 $n{_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:Lt(e)&&this._accumulate(e)<this._upperBound?Rn.RECORD_AND_SAMPLED:Rn.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 n=i*8;const r=parseInt(t.slice(n,n+8),16);e=(e^r)>>>0}return e}}var Dn;(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"})(Dn||(Dn={}));const Fn=1;function Un(){return{sampler:Bn(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function Bn(){const t=Dn.ParentBasedAlwaysOn;switch(t){case Dn.AlwaysOn:return new Nn;case Dn.AlwaysOff:return new jn;case Dn.ParentBasedAlwaysOn:return new zn({root:new Nn});case Dn.ParentBasedAlwaysOff:return new zn({root:new jn});case Dn.TraceIdRatio:return new $n(qn());case Dn.ParentBasedTraceIdRatio:return new zn({root:new $n(qn())});default:Xt.error(`OTEL_TRACES_SAMPLER value "${t}" invalid, defaulting to "${Dn.ParentBasedAlwaysOn}".`);return new zn({root:new Nn})}}function qn(){{Xt.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${Fn}.`);return Fn}}const Hn=128;const Vn=Infinity;function Gn(t){const e={sampler:Bn()};const i=Un();const n=Object.assign({},i,e,t);n.generalLimits=Object.assign({},i.generalLimits,t.generalLimits||{});n.spanLimits=Object.assign({},i.spanLimits,t.spanLimits||{});return n}function Zn(t){const e=Object.assign({},t.spanLimits);e.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??$e()??$e()??Hn;e.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??$e()??$e()??Vn;return Object.assign({},t,{spanLimits:e})}class Wn{_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 xn(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&gt.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 n=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let t=0,e=n;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(me(Wt.active()),(()=>{let n;if(this._finishedSpans.length<=this._maxExportBatchSize){n=this._finishedSpans;this._finishedSpans=[]}else{n=this._finishedSpans.splice(0,this._maxExportBatchSize)}const r=()=>this._exporter.export(n,(n=>{clearTimeout(i);if(n.code===yi.SUCCESS){t()}else{e(n.error??new Error("BatchSpanProcessor: span export failed"))}}));let s=null;for(let t=0,e=n.length;t<e;t++){const e=n[t];if(e.resource.asyncAttributesPending&&e.resource.waitForAsyncAttributes){s??=[];s.push(e.resource.waitForAsyncAttributes())}}if(s===null){r()}else{Promise.all(s).then(r,(t=>{ze(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;ze(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 Xn extends Wn{_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=>{ze(t)}))}};this._pageHideListener=()=>{this.forceFlush().catch((t=>{ze(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 Yn=8;const Jn=16;class Kn{generateTraceId=tr(Jn);generateSpanId=tr(Yn)}const Qn=Array(32);function tr(t){return function e(){for(let e=0;e<t*2;e++){Qn[e]=Math.floor(Math.random()*16)+48;if(Qn[e]>=58){Qn[e]+=39}}return String.fromCharCode.apply(null,Qn.slice(0,t*2))}}class er{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(t,e,i,n){const r=Gn(e);this._sampler=r.sampler;this._generalLimits=r.generalLimits;this._spanLimits=r.spanLimits;this._idGenerator=e.idGenerator||new Kn;this._resource=i;this._spanProcessor=n;this.instrumentationScope=t}startSpan(t,e={},i=Wt.active()){if(e.root){i=de.deleteSpan(i)}const n=de.getSpan(i);if(be(i)){Xt.debug("Instrumentation suppressed, returning Noop Span");const t=de.wrapSpanContext(kt);return t}const r=n?.spanContext();const s=this._idGenerator.generateSpanId();let o;let a;let c;if(!r||!de.isSpanContextValid(r)){a=this._idGenerator.generateTraceId()}else{a=r.traceId;c=r.traceState;o=r}const u=e.kind??Gt.INTERNAL;const f=(e.links??[]).map((t=>({context:t.context,attributes:Me(t.attributes)})));const h=Me(e.attributes);const l=this._sampler.shouldSample(i,a,t,u,h,f);c=l.traceState??c;const d=l.decision===Vt.RECORD_AND_SAMPLED?gt.SAMPLED:gt.NONE;const p={traceId:a,spanId:s,traceFlags:d,traceState:c};if(l.decision===Vt.NOT_RECORD){Xt.debug("Recording is off, propagating context in a non-recording span");const t=de.wrapSpanContext(p);return t}const m=Me(Object.assign(h,l.attributes));const b=new Ln({resource:this._resource,scope:this.instrumentationScope,context:i,spanContext:p,name:t,kind:u,links:f,parentSpanContext:o,attributes:m,startTime:e.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits});return b}startActiveSpan(t,e,i,n){let r;let s;let o;if(arguments.length<2){return}else if(arguments.length===2){o=e}else if(arguments.length===3){r=e;o=i}else{r=e;s=i;o=n}const a=s??Wt.active();const c=this.startSpan(t,r,a);const u=de.setSpan(a,c);return Wt.with(u,o,undefined,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class ir{_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=>{ze(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 nr;(function(t){t[t["resolved"]=0]="resolved";t[t["timeout"]=1]="timeout";t[t["error"]=2]="error";t[t["unresolved"]=3]="unresolved"})(nr||(nr={}));class rr{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(t={}){const e=un({},Un(),Zn(t));this._resource=e.resource??Mn();this._config=Object.assign({},e,{resource:this._resource});const i=[];if(t.spanProcessors?.length){i.push(...t.spanProcessors)}this._activeSpanProcessor=new ir(i)}getTracer(t,e,i){const n=`${t}@${e||""}:${i?.schemaUrl||""}`;if(!this._tracers.has(n)){this._tracers.set(n,new er({name:t,version:e,schemaUrl:i?.schemaUrl},this._config,this._resource,this._activeSpanProcessor))}return this._tracers.get(n)}forceFlush(){const t=this._config.forceFlushTimeoutMillis;const e=this._activeSpanProcessor["_spanProcessors"].map((e=>new Promise((i=>{let n;const r=setTimeout((()=>{i(new Error(`Span processor did not completed within timeout period of ${t} ms`));n=nr.timeout}),t);e.forceFlush().then((()=>{clearTimeout(r);if(n!==nr.timeout){n=nr.resolved;i(n)}})).catch((t=>{clearTimeout(r);n=nr.error;i(t)}))}))));return new Promise(((t,i)=>{Promise.all(e).then((e=>{const n=e.filter((t=>t!==nr.resolved));if(n.length>0){i(n)}else{t()}})).catch((t=>i([t])))}))}shutdown(){return this._activeSpanProcessor.shutdown()}}class sr{_enabled=false;_currentContext=U;_bindFunction(t=U,e){const i=this;const n=function(...n){return i.with(t,(()=>e.apply(this,n)))};Object.defineProperty(n,"length",{enumerable:false,configurable:true,writable:false,value:e.length});return n}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=U;this._enabled=false;return this}enable(){if(this._enabled){return this}this._enabled=true;this._currentContext=U;return this}with(t,e,i,...n){const r=this._currentContext;this._currentContext=t||U;try{return e.call(i,...n)}finally{this._currentContext=r}}}function or(t){if(t===null){return}if(t===undefined){const t=new sr;t.enable();Wt.setGlobalContextManager(t);return}t.enable();Wt.setGlobalContextManager(t)}function ar(t){if(t===null){return}if(t===undefined){fe.setGlobalPropagator(new xi({propagators:[new Hi,new Ce]}));return}fe.setGlobalPropagator(t)}class cr extends rr{constructor(t={}){super(t)}register(t={}){de.setGlobalTracerProvider(this);ar(t.propagator);or(t.contextManager)}}var ur;(function(t){t["CONNECT_END"]="connectEnd";t["CONNECT_START"]="connectStart";t["DECODED_BODY_SIZE"]="decodedBodySize";t["DOM_COMPLETE"]="domComplete";t["DOM_CONTENT_LOADED_EVENT_END"]="domContentLoadedEventEnd";t["DOM_CONTENT_LOADED_EVENT_START"]="domContentLoadedEventStart";t["DOM_INTERACTIVE"]="domInteractive";t["DOMAIN_LOOKUP_END"]="domainLookupEnd";t["DOMAIN_LOOKUP_START"]="domainLookupStart";t["ENCODED_BODY_SIZE"]="encodedBodySize";t["FETCH_START"]="fetchStart";t["LOAD_EVENT_END"]="loadEventEnd";t["LOAD_EVENT_START"]="loadEventStart";t["NAVIGATION_START"]="navigationStart";t["REDIRECT_END"]="redirectEnd";t["REDIRECT_START"]="redirectStart";t["REQUEST_START"]="requestStart";t["RESPONSE_END"]="responseEnd";t["RESPONSE_START"]="responseStart";t["SECURE_CONNECTION_START"]="secureConnectionStart";t["START_TIME"]="startTime";t["UNLOAD_EVENT_END"]="unloadEventEnd";t["UNLOAD_EVENT_START"]="unloadEventStart"})(ur||(ur={}));const fr="http.response_content_length";const hr="http.response_content_length_uncompressed";let lr;function dr(){if(!lr){lr=document.createElement("a")}return lr}function pr(t,e){return e in t}function mr(t,e,i,n=true){if(pr(i,e)&&typeof i[e]==="number"&&!(n&&i[e]===0)){return t.addEvent(e,i[e])}return undefined}function br(t,e,i=false,n,r){if(n===undefined){n=e[ur.START_TIME]!==0}if(!i){mr(t,ur.FETCH_START,e,n);mr(t,ur.DOMAIN_LOOKUP_START,e,n);mr(t,ur.DOMAIN_LOOKUP_END,e,n);mr(t,ur.CONNECT_START,e,n);mr(t,ur.SECURE_CONNECTION_START,e,n);mr(t,ur.CONNECT_END,e,n);mr(t,ur.REQUEST_START,e,n);mr(t,ur.RESPONSE_START,e,n);mr(t,ur.RESPONSE_END,e,n)}if(!r){const i=e[ur.ENCODED_BODY_SIZE];if(i!==undefined){t.setAttribute(fr,i)}const n=e[ur.DECODED_BODY_SIZE];if(n!==undefined&&i!==n){t.setAttribute(hr,n)}}}function vr(t){return t.slice().sort(((t,e)=>{const i=t[ur.FETCH_START];const n=e[ur.FETCH_START];if(i>n){return 1}else if(i<n){return-1}return 0}))}function wr(){return typeof location!=="undefined"?location.origin:undefined}function gr(t,e,i,n,r=new WeakSet,s){const o=kr(t);t=o.toString();const a=xr(t,e,i,n,r,s);if(a.length===0){return{mainRequest:undefined}}if(a.length===1){return{mainRequest:a[0]}}const c=vr(a);if(o.origin!==wr()&&c.length>1){let t=c[0];let e=yr(c,t[ur.RESPONSE_END],i);const n=t[ur.RESPONSE_END];const r=e[ur.FETCH_START];if(r<n){e=t;t=undefined}return{corsPreFlightRequest:t,mainRequest:e}}else{return{mainRequest:a[0]}}}function yr(t,e,i){const n=mi(i);const r=mi(di(e));let s=t[1];let o;const a=t.length;for(let e=1;e<a;e++){const i=t[e];const a=mi(di(i[ur.FETCH_START]));const c=mi(di(i[ur.RESPONSE_END]));const u=n-c;if(a>=r&&(!o||u<o)){o=u;s=i}}return s}function xr(t,e,i,n,r,s){const o=mi(e);const a=mi(i);let c=n.filter((e=>{const i=mi(di(e[ur.FETCH_START]));const n=mi(di(e[ur.RESPONSE_END]));return e.initiatorType.toLowerCase()===(s||"xmlhttprequest")&&e.name===t&&i>=o&&n<=a}));if(c.length>0){c=c.filter((t=>!r.has(t)))}return c}function kr(t){if(typeof URL==="function"){return new URL(t,typeof document!=="undefined"?document.baseURI:typeof location!=="undefined"?location.href:undefined)}const e=dr();e.href=t;return e}function Sr(t,e){if(t.nodeType===Node.DOCUMENT_NODE){return"/"}const i=Tr(t,e);if(e&&i.indexOf("@id")>0){return i}let n="";if(t.parentNode){n+=Sr(t.parentNode,false)}n+=i;return n}function _r(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 n=i.localName;return e.indexOf(i.nodeType)>=0&&n===t.localName}));if(i.length>=1){return i.indexOf(t)+1}return 0}function Tr(t,e){const i=t.nodeType;const n=_r(t);let r="";if(i===Node.ELEMENT_NODE){const i=t.getAttribute("id");if(e&&i){return`//*[@id="${i}"]`}r=t.localName}else if(i===Node.TEXT_NODE||i===Node.CDATA_SECTION_NODE){r="text()"}else if(i===Node.COMMENT_NODE){r="comment()"}else{return""}if(r&&n>1){return`/${r}[${n}]`}return`/${r}`}function Er(t,e){let i=e||[];if(typeof i==="string"||i instanceof RegExp){i=[i]}const n=kr(t);if(n.origin===wr()){return true}else{return i.some((e=>wn(t,e)))}}class Cr{_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 Mr extends Error{code;name="OTLPExporterError";data;constructor(t,e,i){super(t);this.data=i;this.code=e}}function Ar(t){if(Number.isFinite(t)&&t>0){return t}throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${t}')`)}function Pr(t){if(t==null){return undefined}return async()=>t}function Or(t,e,i){return{timeoutMillis:Ar(t.timeoutMillis??e.timeoutMillis??i.timeoutMillis),concurrencyLimit:t.concurrencyLimit??e.concurrencyLimit??i.concurrencyLimit,compression:t.compression??e.compression??i.compression}}function Ir(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class Lr{_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 Rr(t){return new Lr(t.concurrencyLimit)}function jr(t){return Object.prototype.hasOwnProperty.call(t,"partialSuccess")}function Nr(){return{handleResponse(t){if(t==null||!jr(t)||t.partialSuccess==null||Object.keys(t.partialSuccess).length===0){return}Xt.warn("Received Partial Success response:",JSON.stringify(t.partialSuccess))}}}class zr{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(t,e,i,n,r){this._transport=t;this._serializer=e;this._responseHandler=i;this._promiseQueue=n;this._timeout=r;this._diagLogger=Xt.createComponentLogger({namespace:"OTLPExportDelegate"})}export(t,e){this._diagLogger.debug("items to be sent",t);if(this._promiseQueue.hasReachedLimit()){e({code:yi.FAILED,error:new Error("Concurrent export limit reached")});return}const i=this._serializer.serializeRequest(t);if(i==null){e({code:yi.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:yi.SUCCESS});return}else if(t.status==="failure"&&t.error){e({code:yi.FAILED,error:t.error});return}else if(t.status==="retryable"){e({code:yi.FAILED,error:new Mr("Export failed with retryable status")})}else{e({code:yi.FAILED,error:new Mr("Export failed with unknown error")})}}),(t=>e({code:yi.FAILED,error:t}))))}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started");await this.forceFlush();this._transport.shutdown()}}function $r(t,e){return new zr(t.transport,t.serializer,Nr(),t.promiseHandler,e.timeout)}function Dr(t,e,i){return $r({transport:i,serializer:e,promiseHandler:Rr(t)},{timeout:t.timeoutMillis})}function Fr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t["default"]:t}function Ur(t){if(t>=48&&t<=57){return t-48}if(t>=97&&t<=102){return t-87}return t-55}function Br(t){const e=new Uint8Array(t.length/2);let i=0;for(let n=0;n<t.length;n+=2){const r=Ur(t.charCodeAt(n));const s=Ur(t.charCodeAt(n+1));e[i++]=r<<4|s}return e}function qr(t){const e=BigInt(1e9);return BigInt(Math.trunc(t[0]))*e+BigInt(Math.trunc(t[1]))}function Hr(t){const e=Number(BigInt.asUintN(32,t));const i=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:i}}function Vr(t){const e=qr(t);return Hr(e)}function Gr(t){const e=qr(t);return e.toString()}const Zr=typeof BigInt!=="undefined"?Gr:mi;function Wr(t){return t}function Xr(t){if(t===undefined)return undefined;return Br(t)}const Yr={encodeHrTime:Vr,encodeSpanContext:Br,encodeOptionalSpanContext:Xr};function Jr(t){if(t===undefined){return Yr}const e=t.useLongBits??true;const i=t.useHex??false;return{encodeHrTime:e?Vr:Zr,encodeSpanContext:i?Wr:Br,encodeOptionalSpanContext:i?Wr:Xr}}function Kr(t){const e={attributes:ts(t.attributes),droppedAttributesCount:0};const i=t.schemaUrl;if(i&&i!=="")e.schemaUrl=i;return e}function Qr(t){return{name:t.name,version:t.version}}function ts(t){return Object.keys(t).map((e=>es(e,t[e])))}function es(t,e){return{key:t,value:is(e)}}function is(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(is)}};if(e==="object"&&t!=null)return{kvlistValue:{values:Object.entries(t).map((([t,e])=>es(t,e)))}};return{}}var ns;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(ns||(ns={}));var rs;(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"})(rs||(rs={}));var ss;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(ss||(ss={}));function os(t){return t!==undefined&&t!==null}function as(t){let e=Object.keys(t);if(e.length===0)return"";e=e.sort();return JSON.stringify(e.map((e=>[e,t[e]])))}function cs(t){return`${t.name}:${t.version??""}:${t.schemaUrl??""}`}class us extends Error{constructor(t){super(t);Object.setPrototypeOf(this,us.prototype)}}function fs(t,e){let i;const n=new Promise((function t(n,r){i=setTimeout((function t(){r(new us("Operation timed out."))}),e)}));return Promise.race([t,n]).then((t=>{clearTimeout(i);return t}),(t=>{clearTimeout(i);throw t}))}async function hs(t){return Promise.all(t.map((async t=>{try{const e=await t;return{status:"fulfilled",value:e}}catch(t){return{status:"rejected",reason:t}}})))}function ls(t){return t.status==="rejected"}function ds(t,e){const i=[];t.forEach((t=>{i.push(...e(t))}));return i}function ps(t,e){if(t.size!==e.size){return false}for(const i of t){if(!e.has(i)){return false}}return true}function ms(t,e){let i=0;let n=t.length-1;let r=t.length;while(n>=i){const s=i+Math.trunc((n-i)/2);if(t[s]<e){i=s+1}else{r=s;n=s-1}}return r}function bs(t,e){return t.toLowerCase()===e.toLowerCase()}var vs;(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"})(vs||(vs={}));class ws{kind=vs.DROP;createAccumulation(){return undefined}merge(t,e){return undefined}diff(t,e){return undefined}toMetricData(t,e,i,n){return undefined}}function gs(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 ys{startTime;_boundaries;_recordMinMax;_current;constructor(t,e,i=true,n=gs(e)){this.startTime=t;this._boundaries=e;this._recordMinMax=i;this._current=n}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=ms(this._boundaries,t);this._current.buckets.counts[e]+=1}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class xs{_boundaries;_recordMinMax;kind=vs.HISTOGRAM;constructor(t,e){this._boundaries=t;this._recordMinMax=e}createAccumulation(t){return new ys(t,this._boundaries,this._recordMinMax)}merge(t,e){const i=t.toPointValue();const n=e.toPointValue();const r=i.buckets.counts;const s=n.buckets.counts;const o=new Array(r.length);for(let t=0;t<r.length;t++){o[t]=r[t]+s[t]}let a=Infinity;let c=-Infinity;if(this._recordMinMax){if(i.hasMinMax&&n.hasMinMax){a=Math.min(i.min,n.min);c=Math.max(i.max,n.max)}else if(i.hasMinMax){a=i.min;c=i.max}else if(n.hasMinMax){a=n.min;c=n.max}}return new ys(t.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:i.count+n.count,sum:i.sum+n.sum,hasMinMax:this._recordMinMax&&(i.hasMinMax||n.hasMinMax),min:a,max:c})}diff(t,e){const i=t.toPointValue();const n=e.toPointValue();const r=i.buckets.counts;const s=n.buckets.counts;const o=new Array(r.length);for(let t=0;t<r.length;t++){o[t]=s[t]-r[t]}return new ys(e.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:n.count-i.count,sum:n.sum-i.sum,hasMinMax:false,min:Infinity,max:-Infinity})}toMetricData(t,e,i,n){return{descriptor:t,aggregationTemporality:e,dataPointType:ss.HISTOGRAM,dataPoints:i.map((([e,i])=>{const r=i.toPointValue();const s=t.type===rs.GAUGE||t.type===rs.UP_DOWN_COUNTER||t.type===rs.OBSERVABLE_GAUGE||t.type===rs.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:n,value:{min:r.hasMinMax?r.min:undefined,max:r.hasMinMax?r.max:undefined,sum:!s?r.sum:undefined,buckets:r.buckets,count:r.count}}}))}}}class ks{backing;indexBase;indexStart;indexEnd;constructor(t=new Ss,e=0,i=0,n=0){this.backing=t;this.indexBase=e;this.indexStart=i;this.indexEnd=n}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 n=0;let r=0;for(let t=this.indexStart;t<=this.indexEnd;){let s=t%i;if(s<0){s+=i}for(let o=s;o<i&&n<e;o++){this._relocateBucket(r,n);n++;t++}r++}this.indexStart>>=t;this.indexEnd>>=t;this.indexBase=this.indexStart}clone(){return new ks(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 Ss{_counts;constructor(t=[0]){this._counts=t}get length(){return this._counts.length}countAt(t){return this._counts[t]}growTo(t,e,i){const n=new Array(t).fill(0);n.splice(i,this._counts.length-e,...this._counts.slice(e));n.splice(0,e,...this._counts.slice(0,e));this._counts=n}reverse(t,e){const i=Math.floor((t+e)/2)-t;for(let n=0;n<i;n++){const i=this._counts[t+n];this._counts[t+n]=this._counts[e-n-1];this._counts[e-n-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 Ss([...this._counts])}}const _s=52;const Ts=2146435072;const Es=1048575;const Cs=1023;const Ms=-1023+1;const As=Cs;const Ps=Math.pow(2,-1022);function Os(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const n=(i&Ts)>>20;return n-Cs}function Is(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const n=e.getUint32(4);const r=(i&Es)*Math.pow(2,32);return r+n}function Ls(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 Rs(t){t--;t|=t>>1;t|=t>>2;t|=t>>4;t|=t>>8;t|=t>>16;t++;return t}class js extends Error{}class Ns{_shift;constructor(t){this._shift=-t}mapToIndex(t){if(t<Ps){return this._minNormalLowerBoundaryIndex()}const e=Os(t);const i=this._rightShift(Is(t)-1,_s);return e+i>>this._shift}lowerBoundary(t){const e=this._minNormalLowerBoundaryIndex();if(t<e){throw new js(`underflow: ${t} is < minimum lower boundary: ${e}`)}const i=this._maxNormalLowerBoundaryIndex();if(t>i){throw new js(`overflow: ${t} is > maximum lower boundary: ${i}`)}return Ls(1,t<<this._shift)}get scale(){if(this._shift===0){return 0}return-this._shift}_minNormalLowerBoundaryIndex(){let t=Ms>>this._shift;if(this._shift<2){t--}return t}_maxNormalLowerBoundaryIndex(){return As>>this._shift}_rightShift(t,e){return Math.floor(t*Math.pow(2,-e))}}class zs{_scale;_scaleFactor;_inverseFactor;constructor(t){this._scale=t;this._scaleFactor=Ls(Math.LOG2E,t);this._inverseFactor=Ls(Math.LN2,-t)}mapToIndex(t){if(t<=Ps){return this._minNormalLowerBoundaryIndex()-1}if(Is(t)===0){const e=Os(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 js(`overflow: ${t} is > maximum lower boundary: ${e}`)}const i=this._minNormalLowerBoundaryIndex();if(t<=i){if(t===i){return Ps}else if(t===i-1){return Math.exp((t+(1<<this._scale))/this._scaleFactor)/2}throw new js(`overflow: ${t} is < minimum lower boundary: ${i}`)}return Math.exp(t*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Ms<<this._scale}_maxNormalLowerBoundaryIndex(){return(As+1<<this._scale)-1}}const $s=-10;const Ds=20;const Fs=Array.from({length:31},((t,e)=>{if(e>10){return new zs(e-10)}return new Ns(e-10)}));function Us(t){if(t>Ds||t<$s){throw new js(`expected scale >= ${$s} && <= ${Ds}, got: ${t}`)}return Fs[t+10]}class Bs{low;high;static combine(t,e){return new Bs(Math.min(t.low,e.low),Math.max(t.high,e.high))}constructor(t,e){this.low=t;this.high=e}}const qs=20;const Hs=160;const Vs=2;class Gs{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(t,e=Hs,i=true,n=0,r=0,s=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new ks,u=new ks,f=Us(qs)){this.startTime=t;this._maxSize=e;this._recordMinMax=i;this._sum=n;this._count=r;this._zeroCount=s;this._min=o;this._max=a;this._positive=c;this._negative=u;this._mapping=f;if(this._maxSize<Vs){Xt.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${Vs}`);this._maxSize=Vs}}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 Gs(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 n=this._mapping.mapToIndex(e);let r=false;let s=0;let o=0;if(t.length===0){t.indexStart=n;t.indexEnd=t.indexStart;t.indexBase=t.indexStart}else if(n<t.indexStart&&t.indexEnd-n>=this._maxSize){r=true;o=n;s=t.indexEnd}else if(n>t.indexEnd&&n-t.indexStart>=this._maxSize){r=true;o=t.indexStart;s=n}if(r){const t=this._changeScale(s,o);this._downscale(t);n=this._mapping.mapToIndex(e)}this._incrementIndexBy(t,n,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 n=e-t.indexBase;if(n<0){n+=t.backing.length}t.incrementBucket(n,i)}_grow(t,e){const i=t.backing.length;const n=t.indexBase-t.indexStart;const r=i-n;let s=Rs(e);if(s>this._maxSize){s=this._maxSize}const o=s-n;t.backing.growTo(s,r,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=Us(e)}_minScale(t){const e=Math.min(this.scale,t.scale);const i=Bs.combine(this._highLowAtScale(this.positive,this.scale,e),this._highLowAtScale(t.positive,t.scale,e));const n=Bs.combine(this._highLowAtScale(this.negative,this.scale,e),this._highLowAtScale(t.negative,t.scale,e));return Math.min(e-this._changeScale(i.high,i.low),e-this._changeScale(n.high,n.low))}_highLowAtScale(t,e,i){if(t.length===0){return new Bs(0,-1)}const n=e-i;return new Bs(t.indexStart>>n,t.indexEnd>>n)}_mergeBuckets(t,e,i,n){const r=i.offset;const s=e.scale-n;for(let e=0;e<i.length;e++){this._incrementIndexBy(t,r+e>>s,i.at(e))}}_diffBuckets(t,e,i,n){const r=i.offset;const s=e.scale-n;for(let e=0;e<i.length;e++){const n=r+e>>s;let o=n-t.indexBase;if(o<0){o+=t.backing.length}t.decrementBucket(o,i.at(e))}t.trim()}}class Zs{_maxSize;_recordMinMax;kind=vs.EXPONENTIAL_HISTOGRAM;constructor(t,e){this._maxSize=t;this._recordMinMax=e}createAccumulation(t){return new Gs(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,n){return{descriptor:t,aggregationTemporality:e,dataPointType:ss.EXPONENTIAL_HISTOGRAM,dataPoints:i.map((([e,i])=>{const r=i.toPointValue();const s=t.type===rs.GAUGE||t.type===rs.UP_DOWN_COUNTER||t.type===rs.OBSERVABLE_GAUGE||t.type===rs.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:n,value:{min:r.hasMinMax?r.min:undefined,max:r.hasMinMax?r.max:undefined,sum:!s?r.sum:undefined,positive:{offset:r.positive.offset,bucketCounts:r.positive.bucketCounts},negative:{offset:r.negative.offset,bucketCounts:r.negative.bucketCounts},count:r.count,scale:r.scale,zeroCount:r.zeroCount}}}))}}}class Ws{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=fi(Date.now())}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Xs{kind=vs.LAST_VALUE;createAccumulation(t){return new Ws(t)}merge(t,e){const i=bi(e.sampleTime)>=bi(t.sampleTime)?e:t;return new Ws(t.startTime,i.toPointValue(),i.sampleTime)}diff(t,e){const i=bi(e.sampleTime)>=bi(t.sampleTime)?e:t;return new Ws(e.startTime,i.toPointValue(),i.sampleTime)}toMetricData(t,e,i,n){return{descriptor:t,aggregationTemporality:e,dataPointType:ss.GAUGE,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:n,value:e.toPointValue()})))}}}class Ys{startTime;monotonic;_current;reset;constructor(t,e,i=0,n=false){this.startTime=t;this.monotonic=e;this._current=i;this.reset=n}record(t){if(this.monotonic&&t<0){return}this._current+=t}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Js{monotonic;kind=vs.SUM;constructor(t){this.monotonic=t}createAccumulation(t){return new Ys(t,this.monotonic)}merge(t,e){const i=t.toPointValue();const n=e.toPointValue();if(e.reset){return new Ys(e.startTime,this.monotonic,n,e.reset)}return new Ys(t.startTime,this.monotonic,i+n)}diff(t,e){const i=t.toPointValue();const n=e.toPointValue();if(this.monotonic&&i>n){return new Ys(e.startTime,this.monotonic,n,true)}return new Ys(e.startTime,this.monotonic,n-i)}toMetricData(t,e,i,n){return{descriptor:t,aggregationTemporality:e,dataPointType:ss.SUM,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:n,value:e.toPointValue()}))),isMonotonic:this.monotonic}}}class Ks{static DEFAULT_INSTANCE=new ws;createAggregator(t){return Ks.DEFAULT_INSTANCE}}class Qs{static MONOTONIC_INSTANCE=new Js(true);static NON_MONOTONIC_INSTANCE=new Js(false);createAggregator(t){switch(t.type){case rs.COUNTER:case rs.OBSERVABLE_COUNTER:case rs.HISTOGRAM:{return Qs.MONOTONIC_INSTANCE}default:{return Qs.NON_MONOTONIC_INSTANCE}}}}class to{static DEFAULT_INSTANCE=new Xs;createAggregator(t){return to.DEFAULT_INSTANCE}}class eo{static DEFAULT_INSTANCE=new xs([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],true);createAggregator(t){return eo.DEFAULT_INSTANCE}}class io{_recordMinMax;_boundaries;constructor(t,e=true){this._recordMinMax=e;if(t==null){throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array")}t=t.concat();t=t.sort(((t,e)=>t-e));const i=t.lastIndexOf(-Infinity);let n=t.indexOf(Infinity);if(n===-1){n=undefined}this._boundaries=t.slice(i+1,n)}createAggregator(t){return new xs(this._boundaries,this._recordMinMax)}}class no{_maxSize;_recordMinMax;constructor(t=160,e=true){this._maxSize=t;this._recordMinMax=e}createAggregator(t){return new Zs(this._maxSize,this._recordMinMax)}}class ro{_resolve(t){switch(t.type){case rs.COUNTER:case rs.UP_DOWN_COUNTER:case rs.OBSERVABLE_COUNTER:case rs.OBSERVABLE_UP_DOWN_COUNTER:{return oo}case rs.GAUGE:case rs.OBSERVABLE_GAUGE:{return ao}case rs.HISTOGRAM:{if(t.advice.explicitBucketBoundaries){return new io(t.advice.explicitBucketBoundaries)}return co}}Xt.warn(`Unable to recognize instrument type: ${t.type}`);return so}createAggregator(t){return this._resolve(t).createAggregator(t)}}const so=new Ks;const oo=new Qs;const ao=new to;const co=new eo;const uo=new ro;var fo;(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"})(fo||(fo={}));function ho(t){switch(t.type){case fo.DEFAULT:return uo;case fo.DROP:return so;case fo.SUM:return oo;case fo.LAST_VALUE:return ao;case fo.EXPONENTIAL_HISTOGRAM:{const e=t;return new no(e.options?.maxSize,e.options?.recordMinMax)}case fo.EXPLICIT_BUCKET_HISTOGRAM:{const e=t;if(e.options==null){return co}else{return new io(e.options?.boundaries,e.options?.recordMinMax)}}default:throw new Error("Unsupported Aggregation")}}const lo=t=>({type:fo.DEFAULT});const po=t=>ns.CUMULATIVE;class mo{_shutdown=false;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(t){this._aggregationSelector=t?.aggregationSelector??lo;this._aggregationTemporalitySelector=t?.aggregationTemporalitySelector??po;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 n=e.errors.concat(ds(i,(t=>t.errors)));const r=e.resourceMetrics.resource;const s=e.resourceMetrics.scopeMetrics.concat(ds(i,(t=>t.resourceMetrics.scopeMetrics)));return{resourceMetrics:{resource:r,scopeMetrics:s},errors:n}}async shutdown(t){if(this._shutdown){Xt.error("Cannot call shutdown twice.");return}if(t?.timeoutMillis==null){await this.onShutdown()}else{await fs(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 fs(this.onForceFlush(),t.timeoutMillis)}}class bo extends mo{_interval;_exporter;_exportInterval;_exportTimeout;constructor(t){super({aggregationSelector:t.exporter.selectAggregation?.bind(t.exporter),aggregationTemporalitySelector:t.exporter.selectAggregationTemporality?.bind(t.exporter),metricProducers:t.metricProducers});if(t.exportIntervalMillis!==undefined&&t.exportIntervalMillis<=0){throw Error("exportIntervalMillis must be greater than 0")}if(t.exportTimeoutMillis!==undefined&&t.exportTimeoutMillis<=0){throw Error("exportTimeoutMillis must be greater than 0")}if(t.exportTimeoutMillis!==undefined&&t.exportIntervalMillis!==undefined&&t.exportIntervalMillis<t.exportTimeoutMillis){throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis")}this._exportInterval=t.exportIntervalMillis??6e4;this._exportTimeout=t.exportTimeoutMillis??3e4;this._exporter=t.exporter}async _runOnce(){try{await fs(this._doRun(),this._exportTimeout)}catch(t){if(t instanceof us){Xt.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);return}ze(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);ze(t)}}if(t.scopeMetrics.length===0){return}const i=await Sn._export(this._exporter,t);if(i.code!==yi.SUCCESS){throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${i.error})`)}}onInitialized(){this._interval=setInterval((()=>{void this._runOnce()}),this._exportInterval);if(typeof this._interval!=="number"){this._interval.unref()}}async onForceFlush(){await this._runOnce();await this._exporter.forceFlush()}async onShutdown(){if(this._interval){clearInterval(this._interval)}await this.onForceFlush();await this._exporter.shutdown()}}class vo{_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 wo(t,e,i){if(!ko(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??ct.DOUBLE,advice:i?.advice??{}}}function go(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 yo(t,e){return bs(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}const xo=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function ko(t){return t.match(xo)!=null}class So{_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===ct.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,fi(Date.now()))}}class _o extends So{add(t,e,i){this._record(t,e,i)}}class To extends So{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 Eo extends So{record(t,e,i){this._record(t,e,i)}}class Co extends So{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 Mo{_observableRegistry;_metricStorages;_descriptor;constructor(t,e,i){this._observableRegistry=i;this._descriptor=t;this._metricStorages=e}addCallback(t){this._observableRegistry.addCallback(t,this)}removeCallback(t){this._observableRegistry.removeCallback(t,this)}}class Ao extends Mo{}class Po extends Mo{}class Oo extends Mo{}function Io(t){return t instanceof Mo}class Lo{_meterSharedState;constructor(t){this._meterSharedState=t}createGauge(t,e){const i=wo(t,rs.GAUGE,e);const n=this._meterSharedState.registerMetricStorage(i);return new Eo(n,i)}createHistogram(t,e){const i=wo(t,rs.HISTOGRAM,e);const n=this._meterSharedState.registerMetricStorage(i);return new Co(n,i)}createCounter(t,e){const i=wo(t,rs.COUNTER,e);const n=this._meterSharedState.registerMetricStorage(i);return new To(n,i)}createUpDownCounter(t,e){const i=wo(t,rs.UP_DOWN_COUNTER,e);const n=this._meterSharedState.registerMetricStorage(i);return new _o(n,i)}createObservableGauge(t,e){const i=wo(t,rs.OBSERVABLE_GAUGE,e);const n=this._meterSharedState.registerAsyncMetricStorage(i);return new Po(i,n,this._meterSharedState.observableRegistry)}createObservableCounter(t,e){const i=wo(t,rs.OBSERVABLE_COUNTER,e);const n=this._meterSharedState.registerAsyncMetricStorage(i);return new Ao(i,n,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(t,e){const i=wo(t,rs.OBSERVABLE_UP_DOWN_COUNTER,e);const n=this._meterSharedState.registerAsyncMetricStorage(i);return new Oo(i,n,this._meterSharedState.observableRegistry)}addBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.addBatchCallback(t,e)}removeBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.removeBatchCallback(t,e)}}class Ro{_instrumentDescriptor;constructor(t){this._instrumentDescriptor=t}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(t){this._instrumentDescriptor=wo(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:t,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class jo{_hash;_valueMap=new Map;_keyMap=new Map;constructor(t){this._hash=t}get(t,e){e??=this._hash(t);return this._valueMap.get(e)}getOrDefault(t,e){const i=this._hash(t);if(this._valueMap.has(i)){return this._valueMap.get(i)}const n=e();if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,n);return n}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 No extends jo{constructor(){super(as)}}class zo{_aggregator;_activeCollectionStorage=new No;_cumulativeMemoStorage=new No;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":true};_overflowHashCode;constructor(t,e){this._aggregator=t;this._cardinalityLimit=(e??2e3)-1;this._overflowHashCode=as(this._overflowAttributes)}record(t,e,i,n){let r=this._activeCollectionStorage.get(e);if(!r){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const e=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,(()=>this._aggregator.createAccumulation(n)));e?.record(t);return}r=this._aggregator.createAccumulation(n);this._activeCollectionStorage.set(e,r)}r?.record(t)}batchCumulate(t,e){Array.from(t.entries()).forEach((([t,i,n])=>{const r=this._aggregator.createAccumulation(e);r?.record(i);let s=r;if(this._cumulativeMemoStorage.has(t,n)){const e=this._cumulativeMemoStorage.get(t,n);s=this._aggregator.diff(e,r)}else{if(this._cumulativeMemoStorage.size>=this._cardinalityLimit){t=this._overflowAttributes;n=this._overflowHashCode;if(this._cumulativeMemoStorage.has(t,n)){const e=this._cumulativeMemoStorage.get(t,n);s=this._aggregator.diff(e,r)}}}if(this._activeCollectionStorage.has(t,n)){const e=this._activeCollectionStorage.get(t,n);s=this._aggregator.merge(e,s)}this._cumulativeMemoStorage.set(t,r,n);this._activeCollectionStorage.set(t,s,n)}))}collect(){const t=this._activeCollectionStorage;this._activeCollectionStorage=new No;return t}}class $o{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(t,e){this._aggregator=t;e.forEach((t=>{this._unreportedAccumulations.set(t,[])}))}buildMetrics(t,e,i,n){this._stashAccumulations(i);const r=this._getMergedUnreportedAccumulations(t);let s=r;let o;if(this._reportHistory.has(t)){const e=this._reportHistory.get(t);const i=e.collectionTime;o=e.aggregationTemporality;if(o===ns.CUMULATIVE){s=$o.merge(e.accumulations,r,this._aggregator)}else{s=$o.calibrateStartTime(e.accumulations,r,i)}}else{o=t.selectAggregationTemporality(e.type)}this._reportHistory.set(t,{accumulations:s,collectionTime:n,aggregationTemporality:o});const a=Do(s);if(a.length===0){return undefined}return this._aggregator.toMetricData(e,o,a,n)}_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 No;const i=this._unreportedAccumulations.get(t);this._unreportedAccumulations.set(t,[]);if(i===undefined){return e}for(const t of i){e=$o.merge(e,t,this._aggregator)}return e}static merge(t,e,i){const n=t;const r=e.entries();let s=r.next();while(s.done!==true){const[e,o,a]=s.value;if(t.has(e,a)){const r=t.get(e,a);const s=i.merge(r,o);n.set(e,s,a)}else{n.set(e,o,a)}s=r.next()}return n}static calibrateStartTime(t,e,i){for(const[n,r]of t.keys()){const t=e.get(n,r);t?.setStartTime(i)}return e}}function Do(t){return Array.from(t.entries())}class Fo extends Ro{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(t,e,i,n,r){super(t);this._attributesProcessor=i;this._aggregationCardinalityLimit=r;this._deltaMetricStorage=new zo(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new $o(e,n)}record(t,e){const i=new No;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 Uo(t,e){let i="";if(t.unit!==e.unit){i+=`\t- Unit '${t.unit}' does not match '${e.unit}'\n`}if(t.type!==e.type){i+=`\t- Type '${t.type}' does not match '${e.type}'\n`}if(t.valueType!==e.valueType){i+=`\t- Value Type '${t.valueType}' does not match '${e.valueType}'\n`}if(t.description!==e.description){i+=`\t- Description '${t.description}' does not match '${e.description}'\n`}return i}function Bo(t,e){return`\t- use valueType '${t.valueType}' on instrument creation or use an instrument name other than '${e.name}'`}function qo(t,e){return`\t- use unit '${t.unit}' on instrument creation or use an instrument name other than '${e.name}'`}function Ho(t,e){const i={name:e.name,type:e.type,unit:e.unit};const n=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${n}'`}function Vo(t,e){const i={name:e.name,type:e.type,unit:e.unit};const n=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${n}'\n \t- OR - create a new view with the name ${t.name} and description '${t.description}' and InstrumentSelector ${n}\n \t- OR - create a new view with the name ${e.name} and description '${t.description}' and InstrumentSelector ${n}`}function Go(t,e){if(t.valueType!==e.valueType){return Bo(t,e)}if(t.unit!==e.unit){return qo(t,e)}if(t.type!==e.type){return Ho(t,e)}if(t.description!==e.description){return Vo(t,e)}return""}class Zo{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new Zo}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 n=i.get(e.name);if(n===undefined){return null}return this._findOrUpdateCompatibleStorage(e,n)}_registerStorage(t,e){const i=t.getInstrumentDescriptor();const n=e.get(i.name);if(n===undefined){e.set(i.name,[t]);return}n.push(t)}_findOrUpdateCompatibleStorage(t,e){let i=null;for(const n of e){const e=n.getInstrumentDescriptor();if(yo(e,t)){if(e.description!==t.description){if(t.description.length>e.description.length){n.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",Uo(e,t),"The longer description will be used.\nTo resolve the conflict:",Go(e,t))}i=n}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",Uo(e,t),"To resolve the conflict:\n",Go(e,t))}}return i}}class Wo{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,i,n){this._backingStorages.forEach((r=>{r.record(t,e,i,n)}))}}class Xo{_instrumentName;_valueType;_buffer=new No;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===ct.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 Yo{_buffer=new Map;observe(t,e,i={}){if(!Io(t)){return}let n=this._buffer.get(t);if(n==null){n=new No;this._buffer.set(t,n)}if(typeof e!=="number"){Xt.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}if(t._descriptor.valueType===ct.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}}n.set(i,e)}}class Jo{_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(Io));if(i.size===0){Xt.error("BatchObservableCallback is not associated with valid instruments",e);return}const n=this._findBatchCallback(t,i);if(n>=0){return}this._batchCallbacks.push({callback:t,instruments:i})}removeBatchCallback(t,e){const i=new Set(e.filter(Io));const n=this._findBatchCallback(t,i);if(n<0){return}this._batchCallbacks.splice(n,1)}async observe(t,e){const i=this._observeCallbacks(t,e);const n=this._observeBatchCallbacks(t,e);const r=await hs([...i,...n]);const s=r.filter(ls).map((t=>t.reason));return s}_observeCallbacks(t,e){return this._callbacks.map((async({callback:i,instrument:n})=>{const r=new Xo(n._descriptor.name,n._descriptor.valueType);let s=Promise.resolve(i(r));if(e!=null){s=fs(s,e)}await s;n._metricStorages.forEach((e=>{e.record(r._buffer,t)}))}))}_observeBatchCallbacks(t,e){return this._batchCallbacks.map((async({callback:i,instruments:n})=>{const r=new Yo;let s=Promise.resolve(i(r));if(e!=null){s=fs(s,e)}await s;n.forEach((e=>{const i=r._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&&ps(i.instruments,e)))}}class Ko extends Ro{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(t,e,i,n,r){super(t);this._attributesProcessor=i;this._aggregationCardinalityLimit=r;this._deltaMetricStorage=new zo(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new $o(e,n)}record(t,e,i,n){e=this._attributesProcessor.process(e,i);this._deltaMetricStorage.record(t,e,i,n)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}class Qo{process(t,e){return t}}class ta{_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 ea(){return na}function ia(t){return new ta(t)}const na=new Qo;class ra{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new Zo;observableRegistry=new Jo;meter;constructor(t,e){this._meterProviderSharedState=t;this._instrumentationScope=e;this.meter=new Lo(this)}registerMetricStorage(t){const e=this._registerMetricStorage(t,Ko);if(e.length===1){return e[0]}return new Wo(e)}registerAsyncMetricStorage(t){const e=this._registerMetricStorage(t,Fo);return e}async collect(t,e,i){const n=await this.observableRegistry.observe(e,i?.timeoutMillis);const r=this.metricStorageRegistry.getStorages(t);if(r.length===0){return null}const s=r.map((i=>i.collect(t,e))).filter(os);if(s.length===0){return{errors:n}}return{scopeMetrics:{scope:this._instrumentationScope,metrics:s},errors:n}}_registerMetricStorage(t,e){const i=this._meterProviderSharedState.viewRegistry.findViews(t,this._instrumentationScope);let n=i.map((i=>{const n=go(i,t);const r=this.metricStorageRegistry.findOrUpdateCompatibleStorage(n);if(r!=null){return r}const s=i.aggregation.createAggregator(n);const o=new e(n,s,i.attributesProcessor,this._meterProviderSharedState.metricCollectors,i.aggregationCardinalityLimit);this.metricStorageRegistry.register(o);return o}));if(n.length===0){const i=this._meterProviderSharedState.selectAggregations(t.type);const r=i.map((([i,n])=>{const r=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(i,t);if(r!=null){return r}const s=n.createAggregator(t);const o=i.selectCardinalityLimit(t.type);const a=new e(t,s,ea(),[i],o);this.metricStorageRegistry.registerForCollector(i,a);return a}));n=n.concat(r)}return n}}class sa{resource;viewRegistry=new vo;metricCollectors=[];meterSharedStates=new Map;constructor(t){this.resource=t}getMeterSharedState(t){const e=cs(t);let i=this.meterSharedStates.get(e);if(i==null){i=new ra(this,t);this.meterSharedStates.set(e,i)}return i}selectAggregations(t){const e=[];for(const i of this.metricCollectors){e.push([i,ho(i.selectAggregation(t))])}return e}}class oa{_sharedState;_metricReader;constructor(t,e){this._sharedState=t;this._metricReader=e}async collect(t){const e=fi(Date.now());const i=[];const n=[];const r=Array.from(this._sharedState.meterSharedStates.values()).map((async r=>{const s=await r.collect(this,e,t);if(s?.scopeMetrics!=null){i.push(s.scopeMetrics)}if(s?.errors!=null){n.push(...s.errors)}}));await Promise.all(r);return{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:i},errors:n}}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 aa=/[\^$\\.+?()[\]{}|]/g;class ca{_matchAll;_regexp;constructor(t){if(t==="*"){this._matchAll=true;this._regexp=/.*/}else{this._matchAll=false;this._regexp=new RegExp(ca.escapePattern(t))}}match(t){if(this._matchAll){return true}return this._regexp.test(t)}static escapePattern(t){return`^${t.replace(aa,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}}class ua{_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 fa{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new ca(t?.name??"*");this._type=t?.type;this._unitFilter=new ua(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class ha{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new ua(t?.name);this._versionFilter=new ua(t?.version);this._schemaUrlFilter=new ua(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function la(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}function da(t){if(la(t)){throw new Error("Cannot create view with no selector arguments supplied")}if(t.name!=null&&(t?.instrumentName==null||ca.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 pa{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){da(t);if(t.attributesProcessors!=null){this.attributesProcessor=ia(t.attributesProcessors)}else{this.attributesProcessor=ea()}this.name=t.name;this.description=t.description;this.aggregation=ho(t.aggregation??{type:fo.DEFAULT});this.instrumentSelector=new fa({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit});this.meterSelector=new ha({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl});this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}}class ma{_sharedState;_shutdown=false;constructor(t){this._sharedState=new sa(t?.resource??Mn());if(t?.views!=null&&t.views.length>0){for(const e of t.views){this._sharedState.viewRegistry.addView(new pa(e))}}if(t?.readers!=null&&t.readers.length>0){for(const e of t.readers){const t=new oa(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 at()}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 ba;(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"})(ba||(ba={}));function va(t,e){const i=Jr(e);const n=Kr(t.resource);return{resource:n,schemaUrl:n.schemaUrl,scopeMetrics:wa(t.scopeMetrics,i)}}function wa(t,e){return Array.from(t.map((t=>({scope:Qr(t.scope),metrics:t.metrics.map((t=>ga(t,e))),schemaUrl:t.scope.schemaUrl}))))}function ga(t,e){const i={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit};const n=_a(t.aggregationTemporality);switch(t.dataPointType){case ss.SUM:i.sum={aggregationTemporality:n,isMonotonic:t.isMonotonic,dataPoints:xa(t,e)};break;case ss.GAUGE:i.gauge={dataPoints:xa(t,e)};break;case ss.HISTOGRAM:i.histogram={aggregationTemporality:n,dataPoints:ka(t,e)};break;case ss.EXPONENTIAL_HISTOGRAM:i.exponentialHistogram={aggregationTemporality:n,dataPoints:Sa(t,e)};break}return i}function ya(t,e,i){const n={attributes:ts(t.attributes),startTimeUnixNano:i.encodeHrTime(t.startTime),timeUnixNano:i.encodeHrTime(t.endTime)};switch(e){case ct.INT:n.asInt=t.value;break;case ct.DOUBLE:n.asDouble=t.value;break}return n}function xa(t,e){return t.dataPoints.map((i=>ya(i,t.descriptor.valueType,e)))}function ka(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:ts(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 Sa(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:ts(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 _a(t){switch(t){case ns.DELTA:return ba.AGGREGATION_TEMPORALITY_DELTA;case ns.CUMULATIVE:return ba.AGGREGATION_TEMPORALITY_CUMULATIVE}}function Ta(t,e){return{resourceMetrics:t.map((t=>va(t,e)))}}const Ea=256;const Ca=512;function Ma(t,e){let i=t&255|Ea;if(e){i|=Ca}return i}function Aa(t,e){const i=t.spanContext();const n=t.status;const r=t.parentSpanContext?.spanId?e.encodeSpanContext(t.parentSpanContext?.spanId):undefined;return{traceId:e.encodeSpanContext(i.traceId),spanId:e.encodeSpanContext(i.spanId),parentSpanId:r,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:ts(t.attributes),droppedAttributesCount:t.droppedAttributesCount,events:t.events.map((t=>Oa(t,e))),droppedEventsCount:t.droppedEventsCount,status:{code:n.code,message:n.message},links:t.links.map((t=>Pa(t,e))),droppedLinksCount:t.droppedLinksCount,flags:Ma(i.traceFlags,t.parentSpanContext?.isRemote)}}function Pa(t,e){return{attributes:t.attributes?ts(t.attributes):[],spanId:e.encodeSpanContext(t.context.spanId),traceId:e.encodeSpanContext(t.context.traceId),traceState:t.context.traceState?.serialize(),droppedAttributesCount:t.droppedAttributesCount||0,flags:Ma(t.context.traceFlags,t.context.isRemote)}}function Oa(t,e){return{attributes:t.attributes?ts(t.attributes):[],name:t.name,timeUnixNano:e.encodeHrTime(t.time),droppedAttributesCount:t.droppedAttributesCount||0}}function Ia(t,e){const i=Jr(e);return{resourceSpans:Ra(t,i)}}function La(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 n=`${i.instrumentationScope.name}@${i.instrumentationScope.version||""}:${i.instrumentationScope.schemaUrl||""}`;let r=t.get(n);if(!r){r=[];t.set(n,r)}r.push(i)}return e}function Ra(t,e){const i=La(t);const n=[];const r=i.entries();let s=r.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=>Aa(t,e)));o.push({scope:Qr(t[0].instrumentationScope),spans:i,schemaUrl:t[0].instrumentationScope.schemaUrl})}c=a.next()}const u=Kr(t);const f={resource:u,scopeSpans:o,schemaUrl:u.schemaUrl};n.push(f);s=r.next()}return n}const ja={serializeRequest:t=>{const e=Ta([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 Na={serializeRequest:t=>{const e=Ia(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 za=5;const $a=1e3;const Da=5e3;const Fa=1.5;const Ua=.2;function Ba(){return Math.random()*(2*Ua)-Ua}class qa{_transport;constructor(t){this._transport=t}retry(t,e,i){return new Promise(((n,r)=>{setTimeout((()=>{this._transport.send(t,e).then(n,r)}),i)}))}async send(t,e){const i=Date.now()+e;let n=await this._transport.send(t,e);let r=za;let s=$a;while(n.status==="retryable"&&r>0){r--;const e=Math.max(Math.min(s,Da)+Ba(),0);s=s*Fa;const o=n.retryInMillis??e;const a=i-Date.now();if(o>a){return n}n=await this.retry(t,a,o)}return n}shutdown(){return this._transport.shutdown()}}function Ha(t){return new qa(t.transport)}function Va(t){const e=[429,502,503,504];return e.includes(t)}function Ga(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 Za{_parameters;constructor(t){this._parameters=t}async send(t,e){const i=await this._parameters.headers();const n=await new Promise((n=>{const r=new XMLHttpRequest;r.timeout=e;r.open("POST",this._parameters.url);Object.entries(i).forEach((([t,e])=>{r.setRequestHeader(t,e)}));r.ontimeout=t=>{n({status:"failure",error:new Error("XHR request timed out")})};r.onreadystatechange=()=>{if(r.status>=200&&r.status<=299){Xt.debug("XHR success");n({status:"success"})}else if(r.status&&Va(r.status)){n({status:"retryable",retryInMillis:Ga(r.getResponseHeader("Retry-After"))})}else if(r.status!==0){n({status:"failure",error:new Error("XHR request failed with non-retryable status")})}};r.onabort=()=>{n({status:"failure",error:new Error("XHR request aborted")})};r.onerror=()=>{n({status:"failure",error:new Error("XHR request errored")})};r.send(t)}));return n}shutdown(){}}function Wa(t){return new Za(t)}class Xa{_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 Ya(t){return new Xa(t)}class Ja{_parameters;constructor(t){this._parameters=t}async send(t,e){const i=new AbortController;const n=setTimeout((()=>i.abort()),e);try{const e=!!globalThis.location;const n=new URL(this._parameters.url);const r=await fetch(n.href,{method:"POST",headers:await this._parameters.headers(),body:t,signal:i.signal,keepalive:e,mode:e?globalThis.location?.origin===n.origin?"same-origin":"cors":"no-cors"});if(r.status>=200&&r.status<=299){Xt.debug("response success");return{status:"success"}}else if(Va(r.status)){const t=r.headers.get("Retry-After");const e=Ga(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(n)}}shutdown(){}}function Ka(t){return new Ja(t)}function Qa(t,e){return Dr(t,e,Ha({transport:Wa(t)}))}function tc(t,e){return Dr(t,e,Ha({transport:Ka(t)}))}function ec(t,e){return Dr(t,e,Ha({transport:Ya({url:t.url,headers:t.headers})}))}function ic(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 nc(t,e,i){return async()=>{const n={...await i()};const r={};if(e!=null){Object.assign(r,await e())}if(t!=null){Object.assign(r,ic(await t()))}return Object.assign(r,n)}}function rc(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 sc(t,e,i){return{...Or(t,e,i),headers:nc(t.headers,e.headers,i.headers),url:rc(t.url)??e.url??i.url}}function oc(t,e){return{...Ir(),headers:async()=>t,url:"http://localhost:4318/"+e}}function ac(t){if(typeof t.headers==="function"){return t.headers}return Pr(t.headers)}function cc(t,e,i){return sc({url:t.url,timeoutMillis:t.timeoutMillis,headers:ac(t),concurrencyLimit:t.concurrencyLimit},{},oc(i,e))}function uc(t,e,i,n){const r=fc(t.headers);const s=cc(t,i,n);return r(s,e)}function fc(t){if(!t&&typeof navigator.sendBeacon==="function"){return ec}else if(typeof globalThis.fetch!=="undefined"){return tc}else{return Qa}}class hc extends Cr{constructor(t={}){super(uc(t,Na,"v1/traces",{"Content-Type":"application/json"}))}}function lc(t){return typeof t==="object"&&t!==null&&"addEventListener"in t&&typeof t.addEventListener==="function"&&"removeEventListener"in t&&typeof t.removeEventListener==="function"}const dc="OT_ZONE_CONTEXT";class pc{_enabled=false;_zoneCounter=0;_activeContextFromZone(t){return t&&t.get(dc)||U}_bindFunction(t,e){const i=this;const n=function(...n){return i.with(t,(()=>e.apply(this,n)))};Object.defineProperty(n,"length",{enumerable:false,configurable:true,writable:false,value:e.length});return n}_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:{[dc]:e}})}_getActiveZone(){return Zone.current}_patchAddEventListener(t,e,i){const n=this;return function(r,s,o){if(t.__ot_listeners===undefined){t.__ot_listeners={}}let a=t.__ot_listeners[r];if(a===undefined){a=new WeakMap;t.__ot_listeners[r]=a}const c=n.bind(i,s);a.set(s,c);return e.call(this,r,c,o)}}_patchRemoveEventListener(t,e){return function(i,n){if(t.__ot_listeners===undefined||t.__ot_listeners[i]===undefined){return e.call(this,i,n)}const r=t.__ot_listeners[i];const s=r.get(n);r.delete(n);return e.call(this,i,s||n)}}active(){if(!this._enabled){return U}const t=this._getActiveZone();const e=this._activeContextFromZone(t);if(e){return e}return U}bind(t,e){if(t===undefined){t=this.active()}if(typeof e==="function"){return this._bindFunction(t,e)}else if(lc(e)){this._bindListener(t,e)}return e}disable(){this._enabled=false;return this}enable(){this._enabled=true;return this}with(t,e,i,...n){const r=this._createZoneName();const s=this._createZone(r,t);return s.run(e,i,n)}}var mc={};var bc;function vc(){if(bc)return mc;bc=1;var t=mc&&mc.__assign||function(){t=Object.assign||function(t){for(var e,i=1,n=arguments.length;i<n;i++){e=arguments[i];for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r))t[r]=e[r]}return t};return t.apply(this,arguments)};
2
+ /**
3
+ * @license Angular v<unknown>
4
+ * (c) 2010-2025 Google LLC. https://angular.io/
5
+ * License: MIT
6
+ */(function(t){t()})((function(){var e=globalThis;function i(t){var i=e["__Zone_symbol_prefix"]||"__zone_symbol__";return i+t}function n(){var t=e["performance"];function n(e){t&&t["mark"]&&t["mark"](e)}function r(e,i){t&&t["measure"]&&t["measure"](e,i)}n("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 P.zone},enumerable:false,configurable:true});Object.defineProperty(t,"currentTask",{get:function(){return O},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;n(u);M[s]=o(e,t,A);r(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 n=this;return function(){return n.runGuarded(i,this,arguments,e)}};t.prototype.run=function(t,e,i,n){P={parent:P,zone:this};try{return this._zoneDelegate.invoke(this,t,e,i,n)}finally{P=P.parent}};t.prototype.runGuarded=function(t,e,i,n){if(e===void 0){e=null}P={parent:P,zone:this};try{try{return this._zoneDelegate.invoke(this,t,e,i,n)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{P=P.parent}};t.prototype.runTask=function(t,e,i){if(t.zone!=this){throw new Error("A task can only be run in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")")}var n=t;var r=t.type,s=t.data,o=s===void 0?{}:s,a=o.isPeriodic,c=a===void 0?false:a,u=o.isRefreshable,f=u===void 0?false:u;if(t.state===g&&(r===C||r===E)){return}var h=t.state!=k;h&&n._transitionTo(k,x);var l=O;O=n;P={parent:P,zone:this};try{if(r==E&&t.data&&!c&&!f){t.cancelFn=undefined}try{return this._zoneDelegate.invokeTask(this,n,e,i)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{var d=t.state;if(d!==g&&d!==_){if(r==C||c||f&&d===y){h&&n._transitionTo(x,k,y)}else{var p=n._zoneDelegates;this._updateTaskCount(n,-1);h&&n._transitionTo(g,k,g);if(f){n._zoneDelegates=p}}}P=P.parent;O=l}};t.prototype.scheduleTask=function(t){if(t.zone&&t.zone!==this){var e=this;while(e){if(e===t.zone){throw Error("can not reschedule task to ".concat(this.name," which is descendants of the original zone ").concat(t.zone.name))}e=e.parent}}t._transitionTo(y,g);var i=[];t._zoneDelegates=i;t._zone=this;try{t=this._zoneDelegate.scheduleTask(this,t)}catch(e){t._transitionTo(_,y,g);this._zoneDelegate.handleError(this,e);throw e}if(t._zoneDelegates===i){this._updateTaskCount(t,1)}if(t.state==y){t._transitionTo(x,y)}return t};t.prototype.scheduleMicroTask=function(t,e,i,n){return this.scheduleTask(new c(T,t,e,i,n,undefined))};t.prototype.scheduleMacroTask=function(t,e,i,n,r){return this.scheduleTask(new c(E,t,e,i,n,r))};t.prototype.scheduleEventTask=function(t,e,i,n,r){return this.scheduleTask(new c(C,t,e,i,n,r))};t.prototype.cancelTask=function(t){if(t.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")");if(t.state!==x&&t.state!==k){return}t._transitionTo(S,x,k);try{this._zoneDelegate.cancelTask(this,t)}catch(e){t._transitionTo(_,S);this._zoneDelegate.handleError(this,e);throw e}this._updateTaskCount(t,-1);t._transitionTo(g,S);t.runCount=-1;return t};t.prototype._updateTaskCount=function(t,e){var i=t._zoneDelegates;if(e==-1){t._zoneDelegates=null}for(var n=0;n<i.length;n++){i[n]._updateTaskCount(t.type,e)}};t.__symbol__=i;return t}();var o={name:"",onHasTask:function(t,e,i,n){return t.hasTask(i,n)},onScheduleTask:function(t,e,i,n){return t.scheduleTask(i,n)},onInvokeTask:function(t,e,i,n,r,s){return t.invokeTask(i,n,r,s)},onCancelTask:function(t,e,i,n){return t.cancelTask(i,n)}};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 n=i&&i.onHasTask;var r=e&&e._hasTaskZS;if(n||r){this._hasTaskZS=n?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,n,r){return this._invokeZS?this._invokeZS.onInvoke(this._invokeDlgt,this._invokeCurrZone,t,e,i,n,r):e.apply(i,n)};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,n){return this._invokeTaskZS?this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt,this._invokeTaskCurrZone,t,e,i,n):e.callback.apply(i,n)};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 n=i[t];var r=i[t]=n+e;if(r<0){throw new Error("More tasks executed then were scheduled.")}if(n==0||r==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,n,r,s,o,a){this._zone=null;this.runCount=0;this._zoneDelegates=null;this._state="notScheduled";this.type=i;this.source=n;this.data=s;this.scheduleFn=o;this.cancelFn=a;if(!r){throw new Error("callback is not defined")}this.callback=r;var c=this;if(i===C&&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}I++;try{t.runCount++;return t.zone.runTask(t,e,i)}finally{if(I==1){v()}I--}};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 f=i("Promise");var h=i("then");var l=[];var d=false;var p;function m(t){if(!p){if(e[f]){p=e[f].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(I===0&&l.length===0){m(v)}t&&l.push(t)}function v(){if(!d){d=true;while(l.length){var t=l;l=[];for(var e=0;e<t.length;e++){var i=t[e];try{i.zone.runTask(i,null,null)}catch(t){A.onUnhandledError(t)}}}A.microtaskDrainDone();d=false}}var w={name:"NO ZONE"};var g="notScheduled",y="scheduling",x="scheduled",k="running",S="canceling",_="unknown";var T="microTask",E="macroTask",C="eventTask";var M={};var A={symbol:i,currentZoneFrame:function(){return P},onUnhandledError:L,microtaskDrainDone:L,scheduleMicroTask:b,showUncaughtError:function(){return!s[i("ignoreConsoleErrorUncaughtError")]},patchEventTarget:function(){return[]},patchOnProperties:L,patchMethod:function(){return L},bindArguments:function(){return[]},patchThen:function(){return L},patchMacroTask:function(){return L},patchEventPrototype:function(){return L},isIEOrEdge:function(){return false},getGlobalObjects:function(){return undefined},ObjectDefineProperty:function(){return L},ObjectGetOwnPropertyDescriptor:function(){return undefined},ObjectCreate:function(){return undefined},ArraySlice:function(){return[]},patchClass:function(){return L},wrapWithCurrentZone:function(){return L},filterProperties:function(){return[]},attachOriginToPatched:function(){return L},_redefineProperty:function(){return L},patchCallbacks:function(){return L},nativeScheduleMicroTask:m};var P={parent:null,zone:new s(null,null)};var O=null;var I=0;function L(){}r("Zone","Zone");return s}function r(){var t;var e=globalThis;var r=e[i("forceDuplicateZoneCheck")]===true;if(e["Zone"]&&(r||typeof e["Zone"].__symbol__!=="function")){throw new Error("Zone already loaded.")}(t=e["Zone"])!==null&&t!==void 0?t:e["Zone"]=n();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 f="addEventListener";var h="removeEventListener";var l=i(f);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,n,r){return Zone.current.scheduleMacroTask(t,e,i,n,r)}var g=i;var y=typeof window!=="undefined";var x=y?window:undefined;var k=y&&x||globalThis;var S="removeAttribute";function _(t,e){for(var i=t.length-1;i>=0;i--){if(typeof t[i]==="function"){t[i]=v(t[i],e+"_"+i)}}return t}function T(t,e){var i=t.constructor["name"];var n=function(n){var r=e[n];var o=t[r];if(o){var a=s(t,r);if(!E(a)){return"continue"}t[r]=function(t){var e=function(){return t.apply(this,_(arguments,i+"."+r))};F(e,t);return e}(o)}};for(var r=0;r<e.length;r++){n(r)}}function E(t){if(!t){return true}if(t.writable===false){return false}return!(typeof t.get==="function"&&typeof t.set==="undefined")}var C=typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope;var M=!("nw"in k)&&typeof k.process!=="undefined"&&k.process.toString()==="[object process]";var A=!M&&!C&&!!(y&&x["HTMLElement"]);var P=typeof k.process!=="undefined"&&k.process.toString()==="[object process]"&&!C&&!!(y&&x["HTMLElement"]);var O={};var I=g("enable_beforeunload");var L=function(t){t=t||k.event;if(!t){return}var e=O[t.type];if(!e){e=O[t.type]=g("ON_PROPERTY"+t.type)}var i=this||t.target||k;var n=i[e];var r;if(A&&i===x&&t.type==="error"){var s=t;r=n&&n.call(this,s.message,s.filename,s.lineno,s.colno,s.error);if(r===true){t.preventDefault()}}else{r=n&&n.apply(this,arguments);if(t.type==="beforeunload"&&k[I]&&typeof r==="string"){t.returnValue=r}else if(r!=undefined&&!r){t.preventDefault()}}return r};function R(t,e,i){var n=s(t,e);if(!n&&i){var r=s(i,e);if(r){n={enumerable:true,configurable:true}}}if(!n||!n.configurable){return}var a=g("on"+e+"patched");if(t.hasOwnProperty(a)&&t[a]){return}delete n.writable;delete n.value;var c=n.get;var u=n.set;var f=e.slice(2);var h=O[f];if(!h){h=O[f]=g("ON_PROPERTY"+f)}n.set=function(e){var i=this;if(!i&&t===k){i=k}if(!i){return}var n=i[h];if(typeof n==="function"){i.removeEventListener(f,L)}u===null||u===void 0?void 0:u.call(i,null);i[h]=e;if(typeof e==="function"){i.addEventListener(f,L,false)}};n.get=function(){var i=this;if(!i&&t===k){i=k}if(!i){return null}var r=i[h];if(r){return r}else if(c){var s=c.call(this);if(s){n.set.call(this,s);if(typeof i[S]==="function"){i.removeAttribute(e)}return s}}return null};o(t,e,n);t[a]=true}function j(t,e,i){if(e){for(var n=0;n<e.length;n++){R(t,"on"+e[n],i)}}else{var r=[];for(var s in t){if(s.slice(0,2)=="on"){r.push(s)}}for(var o=0;o<r.length;o++){R(t,r[o],i)}}}var N=g("originalInstance");function z(t){var e=k[t];if(!e)return;k[g(t)]=e;k[t]=function(){var i=_(arguments,t);switch(i.length){case 0:this[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.")}};F(k[t],e);var i=new e((function(){}));var n;for(n in i){if(t==="XMLHttpRequest"&&n==="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);F(this[N][e],i)}else{this[N][e]=i}},get:function(){return this[N][e]}})}})(n)}for(n in e){if(n!=="prototype"&&e.hasOwnProperty(n)){k[t][n]=e[n]}}}function $(t,e,i){var n=t;while(n&&!n.hasOwnProperty(e)){n=a(n)}if(!n&&t[e]){n=t}var r=g(e);var o=null;if(n&&(!(o=n[r])||!n.hasOwnProperty(r))){o=n[r]=n[e];var c=n&&s(n,e);if(E(c)){var u=i(o,r,e);n[e]=function(){return u(this,arguments)};F(n[e],o)}}return o}function D(t,e,i){var n=null;function r(t){var e=t.data;e.args[e.cbIdx]=function(){t.invoke.apply(this,arguments)};n.apply(e.target,e.args);return t}n=$(t,e,(function(t){return function(e,n){var s=i(e,n);if(s.cbIdx>=0&&typeof n[s.cbIdx]==="function"){return w(s.name,n[s.cbIdx],s,r)}else{return t.apply(e,n)}}}))}function F(t,e){t[g("OriginalDelegate")]=e}var U=false;var B=false;function q(){if(U){return B}U=true;try{var t=x.navigator.userAgent;if(t.indexOf("MSIE ")!==-1||t.indexOf("Trident/")!==-1||t.indexOf("Edge/")!==-1){B=true}}catch(t){}return B}function H(t){return typeof t==="function"}function V(t){return typeof t==="number"}var G={useG:true};var Z={};var W={};var X=new RegExp("^"+b+"(\\w+)(true|false)$");var Y=g("propagationStopped");function J(t,e){var i=(e?e(t):t)+m;var n=(e?e(t):t)+p;var r=b+i;var s=b+n;Z[t]={};Z[t][m]=r;Z[t][p]=s}function K(e,i,n,r){var s=r&&r.add||f;var o=r&&r.rm||h;var c=r&&r.listeners||"eventListeners";var u=r&&r.rmAll||"removeAllListeners";var l=g(s);var d="."+s+":";var v="prependListener";var w="."+v+":";var y=function(t,e,i){if(t.isRemoved){return}var n=t.callback;if(typeof n==="object"&&n.handleEvent){t.callback=function(t){return n.handleEvent(t)};t.originalDelegate=n}var r;try{t.invoke(t,e,[i])}catch(t){r=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 r};function x(t,n,r){n=n||e.event;if(!n){return}var s=t||n.target||e;var o=s[Z[n.type][r?p:m]];if(o){var a=[];if(o.length===1){var c=y(o[0],s,n);c&&a.push(c)}else{var u=o.slice();for(var f=0;f<u.length;f++){if(n&&n[Y]===true){break}var c=y(u[f],s,n);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 f=0;f<a.length;f++){h(f)}}}}var k=function(t){return x(this,t,false)};var S=function(t){return x(this,t,true)};function _(i,n){if(!i){return false}var r=true;if(n&&n.useG!==undefined){r=n.useG}var f=n&&n.vh;var h=true;if(n&&n.chkDup!==undefined){h=n.chkDup}var y=false;if(n&&n.rt!==undefined){y=n.rt}var x=i;while(x&&!x.hasOwnProperty(s)){x=a(x)}if(!x&&i[s]){x=i}if(!x){return false}if(x[l]){return false}var _=n&&n.eventNameToString;var T={};var E=x[l]=x[s];var C=x[g(o)]=x[o];var A=x[g(c)]=x[c];var P=x[g(u)]=x[u];var O;if(n&&n.prepend){O=x[g(n.prepend)]=x[n.prepend]}function I(e,i){if(!i){return e}if(typeof e==="boolean"){return{capture:e,passive:true}}if(!e){return{passive:true}}if(typeof e==="object"&&e.passive!==false){return t(t({},e),{passive:true})}return e}var L=function(t){if(T.isExisting){return}return E.call(T.target,T.eventName,T.capture?S:k,T.options)};var R=function(t){if(!t.isRemoved){var e=Z[t.eventName];var i=void 0;if(e){i=e[t.capture?p:m]}var n=i&&t.target[i];if(n){for(var r=0;r<n.length;r++){var s=n[r];if(s===t){n.splice(r,1);t.isRemoved=true;if(t.removeAbortListener){t.removeAbortListener();t.removeAbortListener=null}if(n.length===0){t.allRemoved=true;t.target[i]=null}break}}}}if(!t.allRemoved){return}return C.call(t.target,t.eventName,t.capture?S:k,t.options)};var j=function(t){return E.call(T.target,T.eventName,t.invoke,T.options)};var N=function(t){return O.call(T.target,T.eventName,t.invoke,T.options)};var z=function(t){return C.call(t.target,t.eventName,t.invoke,t.options)};var $=r?L:j;var D=r?R:z;var U=function(t,e){var i=typeof e;return i==="function"&&t.callback===e||i==="object"&&t.originalDelegate===e};var B=(n===null||n===void 0?void 0:n.diff)||U;var q=Zone[g("UNPATCHED_EVENTS")];var H=e[g("PASSIVE_EVENTS")];function V(e){if(typeof e==="object"&&e!==null){var i=t({},e);if(e.signal){i.signal=e.signal}return i}return e}var Y=function(t,i,s,o,a,c){if(a===void 0){a=false}if(c===void 0){c=false}return function(){var u=this||e;var l=arguments[0];if(n&&n.transferEventName){l=n.transferEventName(l)}var d=arguments[1];if(!d){return t.apply(this,arguments)}if(M&&l==="uncaughtException"){return t.apply(this,arguments)}var b=false;if(typeof d!=="function"){if(!d.handleEvent){return t.apply(this,arguments)}b=true}if(f&&!f(t,d,u,arguments)){return}var v=!!H&&H.indexOf(l)!==-1;var w=V(I(arguments[2],v));var g=w===null||w===void 0?void 0:w.signal;if(g===null||g===void 0?void 0:g.aborted){return}if(q){for(var y=0;y<q.length;y++){if(l===q[y]){if(v){return t.call(u,l,d,w)}else{return t.apply(this,arguments)}}}}var x=!w?false:typeof w==="boolean"?true:w.capture;var k=w&&typeof w==="object"?w.once:false;var S=Zone.current;var E=Z[l];if(!E){J(l,_);E=Z[l]}var C=E[x?p:m];var A=u[C];var P=false;if(A){P=true;if(h){for(var y=0;y<A.length;y++){if(B(A[y],d)){return}}}}else{A=u[C]=[]}var O;var L=u.constructor["name"];var R=W[L];if(R){O=R[l]}if(!O){O=L+i+(_?_(l):l)}T.options=w;if(k){T.options.once=false}T.target=u;T.capture=x;T.eventName=l;T.isExisting=P;var j=r?G:undefined;if(j){j.taskData=T}if(g){T.options.signal=undefined}var N=S.scheduleEventTask(O,d,j,s,o);if(g){T.options.signal=g;var z=function(){return N.zone.cancelTask(N)};t.call(g,"abort",z,{once:true});N.removeAbortListener=function(){return g.removeEventListener("abort",z)}}T.target=null;if(j){j.taskData=null}if(k){T.options.once=true}if(typeof N.options!=="boolean"){N.options=w}N.target=u;N.capture=x;N.eventName=l;if(b){N.originalDelegate=d}if(!c){A.push(N)}else{A.unshift(N)}if(a){return u}}};x[s]=Y(E,d,$,D,y);if(O){x[v]=Y(O,w,N,D,y,true)}x[o]=function(){var t=this||e;var i=arguments[0];if(n&&n.transferEventName){i=n.transferEventName(i)}var r=arguments[2];var s=!r?false:typeof r==="boolean"?true:r.capture;var o=arguments[1];if(!o){return C.apply(this,arguments)}if(f&&!f(C,o,t,arguments)){return}var a=Z[i];var c;if(a){c=a[s?p:m]}var u=c&&t[c];if(u){for(var h=0;h<u.length;h++){var l=u[h];if(B(l,o)){u.splice(h,1);l.isRemoved=true;if(u.length===0){l.allRemoved=true;t[c]=null;if(!s&&typeof i==="string"){var d=b+"ON_PROPERTY"+i;t[d]=null}}l.zone.cancelTask(l);if(y){return t}return}}}return C.apply(this,arguments)};x[c]=function(){var t=this||e;var i=arguments[0];if(n&&n.transferEventName){i=n.transferEventName(i)}var r=[];var s=Q(t,_?_(i):i);for(var o=0;o<s.length;o++){var a=s[o];var c=a.originalDelegate?a.originalDelegate:a.callback;r.push(c)}return r};x[u]=function(){var t=this||e;var i=arguments[0];if(!i){var r=Object.keys(t);for(var s=0;s<r.length;s++){var a=r[s];var c=X.exec(a);var f=c&&c[1];if(f&&f!=="removeListener"){this[u].call(this,f)}}this[u].call(this,"removeListener")}else{if(n&&n.transferEventName){i=n.transferEventName(i)}var h=Z[i];if(h){var l=h[m];var d=h[p];var b=t[l];var v=t[d];if(b){var w=b.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}if(v){var w=v.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}}}if(y){return this}};F(x[s],E);F(x[o],C);if(P){F(x[u],P)}if(A){F(x[c],A)}return true}var T=[];for(var E=0;E<n.length;E++){T[E]=_(n[E],r)}return T}function Q(t,e){if(!e){var i=[];for(var n in t){var r=X.exec(n);var s=r&&r[1];if(s&&(!e||s===e)){var o=t[n];if(o){for(var a=0;a<o.length;a++){i.push(o[a])}}}}return i}var c=Z[e];if(!c){J(e);c=Z[e]}var u=t[c[m]];var f=t[c[p]];if(!u){return f?f.slice():[]}else{return f?u.concat(f):u.slice()}}function tt(t,e){var i=t["Event"];if(i&&i.prototype){e.patchMethod(i.prototype,"stopImmediatePropagation",(function(t){return function(e,i){e[Y]=true;t&&t.apply(e,i)}}))}}function et(t,e){e.patchMethod(t,"queueMicrotask",(function(t){return function(t,e){Zone.current.scheduleMicroTask("queueMicrotask",e[0])}}))}var it=g("zoneTask");function nt(t,e,i,n){var r=null;var s=null;e+=n;i+=n;var o={};function a(e){var i=e.data;i.args[0]=function(){return e.invoke.apply(this,arguments)};var n=r.apply(t,i.args);if(V(n)){i.handleId=n}else{i.handle=n;i.isRefreshable=H(n.refresh)}return e}function c(e){var i=e.data,n=i.handle,r=i.handleId;return s.call(t,n!==null&&n!==void 0?n:r)}r=$(t,e,(function(i){return function(r,s){var u;if(H(s[0])){var f={isRefreshable:false,isPeriodic:n==="Interval",delay:n==="Timeout"||n==="Interval"?s[1]||0:undefined,args:s};var h=s[0];s[0]=function t(){try{return h.apply(this,arguments)}finally{var e=f.handle,i=f.handleId,n=f.isPeriodic,r=f.isRefreshable;if(!n&&!r){if(i){delete o[i]}else if(e){e[it]=null}}}};var l=w(e,s[0],f,a,c);if(!l){return l}var d=l.data,p=d.handleId,m=d.handle,b=d.isRefreshable,v=d.isPeriodic;if(p){o[p]=l}else if(m){m[it]=l;if(b&&!v){var g=m.refresh;m.refresh=function(){var t=l.zone,e=l.state;if(e==="notScheduled"){l._state="scheduled";t._updateTaskCount(l,1)}else if(e==="running"){l._state="scheduling"}return g.call(this)}}}return(u=m!==null&&m!==void 0?m:p)!==null&&u!==void 0?u:l}else{return i.apply(t,s)}}}));s=$(t,i,(function(e){return function(i,n){var r=n[0];var s;if(V(r)){s=o[r];delete o[r]}else{s=r===null||r===void 0?void 0:r[it];if(s){r[it]=null}else{s=r}}if(s===null||s===void 0?void 0:s.type){if(s.cancelFn){s.zone.cancelTask(s)}}else{e.apply(t,n)}}}))}function rt(t,e){var i=e.getGlobalObjects(),n=i.isBrowser,r=i.isMix;if(!n&&!r||!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(),n=i.eventNames,r=i.zoneSymbolEventNames,s=i.TRUE_STR,o=i.FALSE_STR,a=i.ZONE_SYMBOL_PREFIX;for(var c=0;c<n.length;c++){var u=n[c];var f=u+o;var h=u+s;var l=a+f;var d=a+h;r[u]={};r[u][o]=l;r[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 n=i.filter((function(e){return e.target===t}));if(n.length===0){return e}var r=n[0].ignoreProperties;return e.filter((function(t){return r.indexOf(t)===-1}))}function ct(t,e,i,n){if(!t){return}var r=at(t,e,i);j(t,r,n)}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 ft(t,e){if(M&&!P){return}if(Zone[t.symbol("patchEvents")]){return}var i=e["__Zone_ignore_on_properties"];var n=[];if(A){var r=window;n=n.concat(["Document","SVGElement","Element","HTMLElement","HTMLBodyElement","HTMLMediaElement","HTMLFrameSetElement","HTMLFrameElement","HTMLIFrameElement","HTMLMarqueeElement","Worker"]);var s=[];ct(r,ut(r),i?i.concat(s):i,a(r))}n=n.concat(["XMLHttpRequest","XMLHttpRequestEventTarget","IDBIndex","IDBRequest","IDBOpenDBRequest","IDBDatabase","IDBTransaction","IDBCursor","WebSocket"]);for(var o=0;o<n.length;o++){var c=e[n[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";nt(t,e,i,"Timeout");nt(t,e,i,"Interval");nt(t,e,i,"Immediate")}));t.__load_patch("requestAnimationFrame",(function(t){nt(t,"request","cancel","AnimationFrame");nt(t,"mozRequest","mozCancel","AnimationFrame");nt(t,"webkitRequest","webkitCancel","AnimationFrame")}));t.__load_patch("blocking",(function(t,e){var i=["alert","prompt","confirm"];for(var n=0;n<i.length;n++){var r=i[n];$(t,r,(function(i,n,r){return function(n,s){return e.current.run(i,t,s,r)}}))}}));t.__load_patch("EventTarget",(function(t,e,i){ot(t,i);st(t,i);var n=t["XMLHttpRequestEventTarget"];if(n&&n.prototype){i.patchEventTarget(t,i,[n.prototype])}}));t.__load_patch("MutationObserver",(function(t,e,i){z("MutationObserver");z("WebKitMutationObserver")}));t.__load_patch("IntersectionObserver",(function(t,e,i){z("IntersectionObserver")}));t.__load_patch("FileReader",(function(t,e,i){z("FileReader")}));t.__load_patch("on_property",(function(t,e,i){ft(i,t)}));t.__load_patch("customElements",(function(t,e,i){rt(t,i)}));t.__load_patch("XHR",(function(t,e){c(t);var i=g("xhrTask");var n=g("xhrSync");var r=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 f(t){return t[i]}var h=u[l];var p=u[d];if(!h){var m=t["XMLHttpRequestEventTarget"];if(m){var b=m.prototype;h=b[l];p=b[d]}}var v="readystatechange";var y="scheduled";function x(t){var n=t.data;var o=n.target;o[s]=false;o[a]=false;var c=o[r];if(!h){h=o[l];p=o[d]}if(c){p.call(o,v,c)}var u=o[r]=function(){if(o.readyState===o.DONE){if(!n.aborted&&o[s]&&t.state===y){var i=o[e.__symbol__("loadfalse")];if(o.status!==0&&i&&i.length>0){var r=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(!n.aborted&&t.state===y){r.call(t)}};i.push(t)}else{t.invoke()}}else if(!n.aborted&&o[s]===false){o[a]=true}}};h.call(o,v,u);var f=o[i];if(!f){o[i]=t}M.apply(o,n.args);o[s]=true;return t}function k(){}function S(t){var e=t.data;e.aborted=true;return A.apply(e.target,e.args)}var _=$(u,"open",(function(){return function(t,e){t[n]=e[2]==false;t[o]=e[1];return _.apply(t,e)}}));var T="XMLHttpRequest.send";var E=g("fetchTaskAborting");var C=g("fetchTaskScheduling");var M=$(u,"send",(function(){return function(t,i){if(e.current[C]===true){return M.apply(t,i)}if(t[n]){return M.apply(t,i)}else{var r={target:t,url:t[o],isPeriodic:false,args:i,aborted:false};var s=w(T,k,r,x,S);if(t&&t[a]===true&&!r.aborted&&s.state===y){s.invoke()}}}}));var A=$(u,"abort",(function(){return function(t,i){var n=f(t);if(n&&typeof n.type=="string"){if(n.cancelFn==null||n.data&&n.data.aborted){return}n.zone.cancelTask(n)}else if(e.current[E]===true){return A.apply(t,i)}}}))}}));t.__load_patch("geolocation",(function(t){if(t["navigator"]&&t["navigator"].geolocation){T(t["navigator"].geolocation,["getCurrentPosition","watchPosition"])}}));t.__load_patch("PromiseRejectionEvent",(function(t,e){function i(e){return function(i){var n=Q(t,e);n.forEach((function(n){var r=t["PromiseRejectionEvent"];if(r){var s=new r(e,{promise:i.promise,reason:i.rejection});n.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 lt(t){t.__load_patch("ZoneAwarePromise",(function(t,e,i){var n=Object.getOwnPropertyDescriptor;var r=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 f=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 l=o("unhandledPromiseRejectionHandler");function d(t){i.onUnhandledError(t);try{var n=e[l];if(typeof n==="function"){n.call(this,t)}}catch(t){}}function p(t){return t&&typeof t.then==="function"}function m(t){return t}function b(t){return D.reject(t)}var v=o("state");var w=o("value");var g=o("finally");var y=o("parentPromiseValue");var x=o("parentPromiseState");var k="Promise.then";var S=null;var _=true;var T=false;var E=0;function C(t,e){return function(i){try{O(t,e,i)}catch(e){O(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 A="Promise resolved with itself";var P=o("currentTaskTrace");function O(t,n,o){var u=M();if(t===o){throw new TypeError(A)}if(t[v]===S){var f=null;try{if(typeof o==="object"||typeof o==="function"){f=o&&o.then}}catch(e){u((function(){O(t,false,e)}))();return t}if(n!==T&&o instanceof D&&o.hasOwnProperty(v)&&o.hasOwnProperty(w)&&o[v]!==S){L(o);O(t,o[v],o[w])}else if(n!==T&&typeof f==="function"){try{f.call(o,u(C(t,n)),u(C(t,false)))}catch(e){u((function(){O(t,false,e)}))()}}else{t[v]=n;var l=t[w];t[w]=o;if(t[g]===g){if(n===_){t[v]=t[x];t[w]=t[y]}}if(n===T&&o instanceof Error){var d=e.currentTask&&e.currentTask.data&&e.currentTask.data[h];if(d){r(o,P,{configurable:true,enumerable:false,writable:true,value:d})}}for(var p=0;p<l.length;){R(t,l[p++],l[p++],l[p++],l[p++])}if(l.length==0&&n==T){t[v]=E;var m=o;try{throw new Error("Uncaught (in promise): "+s(o)+(o&&o.stack?"\n"+o.stack:""))}catch(t){m=t}if(c){m.throwOriginal=true}m.rejection=o;m.promise=t;m.zone=e.current;m.task=e.currentTask;a.push(m);i.scheduleMicroTask()}}}return t}var I=o("rejectionHandledHandler");function L(t){if(t[v]===E){try{var i=e[I];if(i&&typeof i==="function"){i.call(this,{rejection:t[w],promise:t})}}catch(t){}t[v]=T;for(var n=0;n<a.length;n++){if(t===a[n].promise){a.splice(n,1)}}}}function R(t,e,i,n,r){L(t);var s=t[v];var o=s?typeof n==="function"?n:m:typeof r==="function"?r:b;e.scheduleMicroTask(k,(function(){try{var n=t[w];var r=!!i&&g===i[g];if(r){i[y]=n;i[x]=s}var a=e.run(o,undefined,r&&o!==b&&o!==m?[]:[n]);O(i,true,a)}catch(t){O(i,false,t)}}),i)}var j="function ZoneAwarePromise() { [native code] }";var N=function(){};var z=t.AggregateError;var D=function(){function t(e){var i=this;if(!(i instanceof t)){throw new Error("Must be an instanceof Promise.")}i[v]=S;i[w]=[];try{var n=M();e&&e(n(C(i,_)),n(C(i,T)))}catch(t){O(i,false,t)}}t.toString=function(){return j};t.resolve=function(e){if(e instanceof t){return e}return O(new this(null),_,e)};t.reject=function(t){return O(new this(null),T,t)};t.withResolvers=function(){var e={};e.promise=new t((function(t,i){e.resolve=t;e.reject=i}));return e};t.any=function(e){if(!e||typeof e[Symbol.iterator]!=="function"){return Promise.reject(new z([],"All promises were rejected"))}var i=[];var n=0;try{for(var r=0,s=e;r<s.length;r++){var o=s[r];n++;i.push(t.resolve(o))}}catch(t){return Promise.reject(new z([],"All promises were rejected"))}if(n===0){return Promise.reject(new z([],"All promises were rejected"))}var a=false;var c=[];return new t((function(t,e){for(var r=0;r<i.length;r++){i[r].then((function(e){if(a){return}a=true;t(e)}),(function(t){c.push(t);n--;if(n===0){a=true;e(new z(c,"All promises were rejected"))}}))}}))};t.race=function(t){var e;var i;var n=new this((function(t,n){e=t;i=n}));function r(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(r,s)}return n};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 n;var r=new this((function(t,e){i=t;n=e}));var s=2;var o=0;var a=[];var c=function(t){if(!p(t)){t=u.resolve(t)}var r=o;try{t.then((function(t){a[r]=e?e.thenCallback(t):t;s--;if(s===0){i(a)}}),(function(t){if(!e){n(t)}else{a[r]=e.errorCallback(t);s--;if(s===0){i(a)}}}))}catch(t){n(t)}s++;o++};var u=this;for(var f=0,h=t;f<h.length;f++){var l=h[f];c(l)}s-=2;if(s===0){i(a)}return r};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,n){var r;var s=(r=this.constructor)===null||r===void 0?void 0:r[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,n)}else{R(this,a,o,i,n)}return o};t.prototype.catch=function(t){return this.then(null,t)};t.prototype.finally=function(i){var n;var r=(n=this.constructor)===null||n===void 0?void 0:n[Symbol.species];if(!r||typeof r!=="function"){r=t}var s=new r(N);s[g]=g;var o=e.current;if(this[v]==S){this[w].push(o,s,i,i)}else{R(this,o,s,i,i)}return s};return t}();D["resolve"]=D.resolve;D["reject"]=D.reject;D["race"]=D.race;D["all"]=D.all;var F=t[u]=t["Promise"];t["Promise"]=D;var U=o("thenPatched");function B(t){var e=t.prototype;var i=n(e,"then");if(i&&(i.writable===false||!i.configurable)){return}var r=e.then;e[f]=r;t.prototype.then=function(t,e){var i=this;var n=new D((function(t,e){r.call(i,t,e)}));return n.then(t,e)};t[U]=true}i.patchThen=B;function q(t){return function(e,i){var n=t.apply(e,i);if(n instanceof D){return n}var r=n.constructor;if(!r[U]){B(r)}return n}}if(F){B(F);$(t,"fetch",(function(t){return q(t)}))}Promise[e.__symbol__("uncaughtPromiseErrors")]=a;return D}))}function dt(t){t.__load_patch("toString",(function(t){var e=Function.prototype.toString;var i=g("OriginalDelegate");var n=g("Promise");var r=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[n];if(a){return e.call(a)}}if(this===Error){var c=t[r];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,n,r){var s=Zone.__symbol__(n);if(e[s]){return}var o=e[s]=e[n];e[n]=function(s,a,c){if(a&&a.prototype){r.forEach((function(e){var r="".concat(i,".").concat(n,"::")+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,r);t._redefineProperty(a.prototype,e,o)}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],r)}}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],r)}}catch(t){}}))}return o.call(e,s,a,c)};t.attachOriginToPatched(e[n],o)}function mt(t){t.__load_patch("util",(function(t,e,i){var n=ut(t);i.patchOnProperties=j;i.patchMethod=$;i.bindArguments=_;i.patchMacroTask=D;var r=e.__symbol__("BLACK_LISTED_EVENTS");var a=e.__symbol__("UNPATCHED_EVENTS");if(t[a]){t[r]=t[a]}if(t[r]){e[r]=e[a]=t[r]}i.patchEventPrototype=tt;i.patchEventTarget=K;i.isIEOrEdge=q;i.ObjectDefineProperty=o;i.ObjectGetOwnPropertyDescriptor=s;i.ObjectCreate=c;i.ArraySlice=u;i.patchClass=z;i.wrapWithCurrentZone=v;i.filterProperties=at;i.attachOriginToPatched=F;i._redefineProperty=Object.defineProperty;i.patchCallbacks=pt;i.getGlobalObjects=function(){return{globalSources:W,zoneSymbolEventNames:Z,eventNames:n,isBrowser:A,isMix:P,isNode:M,TRUE_STR:p,FALSE_STR:m,ZONE_SYMBOL_PREFIX:b,ADD_EVENT_LISTENER_STR:f,REMOVE_EVENT_LISTENER_STR:h}}}))}function bt(t){lt(t);dt(t);mt(t)}var vt=r();bt(vt);ht(vt)}));return mc}vc();class wc{emit(t){}}const gc=new wc;class yc{getLogger(t,e,i){return new wc}}const xc=new yc;class kc{constructor(t,e,i,n){this._provider=t;this.name=e;this.version=i;this.options=n}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 gc}this._delegate=t;return this._delegate}}class Sc{getLogger(t,e,i){var n;return(n=this._getDelegateLogger(t,e,i))!==null&&n!==void 0?n:new kc(this,t,e,i)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:xc}_setDelegate(t){this._delegate=t}_getDelegateLogger(t,e,i){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getLogger(t,e,i)}}const _c=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};const Tc=Symbol.for("io.opentelemetry.js.api.logs");const Ec=_c;function Cc(t,e,i){return n=>n===t?e:i}const Mc=1;class Ac{constructor(){this._proxyLoggerProvider=new Sc}static getInstance(){if(!this._instance){this._instance=new Ac}return this._instance}setGlobalLoggerProvider(t){if(Ec[Tc]){return this.getLoggerProvider()}Ec[Tc]=Cc(Mc,t,xc);this._proxyLoggerProvider._setDelegate(t);return t}getLoggerProvider(){var t,e;return(e=(t=Ec[Tc])===null||t===void 0?void 0:t.call(Ec,Mc))!==null&&e!==void 0?e:this._proxyLoggerProvider}getLogger(t,e,i){return this.getLoggerProvider().getLogger(t,e,i)}disable(){delete Ec[Tc];this._proxyLoggerProvider=new Sc}}const Pc=Ac.getInstance();function Oc(t,e,i,n){for(let r=0,s=t.length;r<s;r++){const s=t[r];if(e){s.setTracerProvider(e)}if(i){s.setMeterProvider(i)}if(n&&s.setLoggerProvider){s.setLoggerProvider(n)}if(!s.getConfig().enabled){s.enable()}}}function Ic(t){t.forEach((t=>t.disable()))}function Lc(t){const e=t.tracerProvider||de.getTracerProvider();const i=t.meterProvider||te.getMeterProvider();const n=t.loggerProvider||Pc.getLoggerProvider();const r=t.instrumentations?.flat()??[];Oc(r,e,i,n);return()=>{Ic(r)}}let Rc=console.error.bind(console);function jc(t,e,i){const n=!!t[e]&&Object.prototype.propertyIsEnumerable.call(t,e);Object.defineProperty(t,e,{configurable:true,enumerable:n,writable:true,value:i})}const Nc=(t,e,i)=>{if(!t||!t[e]){Rc("no original function "+String(e)+" to wrap");return}if(!i){Rc("no wrapper function");Rc((new Error).stack);return}const n=t[e];if(typeof n!=="function"||typeof i!=="function"){Rc("original object and wrapper must be functions");return}const r=i(n,e);jc(r,"__original",n);jc(r,"__unwrap",(()=>{if(t[e]===r){jc(t,e,n)}}));jc(r,"__wrapped",true);jc(t,e,r);return r};const zc=(t,e,i)=>{if(!t){Rc("must provide one or more modules to patch");Rc((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Rc("must provide one or more functions to wrap on modules");return}t.forEach((t=>{e.forEach((e=>{Nc(t,e,i)}))}))};const $c=(t,e)=>{if(!t||!t[e]){Rc("no function to unwrap.");Rc((new Error).stack);return}const i=t[e];if(!i.__unwrap){Rc("no original to unwrap to -- has "+String(e)+" already been unwrapped?")}else{i.__unwrap();return}};const Dc=(t,e)=>{if(!t){Rc("must provide one or more modules to patch");Rc((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Rc("must provide one or more functions to unwrap on modules");return}t.forEach((t=>{e.forEach((e=>{$c(t,e)}))}))};class Fc{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=de.getTracer(t,e);this._meter=te.getMeter(t,e);this._logger=Pc.getLogger(t,e);this._updateMetricInstruments()}_wrap=Nc;_unwrap=$c;_massWrap=zc;_massUnwrap=Dc;get meter(){return this._meter}setMeterProvider(t){this._meter=t.getMeter(this.instrumentationName,this.instrumentationVersion);this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(t){this._logger=t.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const t=this.init()??[];if(!Array.isArray(t)){return[t]}return t}_updateMetricInstruments(){return}getConfig(){return this._config}setConfig(t){this._config={enabled:true,...t}}setTracerProvider(t){this._tracer=t.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(t,e,i,n){if(!t){return}try{t(i,n)}catch(t){this._diag.error(`Error running span customization hook due to exception in handler`,{triggerName:e},t)}}}class Uc extends Fc{constructor(t,e,i){super(t,e,i);if(this._config.enabled){this.enable()}}}function Bc(t,e,i){let n;let r;try{r=t()}catch(t){n=t}finally{e(n,r);return r}}function qc(t){return typeof t==="function"&&typeof t.__original==="function"&&typeof t.__unwrap==="function"&&t.__wrapped===true}var Hc;(function(t){t[t["STABLE"]=1]="STABLE";t[t["OLD"]=2]="OLD";t[t["DUPLICATE"]=3]="DUPLICATE"})(Hc||(Hc={}));function Vc(t,e){let i=Hc.OLD;const n=e?.split(",").map((t=>t.trim())).filter((t=>t!==""));for(const e of n??[]){if(e.toLowerCase()===t+"/dup"){i=Hc.DUPLICATE;break}else if(e.toLowerCase()===t){i=Hc.STABLE}}return i}var Gc;(function(t){t["COMPONENT"]="component";t["HTTP_STATUS_TEXT"]="http.status_text"})(Gc||(Gc={}));const Zc="http.host";const Wc="http.method";const Xc="http.request.body.size";const Yc="http.request_content_length_uncompressed";const Jc="http.scheme";const Kc="http.status_code";const Qc="http.url";const tu="http.user_agent";const eu=Xt.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-fetch/utils"});function iu(...t){if(t[0]instanceof URL||typeof t[0]==="string"){const e=t[1];if(!e?.body){return Promise.resolve()}if(e.body instanceof ReadableStream){const{body:t,length:i}=nu(e.body);e.body=t;return i}else{return Promise.resolve(su(e.body))}}else{const e=t[0];if(!e?.body){return Promise.resolve()}return e.clone().text().then((t=>au(t)))}}function nu(t){if(!t.pipeThrough){eu.warn("Platform has ReadableStream but not pipeThrough!");return{body:t,length:Promise.resolve(undefined)}}let e=0;let i;const n=new Promise((t=>{i=t}));const r=new TransformStream({start(){},async transform(t,i){const n=await t;e+=n.byteLength;i.enqueue(t)},flush(){i(e)}});return{body:t.pipeThrough(r),length:n}}function ru(t){return typeof Document!=="undefined"&&t instanceof Document}function su(t){if(ru(t)){return(new XMLSerializer).serializeToString(document).length}if(typeof t==="string"){return au(t)}if(t instanceof Blob){return t.size}if(t instanceof FormData){return cu(t)}if(t instanceof URLSearchParams){return au(t.toString())}if(t.byteLength!==undefined){return t.byteLength}eu.warn("unknown body type");return undefined}const ou=new TextEncoder;function au(t){return ou.encode(t).byteLength}function cu(t){let e=0;for(const[i,n]of t.entries()){e+=i.length;if(n instanceof Blob){e+=n.size}else{e+=n.length}}return e}function uu(t){const e=lu();const i=t.toUpperCase();if(i in e){return i}else{return"_OTHER"}}const fu={CONNECT:true,DELETE:true,GET:true,HEAD:true,OPTIONS:true,PATCH:true,POST:true,PUT:true,TRACE:true};let hu;function lu(){if(hu===undefined){{hu=fu}}return hu}const du={"https:":"443","http:":"80"};function pu(t){const e=Number(t.port||du[t.protocol]);if(e&&!isNaN(e)){return e}else{return undefined}}const mu="0.208.0";const bu=300;const vu=typeof process==="object"&&process.release?.name==="node";class wu extends Uc{component="fetch";version=mu;moduleName=this.component;_usedResources=new WeakSet;_tasksCount=0;_semconvStability;constructor(t={}){super("@opentelemetry/instrumentation-fetch",mu,t);this._semconvStability=Vc("http",t?.semconvStabilityOptIn)}init(){}_addChildSpan(t,e){const i=this.tracer.startSpan("CORS Preflight",{startTime:e[ur.FETCH_START]},de.setSpan(Wt.active(),t));const n=!(this._semconvStability&Hc.OLD);br(i,e,this.getConfig().ignoreNetworkEvents,undefined,n);i.end(e[ur.RESPONSE_END])}_addFinalSpanAttributes(t,e){const i=kr(e.url);if(this._semconvStability&Hc.OLD){t.setAttribute(Kc,e.status);if(e.statusText!=null){t.setAttribute(Gc.HTTP_STATUS_TEXT,e.statusText)}t.setAttribute(Zc,i.host);t.setAttribute(Jc,i.protocol.replace(":",""));if(typeof navigator!=="undefined"){t.setAttribute(tu,navigator.userAgent)}}if(this._semconvStability&Hc.STABLE){t.setAttribute(We,e.status);t.setAttribute(Xe,i.hostname);const n=pu(i);if(n){t.setAttribute(Ye,n)}}}_addHeaders(t,e){if(!Er(e,this.getConfig().propagateTraceHeaderCorsUrls)){const t={};fe.inject(Wt.active(),t);if(Object.keys(t).length>0){this._diag.debug("headers inject skipped due to CORS policy")}return}if(t instanceof Request){fe.inject(Wt.active(),t.headers,{set:(t,e,i)=>t.set(e,typeof i==="string"?i:String(i))})}else if(t.headers instanceof Headers){fe.inject(Wt.active(),t.headers,{set:(t,e,i)=>t.set(e,typeof i==="string"?i:String(i))})}else if(t.headers instanceof Map){fe.inject(Wt.active(),t.headers,{set:(t,e,i)=>t.set(e,typeof i==="string"?i:String(i))})}else{const e={};fe.inject(Wt.active(),e);t.headers=Object.assign({},e,t.headers||{})}}_clearResources(){if(this._tasksCount===0&&this.getConfig().clearTimingResources){performance.clearResourceTimings();this._usedResources=new WeakSet}}_createSpan(t,e={}){if(gn(t,this.getConfig().ignoreUrls)){this._diag.debug("ignoring span as url matches ignored url");return}let i="";const n={};if(this._semconvStability&Hc.OLD){const r=(e.method||"GET").toUpperCase();i=`HTTP ${r}`;n[Gc.COMPONENT]=this.moduleName;n[Wc]=r;n[Qc]=t}if(this._semconvStability&Hc.STABLE){const r=e.method;const s=uu(e.method||"GET");if(!i){i=s}n[Ge]=s;if(s!==r){n[Ze]=r}n[ii]=t}return this.tracer.startSpan(i,{kind:Gt.CLIENT,attributes:n})}_findResourceAndAddNetworkEvents(t,e,i){let n=e.entries;if(!n.length){if(!performance.getEntriesByType){return}n=performance.getEntriesByType("resource")}const r=gr(e.spanUrl,e.startTime,i,n,this._usedResources,"fetch");if(r.mainRequest){const e=r.mainRequest;this._markResourceAsUsed(e);const i=r.corsPreFlightRequest;if(i){this._addChildSpan(t,i);this._markResourceAsUsed(i)}const n=!(this._semconvStability&Hc.OLD);br(t,e,this.getConfig().ignoreNetworkEvents,undefined,n)}}_markResourceAsUsed(t){this._usedResources.add(t)}_endSpan(t,e,i){const n=fi(Date.now());const r=li();this._addFinalSpanAttributes(t,i);if(this._semconvStability&Hc.STABLE){if(i.status>=400){t.setStatus({code:Zt.ERROR});t.setAttribute(Be,String(i.status))}}setTimeout((()=>{e.observer?.disconnect();this._findResourceAndAddNetworkEvents(t,e,r);this._tasksCount--;this._clearResources();t.end(n)}),bu)}_patchConstructor(){return t=>{const e=this;return function i(...n){const r=this;const s=kr(n[0]instanceof Request?n[0].url:String(n[0])).href;const o=n[0]instanceof Request?n[0]:n[1]||{};const a=e._createSpan(s,o);if(!a){return t.apply(this,n)}const c=e._prepareSpanData(s);if(e.getConfig().measureRequestSize){iu(...n).then((t=>{if(!t)return;if(e._semconvStability&Hc.OLD){a.setAttribute(Yc,t)}if(e._semconvStability&Hc.STABLE){a.setAttribute(Xc,t)}})).catch((t=>{e._diag.warn("getFetchBodyLength",t)}))}function u(t,i){e._applyAttributesAfterFetch(t,o,i);e._endSpan(t,c,{status:i.status||0,statusText:i.message,url:s})}function f(t,i){e._applyAttributesAfterFetch(t,o,i);if(i.status>=200&&i.status<400){e._endSpan(t,c,i)}else{e._endSpan(t,c,{status:i.status,statusText:i.statusText,url:s})}}function h(t,e){if(!t)return null;const i=t.getReader();return new ReadableStream({async pull(t){try{const{value:e,done:n}=await i.read();if(n){i.releaseLock();t.close()}else{t.enqueue(e)}}catch(e){t.error(e);i.cancel(e).catch((t=>{}));try{i.releaseLock()}catch{}}},cancel(t){e.cancel(t).catch((t=>{}));return i.cancel(t)}})}function l(t,e,i){let n=null;try{const e=i.clone();const r=e.body;if(r){const e=r.getReader();const s=i.status===204||i.status===205||i.status===304;const o=s?null:h(i.body,e);n=new Response(o,{status:i.status,statusText:i.statusText,headers:i.headers});const a=()=>{e.read().then((({done:e})=>{if(e){f(t,i)}else{a()}}),(e=>{u(t,e)}))};a()}else{f(t,i)}}finally{e(n??i)}}function d(t,e,i){try{u(t,i)}finally{e(i)}}return new Promise(((i,n)=>Wt.with(de.setSpan(Wt.active(),a),(()=>{e._addHeaders(o,s);e._callRequestHook(a,o);e._tasksCount++;return t.apply(r,o instanceof Request?[o]:[s,o]).then(l.bind(r,a,i),d.bind(r,a,n))}))))}}}_applyAttributesAfterFetch(t,e,i){const n=this.getConfig().applyCustomAttributesOnSpan;if(n){Bc((()=>n(t,e,i)),(t=>{if(!t){return}this._diag.error("applyCustomAttributesOnSpan",t)}))}}_callRequestHook(t,e){const i=this.getConfig().requestHook;if(i){Bc((()=>i(t,e)),(t=>{if(!t){return}this._diag.error("requestHook",t)}))}}_prepareSpanData(t){const e=li();const i=[];if(typeof PerformanceObserver!=="function"){return{entries:i,startTime:e,spanUrl:t}}const n=new PerformanceObserver((e=>{const n=e.getEntries();n.forEach((e=>{if(e.initiatorType==="fetch"&&e.name===t){i.push(e)}}))}));n.observe({entryTypes:["resource"]});return{entries:i,observer:n,startTime:e,spanUrl:t}}enable(){if(vu){this._diag.warn("this instrumentation is intended for web usage only, it does not instrument Node.js's fetch()");return}if(qc(fetch)){this._unwrap(De,"fetch");this._diag.debug("removing previous patch for constructor")}this._wrap(De,"fetch",this._patchConstructor())}disable(){if(vu){return}this._unwrap(De,"fetch");this._usedResources=new WeakSet}}const gu="http.host";const yu="http.method";const xu="http.request.body.size";const ku="http.request_content_length_uncompressed";const Su="http.scheme";const _u="http.status_code";const Tu="http.url";const Eu="http.user_agent";var Cu;(function(t){t["METHOD_OPEN"]="open";t["METHOD_SEND"]="send";t["EVENT_ABORT"]="abort";t["EVENT_ERROR"]="error";t["EVENT_LOAD"]="loaded";t["EVENT_TIMEOUT"]="timeout"})(Cu||(Cu={}));const Mu=Xt.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-xml-http-request/utils"});function Au(t){return typeof Document!=="undefined"&&t instanceof Document}function Pu(t){if(Au(t)){return(new XMLSerializer).serializeToString(document).length}if(typeof t==="string"){return Iu(t)}if(t instanceof Blob){return t.size}if(t instanceof FormData){return Lu(t)}if(t instanceof URLSearchParams){return Iu(t.toString())}if(t.byteLength!==undefined){return t.byteLength}Mu.warn("unknown body type");return undefined}const Ou=new TextEncoder;function Iu(t){return Ou.encode(t).byteLength}function Lu(t){let e=0;for(const[i,n]of t.entries()){e+=i.length;if(n instanceof Blob){e+=n.size}else{e+=n.length}}return e}function Ru(t){const e=zu();const i=t.toUpperCase();if(i in e){return i}else{return"_OTHER"}}const ju={CONNECT:true,DELETE:true,GET:true,HEAD:true,OPTIONS:true,PATCH:true,POST:true,PUT:true,TRACE:true};let Nu;function zu(){if(Nu===undefined){{Nu=ju}}return Nu}const $u={"https:":"443","http:":"80"};function Du(t){const e=Number(t.port||$u[t.protocol]);if(e&&!isNaN(e)){return e}else{return undefined}}const Fu="0.208.0";var Uu;(function(t){t["HTTP_STATUS_TEXT"]="http.status_text"})(Uu||(Uu={}));const Bu=300;class qu extends Uc{component="xml-http-request";version=Fu;moduleName=this.component;_tasksCount=0;_xhrMem=new WeakMap;_usedResources=new WeakSet;_semconvStability;constructor(t={}){super("@opentelemetry/instrumentation-xml-http-request",Fu,t);this._semconvStability=Vc("http",t?.semconvStabilityOptIn)}init(){}_addHeaders(t,e){const i=kr(e).href;if(!Er(i,this.getConfig().propagateTraceHeaderCorsUrls)){const t={};fe.inject(Wt.active(),t);if(Object.keys(t).length>0){this._diag.debug("headers inject skipped due to CORS policy")}return}const n={};fe.inject(Wt.active(),n);Object.keys(n).forEach((e=>{t.setRequestHeader(e,String(n[e]))}))}_addChildSpan(t,e){Wt.with(de.setSpan(Wt.active(),t),(()=>{const t=this.tracer.startSpan("CORS Preflight",{startTime:e[ur.FETCH_START]});const i=!(this._semconvStability&Hc.OLD);br(t,e,this.getConfig().ignoreNetworkEvents,undefined,i);t.end(e[ur.RESPONSE_END])}))}_addFinalSpanAttributes(t,e,i){if(this._semconvStability&Hc.OLD){if(e.status!==undefined){t.setAttribute(_u,e.status)}if(e.statusText!==undefined){t.setAttribute(Uu.HTTP_STATUS_TEXT,e.statusText)}if(typeof i==="string"){const e=kr(i);t.setAttribute(gu,e.host);t.setAttribute(Su,e.protocol.replace(":",""))}t.setAttribute(Eu,navigator.userAgent)}if(this._semconvStability&Hc.STABLE){if(e.status){t.setAttribute(We,e.status)}}}_applyAttributesAfterXHR(t,e){const i=this.getConfig().applyCustomAttributesOnSpan;if(typeof i==="function"){Bc((()=>i(t,e)),(t=>{if(!t){return}this._diag.error("applyCustomAttributesOnSpan",t)}))}}_addResourceObserver(t,e){const i=this._xhrMem.get(t);if(!i||typeof PerformanceObserver!=="function"||typeof PerformanceResourceTiming!=="function"){return}i.createdResources={observer:new PerformanceObserver((t=>{const n=t.getEntries();const r=kr(e);n.forEach((t=>{if(t.initiatorType==="xmlhttprequest"&&t.name===r.href){if(i.createdResources){i.createdResources.entries.push(t)}}}))})),entries:[]};i.createdResources.observer.observe({entryTypes:["resource"]})}_clearResources(){if(this._tasksCount===0&&this.getConfig().clearTimingResources){Fe.clearResourceTimings();this._xhrMem=new WeakMap;this._usedResources=new WeakSet}}_findResourceAndAddNetworkEvents(t,e,i,n,r){if(!i||!n||!r||!t.createdResources){return}let s=t.createdResources.entries;if(!s||!s.length){s=Fe.getEntriesByType("resource")}const o=gr(kr(i).href,n,r,s,this._usedResources);if(o.mainRequest){const t=o.mainRequest;this._markResourceAsUsed(t);const i=o.corsPreFlightRequest;if(i){this._addChildSpan(e,i);this._markResourceAsUsed(i)}const n=!(this._semconvStability&Hc.OLD);br(e,t,this.getConfig().ignoreNetworkEvents,undefined,n)}}_cleanPreviousSpanInformation(t){const e=this._xhrMem.get(t);if(e){const i=e.callbackToRemoveEvents;if(i){i()}this._xhrMem.delete(t)}}_createSpan(t,e,i){if(gn(e,this.getConfig().ignoreUrls)){this._diag.debug("ignoring span as url matches ignored url");return}let n="";const r=kr(e);const s={};if(this._semconvStability&Hc.OLD){n=i.toUpperCase();s[yu]=i;s[Tu]=r.toString()}if(this._semconvStability&Hc.STABLE){const t=i;const e=Ru(i);if(!n){n=e}s[Ge]=e;if(e!==t){s[Ze]=t}s[ii]=r.toString();s[Xe]=r.hostname;const o=Du(r);if(o){s[Ye]=o}}const o=this.tracer.startSpan(n,{kind:Gt.CLIENT,attributes:s});o.addEvent(Cu.METHOD_OPEN);this._cleanPreviousSpanInformation(t);this._xhrMem.set(t,{span:o,spanUrl:e});return o}_markResourceAsUsed(t){this._usedResources.add(t)}_patchOpen(){return t=>{const e=this;return function i(...n){const r=n[0];const s=n[1];e._createSpan(this,s,r);return t.apply(this,n)}}}_patchSend(){const t=this;function e(e,i,n,r){const s=i.callbackToRemoveEvents;if(typeof s==="function"){s()}const{span:o,spanUrl:a,sendStartTime:c}=i;if(o){t._findResourceAndAddNetworkEvents(i,o,a,c,n);o.addEvent(e,r);t._addFinalSpanAttributes(o,i,a);o.end(r);t._tasksCount--}t._clearResources()}function i(i,n,r,s){const o=t._xhrMem.get(n);if(!o){return}o.status=n.status;o.statusText=n.statusText;t._xhrMem.delete(n);if(o.span){const e=o.span;t._applyAttributesAfterXHR(e,n);if(t._semconvStability&Hc.STABLE){if(r){if(s){e.setStatus({code:Zt.ERROR,message:s});e.setAttribute(Be,s)}}else if(o.status&&o.status>=400){e.setStatus({code:Zt.ERROR});e.setAttribute(Be,String(o.status))}}}const a=li();const c=Date.now();setTimeout((()=>{e(i,o,a,c)}),Bu)}function n(){i(Cu.EVENT_ERROR,this,true,"error")}function r(){i(Cu.EVENT_ABORT,this,false)}function s(){i(Cu.EVENT_TIMEOUT,this,true,"timeout")}function o(){if(this.status<299){i(Cu.EVENT_LOAD,this,false)}else{i(Cu.EVENT_ERROR,this,false)}}function a(e){e.removeEventListener("abort",r);e.removeEventListener("error",n);e.removeEventListener("load",o);e.removeEventListener("timeout",s);const i=t._xhrMem.get(e);if(i){i.callbackToRemoveEvents=undefined}}return e=>function i(...c){const u=t._xhrMem.get(this);if(!u){return e.apply(this,c)}const f=u.span;const h=u.spanUrl;if(f&&h){if(t.getConfig().measureRequestSize&&c?.[0]){const e=c[0];const i=Pu(e);if(i!==undefined){if(t._semconvStability&Hc.OLD){f.setAttribute(ku,i)}if(t._semconvStability&Hc.STABLE){f.setAttribute(xu,i)}}}Wt.with(de.setSpan(Wt.active(),f),(()=>{t._tasksCount++;u.sendStartTime=li();f.addEvent(Cu.METHOD_SEND);this.addEventListener("abort",r);this.addEventListener("error",n);this.addEventListener("load",o);this.addEventListener("timeout",s);u.callbackToRemoveEvents=()=>{a(this);if(u.createdResources){u.createdResources.observer.disconnect()}};t._addHeaders(this,h);t._addResourceObserver(this,h)}))}return e.apply(this,c)}}enable(){this._diag.debug("applying patch to",this.moduleName,this.version);if(qc(XMLHttpRequest.prototype.open)){this._unwrap(XMLHttpRequest.prototype,"open");this._diag.debug("removing previous patch from method open")}if(qc(XMLHttpRequest.prototype.send)){this._unwrap(XMLHttpRequest.prototype,"send");this._diag.debug("removing previous patch from method send")}this._wrap(XMLHttpRequest.prototype,"open",this._patchOpen());this._wrap(XMLHttpRequest.prototype,"send",this._patchSend())}disable(){this._diag.debug("removing patch from",this.moduleName,this.version);this._unwrap(XMLHttpRequest.prototype,"open");this._unwrap(XMLHttpRequest.prototype,"send");this._tasksCount=0;this._xhrMem=new WeakMap;this._usedResources=new WeakSet}}var Hu;(function(t){t["EVENT_TYPE"]="event_type";t["TARGET_ELEMENT"]="target_element";t["TARGET_XPATH"]="target_xpath";t["HTTP_URL"]="http.url"})(Hu||(Hu={}));const Vu="0.53.0";const Gu="@opentelemetry/instrumentation-user-interaction";const Zu="OT_ZONE_CONTEXT";const Wu="Navigation:";const Xu=["click"];function Yu(){return false}class Ju extends Uc{version=Vu;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(t={}){super(Gu,Vu,t);this._eventNames=new Set(t?.eventNames??Xu);this._shouldPreventSpanCreation=typeof t?.shouldPreventSpanCreation==="function"?t.shouldPreventSpanCreation:Yu}init(){}_checkForTimeout(t,e){const i=this._spansData.get(e);if(i){if(t.source==="setTimeout"){i.hrTimeLastTimeout=li()}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 n=Sr(t,true);try{const r=this.tracer.startSpan(e,{attributes:{[Hu.EVENT_TYPE]:e,[Hu.TARGET_ELEMENT]:t.tagName,[Hu.TARGET_XPATH]:n,[Hu.HTTP_URL]:window.location.href}},i?de.setSpan(Wt.active(),i):undefined);if(this._shouldPreventSpanCreation(e,t,r)===true){return undefined}this._spansData.set(r,{taskCount:0});return r}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(Zu);if(e){return de.getSpan(e)}return e}_incrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount++}}addPatchedListener(t,e,i,n){let r=this._wrappedListeners.get(i);if(!r){r=new Map;this._wrappedListeners.set(i,r)}let s=r.get(e);if(!s){s=new Map;r.set(e,s)}if(s.has(t)){return false}s.set(t,n);return true}removePatchedListener(t,e,i){const n=this._wrappedListeners.get(i);if(!n){return undefined}const r=n.get(e);if(!r){return undefined}const s=r.get(t);if(s){r.delete(t);if(r.size===0){n.delete(e);if(n.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(n,r,s){if(!r){return e.call(this,n,r,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,n,r)}const c=t._createSpan(a,n,i);if(c){if(s){t._eventsSpanMap.set(s,c)}return Wt.with(de.setSpan(Wt.active(),c),(()=>{const i=t._invokeListener(r,this,e);c.end();return i}))}else{return t._invokeListener(r,this,e)}};if(t.addPatchedListener(this,n,r,a)){return e.call(this,n,a,s)}}}_patchRemoveEventListener(){const t=this;return e=>function i(n,r,s){const o=t.removePatchedListener(this,n,r);if(o){return e.call(this,n,o,s)}else{return e.call(this,n,r,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(...n){const r=`${location.pathname}${location.hash}${location.search}`;const s=e.apply(this,n);const o=`${location.pathname}${location.hash}${location.search}`;if(r!==o){t._updateInteractionName(o)}return s}}_unpatchHistoryApi(){if(qc(history.replaceState))this._unwrap(history,"replaceState");if(qc(history.pushState))this._unwrap(history,"pushState");if(qc(history.back))this._unwrap(history,"back");if(qc(history.forward))this._unwrap(history,"forward");if(qc(history.go))this._unwrap(history,"go")}_updateInteractionName(t){const e=de.getSpan(Wt.active());if(e&&typeof e.updateName==="function"){e.updateName(`${Wu} ${t}`)}}_patchZoneCancelTask(){const t=this;return e=>function i(n){const r=Zone.current;const s=t._getCurrentSpan(r);if(s&&t._shouldCountTask(n,r)){t._decrementTask(s)}return e.call(this,n)}}_patchZoneScheduleTask(){const t=this;return e=>function i(n){const r=Zone.current;const s=t._getCurrentSpan(r);if(s&&t._shouldCountTask(n,r)){t._incrementTask(s);t._checkForTimeout(n,s)}return e.call(this,n)}}_patchZoneRunTask(){const t=this;return e=>function i(n,r,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,n.eventName);if(c){t._incrementTask(c);return u.run((()=>{try{return Wt.with(de.setSpan(Wt.active(),c),(()=>{const t=Zone.current;n._zone=t;return e.call(t,n,r,s)}))}finally{t._decrementTask(c)}}))}}else{c=t._getCurrentSpan(u)}try{return e.call(u,n,r,s)}finally{if(c&&t._shouldCountTask(n,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(qc(t.prototype.runTask)){this._unwrap(t.prototype,"runTask");this._diag.debug("removing previous patch from method runTask")}if(qc(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask");this._diag.debug("removing previous patch from method scheduleTask")}if(qc(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(qc(t.addEventListener)){this._unwrap(t,"addEventListener");this._diag.debug("removing previous patch from method addEventListener")}if(qc(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(qc(t.prototype.runTask)){this._unwrap(t.prototype,"runTask")}if(qc(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask")}if(qc(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask")}}else{const t=this._getPatchableEventTargets();t.forEach((t=>{if(qc(t.addEventListener)){this._unwrap(t,"addEventListener")}if(qc(t.removeEventListener)){this._unwrap(t,"removeEventListener")}}))}this._unpatchHistoryApi()}_getZoneWithPrototype(){const t=window;return t.Zone}}var Ku;(function(t){t["DOCUMENT_LOAD"]="documentLoad";t["DOCUMENT_FETCH"]="documentFetch";t["RESOURCE_FETCH"]="resourceFetch"})(Ku||(Ku={}));const Qu="0.54.0";const tf="@opentelemetry/instrumentation-document-load";const ef="http.url";const nf="http.user_agent";var rf;(function(t){t["FIRST_PAINT"]="firstPaint";t["FIRST_CONTENTFUL_PAINT"]="firstContentfulPaint"})(rf||(rf={}));const sf=()=>{const t={};const e=Fe.getEntriesByType?.("navigation")[0];if(e){const i=Object.values(ur);i.forEach((i=>{if(pr(e,i)){const n=e[i];if(typeof n==="number"){t[i]=n}}}))}else{const e=Fe;const i=e.timing;if(i){const e=Object.values(ur);e.forEach((e=>{if(pr(i,e)){const n=i[e];if(typeof n==="number"){t[e]=n}}}))}}return t};const of={"first-paint":rf.FIRST_PAINT,"first-contentful-paint":rf.FIRST_CONTENTFUL_PAINT};const af=t=>{const e=Fe.getEntriesByType?.("paint");if(e){e.forEach((({name:e,startTime:i})=>{if(pr(of,e)){t.addEvent(of[e],i)}}))}};class cf extends Uc{component="document-load";version="1";moduleName=this.component;_semconvStability;constructor(t={}){super(tf,Qu,t);this._semconvStability=Vc("http",t?.semconvStabilityOptIn)}init(){}_onDocumentLoaded(){window.setTimeout((()=>{this._collectPerformance()}))}_addResourcesSpans(t){const e=Fe.getEntriesByType?.("resource");if(e){e.forEach((e=>{this._initResourceSpan(e,t)}))}}_collectPerformance(){const t=Array.from(document.getElementsByTagName("meta")).find((t=>t.getAttribute("name")===ji));const e=sf();const i=t&&t.content||"";Wt.with(fe.extract(U,{traceparent:i}),(()=>{const t=this._startSpan(Ku.DOCUMENT_LOAD,ur.FETCH_START,e);if(!t){return}Wt.with(de.setSpan(Wt.active(),t),(()=>{const t=this._startSpan(Ku.DOCUMENT_FETCH,ur.FETCH_START,e);if(t){if(this._semconvStability&Hc.OLD){t.setAttribute(ef,location.href)}if(this._semconvStability&Hc.STABLE){t.setAttribute(ii,location.href)}Wt.with(de.setSpan(Wt.active(),t),(()=>{const i=!(this._semconvStability&Hc.OLD);br(t,e,this.getConfig().ignoreNetworkEvents,undefined,i);this._addCustomAttributesOnSpan(t,this.getConfig().applyCustomAttributesOnSpan?.documentFetch);this._endSpan(t,ur.RESPONSE_END,e)}))}}));if(this._semconvStability&Hc.OLD){t.setAttribute(ef,location.href);t.setAttribute(nf,navigator.userAgent)}if(this._semconvStability&Hc.STABLE){t.setAttribute(ii,location.href);t.setAttribute(ni,navigator.userAgent)}this._addResourcesSpans(t);if(!this.getConfig().ignoreNetworkEvents){mr(t,ur.FETCH_START,e);mr(t,ur.UNLOAD_EVENT_START,e);mr(t,ur.UNLOAD_EVENT_END,e);mr(t,ur.DOM_INTERACTIVE,e);mr(t,ur.DOM_CONTENT_LOADED_EVENT_START,e);mr(t,ur.DOM_CONTENT_LOADED_EVENT_END,e);mr(t,ur.DOM_COMPLETE,e);mr(t,ur.LOAD_EVENT_START,e);mr(t,ur.LOAD_EVENT_END,e)}if(!this.getConfig().ignorePerformancePaintEvents){af(t)}this._addCustomAttributesOnSpan(t,this.getConfig().applyCustomAttributesOnSpan?.documentLoad);this._endSpan(t,ur.LOAD_EVENT_END,e)}))}_endSpan(t,e,i){if(t){if(pr(i,e)){t.end(i[e])}else{t.end()}}}_initResourceSpan(t,e){const i=this._startSpan(Ku.RESOURCE_FETCH,ur.FETCH_START,t,e);if(i){if(this._semconvStability&Hc.OLD){i.setAttribute(ef,t.name)}if(this._semconvStability&Hc.STABLE){i.setAttribute(ii,t.name)}const e=!(this._semconvStability&Hc.OLD);br(i,t,this.getConfig().ignoreNetworkEvents,undefined,e);this._addCustomAttributesOnResourceSpan(i,t,this.getConfig().applyCustomAttributesOnSpan?.resourceFetch);this._endSpan(i,ur.RESPONSE_END,t)}}_startSpan(t,e,i,n){if(pr(i,e)&&typeof i[e]==="number"){const r=this.tracer.startSpan(t,{startTime:i[e]},n?de.setSpan(Wt.active(),n):undefined);return r}return undefined}_waitForPageLoad(){if(window.document.readyState==="complete"){this._onDocumentLoaded()}else{this._onDocumentLoaded=this._onDocumentLoaded.bind(this);window.addEventListener("load",this._onDocumentLoaded)}}_addCustomAttributesOnSpan(t,e){if(e){Bc((()=>e(t)),(t=>{if(!t){return}this._diag.error("addCustomAttributesOnSpan",t)}))}}_addCustomAttributesOnResourceSpan(t,e,i){if(i){Bc((()=>i(t,e)),(t=>{if(!t){return}this._diag.error("addCustomAttributesOnResourceSpan",t)}))}}enable(){window.removeEventListener("load",this._onDocumentLoaded);this._waitForPageLoad()}disable(){window.removeEventListener("load",this._onDocumentLoaded)}}var uf={exports:{}};var ff=uf.exports;var hf;function lf(){if(hf)return uf.exports;hf=1;(function(t,e){(function(i,n){var r="1.0.41",s="",o="?",a="function",c="undefined",u="object",f="string",h="major",l="model",d="name",p="type",m="vendor",b="version",v="architecture",w="console",g="mobile",y="tablet",x="smarttv",k="wearable",S="embedded",_=500;var T="Amazon",E="Apple",C="ASUS",M="BlackBerry",A="Browser",P="Chrome",O="Edge",I="Firefox",L="Google",R="Honor",j="Huawei",N="Lenovo",z="LG",$="Microsoft",D="Motorola",F="Nvidia",U="OnePlus",B="Opera",q="OPPO",H="Samsung",V="Sharp",G="Sony",Z="Xiaomi",W="Zebra",X="Facebook",Y="Chromium OS",J="Mac OS",K=" Browser";var Q=function(t,e){var i={};for(var n in t){if(e[n]&&e[n].length%2===0){i[n]=e[n].concat(t[n])}else{i[n]=t[n]}}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===f?it(e).indexOf(it(t))!==-1:false},it=function(t){return t.toLowerCase()},nt=function(t){return typeof t===f?t.replace(/[^\d\.]/g,s).split(".")[0]:n},rt=function(t,e){if(typeof t===f){t=t.replace(/^\s\s*/,s);return typeof e===c?t:t.substring(0,_)}};var st=function(t,e){var i=0,r,s,o,c,f,h;while(i<e.length&&!f){var l=e[i],d=e[i+1];r=s=0;while(r<l.length&&!f){if(!l[r]){break}f=l[r++].exec(t);if(!!f){for(o=0;o<d.length;o++){h=f[++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]):n}else{this[c[0]]=h?h.replace(c[1],c[2]):n}}else if(c.length===4){this[c[0]]=h?c[3].call(this,h.replace(c[1],c[2])):n}}else{this[c]=h?h:n}}}}i+=2}},ot=function(t,e){for(var i in e){if(typeof e[i]===u&&e[i].length>0){for(var r=0;r<e[i].length;r++){if(et(e[i][r],t)){return i===o?n:i}}}else if(et(e[i],t)){return i===o?n:i}}return e.hasOwnProperty("*")?e["*"]:t};var at={"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},ct={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"};var ut={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[b,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[b,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,b],[/opios[\/ ]+([\w\.]+)/i],[b,[d,B+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[b,[d,B+" GX"]],[/\bopr\/([\w\.]+)/i],[b,[d,B]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[b,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[b,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,b],[/quark(?:pc)?\/([-\w\.]+)/i],[b,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[b,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[b,[d,"UC"+A]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[b,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[b,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[b,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[b,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[b,[d,"Smart Lenovo "+A]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+A],b],[/\bfocus\/([\w\.]+)/i],[b,[d,I+" Focus"]],[/\bopt\/([\w\.]+)/i],[b,[d,B+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[b,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[b,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[b,[d,B+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[b,[d,"MIUI"+K]],[/fxios\/([\w\.-]+)/i],[b,[d,I]],[/\bqihoobrowser\/?([\w\.]*)/i],[b,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],b],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+K],b],[/samsungbrowser\/([\w\.]+)/i],[b,[d,H+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[b,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],b],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,b],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[b,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,X],b],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,b],[/\bgsa\/([\w\.]+) .*safari\//i],[b,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[b,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[b,[d,P+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,P+" WebView"],b],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[b,[d,"Android "+A]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,b],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[b,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[b,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[b,ot,at]],[/(webkit|khtml)\/([\w\.]+)/i],[d,b],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],b],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,b],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[b,[d,I+" 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],[l,[m,H],[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],[l,[m,H],[p,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[m,E],[p,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[m,E],[p,y]],[/(macintosh);/i],[l,[m,E]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[m,V],[p,g]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[l,[m,R],[p,y]],[/honor([-\w ]+)[;\)]/i],[l,[m,R],[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],[l,[m,j],[p,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[m,j],[p,g]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[l,/_/g," "],[m,Z],[p,y]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[l,/_/g," "],[m,Z],[p,g]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[m,q],[p,g]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[l,[m,ot,{OnePlus:["304","403","203"],"*":q}],[p,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[m,"Vivo"],[p,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[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],[l,[m,D],[p,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[m,D],[p,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[m,z],[p,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[m,z],[p,g]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[l,[m,N],[p,y]],[/(nokia) (t[12][01])/i],[m,l,[p,y]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[l,/_/g," "],[p,g],[m,"Nokia"]],[/(pixel (c|tablet))\b/i],[l,[m,L],[p,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[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],[l,[m,G],[p,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[m,G],[p,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[m,U],[p,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[m,T],[p,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[m,T],[p,g]],[/(playbook);[-\w\),; ]+(rim)/i],[l,m,[p,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[m,M],[p,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[m,C],[p,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[m,C],[p,g]],[/(nexus 9)/i],[l,[m,"HTC"],[p,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[m,[l,/_/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],[l,[m,"TCL"],[p,y]],[/(itel) ((\w+))/i],[[m,it],l,[p,ot,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[m,"Acer"],[p,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[m,"Meizu"],[p,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[m,"Ulefone"],[p,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[m,"Energizer"],[p,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[m,"Cat"],[p,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[m,"Smartfren"],[p,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[m,"Nothing"],[p,g]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[l,[m,"Archos"],[p,y]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[l,[m,"Archos"],[p,g]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[m,l,[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,l,[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,l,[p,y]],[/(surface duo)/i],[l,[m,$],[p,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[m,"Fairphone"],[p,g]],[/(u304aa)/i],[l,[m,"AT&T"],[p,g]],[/\bsie-(\w*)/i],[l,[m,"Siemens"],[p,g]],[/\b(rct\w+) b/i],[l,[m,"RCA"],[p,y]],[/\b(venue[\d ]{2,7}) b/i],[l,[m,"Dell"],[p,y]],[/\b(q(?:mv|ta)\w+) b/i],[l,[m,"Verizon"],[p,y]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[m,"Barnes & Noble"],[p,y]],[/\b(tm\d{3}\w+) b/i],[l,[m,"NuVision"],[p,y]],[/\b(k88) b/i],[l,[m,"ZTE"],[p,y]],[/\b(nx\d{3}j) b/i],[l,[m,"ZTE"],[p,g]],[/\b(gen\d{3}) b.+49h/i],[l,[m,"Swiss"],[p,g]],[/\b(zur\d{3}) b/i],[l,[m,"Swiss"],[p,y]],[/\b((zeki)?tb.*\b) b/i],[l,[m,"Zeki"],[p,y]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[m,"Dragon Touch"],l,[p,y]],[/\b(ns-?\w{0,9}) b/i],[l,[m,"Insignia"],[p,y]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[m,"NextBook"],[p,y]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[m,"Voice"],l,[p,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[m,"LvTel"],l,[p,g]],[/\b(ph-1) /i],[l,[m,"Essential"],[p,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[m,"Envizen"],[p,y]],[/\b(trio[-\w\. ]+) b/i],[l,[m,"MachSpeed"],[p,y]],[/\btu_(1491) b/i],[l,[m,"Rotor"],[p,y]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[l,[m,F],[p,y]],[/(sprint) (\w+)/i],[m,l,[p,g]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[m,$],[p,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[m,W],[p,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[m,W],[p,g]],[/smart-tv.+(samsung)/i],[m,[p,x]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[m,H],[p,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[m,z],[p,x]],[/(apple) ?tv/i],[m,[l,E+" TV"],[p,x]],[/crkey/i],[[l,P+"cast"],[m,L],[p,x]],[/droid.+aft(\w+)( bui|\))/i],[l,[m,T],[p,x]],[/(shield \w+ tv)/i],[l,[m,F],[p,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[m,V],[p,x]],[/(bravia[\w ]+)( bui|\))/i],[l,[m,G],[p,x]],[/(mi(tv|box)-?\w+) bui/i],[l,[m,Z],[p,x]],[/Hbbtv.*(technisat) (.*);/i],[m,l,[p,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[m,rt],[l,rt],[p,x]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[l,[p,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[p,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[m,l,[p,w]],[/droid.+; (shield)( bui|\))/i],[l,[m,F],[p,w]],[/(playstation \w+)/i],[l,[m,G],[p,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[m,$],[p,w]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[l,[m,H],[p,k]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[m,l,[p,k]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[l,[m,q],[p,k]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[m,E],[p,k]],[/(opwwe\d{3})/i],[l,[m,U],[p,k]],[/(moto 360)/i],[l,[m,D],[p,k]],[/(smartwatch 3)/i],[l,[m,G],[p,k]],[/(g watch r)/i],[l,[m,z],[p,k]],[/droid.+; (wt63?0{2,3})\)/i],[l,[m,W],[p,k]],[/droid.+; (glass) \d/i],[l,[m,L],[p,k]],[/(pico) (4|neo3(?: link|pro)?)/i],[m,l,[p,k]],[/; (quest( \d| pro)?)/i],[l,[m,X],[p,k]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[m,[p,S]],[/(aeobc)\b/i],[l,[m,T],[p,S]],[/(homepod).+mac os/i],[l,[m,E],[p,S]],[/windows iot/i],[[p,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[p,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[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],[l,[m,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[b,[d,O+"HTML"]],[/(arkweb)\/([\w\.]+)/i],[d,b],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[b,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,b],[/ladybird\//i],[[d,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[b,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,b],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[d,[b,ot,ct]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[b,ot,ct],[d,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[b,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,J],[b,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[b,d],[/(ubuntu) ([\w\.]+) like android/i],[[d,/(.+)/,"$1 Touch"],b],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[d,b],[/\(bb(10);/i],[b,[d,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,I+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[b,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[b,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[b,[d,P+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,Y],b],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,b],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],b],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,b]]};var ft=function(t,e){if(typeof t===u){e=t;t=n}if(!(this instanceof ft)){return new ft(t,e).getResult()}var r=typeof i!==c&&i.navigator?i.navigator:n;var o=t||(r&&r.userAgent?r.userAgent:s);var w=r&&r.userAgentData?r.userAgentData:n;var x=e?Q(ut,e):ut;var k=r&&r.userAgent==o;this.getBrowser=function(){var t={};t[d]=n;t[b]=n;st.call(t,o,x.browser);t[h]=nt(t[b]);if(k&&r&&r.brave&&typeof r.brave.isBrave==a){t[d]="Brave"}return t};this.getCPU=function(){var t={};t[v]=n;st.call(t,o,x.cpu);return t};this.getDevice=function(){var t={};t[m]=n;t[l]=n;t[p]=n;st.call(t,o,x.device);if(k&&!t[p]&&w&&w.mobile){t[p]=g}if(k&&t[l]=="Macintosh"&&r&&typeof r.standalone!==c&&r.maxTouchPoints&&r.maxTouchPoints>2){t[l]="iPad";t[p]=y}return t};this.getEngine=function(){var t={};t[d]=n;t[b]=n;st.call(t,o,x.engine);return t};this.getOS=function(){var t={};t[d]=n;t[b]=n;st.call(t,o,x.os);if(k&&!t[d]&&w&&w.platform&&w.platform!="Unknown"){t[d]=w.platform.replace(/chrome os/i,Y).replace(/macos/i,J)}return t};this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}};this.getUA=function(){return o};this.setUA=function(t){o=typeof t===f&&t.length>_?rt(t,_):t;return this};this.setUA(o);return this};ft.VERSION=r;ft.BROWSER=tt([d,b,h]);ft.CPU=tt([v]);ft.DEVICE=tt([l,m,p,w,g,x,y,k,S]);ft.ENGINE=ft.OS=tt([d,b]);{if(t.exports){e=t.exports=ft}e.UAParser=ft}var ht=typeof i!==c&&(i.jQuery||i.Zepto);if(ht&&!ht.ua){var lt=new ft;ht.ua=lt.getResult();ht.ua.get=function(){return lt.getUA()};ht.ua.set=function(t){lt.setUA(t);var e=lt.getResult();for(var i in e){ht.ua[i]=e[i]}}}})(typeof window==="object"?window:ff)})(uf,uf.exports);return uf.exports}var df=lf();var pf=Fr(df);const mf="service.name";const bf="service.version";class vf{provider=null;tracer=null;sessionTraceId=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;propagateTraceHeaderCorsUrls;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.propagateTraceHeaderCorsUrls=t.propagateTraceHeaderCorsUrls||[];this.enableAutoInstrumentation=t.enableAutoInstrumentation??false;this.parser=new pf}initialize(){try{const t=new hc({url:this.collectorUrl,headers:{"Content-Type":"application/json"}});this.spanProcessor=new Xn(t,{maxQueueSize:100,maxExportBatchSize:10,scheduledDelayMillis:5e3,exportTimeoutMillis:3e4});const e={[mf]:this.serviceName,[bf]:this.serviceVersion,"deployment.environment":this.environment};if(this.customerId){e["customer.id"]=this.customerId}if(this.tenantId){e["tenant.id"]=this.tenantId}this.provider=new cr({});this.provider.addSpanProcessor?.(this.spanProcessor);const i=new pc;const n=new Hi;this.provider.register({contextManager:i,propagator:n});this.tracer=de.getTracer(this.serviceName,this.serviceVersion);if(this.enableAutoInstrumentation){this.initializeAutoInstrumentation(e)}if(this.debug){console.log("[TracingService] Initialized successfully",{collectorUrl:this.collectorUrl,serviceName:this.serviceName,serviceVersion:this.serviceVersion,environment:this.environment,customerId:this.customerId,tenantId:this.tenantId,autoInstrumentation:this.enableAutoInstrumentation,propagateUrls:this.propagateTraceHeaderCorsUrls})}}catch(t){console.error("[TracingService] Failed to initialize:",t)}}initializeAutoInstrumentation(t){try{Lc({instrumentations:[new wu({propagateTraceHeaderCorsUrls:this.propagateTraceHeaderCorsUrls,clearTimingResources:true,applyCustomAttributesOnSpan:(e,i,n)=>{Object.entries(t).forEach((([t,i])=>{e.setAttribute(t,i)}));if(n&&"status"in n){e.setAttribute("http.response.status_code",n.status)}}}),new qu({propagateTraceHeaderCorsUrls:this.propagateTraceHeaderCorsUrls,applyCustomAttributesOnSpan:e=>{Object.entries(t).forEach((([t,i])=>{e.setAttribute(t,i)}))}}),new Ju({eventNames:["click","submit"],shouldPreventSpanCreation:(t,e)=>e.tagName==="BUTTON"||e.tagName==="A"||e.tagName==="FORM"}),new cf]});if(this.debug){console.log("[TracingService] Auto-instrumentation enabled")}}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){return de.getTracer("noop").startSpan("noop")}try{let i=Wt.active();if(this.sessionTraceId){const t={traceId:this.sessionTraceId,spanId:this.generateSpanId(),traceFlags:1};i=de.setSpanContext(i,t)}const n=this.getDeviceInfo();const r=this.getBrowserInfo();const s=this.getOSInfo();const o=this.tracer.startSpan(t,{attributes:{...e,component:this.serviceName.includes("stamps")?"jaak-stamps":"jaak-visage",[mf]:this.serviceName,[bf]:this.serviceVersion,"deployment.environment":this.environment,"trace.id":this.sessionTraceId||"auto-generated","device.type":n.type,"device.vendor":n.vendor,"device.model":n.model,"browser.name":r.name,"browser.version":r.version,"browser.major":r.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 de.getTracer("noop").startSpan("noop")}}endSpan(t){if(!t)return;try{t.end();if(this.debug){const e=t.spanContext();console.log("[TracingService] Ended span",{traceId:e.traceId,spanId:e.spanId})}}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});if(this.debug){console.log("[TracingService] Recorded exception:",e)}}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 n=this.startSpan(t,i);try{const t=await Wt.with(de.setSpan(Wt.active(),n),(async()=>await e()));n.setStatus({code:Zt.OK});return t}catch(t){this.recordException(n,t);throw t}finally{this.endSpan(n)}}async cleanup(){try{if(this.spanProcessor){await this.spanProcessor.forceFlush();await this.spanProcessor.shutdown()}if(this.provider){await this.provider.shutdown()}if(this.debug){console.log("[TracingService] Cleaned up successfully")}}catch(t){console.error("[TracingService] Failed to cleanup:",t)}}getCurrentTraceId(){try{const t=de.getSpan(Wt.active());return t?.spanContext().traceId}catch{return undefined}}getCurrentSpanId(){try{const t=de.getSpan(Wt.active());return t?.spanContext().spanId}catch{return undefined}}}var wf;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE";t[t["LOWMEMORY"]=2]="LOWMEMORY"})(wf||(wf={}));const gf=()=>ns.CUMULATIVE;const yf=t=>{switch(t){case rs.COUNTER:case rs.OBSERVABLE_COUNTER:case rs.GAUGE:case rs.HISTOGRAM:case rs.OBSERVABLE_GAUGE:return ns.DELTA;case rs.UP_DOWN_COUNTER:case rs.OBSERVABLE_UP_DOWN_COUNTER:return ns.CUMULATIVE}};const xf=t=>{switch(t){case rs.COUNTER:case rs.HISTOGRAM:return ns.DELTA;case rs.GAUGE:case rs.UP_DOWN_COUNTER:case rs.OBSERVABLE_UP_DOWN_COUNTER:case rs.OBSERVABLE_COUNTER:case rs.OBSERVABLE_GAUGE:return ns.CUMULATIVE}};function kf(){const t="cumulative".toLowerCase();if(t==="cumulative"){return gf}if(t==="delta"){return yf}if(t==="lowmemory"){return xf}Xt.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${t}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);return gf}function Sf(t){if(t!=null){if(t===wf.DELTA){return yf}else if(t===wf.LOWMEMORY){return xf}return gf}return kf()}const _f=Object.freeze({type:fo.DEFAULT});function Tf(t){return t?.aggregationPreference??(()=>_f)}class Ef extends Cr{_aggregationTemporalitySelector;_aggregationSelector;constructor(t,e){super(t);this._aggregationSelector=Tf(e);this._aggregationTemporalitySelector=Sf(e?.temporalityPreference)}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}}class Cf extends Ef{constructor(t){super(uc(t??{},ja,"v1/metrics",{"Content-Type":"application/json"}),t)}}class Mf{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 Cf({url:this.collectorUrl,headers:{"Content-Type":"application/json"}});this.metricReader=new bo({exporter:t,exportIntervalMillis:this.exportIntervalMillis,exportTimeoutMillis:3e4});this.meterProvider=new ma({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 n=this.getBaseAttributes();const r={...n,...i};switch(t){case"captures":this.captureCounter?.add(e,r);break;case"errors":this.errorCounter?.add(e,r);break;case"model_loads":this.modelLoadCounter?.add(e,r);break;case"user_interactions":this.userInteractionCounter?.add(e,r);break;default:if(this.meter){const i=this.meter.createCounter(`jaak.${t}.total`,{description:`Total ${t}`,unit:"1"});i.add(e,r)}}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 n=this.getBaseAttributes();const r={...n,...i};switch(t){case"capture_duration":this.captureLatencyHistogram?.record(e,r);break;case"model_load_duration":this.modelLoadLatencyHistogram?.record(e,r);break;case"detection_duration":this.detectionLatencyHistogram?.record(e,r);break;case"image_size":this.imageSizeHistogram?.record(e,r);break;default:if(this.meter){const i=this.meter.createHistogram(`jaak.${t}`,{description:`Distribution of ${t}`,unit:"ms"});i.record(e,r)}}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 n=performance.now();try{const r=await e();const s=performance.now()-n;this.recordHistogram(t,s,i);return r}catch(e){const r=performance.now()-n;this.recordHistogram(t,r,{...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 Af{services=new Map;constructor(t){this.initializeServices(t)}initializeServices(t){const e=new r;const i=new s(e);const n=new o(e,t.preferredCamera);const a=new f(t.debug,t.useDocumentClassification,t.useDocumentDetector);let c=null;if(t.enableTelemetry!==false){c=new vf({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 Mf({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",n);this.services.set("detectionService",a);if(c){this.services.set("tracingService",c)}if(u){this.services.set("metricsService",u)}}get(t){const e=this.services.get(t);if(!e){throw new Error(`Service ${t} not found`)}return e}getEventBus(){return this.get("eventBus")}getStateManager(){return this.get("stateManager")}getCameraService(){return this.get("cameraService")}getDetectionService(){return this.get("detectionService")}getTracingService(){try{return this.get("tracingService")}catch{return null}}getMetricsService(){try{return this.get("metricsService")}catch{return null}}updateConfig(t){}async cleanup(){this.getDetectionService().cleanup();const t=this.getMetricsService();if(t){await t.cleanup()}const e=this.getTracingService();if(e){await e.cleanup()}this.getEventBus().clear();this.services.clear()}}class Pf{apiEndpoint="/api/v1/license/validate";baseUrl;static ENVIRONMENT_URLS={dev:"https://api.dev.jaak.ai",qa:"https://api.qa.jaak.ai",staging:"https://api-staging.jaak.ai",prod:"https://api.jaak.ai"};constructor(t="prod"){this.baseUrl=Pf.ENVIRONMENT_URLS[t]}async validateLicense(t,e,i="jaak-stamps-web"){const n=e||this.generateTraceId();const r={license:e?`L${n}`:t,origin:"web",app_id:i,product:"kyc",metadata:{sdk_version:"2.1.0"}};const s={"Content-Type":"application/json"};s["traceparent"]=`00-${n}-${this.generateSpanId()}-01`;try{const t=await fetch(`${this.baseUrl}${this.apiEndpoint}`,{method:"POST",headers:s,body:JSON.stringify(r)});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:n}}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 Of=":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:#333;border:1px solid #e0e0e0;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}.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 If=class{constructor(i){t(this,i);this.captureCompleted=e(this,"captureCompleted");this.isReady=e(this,"isReady");this.traceIdGenerated=e(this,"traceIdGenerated")}get el(){return i(this)}debug=false;alignmentTolerance=15;maskSize=90;cropMargin=20;useDocumentClassification=false;useDocumentDetector=true;preferredCamera="auto";captureDelay=1500;enableBackDocumentTimer=false;backDocumentTimerDuration=20;telemetryCollectorUrl="https://collector.jaak.ai/v1/traces";metricsCollectorUrl="https://collector.jaak.ai/v1/metrics";enableTelemetry=true;enableMetrics=true;customerId;tenantId;environment="production";propagateTraceHeaderCorsUrls;metricsExportIntervalMillis=6e4;license;licenseEnvironment="prod";traceId;appId="jaak-stamps-web";captureCompleted;isReady;traceIdGenerated;detectionBoxes=[];sideAlignment={top:false,right:false,bottom:false,left:false};isMaskReady=false;shouldMirrorVideo=true;showCameraSelector=false;isSwitchingCamera=false;hasDocumentDetected=false;cameraInfoWithAutofocus={availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null};currentStatus={message:"Preparando capturador...",description:"Configurando herramientas de captura",type:"initializing",isInitialized:false};performanceData={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0};backDocumentTimerRemaining=0;showManualCaptureButton=false;performanceDegradedMode=false;showPerformanceMessage=false;captureStateVersion=0;processingButton=null;licenseValid=true;licenseError=null;licenseValidationService=null;serviceContainer;eventBus;stateManager;cameraService;detectionService;tracingService;metricsService;videoRef;detectionContainer;videoStream;animationId;lastDetectedBox;startTime;hasScreenshotTaken=false;alignmentStartTime;alignmentTimer;backDocumentTimer;orientationTimer;performanceMetrics={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0,lastUpdateTime:0};performanceUpdateInterval;frameSkipCounter=0;BASE_FRAME_SKIP=2;MAX_FRAME_SKIP=8;consecutiveFailures=0;MAX_FAILURES=30;lastInferenceTime=0;MIN_INFERENCE_INTERVAL=50;performanceHistory=[];PERFORMANCE_HISTORY_SIZE=10;PERFORMANCE_THRESHOLD_MS=2e3;SLOW_FRAMES_TO_TRIGGER=2;slowFrameCount=0;processedFramesCount=0;hasAutoSwitchedToManual=false;canvasPool=[];MAX_CANVAS_POOL_SIZE=3;async componentWillLoad(){await new Promise((t=>setTimeout(t,50)));this.updateStatus("Validando licencia...","Verificando autorización de uso","initializing");await this.validateLicense();if(!this.licenseValid){return}}async componentDidLoad(){try{if(!this.licenseValid){return}this.updateStatus("Preparando capturador...","Configurando herramientas de captura","initializing");await this.initializeServices();this.updateStatus("Preparando funciones...","Configurando herramientas de trabajo","initializing");await this.setupEventListeners();this.updateStatus("Configurando cámara...","Detectando dispositivos disponibles","initializing");await this.initializeComponent();if(this.debug){this.initializePerformanceMonitor()}}catch(t){this.updateStatus("Error de inicialización",t.message,"error")}}async initializeServices(){const t=this.propagateTraceHeaderCorsUrls?this.propagateTraceHeaderCorsUrls.split(",").map((t=>t.trim())):[];const e={debug:this.debug,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,cropMargin:this.cropMargin,useDocumentClassification:this.useDocumentClassification,useDocumentDetector:this.useDocumentDetector,preferredCamera:this.preferredCamera,captureDelay:this.captureDelay,telemetryCollectorUrl:this.telemetryCollectorUrl,metricsCollectorUrl:this.metricsCollectorUrl,enableTelemetry:this.enableTelemetry,enableMetrics:this.enableMetrics,customerId:this.customerId,tenantId:this.tenantId,environment:this.environment,propagateTraceHeaderCorsUrls:t,metricsExportIntervalMillis:this.metricsExportIntervalMillis};this.serviceContainer=new Af(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){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 Pf(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");t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.0/dist/ort.min.js";document.head.appendChild(t);await new Promise((e=>{t.onload=()=>{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 n=e/i;const r=t.width/t.height;let s,o;let a=0,c=0;if(n>r){s=t.width;o=t.width/n;c=(t.height-o)/2}else{o=t.height;s=t.height*n;a=(t.width-s)/2}const u=85.6/53.98;const f=o*u;let h,l;const d=this.maskSize/100;if(f<=s){l=o*d;h=l*u}else{h=s*d;l=h/u}const p=h/t.width*100;const m=l/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 n=i-e;if(this.debug){this.recordOnnxPerformance(n,0)}if(t){this.tracingService?.setSpanAttribute(t,"loadTime",n)}this.updateStatus("Finalizando configuración...","Preparando herramientas para captura","loading");await new Promise((t=>setTimeout(t,300)));this.updateStatus("Reconocimiento preparado","","ready");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}this.emitReadyEvent();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true,message:"Models preloaded successfully"}}catch(e){this.updateStatus("Error de configuración","No se pudieron preparar las herramientas necesarias","error");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async getCameraInfo(){const t=this.isComponentReady();if(!t.ready){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}try{return await this.cameraService.getCameraInfo()}catch(t){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}}async setPreferredCamera(t){const e=this.isComponentReady();if(!e.ready){return{success:false,error:e.message,selectedCamera:null,availableCameras:0}}try{this.preferredCamera=t;this.serviceContainer.updateConfig({preferredCamera:t});await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();const e=this.stateManager.getCaptureState();if(e.isVideoActive){const t=this.cameraService.getSelectedCameraId();if(t){await this.cameraService.switchCamera(t)}}return{success:true,selectedCamera:this.cameraService.getSelectedCameraId(),availableCameras:this.cameraService.getAvailableCameras().length}}catch(t){return{success:false,error:t.message,selectedCamera:null,availableCameras:0}}}async setCaptureDelay(t){if(t<0||t>1e4){return{success:false,error:"Capture delay must be between 0 and 10000 milliseconds",captureDelay:this.captureDelay}}this.captureDelay=t;if(this.serviceContainer){this.serviceContainer.updateConfig({captureDelay:t})}return{success:true,captureDelay:this.captureDelay}}async getCaptureDelay(){return this.captureDelay}checkDeviceCapabilities(){const t=navigator.deviceMemory;return{canUseML:true,reason:"Dispositivo compatible con detección automática.",memoryMB:t?t*1024:null}}async startDetection(){try{const t=this.checkDeviceCapabilities();if(!t.canUseML&&this.useDocumentDetector){this.switchToManualModeWithWarning(t.reason);return}if(!this.detectionService.isModelLoaded()){const t=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");this.stateManager.updateCaptureState({isLoading:true});try{await this.detectionService.loadModel()}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";this.switchToManualModeWithWarning(`Memoria insuficiente para detección automática ${t}. Modo manual activado - funciona igual de bien!`);return}else{this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");try{await this.detectionService.loadClassificationModel()}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";this.switchToManualModeWithWarning(`Memoria insuficiente para clasificación automática ${t}. Modo manual activado para optimizar rendimiento.`);return}else{this.switchToManualModeWithError("Error al cargar modelo de clasificación");throw t}}const e=performance.now();const i=e-t;if(this.debug){this.recordOnnxPerformance(i,0)}}this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus()}catch(t){throw new Error(`Error al actualizar información de cámara: ${t.message}`)}this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");let e;try{e=await this.cameraService.setupCamera()}catch(t){throw new Error(`Error al configurar cámara: ${t.message}`)}if(this.useDocumentDetector){this.updateStatus("Analizando estabilidad...","Evaluando rendimiento del sistema","loading")}else{this.updateStatus("Captura activa","Posicione su documento y use el botón para capturar","active")}try{await this.initializeVideoStream(e)}catch(t){throw new Error(`Error al inicializar video: ${t.message}`)}if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});if(!this.useDocumentDetector){this.showManualCaptureButton=true}this.detectFrame()}catch(t){this.updateStatus("Error al iniciar","No se pudo preparar la captura","error");this.stateManager.updateCaptureState({isLoading:false})}}async initializeVideoStream(t){if(this.videoRef){this.videoRef.srcObject=t;this.videoStream=t;const e=this.cameraService.isRearCamera(t);this.shouldMirrorVideo=!e;return new Promise((t=>{this.videoRef.onloadedmetadata=async()=>{await this.videoRef.play();this.stateManager.updateCaptureState({isVideoActive:true});if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}t()}}))}else{throw new Error("Video element not available")}}async detectFrame(){try{const t=performance.now();const e=this.stateManager.getCaptureState();if(!this.videoRef||!this.detectionContainer||!this.detectionService.isModelLoaded())return;if(!this.useDocumentDetector||this.performanceDegradedMode){this.showManualCaptureButton=true;if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}else if(!this.performanceDegradedMode){this.showManualCaptureButton=false}if(e.isDetectionPaused){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter++;const i=this.getAdaptiveFrameSkip();if(this.frameSkipCounter<=i){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter=0;const n=Date.now();if(n-this.lastInferenceTime<this.MIN_INFERENCE_INTERVAL){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.lastInferenceTime=n;const r=performance.now();let s;let o;let a;try{s=this.detectionService.preprocess(this.videoRef)}catch(t){this.switchToManualModeWithError("Error al procesar imagen");return}try{o=await this.detectionService.runInference(s);a=performance.now()-r}catch(t){this.switchToManualModeWithError("Error en detección automática");return}this.processedFramesCount++;if(this.debug){this.recordOnnxPerformance(0,a)}if(this.startTime&&Date.now()-this.startTime<5e3){o.forEach((t=>{const i=this.detectionService.isCardInFrame(t);const n=i?t.score*1.2:t.score;if(n>e.bestScore){this.stateManager.updateCaptureState({bestScore:n})}}))}const c=this.hasDocumentDetected;this.hasDocumentDetected=o.length>0;if(!c&&this.hasDocumentDetected&&e.step==="back"&&this.enableBackDocumentTimer){this.startBackDocumentTimer()}if(o.length===0){this.consecutiveFailures++}else{this.consecutiveFailures=0}if(this.debug){this.updateDetectionBoxes(o)}else{this.detectionBoxes=[]}this.updateMaskColor(o);const u=performance.now();const f=u-t;if(this.useDocumentDetector&&!this.hasAutoSwitchedToManual){if(f>=this.PERFORMANCE_THRESHOLD_MS){this.slowFrameCount++;if(this.slowFrameCount>=this.SLOW_FRAMES_TO_TRIGGER){this.switchToManualMode()}}else{if(this.slowFrameCount>0){this.slowFrameCount=0}}if(this.processedFramesCount===2){this.updateStatus("Captura activa","Buscando documento en el marco de captura","active")}}if(this.debug){this.recordFrameProcessing(f,o.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 n("div",{key:"69b36b10f1a790caa352acd5e149fe012ddebd3d",class:"detector-container"},!this.licenseValid&&this.licenseError&&n("div",{key:"b96d8b52f6bb366b1d6239922a95b100befa5735",class:"license-error-container"},n("div",{key:"58fb20b1acae97631c35730ed395acf9fa583df2",class:"license-error-card"},n("svg",{key:"f2726621e000bad3c62b1106778bb50e32ece973",class:"license-error-icon",width:"64",height:"64",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},n("path",{key:"18a51f219cdc93f717867f61502c55b35d250532",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"}),n("path",{key:"0f157178a69c10590dd55f55c2223fdef31c2569",d:"M12 8V12",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"}),n("circle",{key:"0352746bef8e2e5a6be0c3868406005aae574a71",cx:"12",cy:"16",r:"0.5",fill:"currentColor",stroke:"currentColor","stroke-width":"1"})),n("h2",{key:"c63de740aa94503f1cf5e1cd1b366b11bc3253b3",class:"license-error-title"},"Licencia Requerida"),n("p",{key:"e36cefd08b510fc38f326de557ffc16425a0b324",class:"license-error-message"},this.licenseError),n("p",{key:"c77c6545b5186f7fb77a414120d3f6f5ba4a45f0",class:"license-error-help"},"Contacte a soporte: ",n("a",{key:"bef70b41a7ec454bed38c4162ce3cafc02c81071",href:"mailto:support@jaak.ai"},"support@jaak.ai")),n("div",{key:"7fd679252453474021494c8dac3ec44da60b40eb",class:"license-error-footer"},"JAAK Stamps"))),this.licenseValid&&n("div",{key:"369edcb3d7fcaa18059ae89f340f5e65bd0f0785",class:"video-container"},n("video",{key:"88a67cf2451ebd53cb4fa709d34d11c7fa98cfc9",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{display:t.isVideoActive?"block":"none"}}),n("div",{key:"d309664c7a9e64f33dd45e0925f27768483b6795",ref:t=>this.detectionContainer=t,class:`detection-overlay ${this.shouldMirrorVideo?"mirror":""}`},this.debug&&this.detectionBoxes.map(((t,e)=>n("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&&n("div",{key:"fbfc808e22ec640ddd9e34d52fab476d7a9becc1",class:"overlay-mask"},n("div",{key:"40846a04d852bbcc2ac6c4a0ca356adae1c67765",class:"card-outline"},n("div",{key:"452fe1786b67d0f9194e5d03ad2aaee08868a5fd",class:"side side-top"}),n("div",{key:"a462c388ea55cd022b9616571f0012bd5eb380d4",class:"side side-right"}),n("div",{key:"bfa2232443e23f2e72f009c62f7a866b9ff1b084",class:"side side-bottom"}),n("div",{key:"581746eca6fde6340d78e8ab48d6e21d17e7dfd3",class:"side side-left"})),!t.showFlipAnimation&&!t.showSuccessAnimation&&n("div",{key:"8e57ac550ea3718322ba954682f93239acbabc78",class:`guide-text ${this.showPerformanceMessage?"performance-warning-text":""}`},this.getGuideText(t.step)),t.step==="back"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&n("div",{key:"81cfab68789796d901afadc895d28f398e8c15cf",class:"back-capture-section"},n("div",{key:"d80455bd916c2d7ac47eb0ce3c62b0e5efbe4dff",class:"back-capture-buttons"},(!this.useDocumentDetector||this.performanceDegradedMode||this.showManualCaptureButton)&&n("button",{key:"c6d427cb32ecfb1ff40150d39f1d8ad7565f7156",class:"capture-button primary-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-back"&&n("span",{key:"cb57aec75ff91f2887fa258bd79b8efb98614d13",class:"button-spinner"}),"Capturar Reverso"),n("button",{key:"c76f356a34fcbc790ebe2d900ed61cc4a6a02e28",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button",disabled:this.processingButton!==null},this.processingButton==="skip-back"&&n("span",{key:"d8fe69623902a5f41587f630552ef28a352733c6",class:"button-spinner"}),this.enableBackDocumentTimer&&this.backDocumentTimerRemaining>0?`Saltar reverso (${this.backDocumentTimerRemaining}s)`:"Saltar reverso"))),t.isVideoActive&&n("div",{key:"08f4037c20b4dfed59553a7f29474940f5f3eb49",class:"camera-controls"},n("button",{key:"e873835d5d6587b19eb5e61e0073e4992fe115b6",class:`camera-selector-button ${this.isSwitchingCamera?"loading":""}`,onClick:()=>this.toggleCameraSelector(),type:"button",title:"Seleccionar cámara",disabled:this.isSwitchingCamera},this.isSwitchingCamera?n("div",{class:"button-spinner"}):"Cámaras")),this.showCameraSelector&&e.availableCameras.length>0&&n("div",{key:"8fca7e29f868570bb99dd2d09ca7da807656dad0",class:"camera-selector-dropdown"},n("div",{key:"abfac31042d3b362c094a297429e0272dabb2511",class:"camera-selector-header"},n("span",{key:"ffcd0e3c262aa86c431617568c1070548d88f38a"},"Seleccionar Cámara"),n("button",{key:"8351be02ccbfa818cab352a37a29d2cd5bfd53ef",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),n("div",{key:"b42d7a5855ec2f76bc105f7b03369b3d4c950762",class:"camera-list"},e.availableCameras.map((t=>n("button",{key:t.id,class:`camera-option ${e.selectedCameraId===t.id?"selected":""}`,onClick:()=>this.handleCameraSwitch(t.id),type:"button"},n("span",{class:"camera-label"},t.label||`Cámara ${e.availableCameras.indexOf(t)+1}`,t.hasAutofocus&&n("span",{class:"autofocus-icon",title:"Autofoco disponible"},"⦿")),e.selectedCameraId===t.id&&n("span",{class:"selected-indicator"},"✓"))))),n("div",{key:"cf3ca9fe1d626320ad2653a3db44cd86e998bcdf",class:"device-info"},n("small",{key:"9b908dc6e759f1a5311b068dba10428ebd22cdc3"},"Dispositivo: ",e.deviceType))),this.showManualCaptureButton&&t.step==="front"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&n("div",{key:"9aa48412eaac0b2adf19f1defb3bc835ab031d9f",class:"manual-capture-section"},n("button",{key:"1828e293ae4e544b00d0dd17a86401ff0436de37",class:"manual-capture-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-front"&&n("span",{key:"bbea1d654f80e537ff6616920fb6a2cb410e55f0",class:"button-spinner"}),"Capturar Frente"))),t.isCapturing&&n("div",{key:"532f72395868ecf58bef350aed4da4e4fc0fa13c",class:"capture-animation"}),t.showFlipAnimation&&n("div",{key:"555cbc7504660b722f23389899956cf979a27e6c",class:"flip-animation"},n("div",{key:"e5de939b02cfb65697c70f265492f1f30f75c771",class:"id-card-icon"}),n("div",{key:"35867c2fbdf463d5b28f0bd3a58313d0d6f15e7b",class:"flip-text"},"¡Voltea tu identificación!")),t.showSuccessAnimation&&n("div",{key:"4a96d077e993012ed333384219ba27d5a68787ea",class:"success-animation"},n("div",{key:"836809412d0674a0061aadaaa7c712a22f8770da",class:"check-icon"}),n("div",{key:"d541dbdfa548760b196dd09dc44c3d1a6af8093c",class:"success-text"},"¡Proceso completado!")),n("div",{key:"89a9d99fbeedff1bbcf723ba13d551c3290150fe",class:`component-status status-${this.currentStatus.type}`},(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing")&&n("div",{key:"f100984baef7602ea40cea9bb74b4c84fd1f6ed9",class:"status-spinner"}),n("div",{key:"ad4161c71f438174117e306e5084bfdff3d18dce",class:"status-content"},n("div",{key:"26310245b58f331075dd344a6497e90631d5d78c",class:"status-message"},this.currentStatus.message),this.currentStatus.description&&n("div",{key:"f739148b45f7d43a3015cca3de8efc8b71d3d5e4",class:"status-description"},this.currentStatus.description))),this.debug&&n("div",{key:"0397b96391dff4f0662c913068a62c714df168bf",class:"performance-monitor"},n("div",{key:"da3c3638b3c048a425bf691b29755762ad40aa5c",class:"performance-expanded"},n("div",{key:"467f5e2dc207cfd9fd31cef24d434452b3247c5f",class:"metrics-row"},n("div",{key:"e620d9017402317e09ec554bf933a4f5a5d0b0de",class:"metric-compact"},n("span",{key:"8d21fa081bbf3ec7ad54f553b60b0a64ae41fb01",class:"metric-label"},"FPS"),n("span",{key:"8e99113c7b93c128d7e390900a63f16c5b9483c0",class:`metric-value ${this.performanceData.fps<15?"warning":this.performanceData.fps<10?"danger":"good"}`},this.performanceData.fps)),n("div",{key:"67927ff90810b0c4d6717d520ad50142d5d6c0dd",class:"metric-compact"},n("span",{key:"4810964d65c18248f01aff90dca36d732b80a05c",class:"metric-label"},"MEM"),n("span",{key:"e82ff493a2bc1d3baf60c1f638154e9208d0991f",class:`metric-value ${this.performanceData.memoryUsage>100?"warning":this.performanceData.memoryUsage>200?"danger":"good"}`},this.performanceData.memoryUsage,"MB"))),n("div",{key:"6ef07b3f3dc4c3d991f4bbae34e902a9efc1a359",class:"metrics-row"},n("div",{key:"b5eed3b30cb99d4d088a05494cda2eff0ba393cc",class:"metric-compact"},n("span",{key:"52749839a61316b90f424b0920f4c82c6683dd29",class:"metric-label"},"INF"),n("span",{key:"8509cf19af19b6ac2efc7ab68ac46d9d053c5464",class:`metric-value ${this.performanceData.inferenceTime>100?"warning":this.performanceData.inferenceTime>200?"danger":"good"}`},this.performanceData.inferenceTime,"ms")),n("div",{key:"34a8540d0840056a525a7afc35ca956943b527af",class:"metric-compact"},n("span",{key:"bdc2d8cd180b92ee7b84c8372aba5c2f33289669",class:"metric-label"},"FRAME"),n("span",{key:"481a0735a5b7258fecdc1bab65a4d4018cc0e7b9",class:`metric-value ${this.performanceData.frameProcessingTime>50?"warning":this.performanceData.frameProcessingTime>100?"danger":"good"}`},this.performanceData.frameProcessingTime,"ms"))),n("div",{key:"7b5aa0a6fe97970f09db23103f7f0301fd98c4f8",class:"metrics-row"},n("div",{key:"1c691159409e021176557904a1ceec05abc329e1",class:"metric-compact"},n("span",{key:"5ab6c25d80548aa4e63c79ecf88d2386393ae707",class:"metric-label"},"DET"),n("span",{key:"7641532633bc764d4dc209ba7e1827a2f3f59338",class:"metric-value good"},this.performanceData.successfulDetections,"/",this.performanceData.totalDetections)),n("div",{key:"feee52f464eeb965eeadfd944a65e94600591ed5",class:"metric-compact"},n("span",{key:"c7962650a7bf1bc86f8c733eb01d5eeb9e08d37e",class:"metric-label"},"RATE"),n("span",{key:"337529444c8e7bacb47d686d0be33721a066eebe",class:`metric-value ${this.performanceData.detectionRate<30?"danger":this.performanceData.detectionRate<60?"warning":"good"}`},this.performanceData.detectionRate,"%"))))),n("div",{key:"49717c49e5316bfe10690733c5bf07eb0475a3e2",class:"watermark"},n("img",{key:"f86ff4364196627bb3f169e5ee1c14696126cd68",src:"https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png",alt:"Powered by Jaak"}))))}updateDetectionBoxes(t){if(!this.videoRef||!this.detectionContainer)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;const n=this.detectionContainer.parentElement;const r=n.getBoundingClientRect();const s=r.width;const o=r.height;if(e===0||i===0)return;const a=e/i;const c=s/o;let u,f;let h=0,l=0;if(a>c){u=s;f=s/a;l=(o-f)/2}else{f=o;u=o*a;h=(s-u)/2}const d=320;const p=u/d;const m=f/d;this.detectionBoxes=t.map((t=>({x:t.x*p+h,y:t.y*m+l,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 n=this.el.shadowRoot?.querySelector(".side-top");const r=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}}n?.classList.toggle("aligned",c.top);r?.classList.toggle("aligned",c.right);s?.classList.toggle("aligned",c.bottom);o?.classList.toggle("aligned",c.left);const u=this.detectionService.areAllSidesAligned(c);const f=this.stateManager.getCaptureState();if(f.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 n=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 r=performance.now()-t;this.metricsService?.recordCapture(n,"manual",r);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 n=i.getBoundingClientRect();const r=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 f=c/u;const h=n.width/n.height;let l,d;let p=0,m=0;if(f>h){l=n.width;d=n.width/f;m=(n.height-d)/2}else{d=n.height;l=n.height*f;p=(n.width-l)/2}const b=r/100*n.width;const v=s/100*n.height;const w=o/100*n.width;const g=a/100*n.height;const y=c/l;const x=u/d;const k=(w-p)*y;const S=(g-m)*x;const _=b*y;const T=v*x;const E=Math.max(0,k-_/2-this.cropMargin);const C=Math.max(0,S-T/2-this.cropMargin);const M=Math.min(_+2*this.cropMargin,c-E);const A=Math.min(T+2*this.cropMargin,u-C);const P=this.getPooledCanvas(M,A);const O=P.getContext("2d",{alpha:false});O.clearRect(0,0,P.width,P.height);O.drawImage(this.videoRef,E,C,M,A,0,0,M,A);const I=this.stateManager.getCaptureState();if(I.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/jpeg"),cropped:P.toDataURL("image/jpeg")}});if(this.useDocumentClassification){try{const e=await this.detectionService.classifyDocument(P);if(e&&e.class==="passport"){this.completeProcess(true);this.returnCanvasToPool(t);this.returnCanvasToPool(P);this.processingButton=null;return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});this.triggerRerender();setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.triggerRerender();this.startBackDocumentTimer();this.processingButton=null}),3e3)}else if(I.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/jpeg"),cropped:P.toDataURL("image/jpeg")}});this.completeProcess(false);this.processingButton=null}this.returnCanvasToPool(t);this.returnCanvasToPool(P)}async takeScreenshot(){if(!this.videoRef||!this.lastDetectedBox)return;const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.auto");this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const i=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const n=i.getContext("2d",{alpha:false});n.clearRect(0,0,i.width,i.height);n.drawImage(this.videoRef,0,0,i.width,i.height);const r=320;const s=this.videoRef.videoWidth/r;const o=this.videoRef.videoHeight/r;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 f=Math.min(this.lastDetectedBox.h*o+2*this.cropMargin,this.videoRef.videoHeight-c);const h=this.getPooledCanvas(u,f);const l=h.getContext("2d",{alpha:false});l.clearRect(0,0,h.width,h.height);l.drawImage(this.videoRef,a,c,u,f,0,0,u,f);const d=this.stateManager.getCaptureState();if(d.step==="front"){const n=i.toDataURL("image/jpeg");const r=h.toDataURL("image/jpeg");this.stateManager.setCapturedImages({front:{fullFrame:n,cropped:r}});const s=performance.now()-t;this.metricsService?.recordCapture("front","auto",s);this.metricsService?.recordImageSize("front",n.length);if(e){this.tracingService?.setSpanAttribute(e,"side","front")}if(this.useDocumentClassification){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 n=i.toDataURL("image/jpeg");const r=h.toDataURL("image/jpeg");this.stateManager.setCapturedImages({back:{fullFrame:n,cropped:r}});const s=performance.now()-t;this.metricsService?.recordCapture("back","auto",s);this.metricsService?.recordImageSize("back",n.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}this.stopPerformanceMonitoring();this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.showPerformanceMessage=true;setTimeout((()=>{this.showPerformanceMessage=false}),5e3)}switchToManualModeWithWarning(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.useDocumentDetector=false;this.updateStatus("Modo manual activado",t,"active");this.continueWithCameraSetup()}async continueWithCameraSetup(){try{this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus()}catch(t){throw new Error(`Error al actualizar información de cámara: ${t.message}`)}this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");let t;try{t=await this.cameraService.setupCamera()}catch(t){throw new Error(`Error al configurar cámara: ${t.message}`)}this.updateStatus("Captura manual","Posicione su documento y use el botón para capturar","active");try{await this.initializeVideoStream(t)}catch(t){throw new Error(`Error al inicializar video: ${t.message}`)}if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});this.showManualCaptureButton=true}catch(t){this.updateStatus("Error de cámara",t.message,"error");throw t}}switchToManualModeWithError(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.useDocumentDetector=false;this.updateStatus("Modo manual activado",t,"error");this.continueWithCameraSetup().catch((()=>{setTimeout((()=>{this.updateStatus("Captura manual","Use el botón para capturar","ready")}),5e3)}))}stopPerformanceMonitoring(){}releaseOnnxResources(){try{if(this.detectionService){this.detectionService.cleanup()}}catch(t){}}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()};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(){if(this.consecutiveFailures>20)return this.MAX_FRAME_SKIP;if(this.performanceMetrics.inferenceTime>200)return 6;if(this.performanceMetrics.memoryUsage>200)return 5;if(this.performanceHistory.length>0){const t=this.performanceHistory.reduce(((t,e)=>t+e),0)/this.performanceHistory.length;if(t>100)return 4;if(t>80)return 3;if(t>60)return this.BASE_FRAME_SKIP+1}if(this.performanceMetrics.memoryUsage>150)return 4;return this.BASE_FRAME_SKIP}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 n=this.el.shadowRoot?.querySelector(".side-right");const r=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");n?.classList.remove("aligned");r?.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 n=document.createElement("canvas");n.width=t;n.height=e;return n}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)}}};If.style=Of;export{If as jaak_stamps};
7
+ //# sourceMappingURL=p-8c49893d.entry.js.map