@jaak.ai/stamps 2.5.0 → 2.5.1-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.
- package/dist/cjs/jaak-stamps.cjs.entry.js +5 -0
- package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -1
- package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -1
- package/dist/collection/services/ServiceContainer.js +5 -0
- package/dist/collection/services/ServiceContainer.js.map +1 -1
- package/dist/components/jaak-stamps.js +5 -0
- package/dist/components/jaak-stamps.js.map +1 -1
- package/dist/esm/jaak-stamps.entry.js +5 -0
- package/dist/esm/jaak-stamps.entry.js.map +1 -1
- package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +1 -1
- package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -1
- package/dist/jaak-stamps-webcomponent/{p-bdff3893.entry.js → p-85901267.entry.js} +2 -2
- package/dist/jaak-stamps-webcomponent/p-85901267.entry.js.map +1 -0
- package/dist/types/services/ServiceContainer.d.ts +1 -0
- package/package.json +1 -1
- package/dist/jaak-stamps-webcomponent/p-bdff3893.entry.js.map +0 -1
|
@@ -3,5 +3,5 @@ import{r as t,c as e,g as i,h as r}from"./p-BCfAsrzL.js";class n{events=new Map;
|
|
|
3
3
|
* @license Angular v<unknown>
|
|
4
4
|
* (c) 2010-2025 Google LLC. https://angular.io/
|
|
5
5
|
* License: MIT
|
|
6
|
-
*/(function(t){t()})((function(){var e=globalThis;function i(t){var i=e["__Zone_symbol_prefix"]||"__zone_symbol__";return i+t}function r(){var t=e["performance"];function r(e){t&&t["mark"]&&t["mark"](e)}function n(e,i){t&&t["measure"]&&t["measure"](e,i)}r("Zone");var s=function(){function t(t,e){this._parent=t;this._name=e?e.name||"unnamed":"<root>";this._properties=e&&e.properties||{};this._zoneDelegate=new a(this,this._parent&&this._parent._zoneDelegate,e)}t.assertZonePatched=function(){if(e["Promise"]!==M["ZoneAwarePromise"]){throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` "+"has been overwritten.\n"+"Most likely cause is that a Promise polyfill has been loaded "+"after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. "+"If you must load one, do so before loading zone.js.)")}};Object.defineProperty(t,"root",{get:function(){var e=t.current;while(e.parent){e=e.parent}return e},enumerable:false,configurable:true});Object.defineProperty(t,"current",{get:function(){return O.zone},enumerable:false,configurable:true});Object.defineProperty(t,"currentTask",{get:function(){return P},enumerable:false,configurable:true});t.__load_patch=function(s,o,a){if(a===void 0){a=false}if(M.hasOwnProperty(s)){var c=e[i("forceDuplicateZoneCheck")]===true;if(!a&&c){throw Error("Already loaded patch: "+s)}}else if(!e["__Zone_disable_"+s]){var u="Zone:"+s;r(u);M[s]=o(e,t,C);n(u,u)}};Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},enumerable:false,configurable:true});Object.defineProperty(t.prototype,"name",{get:function(){return this._name},enumerable:false,configurable:true});t.prototype.get=function(t){var e=this.getZoneWith(t);if(e)return e._properties[t]};t.prototype.getZoneWith=function(t){var e=this;while(e){if(e._properties.hasOwnProperty(t)){return e}e=e._parent}return null};t.prototype.fork=function(t){if(!t)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,t)};t.prototype.wrap=function(t,e){if(typeof t!=="function"){throw new Error("Expecting function got: "+t)}var i=this._zoneDelegate.intercept(this,t,e);var r=this;return function(){return r.runGuarded(i,this,arguments,e)}};t.prototype.run=function(t,e,i,r){O={parent:O,zone:this};try{return this._zoneDelegate.invoke(this,t,e,i,r)}finally{O=O.parent}};t.prototype.runGuarded=function(t,e,i,r){if(e===void 0){e=null}O={parent:O,zone:this};try{try{return this._zoneDelegate.invoke(this,t,e,i,r)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{O=O.parent}};t.prototype.runTask=function(t,e,i){if(t.zone!=this){throw new Error("A task can only be run in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")")}var r=t;var n=t.type,s=t.data,o=s===void 0?{}:s,a=o.isPeriodic,c=a===void 0?false:a,u=o.isRefreshable,l=u===void 0?false:u;if(t.state===g&&(n===T||n===A)){return}var f=t.state!=k;f&&r._transitionTo(k,x);var h=P;P=r;O={parent:O,zone:this};try{if(n==A&&t.data&&!c&&!l){t.cancelFn=undefined}try{return this._zoneDelegate.invokeTask(this,r,e,i)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{var d=t.state;if(d!==g&&d!==E){if(n==T||c||l&&d===y){f&&r._transitionTo(x,k,y)}else{var p=r._zoneDelegates;this._updateTaskCount(r,-1);f&&r._transitionTo(g,k,g);if(l){r._zoneDelegates=p}}}O=O.parent;P=h}};t.prototype.scheduleTask=function(t){if(t.zone&&t.zone!==this){var e=this;while(e){if(e===t.zone){throw Error("can not reschedule task to ".concat(this.name," which is descendants of the original zone ").concat(t.zone.name))}e=e.parent}}t._transitionTo(y,g);var i=[];t._zoneDelegates=i;t._zone=this;try{t=this._zoneDelegate.scheduleTask(this,t)}catch(e){t._transitionTo(E,y,g);this._zoneDelegate.handleError(this,e);throw e}if(t._zoneDelegates===i){this._updateTaskCount(t,1)}if(t.state==y){t._transitionTo(x,y)}return t};t.prototype.scheduleMicroTask=function(t,e,i,r){return this.scheduleTask(new c(_,t,e,i,r,undefined))};t.prototype.scheduleMacroTask=function(t,e,i,r,n){return this.scheduleTask(new c(A,t,e,i,r,n))};t.prototype.scheduleEventTask=function(t,e,i,r,n){return this.scheduleTask(new c(T,t,e,i,r,n))};t.prototype.cancelTask=function(t){if(t.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")");if(t.state!==x&&t.state!==k){return}t._transitionTo(S,x,k);try{this._zoneDelegate.cancelTask(this,t)}catch(e){t._transitionTo(E,S);this._zoneDelegate.handleError(this,e);throw e}this._updateTaskCount(t,-1);t._transitionTo(g,S);t.runCount=-1;return t};t.prototype._updateTaskCount=function(t,e){var i=t._zoneDelegates;if(e==-1){t._zoneDelegates=null}for(var r=0;r<i.length;r++){i[r]._updateTaskCount(t.type,e)}};t.__symbol__=i;return t}();var o={name:"",onHasTask:function(t,e,i,r){return t.hasTask(i,r)},onScheduleTask:function(t,e,i,r){return t.scheduleTask(i,r)},onInvokeTask:function(t,e,i,r,n,s){return t.invokeTask(i,r,n,s)},onCancelTask:function(t,e,i,r){return t.cancelTask(i,r)}};var a=function(){function t(t,e,i){this._taskCounts={microTask:0,macroTask:0,eventTask:0};this._zone=t;this._parentDelegate=e;this._forkZS=i&&(i&&i.onFork?i:e._forkZS);this._forkDlgt=i&&(i.onFork?e:e._forkDlgt);this._forkCurrZone=i&&(i.onFork?this._zone:e._forkCurrZone);this._interceptZS=i&&(i.onIntercept?i:e._interceptZS);this._interceptDlgt=i&&(i.onIntercept?e:e._interceptDlgt);this._interceptCurrZone=i&&(i.onIntercept?this._zone:e._interceptCurrZone);this._invokeZS=i&&(i.onInvoke?i:e._invokeZS);this._invokeDlgt=i&&(i.onInvoke?e:e._invokeDlgt);this._invokeCurrZone=i&&(i.onInvoke?this._zone:e._invokeCurrZone);this._handleErrorZS=i&&(i.onHandleError?i:e._handleErrorZS);this._handleErrorDlgt=i&&(i.onHandleError?e:e._handleErrorDlgt);this._handleErrorCurrZone=i&&(i.onHandleError?this._zone:e._handleErrorCurrZone);this._scheduleTaskZS=i&&(i.onScheduleTask?i:e._scheduleTaskZS);this._scheduleTaskDlgt=i&&(i.onScheduleTask?e:e._scheduleTaskDlgt);this._scheduleTaskCurrZone=i&&(i.onScheduleTask?this._zone:e._scheduleTaskCurrZone);this._invokeTaskZS=i&&(i.onInvokeTask?i:e._invokeTaskZS);this._invokeTaskDlgt=i&&(i.onInvokeTask?e:e._invokeTaskDlgt);this._invokeTaskCurrZone=i&&(i.onInvokeTask?this._zone:e._invokeTaskCurrZone);this._cancelTaskZS=i&&(i.onCancelTask?i:e._cancelTaskZS);this._cancelTaskDlgt=i&&(i.onCancelTask?e:e._cancelTaskDlgt);this._cancelTaskCurrZone=i&&(i.onCancelTask?this._zone:e._cancelTaskCurrZone);this._hasTaskZS=null;this._hasTaskDlgt=null;this._hasTaskDlgtOwner=null;this._hasTaskCurrZone=null;var r=i&&i.onHasTask;var n=e&&e._hasTaskZS;if(r||n){this._hasTaskZS=r?i:o;this._hasTaskDlgt=e;this._hasTaskDlgtOwner=this;this._hasTaskCurrZone=this._zone;if(!i.onScheduleTask){this._scheduleTaskZS=o;this._scheduleTaskDlgt=e;this._scheduleTaskCurrZone=this._zone}if(!i.onInvokeTask){this._invokeTaskZS=o;this._invokeTaskDlgt=e;this._invokeTaskCurrZone=this._zone}if(!i.onCancelTask){this._cancelTaskZS=o;this._cancelTaskDlgt=e;this._cancelTaskCurrZone=this._zone}}}Object.defineProperty(t.prototype,"zone",{get:function(){return this._zone},enumerable:false,configurable:true});t.prototype.fork=function(t,e){return this._forkZS?this._forkZS.onFork(this._forkDlgt,this.zone,t,e):new s(t,e)};t.prototype.intercept=function(t,e,i){return this._interceptZS?this._interceptZS.onIntercept(this._interceptDlgt,this._interceptCurrZone,t,e,i):e};t.prototype.invoke=function(t,e,i,r,n){return this._invokeZS?this._invokeZS.onInvoke(this._invokeDlgt,this._invokeCurrZone,t,e,i,r,n):e.apply(i,r)};t.prototype.handleError=function(t,e){return this._handleErrorZS?this._handleErrorZS.onHandleError(this._handleErrorDlgt,this._handleErrorCurrZone,t,e):true};t.prototype.scheduleTask=function(t,e){var i=e;if(this._scheduleTaskZS){if(this._hasTaskZS){i._zoneDelegates.push(this._hasTaskDlgtOwner)}i=this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt,this._scheduleTaskCurrZone,t,e);if(!i)i=e}else{if(e.scheduleFn){e.scheduleFn(e)}else if(e.type==_){b(e)}else{throw new Error("Task is missing scheduleFn.")}}return i};t.prototype.invokeTask=function(t,e,i,r){return this._invokeTaskZS?this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt,this._invokeTaskCurrZone,t,e,i,r):e.callback.apply(i,r)};t.prototype.cancelTask=function(t,e){var i;if(this._cancelTaskZS){i=this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt,this._cancelTaskCurrZone,t,e)}else{if(!e.cancelFn){throw Error("Task is not cancelable")}i=e.cancelFn(e)}return i};t.prototype.hasTask=function(t,e){try{this._hasTaskZS&&this._hasTaskZS.onHasTask(this._hasTaskDlgt,this._hasTaskCurrZone,t,e)}catch(e){this.handleError(t,e)}};t.prototype._updateTaskCount=function(t,e){var i=this._taskCounts;var r=i[t];var n=i[t]=r+e;if(n<0){throw new Error("More tasks executed then were scheduled.")}if(r==0||n==0){var s={microTask:i["microTask"]>0,macroTask:i["macroTask"]>0,eventTask:i["eventTask"]>0,change:t};this.hasTask(this._zone,s)}};return t}();var c=function(){function t(i,r,n,s,o,a){this._zone=null;this.runCount=0;this._zoneDelegates=null;this._state="notScheduled";this.type=i;this.source=r;this.data=s;this.scheduleFn=o;this.cancelFn=a;if(!n){throw new Error("callback is not defined")}this.callback=n;var c=this;if(i===T&&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 l=i("Promise");var f=i("then");var h=[];var d=false;var p;function m(t){if(!p){if(e[l]){p=e[l].resolve(0)}}if(p){var i=p[f];if(!i){i=p["then"]}i.call(p,t)}else{e[u](t,0)}}function b(t){if(I===0&&h.length===0){m(v)}t&&h.push(t)}function v(){if(!d){d=true;while(h.length){var t=h;h=[];for(var e=0;e<t.length;e++){var i=t[e];try{i.zone.runTask(i,null,null)}catch(t){C.onUnhandledError(t)}}}C.microtaskDrainDone();d=false}}var w={name:"NO ZONE"};var g="notScheduled",y="scheduling",x="scheduled",k="running",S="canceling",E="unknown";var _="microTask",A="macroTask",T="eventTask";var M={};var C={symbol:i,currentZoneFrame:function(){return O},onUnhandledError:L,microtaskDrainDone:L,scheduleMicroTask:b,showUncaughtError:function(){return!s[i("ignoreConsoleErrorUncaughtError")]},patchEventTarget:function(){return[]},patchOnProperties:L,patchMethod:function(){return L},bindArguments:function(){return[]},patchThen:function(){return L},patchMacroTask:function(){return L},patchEventPrototype:function(){return L},isIEOrEdge:function(){return false},getGlobalObjects:function(){return undefined},ObjectDefineProperty:function(){return L},ObjectGetOwnPropertyDescriptor:function(){return undefined},ObjectCreate:function(){return undefined},ArraySlice:function(){return[]},patchClass:function(){return L},wrapWithCurrentZone:function(){return L},filterProperties:function(){return[]},attachOriginToPatched:function(){return L},_redefineProperty:function(){return L},patchCallbacks:function(){return L},nativeScheduleMicroTask:m};var O={parent:null,zone:new s(null,null)};var P=null;var I=0;function L(){}n("Zone","Zone");return s}function n(){var t;var e=globalThis;var n=e[i("forceDuplicateZoneCheck")]===true;if(e["Zone"]&&(n||typeof e["Zone"].__symbol__!=="function")){throw new Error("Zone already loaded.")}(t=e["Zone"])!==null&&t!==void 0?t:e["Zone"]=r();return e["Zone"]}var s=Object.getOwnPropertyDescriptor;var o=Object.defineProperty;var a=Object.getPrototypeOf;var c=Object.create;var u=Array.prototype.slice;var l="addEventListener";var f="removeEventListener";var h=i(l);var d=i(f);var p="true";var m="false";var b=i("");function v(t,e){return Zone.current.wrap(t,e)}function w(t,e,i,r,n){return Zone.current.scheduleMacroTask(t,e,i,r,n)}var g=i;var y=typeof window!=="undefined";var x=y?window:undefined;var k=y&&x||globalThis;var S="removeAttribute";function E(t,e){for(var i=t.length-1;i>=0;i--){if(typeof t[i]==="function"){t[i]=v(t[i],e+"_"+i)}}return t}function _(t,e){var i=t.constructor["name"];var r=function(r){var n=e[r];var o=t[n];if(o){var a=s(t,n);if(!A(a)){return"continue"}t[n]=function(t){var e=function(){return t.apply(this,E(arguments,i+"."+n))};$(e,t);return e}(o)}};for(var n=0;n<e.length;n++){r(n)}}function A(t){if(!t){return true}if(t.writable===false){return false}return!(typeof t.get==="function"&&typeof t.set==="undefined")}var T=typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope;var M=!("nw"in k)&&typeof k.process!=="undefined"&&k.process.toString()==="[object process]";var C=!M&&!T&&!!(y&&x["HTMLElement"]);var O=typeof k.process!=="undefined"&&k.process.toString()==="[object process]"&&!T&&!!(y&&x["HTMLElement"]);var P={};var I=g("enable_beforeunload");var L=function(t){t=t||k.event;if(!t){return}var e=P[t.type];if(!e){e=P[t.type]=g("ON_PROPERTY"+t.type)}var i=this||t.target||k;var r=i[e];var n;if(C&&i===x&&t.type==="error"){var s=t;n=r&&r.call(this,s.message,s.filename,s.lineno,s.colno,s.error);if(n===true){t.preventDefault()}}else{n=r&&r.apply(this,arguments);if(t.type==="beforeunload"&&k[I]&&typeof n==="string"){t.returnValue=n}else if(n!=undefined&&!n){t.preventDefault()}}return n};function D(t,e,i){var r=s(t,e);if(!r&&i){var n=s(i,e);if(n){r={enumerable:true,configurable:true}}}if(!r||!r.configurable){return}var a=g("on"+e+"patched");if(t.hasOwnProperty(a)&&t[a]){return}delete r.writable;delete r.value;var c=r.get;var u=r.set;var l=e.slice(2);var f=P[l];if(!f){f=P[l]=g("ON_PROPERTY"+l)}r.set=function(e){var i=this;if(!i&&t===k){i=k}if(!i){return}var r=i[f];if(typeof r==="function"){i.removeEventListener(l,L)}u===null||u===void 0?void 0:u.call(i,null);i[f]=e;if(typeof e==="function"){i.addEventListener(l,L,false)}};r.get=function(){var i=this;if(!i&&t===k){i=k}if(!i){return null}var n=i[f];if(n){return n}else if(c){var s=c.call(this);if(s){r.set.call(this,s);if(typeof i[S]==="function"){i.removeAttribute(e)}return s}}return null};o(t,e,r);t[a]=true}function R(t,e,i){if(e){for(var r=0;r<e.length;r++){D(t,"on"+e[r],i)}}else{var n=[];for(var s in t){if(s.slice(0,2)=="on"){n.push(s)}}for(var o=0;o<n.length;o++){D(t,n[o],i)}}}var N=g("originalInstance");function j(t){var e=k[t];if(!e)return;k[g(t)]=e;k[t]=function(){var i=E(arguments,t);switch(i.length){case 0:this[N]=new e;break;case 1:this[N]=new e(i[0]);break;case 2:this[N]=new e(i[0],i[1]);break;case 3:this[N]=new e(i[0],i[1],i[2]);break;case 4:this[N]=new e(i[0],i[1],i[2],i[3]);break;default:throw new Error("Arg list too long.")}};$(k[t],e);var i=new e((function(){}));var r;for(r in i){if(t==="XMLHttpRequest"&&r==="responseBlob")continue;(function(e){if(typeof i[e]==="function"){k[t].prototype[e]=function(){return this[N][e].apply(this[N],arguments)}}else{o(k[t].prototype,e,{set:function(i){if(typeof i==="function"){this[N][e]=v(i,t+"."+e);$(this[N][e],i)}else{this[N][e]=i}},get:function(){return this[N][e]}})}})(r)}for(r in e){if(r!=="prototype"&&e.hasOwnProperty(r)){k[t][r]=e[r]}}}function U(t,e,i){var r=t;while(r&&!r.hasOwnProperty(e)){r=a(r)}if(!r&&t[e]){r=t}var n=g(e);var o=null;if(r&&(!(o=r[n])||!r.hasOwnProperty(n))){o=r[n]=r[e];var c=r&&s(r,e);if(A(c)){var u=i(o,n,e);r[e]=function(){return u(this,arguments)};$(r[e],o)}}return o}function z(t,e,i){var r=null;function n(t){var e=t.data;e.args[e.cbIdx]=function(){t.invoke.apply(this,arguments)};r.apply(e.target,e.args);return t}r=U(t,e,(function(t){return function(e,r){var s=i(e,r);if(s.cbIdx>=0&&typeof r[s.cbIdx]==="function"){return w(s.name,r[s.cbIdx],s,n)}else{return t.apply(e,r)}}}))}function $(t,e){t[g("OriginalDelegate")]=e}var B=false;var F=false;function G(){if(B){return F}B=true;try{var t=x.navigator.userAgent;if(t.indexOf("MSIE ")!==-1||t.indexOf("Trident/")!==-1||t.indexOf("Edge/")!==-1){F=true}}catch(t){}return F}function V(t){return typeof t==="function"}function q(t){return typeof t==="number"}var H={useG:true};var J={};var K={};var Z=new RegExp("^"+b+"(\\w+)(true|false)$");var W=g("propagationStopped");function X(t,e){var i=(e?e(t):t)+m;var r=(e?e(t):t)+p;var n=b+i;var s=b+r;J[t]={};J[t][m]=n;J[t][p]=s}function Y(e,i,r,n){var s=n&&n.add||l;var o=n&&n.rm||f;var c=n&&n.listeners||"eventListeners";var u=n&&n.rmAll||"removeAllListeners";var h=g(s);var d="."+s+":";var v="prependListener";var w="."+v+":";var y=function(t,e,i){if(t.isRemoved){return}var r=t.callback;if(typeof r==="object"&&r.handleEvent){t.callback=function(t){return r.handleEvent(t)};t.originalDelegate=r}var n;try{t.invoke(t,e,[i])}catch(t){n=t}var s=t.options;if(s&&typeof s==="object"&&s.once){var a=t.originalDelegate?t.originalDelegate:t.callback;e[o].call(e,i.type,a,s)}return n};function x(t,r,n){r=r||e.event;if(!r){return}var s=t||r.target||e;var o=s[J[r.type][n?p:m]];if(o){var a=[];if(o.length===1){var c=y(o[0],s,r);c&&a.push(c)}else{var u=o.slice();for(var l=0;l<u.length;l++){if(r&&r[W]===true){break}var c=y(u[l],s,r);c&&a.push(c)}}if(a.length===1){throw a[0]}else{var f=function(t){var e=a[t];i.nativeScheduleMicroTask((function(){throw e}))};for(var l=0;l<a.length;l++){f(l)}}}}var k=function(t){return x(this,t,false)};var S=function(t){return x(this,t,true)};function E(i,r){if(!i){return false}var n=true;if(r&&r.useG!==undefined){n=r.useG}var l=r&&r.vh;var f=true;if(r&&r.chkDup!==undefined){f=r.chkDup}var y=false;if(r&&r.rt!==undefined){y=r.rt}var x=i;while(x&&!x.hasOwnProperty(s)){x=a(x)}if(!x&&i[s]){x=i}if(!x){return false}if(x[h]){return false}var E=r&&r.eventNameToString;var _={};var A=x[h]=x[s];var T=x[g(o)]=x[o];var C=x[g(c)]=x[c];var O=x[g(u)]=x[u];var P;if(r&&r.prepend){P=x[g(r.prepend)]=x[r.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(_.isExisting){return}return A.call(_.target,_.eventName,_.capture?S:k,_.options)};var D=function(t){if(!t.isRemoved){var e=J[t.eventName];var i=void 0;if(e){i=e[t.capture?p:m]}var r=i&&t.target[i];if(r){for(var n=0;n<r.length;n++){var s=r[n];if(s===t){r.splice(n,1);t.isRemoved=true;if(t.removeAbortListener){t.removeAbortListener();t.removeAbortListener=null}if(r.length===0){t.allRemoved=true;t.target[i]=null}break}}}}if(!t.allRemoved){return}return T.call(t.target,t.eventName,t.capture?S:k,t.options)};var R=function(t){return A.call(_.target,_.eventName,t.invoke,_.options)};var N=function(t){return P.call(_.target,_.eventName,t.invoke,_.options)};var j=function(t){return T.call(t.target,t.eventName,t.invoke,t.options)};var U=n?L:R;var z=n?D:j;var B=function(t,e){var i=typeof e;return i==="function"&&t.callback===e||i==="object"&&t.originalDelegate===e};var F=(r===null||r===void 0?void 0:r.diff)||B;var G=Zone[g("UNPATCHED_EVENTS")];var V=e[g("PASSIVE_EVENTS")];function q(e){if(typeof e==="object"&&e!==null){var i=t({},e);if(e.signal){i.signal=e.signal}return i}return e}var W=function(t,i,s,o,a,c){if(a===void 0){a=false}if(c===void 0){c=false}return function(){var u=this||e;var h=arguments[0];if(r&&r.transferEventName){h=r.transferEventName(h)}var d=arguments[1];if(!d){return t.apply(this,arguments)}if(M&&h==="uncaughtException"){return t.apply(this,arguments)}var b=false;if(typeof d!=="function"){if(!d.handleEvent){return t.apply(this,arguments)}b=true}if(l&&!l(t,d,u,arguments)){return}var v=!!V&&V.indexOf(h)!==-1;var w=q(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(G){for(var y=0;y<G.length;y++){if(h===G[y]){if(v){return t.call(u,h,d,w)}else{return t.apply(this,arguments)}}}}var x=!w?false:typeof w==="boolean"?true:w.capture;var k=w&&typeof w==="object"?w.once:false;var S=Zone.current;var A=J[h];if(!A){X(h,E);A=J[h]}var T=A[x?p:m];var C=u[T];var O=false;if(C){O=true;if(f){for(var y=0;y<C.length;y++){if(F(C[y],d)){return}}}}else{C=u[T]=[]}var P;var L=u.constructor["name"];var D=K[L];if(D){P=D[h]}if(!P){P=L+i+(E?E(h):h)}_.options=w;if(k){_.options.once=false}_.target=u;_.capture=x;_.eventName=h;_.isExisting=O;var R=n?H:undefined;if(R){R.taskData=_}if(g){_.options.signal=undefined}var N=S.scheduleEventTask(P,d,R,s,o);if(g){_.options.signal=g;var j=function(){return N.zone.cancelTask(N)};t.call(g,"abort",j,{once:true});N.removeAbortListener=function(){return g.removeEventListener("abort",j)}}_.target=null;if(R){R.taskData=null}if(k){_.options.once=true}if(typeof N.options!=="boolean"){N.options=w}N.target=u;N.capture=x;N.eventName=h;if(b){N.originalDelegate=d}if(!c){C.push(N)}else{C.unshift(N)}if(a){return u}}};x[s]=W(A,d,U,z,y);if(P){x[v]=W(P,w,N,z,y,true)}x[o]=function(){var t=this||e;var i=arguments[0];if(r&&r.transferEventName){i=r.transferEventName(i)}var n=arguments[2];var s=!n?false:typeof n==="boolean"?true:n.capture;var o=arguments[1];if(!o){return T.apply(this,arguments)}if(l&&!l(T,o,t,arguments)){return}var a=J[i];var c;if(a){c=a[s?p:m]}var u=c&&t[c];if(u){for(var f=0;f<u.length;f++){var h=u[f];if(F(h,o)){u.splice(f,1);h.isRemoved=true;if(u.length===0){h.allRemoved=true;t[c]=null;if(!s&&typeof i==="string"){var d=b+"ON_PROPERTY"+i;t[d]=null}}h.zone.cancelTask(h);if(y){return t}return}}}return T.apply(this,arguments)};x[c]=function(){var t=this||e;var i=arguments[0];if(r&&r.transferEventName){i=r.transferEventName(i)}var n=[];var s=Q(t,E?E(i):i);for(var o=0;o<s.length;o++){var a=s[o];var c=a.originalDelegate?a.originalDelegate:a.callback;n.push(c)}return n};x[u]=function(){var t=this||e;var i=arguments[0];if(!i){var n=Object.keys(t);for(var s=0;s<n.length;s++){var a=n[s];var c=Z.exec(a);var l=c&&c[1];if(l&&l!=="removeListener"){this[u].call(this,l)}}this[u].call(this,"removeListener")}else{if(r&&r.transferEventName){i=r.transferEventName(i)}var f=J[i];if(f){var h=f[m];var d=f[p];var b=t[h];var v=t[d];if(b){var w=b.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}if(v){var w=v.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}}}if(y){return this}};$(x[s],A);$(x[o],T);if(O){$(x[u],O)}if(C){$(x[c],C)}return true}var _=[];for(var A=0;A<r.length;A++){_[A]=E(r[A],n)}return _}function Q(t,e){if(!e){var i=[];for(var r in t){var n=Z.exec(r);var s=n&&n[1];if(s&&(!e||s===e)){var o=t[r];if(o){for(var a=0;a<o.length;a++){i.push(o[a])}}}}return i}var c=J[e];if(!c){X(e);c=J[e]}var u=t[c[m]];var l=t[c[p]];if(!u){return l?l.slice():[]}else{return l?u.concat(l):u.slice()}}function tt(t,e){var i=t["Event"];if(i&&i.prototype){e.patchMethod(i.prototype,"stopImmediatePropagation",(function(t){return function(e,i){e[W]=true;t&&t.apply(e,i)}}))}}function et(t,e){e.patchMethod(t,"queueMicrotask",(function(t){return function(t,e){Zone.current.scheduleMicroTask("queueMicrotask",e[0])}}))}var it=g("zoneTask");function rt(t,e,i,r){var n=null;var s=null;e+=r;i+=r;var o={};function a(e){var i=e.data;i.args[0]=function(){return e.invoke.apply(this,arguments)};var r=n.apply(t,i.args);if(q(r)){i.handleId=r}else{i.handle=r;i.isRefreshable=V(r.refresh)}return e}function c(e){var i=e.data,r=i.handle,n=i.handleId;return s.call(t,r!==null&&r!==void 0?r:n)}n=U(t,e,(function(i){return function(n,s){var u;if(V(s[0])){var l={isRefreshable:false,isPeriodic:r==="Interval",delay:r==="Timeout"||r==="Interval"?s[1]||0:undefined,args:s};var f=s[0];s[0]=function t(){try{return f.apply(this,arguments)}finally{var e=l.handle,i=l.handleId,r=l.isPeriodic,n=l.isRefreshable;if(!r&&!n){if(i){delete o[i]}else if(e){e[it]=null}}}};var h=w(e,s[0],l,a,c);if(!h){return h}var d=h.data,p=d.handleId,m=d.handle,b=d.isRefreshable,v=d.isPeriodic;if(p){o[p]=h}else if(m){m[it]=h;if(b&&!v){var g=m.refresh;m.refresh=function(){var t=h.zone,e=h.state;if(e==="notScheduled"){h._state="scheduled";t._updateTaskCount(h,1)}else if(e==="running"){h._state="scheduling"}return g.call(this)}}}return(u=m!==null&&m!==void 0?m:p)!==null&&u!==void 0?u:h}else{return i.apply(t,s)}}}));s=U(t,i,(function(e){return function(i,r){var n=r[0];var s;if(q(n)){s=o[n];delete o[n]}else{s=n===null||n===void 0?void 0:n[it];if(s){n[it]=null}else{s=n}}if(s===null||s===void 0?void 0:s.type){if(s.cancelFn){s.zone.cancelTask(s)}}else{e.apply(t,r)}}}))}function nt(t,e){var i=e.getGlobalObjects(),r=i.isBrowser,n=i.isMix;if(!r&&!n||!t["customElements"]||!("customElements"in t)){return}var s=["connectedCallback","disconnectedCallback","adoptedCallback","attributeChangedCallback","formAssociatedCallback","formDisabledCallback","formResetCallback","formStateRestoreCallback"];e.patchCallbacks(e,t.customElements,"customElements","define",s)}function st(t,e){if(Zone[e.symbol("patchEventTarget")]){return}var i=e.getGlobalObjects(),r=i.eventNames,n=i.zoneSymbolEventNames,s=i.TRUE_STR,o=i.FALSE_STR,a=i.ZONE_SYMBOL_PREFIX;for(var c=0;c<r.length;c++){var u=r[c];var l=u+o;var f=u+s;var h=a+l;var d=a+f;n[u]={};n[u][o]=h;n[u][s]=d}var p=t["EventTarget"];if(!p||!p.prototype){return}e.patchEventTarget(t,e,[p&&p.prototype]);return true}function ot(t,e){e.patchEventPrototype(t,e)}function at(t,e,i){if(!i||i.length===0){return e}var r=i.filter((function(e){return e.target===t}));if(r.length===0){return e}var n=r[0].ignoreProperties;return e.filter((function(t){return n.indexOf(t)===-1}))}function ct(t,e,i,r){if(!t){return}var n=at(t,e,i);R(t,n,r)}function ut(t){return Object.getOwnPropertyNames(t).filter((function(t){return t.startsWith("on")&&t.length>2})).map((function(t){return t.substring(2)}))}function lt(t,e){if(M&&!O){return}if(Zone[t.symbol("patchEvents")]){return}var i=e["__Zone_ignore_on_properties"];var r=[];if(C){var n=window;r=r.concat(["Document","SVGElement","Element","HTMLElement","HTMLBodyElement","HTMLMediaElement","HTMLFrameSetElement","HTMLFrameElement","HTMLIFrameElement","HTMLMarqueeElement","Worker"]);var s=[];ct(n,ut(n),i?i.concat(s):i,a(n))}r=r.concat(["XMLHttpRequest","XMLHttpRequestEventTarget","IDBIndex","IDBRequest","IDBOpenDBRequest","IDBDatabase","IDBTransaction","IDBCursor","WebSocket"]);for(var o=0;o<r.length;o++){var c=e[r[o]];(c===null||c===void 0?void 0:c.prototype)&&ct(c.prototype,ut(c.prototype),i)}}function ft(t){t.__load_patch("legacy",(function(e){var i=e[t.__symbol__("legacyPatch")];if(i){i()}}));t.__load_patch("timers",(function(t){var e="set";var i="clear";rt(t,e,i,"Timeout");rt(t,e,i,"Interval");rt(t,e,i,"Immediate")}));t.__load_patch("requestAnimationFrame",(function(t){rt(t,"request","cancel","AnimationFrame");rt(t,"mozRequest","mozCancel","AnimationFrame");rt(t,"webkitRequest","webkitCancel","AnimationFrame")}));t.__load_patch("blocking",(function(t,e){var i=["alert","prompt","confirm"];for(var r=0;r<i.length;r++){var n=i[r];U(t,n,(function(i,r,n){return function(r,s){return e.current.run(i,t,s,n)}}))}}));t.__load_patch("EventTarget",(function(t,e,i){ot(t,i);st(t,i);var r=t["XMLHttpRequestEventTarget"];if(r&&r.prototype){i.patchEventTarget(t,i,[r.prototype])}}));t.__load_patch("MutationObserver",(function(t,e,i){j("MutationObserver");j("WebKitMutationObserver")}));t.__load_patch("IntersectionObserver",(function(t,e,i){j("IntersectionObserver")}));t.__load_patch("FileReader",(function(t,e,i){j("FileReader")}));t.__load_patch("on_property",(function(t,e,i){lt(i,t)}));t.__load_patch("customElements",(function(t,e,i){nt(t,i)}));t.__load_patch("XHR",(function(t,e){c(t);var i=g("xhrTask");var r=g("xhrSync");var n=g("xhrListener");var s=g("xhrScheduled");var o=g("xhrURL");var a=g("xhrErrorBeforeScheduled");function c(t){var c=t["XMLHttpRequest"];if(!c){return}var u=c.prototype;function l(t){return t[i]}var f=u[h];var p=u[d];if(!f){var m=t["XMLHttpRequestEventTarget"];if(m){var b=m.prototype;f=b[h];p=b[d]}}var v="readystatechange";var y="scheduled";function x(t){var r=t.data;var o=r.target;o[s]=false;o[a]=false;var c=o[n];if(!f){f=o[h];p=o[d]}if(c){p.call(o,v,c)}var u=o[n]=function(){if(o.readyState===o.DONE){if(!r.aborted&&o[s]&&t.state===y){var i=o[e.__symbol__("loadfalse")];if(o.status!==0&&i&&i.length>0){var n=t.invoke;t.invoke=function(){var i=o[e.__symbol__("loadfalse")];for(var s=0;s<i.length;s++){if(i[s]===t){i.splice(s,1)}}if(!r.aborted&&t.state===y){n.call(t)}};i.push(t)}else{t.invoke()}}else if(!r.aborted&&o[s]===false){o[a]=true}}};f.call(o,v,u);var l=o[i];if(!l){o[i]=t}M.apply(o,r.args);o[s]=true;return t}function k(){}function S(t){var e=t.data;e.aborted=true;return C.apply(e.target,e.args)}var E=U(u,"open",(function(){return function(t,e){t[r]=e[2]==false;t[o]=e[1];return E.apply(t,e)}}));var _="XMLHttpRequest.send";var A=g("fetchTaskAborting");var T=g("fetchTaskScheduling");var M=U(u,"send",(function(){return function(t,i){if(e.current[T]===true){return M.apply(t,i)}if(t[r]){return M.apply(t,i)}else{var n={target:t,url:t[o],isPeriodic:false,args:i,aborted:false};var s=w(_,k,n,x,S);if(t&&t[a]===true&&!n.aborted&&s.state===y){s.invoke()}}}}));var C=U(u,"abort",(function(){return function(t,i){var r=l(t);if(r&&typeof r.type=="string"){if(r.cancelFn==null||r.data&&r.data.aborted){return}r.zone.cancelTask(r)}else if(e.current[A]===true){return C.apply(t,i)}}}))}}));t.__load_patch("geolocation",(function(t){if(t["navigator"]&&t["navigator"].geolocation){_(t["navigator"].geolocation,["getCurrentPosition","watchPosition"])}}));t.__load_patch("PromiseRejectionEvent",(function(t,e){function i(e){return function(i){var r=Q(t,e);r.forEach((function(r){var n=t["PromiseRejectionEvent"];if(n){var s=new n(e,{promise:i.promise,reason:i.rejection});r.invoke(s)}}))}}if(t["PromiseRejectionEvent"]){e[g("unhandledPromiseRejectionHandler")]=i("unhandledrejection");e[g("rejectionHandledHandler")]=i("rejectionhandled")}}));t.__load_patch("queueMicrotask",(function(t,e,i){et(t,i)}))}function ht(t){t.__load_patch("ZoneAwarePromise",(function(t,e,i){var r=Object.getOwnPropertyDescriptor;var n=Object.defineProperty;function s(t){if(t&&t.toString===Object.prototype.toString){var e=t.constructor&&t.constructor.name;return(e?e:"")+": "+JSON.stringify(t)}return t?t.toString():Object.prototype.toString.call(t)}var o=i.symbol;var a=[];var c=t[o("DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION")]!==false;var u=o("Promise");var l=o("then");var f="__creationTrace__";i.onUnhandledError=function(t){if(i.showUncaughtError()){var e=t&&t.rejection;if(e){console.error("Unhandled Promise rejection:",e instanceof Error?e.message:e,"; Zone:",t.zone.name,"; Task:",t.task&&t.task.source,"; Value:",e,e instanceof Error?e.stack:undefined)}else{console.error(t)}}};i.microtaskDrainDone=function(){var t=function(){var t=a.shift();try{t.zone.runGuarded((function(){if(t.throwOriginal){throw t.rejection}throw t}))}catch(t){d(t)}};while(a.length){t()}};var h=o("unhandledPromiseRejectionHandler");function d(t){i.onUnhandledError(t);try{var r=e[h];if(typeof r==="function"){r.call(this,t)}}catch(t){}}function p(t){return t&&typeof t.then==="function"}function m(t){return t}function b(t){return z.reject(t)}var v=o("state");var w=o("value");var g=o("finally");var y=o("parentPromiseValue");var x=o("parentPromiseState");var k="Promise.then";var S=null;var E=true;var _=false;var A=0;function T(t,e){return function(i){try{P(t,e,i)}catch(e){P(t,false,e)}}}var M=function(){var t=false;return function e(i){return function(){if(t){return}t=true;i.apply(null,arguments)}}};var C="Promise resolved with itself";var O=o("currentTaskTrace");function P(t,r,o){var u=M();if(t===o){throw new TypeError(C)}if(t[v]===S){var l=null;try{if(typeof o==="object"||typeof o==="function"){l=o&&o.then}}catch(e){u((function(){P(t,false,e)}))();return t}if(r!==_&&o instanceof z&&o.hasOwnProperty(v)&&o.hasOwnProperty(w)&&o[v]!==S){L(o);P(t,o[v],o[w])}else if(r!==_&&typeof l==="function"){try{l.call(o,u(T(t,r)),u(T(t,false)))}catch(e){u((function(){P(t,false,e)}))()}}else{t[v]=r;var h=t[w];t[w]=o;if(t[g]===g){if(r===E){t[v]=t[x];t[w]=t[y]}}if(r===_&&o instanceof Error){var d=e.currentTask&&e.currentTask.data&&e.currentTask.data[f];if(d){n(o,O,{configurable:true,enumerable:false,writable:true,value:d})}}for(var p=0;p<h.length;){D(t,h[p++],h[p++],h[p++],h[p++])}if(h.length==0&&r==_){t[v]=A;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]===A){try{var i=e[I];if(i&&typeof i==="function"){i.call(this,{rejection:t[w],promise:t})}}catch(t){}t[v]=_;for(var r=0;r<a.length;r++){if(t===a[r].promise){a.splice(r,1)}}}}function D(t,e,i,r,n){L(t);var s=t[v];var o=s?typeof r==="function"?r:m:typeof n==="function"?n:b;e.scheduleMicroTask(k,(function(){try{var r=t[w];var n=!!i&&g===i[g];if(n){i[y]=r;i[x]=s}var a=e.run(o,undefined,n&&o!==b&&o!==m?[]:[r]);P(i,true,a)}catch(t){P(i,false,t)}}),i)}var R="function ZoneAwarePromise() { [native code] }";var N=function(){};var j=t.AggregateError;var z=function(){function t(e){var i=this;if(!(i instanceof t)){throw new Error("Must be an instanceof Promise.")}i[v]=S;i[w]=[];try{var r=M();e&&e(r(T(i,E)),r(T(i,_)))}catch(t){P(i,false,t)}}t.toString=function(){return R};t.resolve=function(e){if(e instanceof t){return e}return P(new this(null),E,e)};t.reject=function(t){return P(new this(null),_,t)};t.withResolvers=function(){var e={};e.promise=new t((function(t,i){e.resolve=t;e.reject=i}));return e};t.any=function(e){if(!e||typeof e[Symbol.iterator]!=="function"){return Promise.reject(new j([],"All promises were rejected"))}var i=[];var r=0;try{for(var n=0,s=e;n<s.length;n++){var o=s[n];r++;i.push(t.resolve(o))}}catch(t){return Promise.reject(new j([],"All promises were rejected"))}if(r===0){return Promise.reject(new j([],"All promises were rejected"))}var a=false;var c=[];return new t((function(t,e){for(var n=0;n<i.length;n++){i[n].then((function(e){if(a){return}a=true;t(e)}),(function(t){c.push(t);r--;if(r===0){a=true;e(new j(c,"All promises were rejected"))}}))}}))};t.race=function(t){var e;var i;var r=new this((function(t,r){e=t;i=r}));function n(t){e(t)}function s(t){i(t)}for(var o=0,a=t;o<a.length;o++){var c=a[o];if(!p(c)){c=this.resolve(c)}c.then(n,s)}return r};t.all=function(e){return t.allWithCallback(e)};t.allSettled=function(e){var i=this&&this.prototype instanceof t?this:t;return i.allWithCallback(e,{thenCallback:function(t){return{status:"fulfilled",value:t}},errorCallback:function(t){return{status:"rejected",reason:t}}})};t.allWithCallback=function(t,e){var i;var r;var n=new this((function(t,e){i=t;r=e}));var s=2;var o=0;var a=[];var c=function(t){if(!p(t)){t=u.resolve(t)}var n=o;try{t.then((function(t){a[n]=e?e.thenCallback(t):t;s--;if(s===0){i(a)}}),(function(t){if(!e){r(t)}else{a[n]=e.errorCallback(t);s--;if(s===0){i(a)}}}))}catch(t){r(t)}s++;o++};var u=this;for(var l=0,f=t;l<f.length;l++){var h=f[l];c(h)}s-=2;if(s===0){i(a)}return n};Object.defineProperty(t.prototype,Symbol.toStringTag,{get:function(){return"Promise"},enumerable:false,configurable:true});Object.defineProperty(t.prototype,Symbol.species,{get:function(){return t},enumerable:false,configurable:true});t.prototype.then=function(i,r){var n;var s=(n=this.constructor)===null||n===void 0?void 0:n[Symbol.species];if(!s||typeof s!=="function"){s=this.constructor||t}var o=new s(N);var a=e.current;if(this[v]==S){this[w].push(a,o,i,r)}else{D(this,a,o,i,r)}return o};t.prototype.catch=function(t){return this.then(null,t)};t.prototype.finally=function(i){var r;var n=(r=this.constructor)===null||r===void 0?void 0:r[Symbol.species];if(!n||typeof n!=="function"){n=t}var s=new n(N);s[g]=g;var o=e.current;if(this[v]==S){this[w].push(o,s,i,i)}else{D(this,o,s,i,i)}return s};return t}();z["resolve"]=z.resolve;z["reject"]=z.reject;z["race"]=z.race;z["all"]=z.all;var $=t[u]=t["Promise"];t["Promise"]=z;var B=o("thenPatched");function F(t){var e=t.prototype;var i=r(e,"then");if(i&&(i.writable===false||!i.configurable)){return}var n=e.then;e[l]=n;t.prototype.then=function(t,e){var i=this;var r=new z((function(t,e){n.call(i,t,e)}));return r.then(t,e)};t[B]=true}i.patchThen=F;function G(t){return function(e,i){var r=t.apply(e,i);if(r instanceof z){return r}var n=r.constructor;if(!n[B]){F(n)}return r}}if($){F($);U(t,"fetch",(function(t){return G(t)}))}Promise[e.__symbol__("uncaughtPromiseErrors")]=a;return z}))}function dt(t){t.__load_patch("toString",(function(t){var e=Function.prototype.toString;var i=g("OriginalDelegate");var r=g("Promise");var n=g("Error");var s=function s(){if(typeof this==="function"){var o=this[i];if(o){if(typeof o==="function"){return e.call(o)}else{return Object.prototype.toString.call(o)}}if(this===Promise){var a=t[r];if(a){return e.call(a)}}if(this===Error){var c=t[n];if(c){return e.call(c)}}}return e.call(this)};s[i]=e;Function.prototype.toString=s;var o=Object.prototype.toString;var a="[object Promise]";Object.prototype.toString=function(){if(typeof Promise==="function"&&this instanceof Promise){return a}return o.call(this)}}))}function pt(t,e,i,r,n){var s=Zone.__symbol__(r);if(e[s]){return}var o=e[s]=e[r];e[r]=function(s,a,c){if(a&&a.prototype){n.forEach((function(e){var n="".concat(i,".").concat(r,"::")+e;var s=a.prototype;try{if(s.hasOwnProperty(e)){var o=t.ObjectGetOwnPropertyDescriptor(s,e);if(o&&o.value){o.value=t.wrapWithCurrentZone(o.value,n);t._redefineProperty(a.prototype,e,o)}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],n)}}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],n)}}catch(t){}}))}return o.call(e,s,a,c)};t.attachOriginToPatched(e[r],o)}function mt(t){t.__load_patch("util",(function(t,e,i){var r=ut(t);i.patchOnProperties=R;i.patchMethod=U;i.bindArguments=E;i.patchMacroTask=z;var n=e.__symbol__("BLACK_LISTED_EVENTS");var a=e.__symbol__("UNPATCHED_EVENTS");if(t[a]){t[n]=t[a]}if(t[n]){e[n]=e[a]=t[n]}i.patchEventPrototype=tt;i.patchEventTarget=Y;i.isIEOrEdge=G;i.ObjectDefineProperty=o;i.ObjectGetOwnPropertyDescriptor=s;i.ObjectCreate=c;i.ArraySlice=u;i.patchClass=j;i.wrapWithCurrentZone=v;i.filterProperties=at;i.attachOriginToPatched=$;i._redefineProperty=Object.defineProperty;i.patchCallbacks=pt;i.getGlobalObjects=function(){return{globalSources:K,zoneSymbolEventNames:J,eventNames:r,isBrowser:C,isMix:O,isNode:M,TRUE_STR:p,FALSE_STR:m,ZONE_SYMBOL_PREFIX:b,ADD_EVENT_LISTENER_STR:l,REMOVE_EVENT_LISTENER_STR:f}}}))}function bt(t){ht(t);dt(t);mt(t)}var vt=n();bt(vt);ft(vt)}));return Os}Is();class Ls{emit(t){}}const Ds=new Ls;class Rs{getLogger(t,e,i){return new Ls}}const Ns=new Rs;class js{constructor(t,e,i,r){this._provider=t;this.name=e;this.version=i;this.options=r}emit(t){this._getLogger().emit(t)}_getLogger(){if(this._delegate){return this._delegate}const t=this._provider._getDelegateLogger(this.name,this.version,this.options);if(!t){return Ds}this._delegate=t;return this._delegate}}class Us{getLogger(t,e,i){var r;return(r=this._getDelegateLogger(t,e,i))!==null&&r!==void 0?r:new js(this,t,e,i)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Ns}_setDelegate(t){this._delegate=t}_getDelegateLogger(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getLogger(t,e,i)}}const zs=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};const $s=Symbol.for("io.opentelemetry.js.api.logs");const Bs=zs;function Fs(t,e,i){return r=>r===t?e:i}const Gs=1;class Vs{constructor(){this._proxyLoggerProvider=new Us}static getInstance(){if(!this._instance){this._instance=new Vs}return this._instance}setGlobalLoggerProvider(t){if(Bs[$s]){return this.getLoggerProvider()}Bs[$s]=Fs(Gs,t,Ns);this._proxyLoggerProvider._setDelegate(t);return t}getLoggerProvider(){var t,e;return(e=(t=Bs[$s])===null||t===void 0?void 0:t.call(Bs,Gs))!==null&&e!==void 0?e:this._proxyLoggerProvider}getLogger(t,e,i){return this.getLoggerProvider().getLogger(t,e,i)}disable(){delete Bs[$s];this._proxyLoggerProvider=new Us}}const qs=Vs.getInstance();function Hs(t,e,i,r){for(let n=0,s=t.length;n<s;n++){const s=t[n];if(e){s.setTracerProvider(e)}if(i){s.setMeterProvider(i)}if(r&&s.setLoggerProvider){s.setLoggerProvider(r)}if(!s.getConfig().enabled){s.enable()}}}function Js(t){t.forEach((t=>t.disable()))}function Ks(t){const e=t.tracerProvider||pe.getTracerProvider();const i=t.meterProvider||ee.getMeterProvider();const r=t.loggerProvider||qs.getLoggerProvider();const n=t.instrumentations?.flat()??[];Hs(n,e,i,r);return()=>{Js(n)}}let Zs=console.error.bind(console);function Ws(t,e,i){const r=!!t[e]&&Object.prototype.propertyIsEnumerable.call(t,e);Object.defineProperty(t,e,{configurable:true,enumerable:r,writable:true,value:i})}const Xs=(t,e,i)=>{if(!t||!t[e]){Zs("no original function "+String(e)+" to wrap");return}if(!i){Zs("no wrapper function");Zs((new Error).stack);return}const r=t[e];if(typeof r!=="function"||typeof i!=="function"){Zs("original object and wrapper must be functions");return}const n=i(r,e);Ws(n,"__original",r);Ws(n,"__unwrap",(()=>{if(t[e]===n){Ws(t,e,r)}}));Ws(n,"__wrapped",true);Ws(t,e,n);return n};const Ys=(t,e,i)=>{if(!t){Zs("must provide one or more modules to patch");Zs((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Zs("must provide one or more functions to wrap on modules");return}t.forEach((t=>{e.forEach((e=>{Xs(t,e,i)}))}))};const Qs=(t,e)=>{if(!t||!t[e]){Zs("no function to unwrap.");Zs((new Error).stack);return}const i=t[e];if(!i.__unwrap){Zs("no original to unwrap to -- has "+String(e)+" already been unwrapped?")}else{i.__unwrap();return}};const to=(t,e)=>{if(!t){Zs("must provide one or more modules to patch");Zs((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Zs("must provide one or more functions to unwrap on modules");return}t.forEach((t=>{e.forEach((e=>{Qs(t,e)}))}))};class eo{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(t,e,i){this.instrumentationName=t;this.instrumentationVersion=e;this.setConfig(i);this._diag=Wt.createComponentLogger({namespace:t});this._tracer=pe.getTracer(t,e);this._meter=ee.getMeter(t,e);this._logger=qs.getLogger(t,e);this._updateMetricInstruments()}_wrap=Xs;_unwrap=Qs;_massWrap=Ys;_massUnwrap=to;get meter(){return this._meter}setMeterProvider(t){this._meter=t.getMeter(this.instrumentationName,this.instrumentationVersion);this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(t){this._logger=t.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const t=this.init()??[];if(!Array.isArray(t)){return[t]}return t}_updateMetricInstruments(){return}getConfig(){return this._config}setConfig(t){this._config={enabled:true,...t}}setTracerProvider(t){this._tracer=t.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(t,e,i,r){if(!t){return}try{t(i,r)}catch(t){this._diag.error(`Error running span customization hook due to exception in handler`,{triggerName:e},t)}}}class io extends eo{constructor(t,e,i){super(t,e,i);if(this._config.enabled){this.enable()}}}function ro(t){return typeof t==="function"&&typeof t.__original==="function"&&typeof t.__unwrap==="function"&&t.__wrapped===true}var no;(function(t){t["EVENT_TYPE"]="event_type";t["TARGET_ELEMENT"]="target_element";t["TARGET_XPATH"]="target_xpath";t["HTTP_URL"]="http.url"})(no||(no={}));const so="0.53.0";const oo="@opentelemetry/instrumentation-user-interaction";const ao="OT_ZONE_CONTEXT";const co="Navigation:";const uo=["click"];function lo(){return false}class fo extends io{version=so;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(t={}){super(oo,so,t);this._eventNames=new Set(t?.eventNames??uo);this._shouldPreventSpanCreation=typeof t?.shouldPreventSpanCreation==="function"?t.shouldPreventSpanCreation:lo}init(){}_checkForTimeout(t,e){const i=this._spansData.get(e);if(i){if(t.source==="setTimeout"){i.hrTimeLastTimeout=ni()}else if(t.source!=="Promise.then"&&t.source!=="setTimeout"){i.hrTimeLastTimeout=undefined}}}_allowEventName(t){return this._eventNames.has(t)}_createSpan(t,e,i){if(!(t instanceof HTMLElement)){return undefined}if(!t.getAttribute){return undefined}if(t.hasAttribute("disabled")){return undefined}if(!this._allowEventName(e)){return undefined}const r=Kr(t,true);try{const n=this.tracer.startSpan(e,{attributes:{[no.EVENT_TYPE]:e,[no.TARGET_ELEMENT]:t.tagName,[no.TARGET_XPATH]:r,[no.HTTP_URL]:window.location.href}},i?pe.setSpan(Zt.active(),i):undefined);if(this._shouldPreventSpanCreation(e,t,n)===true){return undefined}this._spansData.set(n,{taskCount:0});return n}catch(t){this._diag.error("failed to start create new user interaction span",t)}return undefined}_decrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount--;if(e.taskCount===0){this._tryToEndSpan(t,e.hrTimeLastTimeout)}}}_getCurrentSpan(t){const e=t.get(ao);if(e){return pe.getSpan(e)}return e}_incrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount++}}addPatchedListener(t,e,i,r){let n=this._wrappedListeners.get(i);if(!n){n=new Map;this._wrappedListeners.set(i,n)}let s=n.get(e);if(!s){s=new Map;n.set(e,s)}if(s.has(t)){return false}s.set(t,r);return true}removePatchedListener(t,e,i){const r=this._wrappedListeners.get(i);if(!r){return undefined}const n=r.get(e);if(!n){return undefined}const s=n.get(t);if(s){n.delete(t);if(n.size===0){r.delete(e);if(r.size===0){this._wrappedListeners.delete(i)}}}return s}_invokeListener(t,e,i){if(typeof t==="function"){return t.apply(e,i)}else{return t.handleEvent(i[0])}}_patchAddEventListener(){const t=this;return e=>function i(r,n,s){if(!n){return e.call(this,r,n,s)}const o=s&&typeof s==="object"&&s.once;const a=function(...e){let i;const s=e[0];const a=s?.target;if(s){i=t._eventsSpanMap.get(s)}if(o){t.removePatchedListener(this,r,n)}const c=t._createSpan(a,r,i);if(c){if(s){t._eventsSpanMap.set(s,c)}return Zt.with(pe.setSpan(Zt.active(),c),(()=>{const i=t._invokeListener(n,this,e);c.end();return i}))}else{return t._invokeListener(n,this,e)}};if(t.addPatchedListener(this,r,n,a)){return e.call(this,r,a,s)}}}_patchRemoveEventListener(){const t=this;return e=>function i(r,n,s){const o=t.removePatchedListener(this,r,n);if(o){return e.call(this,r,o,s)}else{return e.call(this,r,n,s)}}}_getPatchableEventTargets(){return window.EventTarget?[EventTarget.prototype]:[Node.prototype,Window.prototype]}_patchHistoryApi(){this._unpatchHistoryApi();this._wrap(history,"replaceState",this._patchHistoryMethod());this._wrap(history,"pushState",this._patchHistoryMethod());this._wrap(history,"back",this._patchHistoryMethod());this._wrap(history,"forward",this._patchHistoryMethod());this._wrap(history,"go",this._patchHistoryMethod())}_patchHistoryMethod(){const t=this;return e=>function i(...r){const n=`${location.pathname}${location.hash}${location.search}`;const s=e.apply(this,r);const o=`${location.pathname}${location.hash}${location.search}`;if(n!==o){t._updateInteractionName(o)}return s}}_unpatchHistoryApi(){if(ro(history.replaceState))this._unwrap(history,"replaceState");if(ro(history.pushState))this._unwrap(history,"pushState");if(ro(history.back))this._unwrap(history,"back");if(ro(history.forward))this._unwrap(history,"forward");if(ro(history.go))this._unwrap(history,"go")}_updateInteractionName(t){const e=pe.getSpan(Zt.active());if(e&&typeof e.updateName==="function"){e.updateName(`${co} ${t}`)}}_patchZoneCancelTask(){const t=this;return e=>function i(r){const n=Zone.current;const s=t._getCurrentSpan(n);if(s&&t._shouldCountTask(r,n)){t._decrementTask(s)}return e.call(this,r)}}_patchZoneScheduleTask(){const t=this;return e=>function i(r){const n=Zone.current;const s=t._getCurrentSpan(n);if(s&&t._shouldCountTask(r,n)){t._incrementTask(s);t._checkForTimeout(r,s)}return e.call(this,r)}}_patchZoneRunTask(){const t=this;return e=>function i(r,n,s){const o=Array.isArray(s)&&s[0]instanceof Event?s[0]:undefined;const a=o?.target;let c;const u=this;if(a){c=t._createSpan(a,r.eventName);if(c){t._incrementTask(c);return u.run((()=>{try{return Zt.with(pe.setSpan(Zt.active(),c),(()=>{const t=Zone.current;r._zone=t;return e.call(t,r,n,s)}))}finally{t._decrementTask(c)}}))}}else{c=t._getCurrentSpan(u)}try{return e.call(u,r,n,s)}finally{if(c&&t._shouldCountTask(r,u)){t._decrementTask(c)}}}}_shouldCountTask(t,e){if(t._zone){e=t._zone}if(!e||!t.data||t.data.isPeriodic){return false}const i=this._getCurrentSpan(e);if(!i){return false}if(!this._spansData.get(i)){return false}return t.type==="macroTask"||t.type==="microTask"}_tryToEndSpan(t,e){if(t){const i=this._spansData.get(t);if(i){t.end(e);this._spansData.delete(t)}}}enable(){const t=this._getZoneWithPrototype();this._diag.debug("applying patch to",this.moduleName,this.version,"zone:",!!t);if(t){if(ro(t.prototype.runTask)){this._unwrap(t.prototype,"runTask");this._diag.debug("removing previous patch from method runTask")}if(ro(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask");this._diag.debug("removing previous patch from method scheduleTask")}if(ro(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask");this._diag.debug("removing previous patch from method cancelTask")}this._zonePatched=true;this._wrap(t.prototype,"runTask",this._patchZoneRunTask());this._wrap(t.prototype,"scheduleTask",this._patchZoneScheduleTask());this._wrap(t.prototype,"cancelTask",this._patchZoneCancelTask())}else{this._zonePatched=false;const t=this._getPatchableEventTargets();t.forEach((t=>{if(ro(t.addEventListener)){this._unwrap(t,"addEventListener");this._diag.debug("removing previous patch from method addEventListener")}if(ro(t.removeEventListener)){this._unwrap(t,"removeEventListener");this._diag.debug("removing previous patch from method removeEventListener")}this._wrap(t,"addEventListener",this._patchAddEventListener());this._wrap(t,"removeEventListener",this._patchRemoveEventListener())}))}this._patchHistoryApi()}disable(){const t=this._getZoneWithPrototype();this._diag.debug("removing patch from",this.moduleName,this.version,"zone:",!!t);if(t&&this._zonePatched){if(ro(t.prototype.runTask)){this._unwrap(t.prototype,"runTask")}if(ro(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask")}if(ro(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask")}}else{const t=this._getPatchableEventTargets();t.forEach((t=>{if(ro(t.addEventListener)){this._unwrap(t,"addEventListener")}if(ro(t.removeEventListener)){this._unwrap(t,"removeEventListener")}}))}this._unpatchHistoryApi()}_getZoneWithPrototype(){const t=window;return t.Zone}}var ho={exports:{}};var po=ho.exports;var mo;function bo(){if(mo)return ho.exports;mo=1;(function(t,e){(function(i,r){var n="1.0.41",s="",o="?",a="function",c="undefined",u="object",l="string",f="major",h="model",d="name",p="type",m="vendor",b="version",v="architecture",w="console",g="mobile",y="tablet",x="smarttv",k="wearable",S="embedded",E=500;var _="Amazon",A="Apple",T="ASUS",M="BlackBerry",C="Browser",O="Chrome",P="Edge",I="Firefox",L="Google",D="Honor",R="Huawei",N="Lenovo",j="LG",U="Microsoft",z="Motorola",$="Nvidia",B="OnePlus",F="Opera",G="OPPO",V="Samsung",q="Sharp",H="Sony",J="Xiaomi",K="Zebra",Z="Facebook",W="Chromium OS",X="Mac OS",Y=" Browser";var Q=function(t,e){var i={};for(var r in t){if(e[r]&&e[r].length%2===0){i[r]=e[r].concat(t[r])}else{i[r]=t[r]}}return i},tt=function(t){var e={};for(var i=0;i<t.length;i++){e[t[i].toUpperCase()]=t[i]}return e},et=function(t,e){return typeof t===l?it(e).indexOf(it(t))!==-1:false},it=function(t){return t.toLowerCase()},rt=function(t){return typeof t===l?t.replace(/[^\d\.]/g,s).split(".")[0]:r},nt=function(t,e){if(typeof t===l){t=t.replace(/^\s\s*/,s);return typeof e===c?t:t.substring(0,E)}};var st=function(t,e){var i=0,n,s,o,c,l,f;while(i<e.length&&!l){var h=e[i],d=e[i+1];n=s=0;while(n<h.length&&!l){if(!h[n]){break}l=h[n++].exec(t);if(!!l){for(o=0;o<d.length;o++){f=l[++s];c=d[o];if(typeof c===u&&c.length>0){if(c.length===2){if(typeof c[1]==a){this[c[0]]=c[1].call(this,f)}else{this[c[0]]=c[1]}}else if(c.length===3){if(typeof c[1]===a&&!(c[1].exec&&c[1].test)){this[c[0]]=f?c[1].call(this,f,c[2]):r}else{this[c[0]]=f?f.replace(c[1],c[2]):r}}else if(c.length===4){this[c[0]]=f?c[3].call(this,f.replace(c[1],c[2])):r}}else{this[c]=f?f:r}}}}i+=2}},ot=function(t,e){for(var i in e){if(typeof e[i]===u&&e[i].length>0){for(var n=0;n<e[i].length;n++){if(et(e[i][n],t)){return i===o?r:i}}}else if(et(e[i],t)){return i===o?r:i}}return e.hasOwnProperty("*")?e["*"]:t};var at={"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},ct={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"};var ut={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[b,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[b,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,b],[/opios[\/ ]+([\w\.]+)/i],[b,[d,F+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[b,[d,F+" GX"]],[/\bopr\/([\w\.]+)/i],[b,[d,F]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[b,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[b,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,b],[/quark(?:pc)?\/([-\w\.]+)/i],[b,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[b,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[b,[d,"UC"+C]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[b,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[b,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[b,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[b,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[b,[d,"Smart Lenovo "+C]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+C],b],[/\bfocus\/([\w\.]+)/i],[b,[d,I+" Focus"]],[/\bopt\/([\w\.]+)/i],[b,[d,F+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[b,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[b,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[b,[d,F+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[b,[d,"MIUI"+Y]],[/fxios\/([\w\.-]+)/i],[b,[d,I]],[/\bqihoobrowser\/?([\w\.]*)/i],[b,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],b],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+Y],b],[/samsungbrowser\/([\w\.]+)/i],[b,[d,V+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[b,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],b],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,b],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[b,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,Z],b],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,b],[/\bgsa\/([\w\.]+) .*safari\//i],[b,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[b,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[b,[d,O+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,O+" WebView"],b],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[b,[d,"Android "+C]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,b],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[b,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[b,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[b,ot,at]],[/(webkit|khtml)\/([\w\.]+)/i],[d,b],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],b],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,b],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[b,[d,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],[h,[m,V],[p,y]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[h,[m,V],[p,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[h,[m,A],[p,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[h,[m,A],[p,y]],[/(macintosh);/i],[h,[m,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[h,[m,q],[p,g]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[h,[m,D],[p,y]],[/honor([-\w ]+)[;\)]/i],[h,[m,D],[p,g]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[h,[m,R],[p,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[h,[m,R],[p,g]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[h,/_/g," "],[m,J],[p,y]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[h,/_/g," "],[m,J],[p,g]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[h,[m,G],[p,g]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[h,[m,ot,{OnePlus:["304","403","203"],"*":G}],[p,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[h,[m,"Vivo"],[p,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[h,[m,"Realme"],[p,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[h,[m,z],[p,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[h,[m,z],[p,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[h,[m,j],[p,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[h,[m,j],[p,g]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[h,[m,N],[p,y]],[/(nokia) (t[12][01])/i],[m,h,[p,y]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[h,/_/g," "],[p,g],[m,"Nokia"]],[/(pixel (c|tablet))\b/i],[h,[m,L],[p,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[h,[m,L],[p,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[h,[m,H],[p,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[h,"Xperia Tablet"],[m,H],[p,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[h,[m,B],[p,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[h,[m,_],[p,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[h,/(.+)/g,"Fire Phone $1"],[m,_],[p,g]],[/(playbook);[-\w\),; ]+(rim)/i],[h,m,[p,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[h,[m,M],[p,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[h,[m,T],[p,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[h,[m,T],[p,g]],[/(nexus 9)/i],[h,[m,"HTC"],[p,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[m,[h,/_/g," "],[p,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[h,[m,"TCL"],[p,y]],[/(itel) ((\w+))/i],[[m,it],h,[p,ot,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[h,[m,"Acer"],[p,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[h,[m,"Meizu"],[p,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[h,[m,"Ulefone"],[p,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[h,[m,"Energizer"],[p,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[h,[m,"Cat"],[p,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[h,[m,"Smartfren"],[p,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[h,[m,"Nothing"],[p,g]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[h,[m,"Archos"],[p,y]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[h,[m,"Archos"],[p,g]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[m,h,[p,y]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[m,h,[p,g]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[m,h,[p,y]],[/(surface duo)/i],[h,[m,U],[p,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[h,[m,"Fairphone"],[p,g]],[/(u304aa)/i],[h,[m,"AT&T"],[p,g]],[/\bsie-(\w*)/i],[h,[m,"Siemens"],[p,g]],[/\b(rct\w+) b/i],[h,[m,"RCA"],[p,y]],[/\b(venue[\d ]{2,7}) b/i],[h,[m,"Dell"],[p,y]],[/\b(q(?:mv|ta)\w+) b/i],[h,[m,"Verizon"],[p,y]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[h,[m,"Barnes & Noble"],[p,y]],[/\b(tm\d{3}\w+) b/i],[h,[m,"NuVision"],[p,y]],[/\b(k88) b/i],[h,[m,"ZTE"],[p,y]],[/\b(nx\d{3}j) b/i],[h,[m,"ZTE"],[p,g]],[/\b(gen\d{3}) b.+49h/i],[h,[m,"Swiss"],[p,g]],[/\b(zur\d{3}) b/i],[h,[m,"Swiss"],[p,y]],[/\b((zeki)?tb.*\b) b/i],[h,[m,"Zeki"],[p,y]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[m,"Dragon Touch"],h,[p,y]],[/\b(ns-?\w{0,9}) b/i],[h,[m,"Insignia"],[p,y]],[/\b((nxa|next)-?\w{0,9}) b/i],[h,[m,"NextBook"],[p,y]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[m,"Voice"],h,[p,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[m,"LvTel"],h,[p,g]],[/\b(ph-1) /i],[h,[m,"Essential"],[p,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[h,[m,"Envizen"],[p,y]],[/\b(trio[-\w\. ]+) b/i],[h,[m,"MachSpeed"],[p,y]],[/\btu_(1491) b/i],[h,[m,"Rotor"],[p,y]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[h,[m,$],[p,y]],[/(sprint) (\w+)/i],[m,h,[p,g]],[/(kin\.[onetw]{3})/i],[[h,/\./g," "],[m,U],[p,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[h,[m,K],[p,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[h,[m,K],[p,g]],[/smart-tv.+(samsung)/i],[m,[p,x]],[/hbbtv.+maple;(\d+)/i],[[h,/^/,"SmartTV"],[m,V],[p,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[m,j],[p,x]],[/(apple) ?tv/i],[m,[h,A+" TV"],[p,x]],[/crkey/i],[[h,O+"cast"],[m,L],[p,x]],[/droid.+aft(\w+)( bui|\))/i],[h,[m,_],[p,x]],[/(shield \w+ tv)/i],[h,[m,$],[p,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[h,[m,q],[p,x]],[/(bravia[\w ]+)( bui|\))/i],[h,[m,H],[p,x]],[/(mi(tv|box)-?\w+) bui/i],[h,[m,J],[p,x]],[/Hbbtv.*(technisat) (.*);/i],[m,h,[p,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[m,nt],[h,nt],[p,x]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[h,[p,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[p,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[m,h,[p,w]],[/droid.+; (shield)( bui|\))/i],[h,[m,$],[p,w]],[/(playstation \w+)/i],[h,[m,H],[p,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[h,[m,U],[p,w]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[h,[m,V],[p,k]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[m,h,[p,k]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[h,[m,G],[p,k]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[h,[m,A],[p,k]],[/(opwwe\d{3})/i],[h,[m,B],[p,k]],[/(moto 360)/i],[h,[m,z],[p,k]],[/(smartwatch 3)/i],[h,[m,H],[p,k]],[/(g watch r)/i],[h,[m,j],[p,k]],[/droid.+; (wt63?0{2,3})\)/i],[h,[m,K],[p,k]],[/droid.+; (glass) \d/i],[h,[m,L],[p,k]],[/(pico) (4|neo3(?: link|pro)?)/i],[m,h,[p,k]],[/; (quest( \d| pro)?)/i],[h,[m,Z],[p,k]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[m,[p,S]],[/(aeobc)\b/i],[h,[m,_],[p,S]],[/(homepod).+mac os/i],[h,[m,A],[p,S]],[/windows iot/i],[[p,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[h,[p,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[h,[p,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[p,y]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[p,g]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[h,[m,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[b,[d,P+"HTML"]],[/(arkweb)\/([\w\.]+)/i],[d,b],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[b,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,b],[/ladybird\//i],[[d,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[b,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,b],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[d,[b,ot,ct]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[b,ot,ct],[d,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[b,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,X],[b,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[b,d],[/(ubuntu) ([\w\.]+) like android/i],[[d,/(.+)/,"$1 Touch"],b],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[d,b],[/\(bb(10);/i],[b,[d,M]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[b,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[b,[d,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,O+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,W],b],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,b],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],b],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,b]]};var lt=function(t,e){if(typeof t===u){e=t;t=r}if(!(this instanceof lt)){return new lt(t,e).getResult()}var n=typeof i!==c&&i.navigator?i.navigator:r;var o=t||(n&&n.userAgent?n.userAgent:s);var w=n&&n.userAgentData?n.userAgentData:r;var x=e?Q(ut,e):ut;var k=n&&n.userAgent==o;this.getBrowser=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.browser);t[f]=rt(t[b]);if(k&&n&&n.brave&&typeof n.brave.isBrave==a){t[d]="Brave"}return t};this.getCPU=function(){var t={};t[v]=r;st.call(t,o,x.cpu);return t};this.getDevice=function(){var t={};t[m]=r;t[h]=r;t[p]=r;st.call(t,o,x.device);if(k&&!t[p]&&w&&w.mobile){t[p]=g}if(k&&t[h]=="Macintosh"&&n&&typeof n.standalone!==c&&n.maxTouchPoints&&n.maxTouchPoints>2){t[h]="iPad";t[p]=y}return t};this.getEngine=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.engine);return t};this.getOS=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.os);if(k&&!t[d]&&w&&w.platform&&w.platform!="Unknown"){t[d]=w.platform.replace(/chrome os/i,W).replace(/macos/i,X)}return t};this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}};this.getUA=function(){return o};this.setUA=function(t){o=typeof t===l&&t.length>E?nt(t,E):t;return this};this.setUA(o);return this};lt.VERSION=n;lt.BROWSER=tt([d,b,f]);lt.CPU=tt([v]);lt.DEVICE=tt([h,m,p,w,g,x,y,k,S]);lt.ENGINE=lt.OS=tt([d,b]);{if(t.exports){e=t.exports=lt}e.UAParser=lt}var ft=typeof i!==c&&(i.jQuery||i.Zepto);if(ft&&!ft.ua){var ht=new lt;ft.ua=ht.getResult();ft.ua.get=function(){return ht.getUA()};ft.ua.set=function(t){ht.setUA(t);var e=ht.getResult();for(var i in e){ft.ua[i]=e[i]}}}})(typeof window==="object"?window:po)})(ho,ho.exports);return ho.exports}var vo=bo();var wo=fn(vo);const go="service.name";const yo="service.version";const xo="eAzROSTiqNd3i+M9Jw6q5Tld0jarZc617sJB//pvb5c=";let ko=false;function So(){if(ko){return}ko=true;const t=window.XMLHttpRequest;if(!t){console.error("[TracingService] XMLHttpRequest not available");return}window.XMLHttpRequest=function(){const e=new t;const i=e.open;const r=e.send;let n=false;e.open=function(t,e,...r){const s=typeof e==="string"?e:e.toString();n=s.includes("collector.jaak.ai");return i.apply(this,[t,e,...r])};e.send=function(...t){if(n){this.setRequestHeader("Authorization",`Bearer ${xo}`)}return r.apply(this,t)};return e};for(const e in t){if(t.hasOwnProperty(e)){window.XMLHttpRequest[e]=t[e]}}const e=window.fetch;window.fetch=function(t,i){const r=typeof t==="string"?t:t instanceof URL?t.href:t.url;if(r.includes("collector.jaak.ai")){const t=new Headers(i?.headers||{});t.set("Authorization",`Bearer ${xo}`);i={...i,headers:t}}return e.call(this,t,i)};navigator.sendBeacon=function(){return false}}class Eo{provider=null;tracer=null;sessionTraceId=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;enableAutoInstrumentation;spanProcessor=null;parser;geoCache=null;geoCacheTimestamp=0;GEO_CACHE_DURATION_MS=60*60*1e3;constructor(t={}){this.collectorUrl=t.collectorUrl||"https://collector.jaak.ai/v1/traces";this.serviceName=t.serviceName||"jaak-stamps-webcomponent";this.serviceVersion=t.serviceVersion||"2.1.0";this.debug=t.debug||false;this.customerId=t.customerId;this.tenantId=t.tenantId;this.environment=t.environment||"production";this.enableAutoInstrumentation=t.enableAutoInstrumentation??false;this.parser=new wo}initialize(){try{So();const t=new As({url:this.collectorUrl,headers:{"Content-Type":"application/json",Authorization:`Bearer ${xo}`},useSendBeacon:false});const e={export:(e,i)=>{if(this.debug){console.log("[TracingService] 📤 Exporting",e.length,"spans to collector")}t.export(e,(t=>{if(t.code!==0){console.error("[TracingService] ❌ Export failed:",t)}i(t)}))},shutdown:async()=>t.shutdown(),forceFlush:async()=>t.forceFlush()};this.spanProcessor=new Dr(e,{maxQueueSize:100,maxExportBatchSize:10,scheduledDelayMillis:5e3,exportTimeoutMillis:3e4});this.provider=new Jr({spanProcessors:[this.spanProcessor]});const i=new Cs;const r=new Di;this.provider.register({contextManager:i,propagator:r});this.tracer=pe.getTracer(this.serviceName,this.serviceVersion);if(this.enableAutoInstrumentation){this.initializeAutoInstrumentation()}}catch(t){console.error("[TracingService] Failed to initialize:",t)}}initializeAutoInstrumentation(){try{Ks({instrumentations:[new fo({eventNames:["click","submit"],shouldPreventSpanCreation:(t,e)=>e.tagName==="BUTTON"||e.tagName==="A"||e.tagName==="FORM"})]})}catch(t){console.error("[TracingService] Failed to initialize auto-instrumentation:",t)}}getDeviceInfo(){const t=this.parser.getResult();return{type:t.device.type||"desktop",vendor:t.device.vendor||"unknown",model:t.device.model||"unknown"}}getBrowserInfo(){const t=this.parser.getResult();return{name:t.browser.name||"unknown",version:t.browser.version||"unknown",major:t.browser.major||"unknown"}}getOSInfo(){const t=this.parser.getResult();return{name:t.os.name||"unknown",version:t.os.version||"unknown"}}setSessionTraceId(t){if(t&&t.length===32&&/^[a-f0-9]{32}$/i.test(t)){this.sessionTraceId=t.toLowerCase();if(this.debug){console.log("[TracingService] Session trace ID set:",this.sessionTraceId)}}else if(t){console.warn("[TracingService] Invalid trace ID format. Must be 32 hex characters:",t)}}getSessionTraceId(){return this.sessionTraceId}generateSpanId(){const t=new Uint8Array(8);crypto.getRandomValues(t);return Array.from(t).map((t=>t.toString(16).padStart(2,"0"))).join("")}async getGeoLocation(){const t=Date.now();if(this.geoCache&&t-this.geoCacheTimestamp<this.GEO_CACHE_DURATION_MS){return this.geoCache}try{const e=await fetch("https://ipapi.co/json/",{signal:AbortSignal.timeout(5e3)});if(!e.ok){return{}}const i=await e.json();this.geoCache={country:i.country_name,region:i.region,city:i.city,latitude:i.latitude,longitude:i.longitude};this.geoCacheTimestamp=t;return this.geoCache}catch(t){console.warn("[TracingService] Failed to fetch geo location:",t);return this.geoCache||{}}}startSpan(t,e){if(!this.tracer){console.warn("[TracingService] Tracer not initialized, returning no-op span");return pe.getTracer("noop").startSpan("noop")}try{let i=Zt.active();if(this.sessionTraceId&&!pe.getSpan(i)){const t={traceId:this.sessionTraceId,spanId:this.generateSpanId(),traceFlags:yt.SAMPLED,isRemote:true};const e=pe.wrapSpanContext(t);i=pe.setSpan(i,e)}const r=this.getDeviceInfo();const n=this.getBrowserInfo();const s=this.getOSInfo();const o=this.tracer.startSpan(t,{attributes:{...e,component:this.serviceName.includes("stamps")?"jaak-stamps":"jaak-visage",[go]:this.serviceName,[yo]:this.serviceVersion,"deployment.environment":this.environment,"trace.id":this.sessionTraceId||"auto-generated","device.type":r.type,"device.vendor":r.vendor,"device.model":r.model,"browser.name":n.name,"browser.version":n.version,"browser.major":n.major,"os.name":s.name,"os.version":s.version,user_agent:navigator.userAgent,...this.customerId&&{"customer.id":this.customerId},...this.tenantId&&{"tenant.id":this.tenantId}}},i);this.getGeoLocation().then((t=>{if(t.country)o.setAttribute("geo.country",t.country);if(t.region)o.setAttribute("geo.region",t.region);if(t.city)o.setAttribute("geo.city",t.city)})).catch((t=>console.warn("Failed to add geo attributes:",t)));if(this.debug){console.log(`[TracingService] Started span: ${t}`,{traceId:o.spanContext().traceId,spanId:o.spanContext().spanId,sessionTraceId:this.sessionTraceId,attributes:e})}return o}catch(t){console.error("[TracingService] Failed to start span:",t);return pe.getTracer("noop").startSpan("noop")}}endSpan(t){if(!t){console.warn("[TracingService] endSpan called with null/undefined span");return}try{t.end()}catch(t){console.error("[TracingService] ❌ Failed to end span:",t)}}addSpanEvent(t,e,i){if(!t)return;try{t.addEvent(e,i);if(this.debug){console.log(`[TracingService] Added event to span: ${e}`,i)}}catch(t){console.error("[TracingService] Failed to add span event:",t)}}recordException(t,e){if(!t)return;try{t.recordException(e);t.setStatus({code:Kt.ERROR,message:e.message})}catch(t){console.error("[TracingService] Failed to record exception:",t)}}setSpanAttribute(t,e,i){if(!t)return;try{t.setAttribute(e,i);if(this.debug){console.log(`[TracingService] Set attribute: ${e} = ${i}`)}}catch(t){console.error("[TracingService] Failed to set span attribute:",t)}}async trace(t,e,i){const r=this.startSpan(t,i);try{const t=await Zt.with(pe.setSpan(Zt.active(),r),(async()=>await e()));r.setStatus({code:Kt.OK});return t}catch(t){this.recordException(r,t);throw t}finally{this.endSpan(r)}}async traceAsync(t,e,i){return this.trace(t,e,i)}async flush(){try{if(!this.spanProcessor){console.warn("[TracingService] No span processor available to flush");return}await this.spanProcessor.forceFlush()}catch(t){console.error("[TracingService] ❌ Failed to flush spans:",t);throw t}}async cleanup(){try{if(this.spanProcessor){await this.spanProcessor.forceFlush();await this.spanProcessor.shutdown()}if(this.provider){await this.provider.shutdown()}}catch(t){console.error("[TracingService] Failed to cleanup:",t)}}getCurrentTraceId(){try{const t=pe.getSpan(Zt.active());return t?.spanContext().traceId}catch{return undefined}}getCurrentSpanId(){try{const t=pe.getSpan(Zt.active());return t?.spanContext().spanId}catch{return undefined}}}var _o;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(_o||(_o={}));var Ao;(function(t){t["COUNTER"]="COUNTER";t["GAUGE"]="GAUGE";t["HISTOGRAM"]="HISTOGRAM";t["UP_DOWN_COUNTER"]="UP_DOWN_COUNTER";t["OBSERVABLE_COUNTER"]="OBSERVABLE_COUNTER";t["OBSERVABLE_GAUGE"]="OBSERVABLE_GAUGE";t["OBSERVABLE_UP_DOWN_COUNTER"]="OBSERVABLE_UP_DOWN_COUNTER"})(Ao||(Ao={}));var To;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(To||(To={}));function Mo(t){let e=Object.keys(t);if(e.length===0)return"";e=e.sort();return JSON.stringify(e.map((e=>[e,t[e]])))}function Co(t){return`${t.name}:${t.version??""}:${t.schemaUrl??""}`}class Oo extends Error{constructor(t){super(t);Object.setPrototypeOf(this,Oo.prototype)}}function Po(t,e){let i;const r=new Promise((function t(r,n){i=setTimeout((function t(){n(new Oo("Operation timed out."))}),e)}));return Promise.race([t,r]).then((t=>{clearTimeout(i);return t}),(t=>{clearTimeout(i);throw t}))}function Io(t,e){if(t.size!==e.size){return false}for(const i of t){if(!e.has(i)){return false}}return true}function Lo(t,e){let i=0;let r=t.length-1;let n=t.length;while(r>=i){const s=i+Math.trunc((r-i)/2);if(t[s]<e){i=s+1}else{n=s;r=s-1}}return n}function Do(t,e){return t.toLowerCase()===e.toLowerCase()}var Ro;(function(t){t[t["DROP"]=0]="DROP";t[t["SUM"]=1]="SUM";t[t["LAST_VALUE"]=2]="LAST_VALUE";t[t["HISTOGRAM"]=3]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=4]="EXPONENTIAL_HISTOGRAM"})(Ro||(Ro={}));class No{kind=Ro.DROP;createAccumulation(){return undefined}merge(t,e){return undefined}diff(t,e){return undefined}toMetricData(t,e,i,r){return undefined}}function jo(t){const e=t.map((()=>0));e.push(0);return{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:false,min:Infinity,max:-Infinity}}class Uo{startTime;_boundaries;_recordMinMax;_current;constructor(t,e,i=true,r=jo(e)){this.startTime=t;this._boundaries=e;this._recordMinMax=i;this._current=r}record(t){if(Number.isNaN(t)){return}this._current.count+=1;this._current.sum+=t;if(this._recordMinMax){this._current.min=Math.min(t,this._current.min);this._current.max=Math.max(t,this._current.max);this._current.hasMinMax=true}const e=Lo(this._boundaries,t);this._current.buckets.counts[e]+=1}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class zo{kind=Ro.HISTOGRAM;_boundaries;_recordMinMax;constructor(t,e){this._boundaries=t;this._recordMinMax=e}createAccumulation(t){return new Uo(t,this._boundaries,this._recordMinMax)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();const n=i.buckets.counts;const s=r.buckets.counts;const o=new Array(n.length);for(let t=0;t<n.length;t++){o[t]=n[t]+s[t]}let a=Infinity;let c=-Infinity;if(this._recordMinMax){if(i.hasMinMax&&r.hasMinMax){a=Math.min(i.min,r.min);c=Math.max(i.max,r.max)}else if(i.hasMinMax){a=i.min;c=i.max}else if(r.hasMinMax){a=r.min;c=r.max}}return new Uo(t.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:i.count+r.count,sum:i.sum+r.sum,hasMinMax:this._recordMinMax&&(i.hasMinMax||r.hasMinMax),min:a,max:c})}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();const n=i.buckets.counts;const s=r.buckets.counts;const o=new Array(n.length);for(let t=0;t<n.length;t++){o[t]=s[t]-n[t]}return new Uo(e.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:r.count-i.count,sum:r.sum-i.sum,hasMinMax:false,min:Infinity,max:-Infinity})}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:To.HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===Ao.GAUGE||t.type===Ao.UP_DOWN_COUNTER||t.type===Ao.OBSERVABLE_GAUGE||t.type===Ao.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:r,value:{min:n.hasMinMax?n.min:undefined,max:n.hasMinMax?n.max:undefined,sum:!s?n.sum:undefined,buckets:n.buckets,count:n.count}}}))}}}class $o{backing;indexBase;indexStart;indexEnd;constructor(t=new Bo,e=0,i=0,r=0){this.backing=t;this.indexBase=e;this.indexStart=i;this.indexEnd=r}get offset(){return this.indexStart}get length(){if(this.backing.length===0){return 0}if(this.indexEnd===this.indexStart&&this.at(0)===0){return 0}return this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},((t,e)=>this.at(e)))}at(t){const e=this.indexBase-this.indexStart;if(t<e){t+=this.backing.length}t-=e;return this.backing.countAt(t)}incrementBucket(t,e){this.backing.increment(t,e)}decrementBucket(t,e){this.backing.decrement(t,e)}trim(){for(let t=0;t<this.length;t++){if(this.at(t)!==0){this.indexStart+=t;break}else if(t===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}}for(let t=this.length-1;t>=0;t--){if(this.at(t)!==0){this.indexEnd-=this.length-t-1;break}}this._rotate()}downscale(t){this._rotate();const e=1+this.indexEnd-this.indexStart;const i=1<<t;let r=0;let n=0;for(let t=this.indexStart;t<=this.indexEnd;){let s=t%i;if(s<0){s+=i}for(let o=s;o<i&&r<e;o++){this._relocateBucket(n,r);r++;t++}n++}this.indexStart>>=t;this.indexEnd>>=t;this.indexBase=this.indexStart}clone(){return new $o(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const t=this.indexBase-this.indexStart;if(t===0){return}else if(t>0){this.backing.reverse(0,this.backing.length);this.backing.reverse(0,t);this.backing.reverse(t,this.backing.length)}else{this.backing.reverse(0,this.backing.length);this.backing.reverse(0,this.backing.length+t)}this.indexBase=this.indexStart}_relocateBucket(t,e){if(t===e){return}this.incrementBucket(t,this.backing.emptyBucket(e))}}class Bo{_counts;constructor(t=[0]){this._counts=t}get length(){return this._counts.length}countAt(t){return this._counts[t]}growTo(t,e,i){const r=new Array(t).fill(0);r.splice(i,this._counts.length-e,...this._counts.slice(e));r.splice(0,e,...this._counts.slice(0,e));this._counts=r}reverse(t,e){const i=Math.floor((t+e)/2)-t;for(let r=0;r<i;r++){const i=this._counts[t+r];this._counts[t+r]=this._counts[e-r-1];this._counts[e-r-1]=i}}emptyBucket(t){const e=this._counts[t];this._counts[t]=0;return e}increment(t,e){this._counts[t]+=e}decrement(t,e){if(this._counts[t]>=e){this._counts[t]-=e}else{this._counts[t]=0}}clone(){return new Bo([...this._counts])}}const Fo=52;const Go=2146435072;const Vo=1048575;const qo=1023;const Ho=-1023+1;const Jo=qo;const Ko=Math.pow(2,-1022);function Zo(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=(i&Go)>>20;return r-qo}function Wo(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=e.getUint32(4);const n=(i&Vo)*Math.pow(2,32);return n+r}function Xo(t,e){if(t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)){return t}return t*Math.pow(2,e)}function Yo(t){t--;t|=t>>1;t|=t>>2;t|=t>>4;t|=t>>8;t|=t>>16;t++;return t}class Qo extends Error{}class ta{_shift;constructor(t){this._shift=-t}mapToIndex(t){if(t<Ko){return this._minNormalLowerBoundaryIndex()}const e=Zo(t);const i=this._rightShift(Wo(t)-1,Fo);return e+i>>this._shift}lowerBoundary(t){const e=this._minNormalLowerBoundaryIndex();if(t<e){throw new Qo(`underflow: ${t} is < minimum lower boundary: ${e}`)}const i=this._maxNormalLowerBoundaryIndex();if(t>i){throw new Qo(`overflow: ${t} is > maximum lower boundary: ${i}`)}return Xo(1,t<<this._shift)}get scale(){if(this._shift===0){return 0}return-this._shift}_minNormalLowerBoundaryIndex(){let t=Ho>>this._shift;if(this._shift<2){t--}return t}_maxNormalLowerBoundaryIndex(){return Jo>>this._shift}_rightShift(t,e){return Math.floor(t*Math.pow(2,-e))}}class ea{_scale;_scaleFactor;_inverseFactor;constructor(t){this._scale=t;this._scaleFactor=Xo(Math.LOG2E,t);this._inverseFactor=Xo(Math.LN2,-t)}mapToIndex(t){if(t<=Ko){return this._minNormalLowerBoundaryIndex()-1}if(Wo(t)===0){const e=Zo(t);return(e<<this._scale)-1}const e=Math.floor(Math.log(t)*this._scaleFactor);const i=this._maxNormalLowerBoundaryIndex();if(e>=i){return i}return e}lowerBoundary(t){const e=this._maxNormalLowerBoundaryIndex();if(t>=e){if(t===e){return 2*Math.exp((t-(1<<this._scale))/this._scaleFactor)}throw new Qo(`overflow: ${t} is > maximum lower boundary: ${e}`)}const i=this._minNormalLowerBoundaryIndex();if(t<=i){if(t===i){return Ko}else if(t===i-1){return Math.exp((t+(1<<this._scale))/this._scaleFactor)/2}throw new Qo(`overflow: ${t} is < minimum lower boundary: ${i}`)}return Math.exp(t*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Ho<<this._scale}_maxNormalLowerBoundaryIndex(){return(Jo+1<<this._scale)-1}}const ia=-10;const ra=20;const na=Array.from({length:31},((t,e)=>{if(e>10){return new ea(e-10)}return new ta(e-10)}));function sa(t){if(t>ra||t<ia){throw new Qo(`expected scale >= ${ia} && <= ${ra}, got: ${t}`)}return na[t+10]}class oa{static combine(t,e){return new oa(Math.min(t.low,e.low),Math.max(t.high,e.high))}low;high;constructor(t,e){this.low=t;this.high=e}}const aa=20;const ca=160;const ua=2;class la{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(t,e=ca,i=true,r=0,n=0,s=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new $o,u=new $o,l=sa(aa)){this.startTime=t;this._maxSize=e;this._recordMinMax=i;this._sum=r;this._count=n;this._zeroCount=s;this._min=o;this._max=a;this._positive=c;this._negative=u;this._mapping=l;if(this._maxSize<ua){Wt.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${ua}`);this._maxSize=ua}}record(t){this.updateByIncrement(t,1)}setStartTime(t){this.startTime=t}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){if(this._count===this._zeroCount){return 0}return this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(t,e){if(Number.isNaN(t)){return}if(t>this._max){this._max=t}if(t<this._min){this._min=t}this._count+=e;if(t===0){this._zeroCount+=e;return}this._sum+=t*e;if(t>0){this._updateBuckets(this._positive,t,e)}else{this._updateBuckets(this._negative,-t,e)}}merge(t){if(this._count===0){this._min=t.min;this._max=t.max}else if(t.count!==0){if(t.min<this.min){this._min=t.min}if(t.max>this.max){this._max=t.max}}this.startTime=t.startTime;this._sum+=t.sum;this._count+=t.count;this._zeroCount+=t.zeroCount;const e=this._minScale(t);this._downscale(this.scale-e);this._mergeBuckets(this.positive,t,t.positive,e);this._mergeBuckets(this.negative,t,t.negative,e)}diff(t){this._min=Infinity;this._max=-Infinity;this._sum-=t.sum;this._count-=t.count;this._zeroCount-=t.zeroCount;const e=this._minScale(t);this._downscale(this.scale-e);this._diffBuckets(this.positive,t,t.positive,e);this._diffBuckets(this.negative,t,t.negative,e)}clone(){return new la(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(t,e,i){let r=this._mapping.mapToIndex(e);let n=false;let s=0;let o=0;if(t.length===0){t.indexStart=r;t.indexEnd=t.indexStart;t.indexBase=t.indexStart}else if(r<t.indexStart&&t.indexEnd-r>=this._maxSize){n=true;o=r;s=t.indexEnd}else if(r>t.indexEnd&&r-t.indexStart>=this._maxSize){n=true;o=t.indexStart;s=r}if(n){const t=this._changeScale(s,o);this._downscale(t);r=this._mapping.mapToIndex(e)}this._incrementIndexBy(t,r,i)}_incrementIndexBy(t,e,i){if(i===0){return}if(t.length===0){t.indexStart=t.indexEnd=t.indexBase=e}if(e<t.indexStart){const i=t.indexEnd-e;if(i>=t.backing.length){this._grow(t,i+1)}t.indexStart=e}else if(e>t.indexEnd){const i=e-t.indexStart;if(i>=t.backing.length){this._grow(t,i+1)}t.indexEnd=e}let r=e-t.indexBase;if(r<0){r+=t.backing.length}t.incrementBucket(r,i)}_grow(t,e){const i=t.backing.length;const r=t.indexBase-t.indexStart;const n=i-r;let s=Yo(e);if(s>this._maxSize){s=this._maxSize}const o=s-r;t.backing.growTo(s,n,o)}_changeScale(t,e){let i=0;while(t-e>=this._maxSize){t>>=1;e>>=1;i++}return i}_downscale(t){if(t===0){return}if(t<0){throw new Error(`impossible change of scale: ${this.scale}`)}const e=this._mapping.scale-t;this._positive.downscale(t);this._negative.downscale(t);this._mapping=sa(e)}_minScale(t){const e=Math.min(this.scale,t.scale);const i=oa.combine(this._highLowAtScale(this.positive,this.scale,e),this._highLowAtScale(t.positive,t.scale,e));const r=oa.combine(this._highLowAtScale(this.negative,this.scale,e),this._highLowAtScale(t.negative,t.scale,e));return Math.min(e-this._changeScale(i.high,i.low),e-this._changeScale(r.high,r.low))}_highLowAtScale(t,e,i){if(t.length===0){return new oa(0,-1)}const r=e-i;return new oa(t.indexStart>>r,t.indexEnd>>r)}_mergeBuckets(t,e,i,r){const n=i.offset;const s=e.scale-r;for(let e=0;e<i.length;e++){this._incrementIndexBy(t,n+e>>s,i.at(e))}}_diffBuckets(t,e,i,r){const n=i.offset;const s=e.scale-r;for(let e=0;e<i.length;e++){const r=n+e>>s;let o=r-t.indexBase;if(o<0){o+=t.backing.length}t.decrementBucket(o,i.at(e))}t.trim()}}class fa{kind=Ro.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(t,e){this._maxSize=t;this._recordMinMax=e}createAccumulation(t){return new la(t,this._maxSize,this._recordMinMax)}merge(t,e){const i=e.clone();i.merge(t);return i}diff(t,e){const i=e.clone();i.diff(t);return i}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:To.EXPONENTIAL_HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===Ao.GAUGE||t.type===Ao.UP_DOWN_COUNTER||t.type===Ao.OBSERVABLE_GAUGE||t.type===Ao.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:r,value:{min:n.hasMinMax?n.min:undefined,max:n.hasMinMax?n.max:undefined,sum:!s?n.sum:undefined,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},count:n.count,scale:n.scale,zeroCount:n.zeroCount}}}))}}}const ha=$("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function da(t){return t.setValue(ha,true)}function pa(){return t=>{Wt.error(ma(t))}}function ma(t){if(typeof t==="string"){return t}else{return JSON.stringify(ba(t))}}function ba(t){const e={};let i=t;while(i!==null){Object.getOwnPropertyNames(i).forEach((t=>{if(e[t])return;const r=i[t];if(r){e[t]=String(r)}}));i=Object.getPrototypeOf(i)}return e}let va=pa();function wa(t){try{va(t)}catch{}}const ga="2.6.0";const ya="process.runtime.name";const xa={[Ke]:"opentelemetry",[ya]:"browser",[He]:Je,[Ze]:ga};const ka=6;const Sa=Math.pow(10,ka);function Ea(t){const e=t/1e3;const i=Math.trunc(e);const r=Math.round(t%1e3*Sa);return[i,r]}function _a(t){return t[0]*1e6+t[1]/1e3}var Aa;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(Aa||(Aa={}));function Ta(t,e){return new Promise((i=>{Zt.with(da(Zt.active()),(()=>{t.export(e,i)}))}))}const Ma={_export:Ta};class Ca{startTime;_current;sampleTime;constructor(t,e=0,i=[0,0]){this.startTime=t;this._current=e;this.sampleTime=i}record(t){this._current=t;this.sampleTime=Ea(Date.now())}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Oa{kind=Ro.LAST_VALUE;createAccumulation(t){return new Ca(t)}merge(t,e){const i=_a(e.sampleTime)>=_a(t.sampleTime)?e:t;return new Ca(t.startTime,i.toPointValue(),i.sampleTime)}diff(t,e){const i=_a(e.sampleTime)>=_a(t.sampleTime)?e:t;return new Ca(e.startTime,i.toPointValue(),i.sampleTime)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:To.GAUGE,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()})))}}}class Pa{startTime;monotonic;_current;reset;constructor(t,e,i=0,r=false){this.startTime=t;this.monotonic=e;this._current=i;this.reset=r}record(t){if(this.monotonic&&t<0){return}this._current+=t}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Ia{kind=Ro.SUM;monotonic;constructor(t){this.monotonic=t}createAccumulation(t){return new Pa(t,this.monotonic)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();if(e.reset){return new Pa(e.startTime,this.monotonic,r,e.reset)}return new Pa(t.startTime,this.monotonic,i+r)}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();if(this.monotonic&&i>r){return new Pa(e.startTime,this.monotonic,r,true)}return new Pa(e.startTime,this.monotonic,r-i)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:To.SUM,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()}))),isMonotonic:this.monotonic}}}class La{static DEFAULT_INSTANCE=new No;createAggregator(t){return La.DEFAULT_INSTANCE}}class Da{static MONOTONIC_INSTANCE=new Ia(true);static NON_MONOTONIC_INSTANCE=new Ia(false);createAggregator(t){switch(t.type){case Ao.COUNTER:case Ao.OBSERVABLE_COUNTER:case Ao.HISTOGRAM:{return Da.MONOTONIC_INSTANCE}default:{return Da.NON_MONOTONIC_INSTANCE}}}}class Ra{static DEFAULT_INSTANCE=new Oa;createAggregator(t){return Ra.DEFAULT_INSTANCE}}class Na{static DEFAULT_INSTANCE=new zo([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],true);createAggregator(t){return Na.DEFAULT_INSTANCE}}class ja{_boundaries;_recordMinMax;constructor(t,e=true){if(t==null){throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array")}t=t.concat();t=t.sort(((t,e)=>t-e));const i=t.lastIndexOf(-Infinity);let r=t.indexOf(Infinity);if(r===-1){r=undefined}this._boundaries=t.slice(i+1,r);this._recordMinMax=e}createAggregator(t){return new zo(this._boundaries,this._recordMinMax)}}class Ua{_maxSize;_recordMinMax;constructor(t=160,e=true){this._maxSize=t;this._recordMinMax=e}createAggregator(t){return new fa(this._maxSize,this._recordMinMax)}}class za{_resolve(t){switch(t.type){case Ao.COUNTER:case Ao.UP_DOWN_COUNTER:case Ao.OBSERVABLE_COUNTER:case Ao.OBSERVABLE_UP_DOWN_COUNTER:{return Ba}case Ao.GAUGE:case Ao.OBSERVABLE_GAUGE:{return Fa}case Ao.HISTOGRAM:{if(t.advice.explicitBucketBoundaries){return new ja(t.advice.explicitBucketBoundaries)}return Ga}}Wt.warn(`Unable to recognize instrument type: ${t.type}`);return $a}createAggregator(t){return this._resolve(t).createAggregator(t)}}const $a=new La;const Ba=new Da;const Fa=new Ra;const Ga=new Na;const Va=new za;var qa;(function(t){t[t["DEFAULT"]=0]="DEFAULT";t[t["DROP"]=1]="DROP";t[t["SUM"]=2]="SUM";t[t["LAST_VALUE"]=3]="LAST_VALUE";t[t["EXPLICIT_BUCKET_HISTOGRAM"]=4]="EXPLICIT_BUCKET_HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=5]="EXPONENTIAL_HISTOGRAM"})(qa||(qa={}));function Ha(t){switch(t.type){case qa.DEFAULT:return Va;case qa.DROP:return $a;case qa.SUM:return Ba;case qa.LAST_VALUE:return Fa;case qa.EXPONENTIAL_HISTOGRAM:{const e=t;return new Ua(e.options?.maxSize,e.options?.recordMinMax)}case qa.EXPLICIT_BUCKET_HISTOGRAM:{const e=t;if(e.options==null){return Ga}else{return new ja(e.options?.boundaries,e.options?.recordMinMax)}}default:throw new Error("Unsupported Aggregation")}}const Ja=t=>({type:qa.DEFAULT});const Ka=t=>_o.CUMULATIVE;class Za{_shutdown=false;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(t){this._aggregationSelector=t?.aggregationSelector??Ja;this._aggregationTemporalitySelector=t?.aggregationTemporalitySelector??Ka;this._metricProducers=t?.metricProducers??[];this._cardinalitySelector=t?.cardinalitySelector}setMetricProducer(t){if(this._sdkMetricProducer){throw new Error("MetricReader can not be bound to a MeterProvider again.")}this._sdkMetricProducer=t;this.onInitialized()}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}selectCardinalityLimit(t){return this._cardinalitySelector?this._cardinalitySelector(t):2e3}onInitialized(){}async collect(t){if(this._sdkMetricProducer===undefined){throw new Error("MetricReader is not bound to a MetricProducer")}if(this._shutdown){throw new Error("MetricReader is shutdown")}const[e,...i]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:t?.timeoutMillis}),...this._metricProducers.map((e=>e.collect({timeoutMillis:t?.timeoutMillis})))]);const r=e.errors.concat(i.flatMap((t=>t.errors)));const n=e.resourceMetrics.resource;const s=e.resourceMetrics.scopeMetrics.concat(i.flatMap((t=>t.resourceMetrics.scopeMetrics)));return{resourceMetrics:{resource:n,scopeMetrics:s},errors:r}}async shutdown(t){if(this._shutdown){Wt.error("Cannot call shutdown twice.");return}if(t?.timeoutMillis==null){await this.onShutdown()}else{await Po(this.onShutdown(),t.timeoutMillis)}this._shutdown=true}async forceFlush(t){if(this._shutdown){Wt.warn("Cannot forceFlush on already shutdown MetricReader.");return}if(t?.timeoutMillis==null){await this.onForceFlush();return}await Po(this.onForceFlush(),t.timeoutMillis)}}class Wa extends Za{_interval;_exporter;_exportInterval;_exportTimeout;constructor(t){const{exporter:e,exportIntervalMillis:i=6e4,metricProducers:r}=t;let{exportTimeoutMillis:n=3e4}=t;super({aggregationSelector:e.selectAggregation?.bind(e),aggregationTemporalitySelector:e.selectAggregationTemporality?.bind(e),metricProducers:r});if(i<=0){throw Error("exportIntervalMillis must be greater than 0")}if(n<=0){throw Error("exportTimeoutMillis must be greater than 0")}if(i<n){if("exportIntervalMillis"in t&&"exportTimeoutMillis"in t){throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis")}else{Wt.info(`Timeout of ${n} exceeds the interval of ${i}. Clamping timeout to interval duration.`);n=i}}this._exportInterval=i;this._exportTimeout=n;this._exporter=e}async _runOnce(){try{await Po(this._doRun(),this._exportTimeout)}catch(t){if(t instanceof Oo){Wt.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);return}wa(t)}}async _doRun(){const{resourceMetrics:t,errors:e}=await this.collect({timeoutMillis:this._exportTimeout});if(e.length>0){Wt.error("PeriodicExportingMetricReader: metrics collection errors",...e)}if(t.resource.asyncAttributesPending){try{await(t.resource.waitForAsyncAttributes?.())}catch(t){Wt.debug("Error while resolving async portion of resource: ",t);wa(t)}}if(t.scopeMetrics.length===0){return}const i=await Ma._export(this._exporter,t);if(i.code!==Aa.SUCCESS){throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${i.error})`)}}onInitialized(){this._interval=setInterval((()=>{void this._runOnce()}),this._exportInterval);if(typeof this._interval!=="number"){this._interval.unref()}}async onForceFlush(){await this._runOnce();await this._exporter.forceFlush()}async onShutdown(){if(this._interval){clearInterval(this._interval)}await this.onForceFlush();await this._exporter.shutdown()}}let Xa;function Ya(){if(Xa===undefined){try{const t=globalThis.process.argv0;Xa=t?`unknown_service:${t}`:"unknown_service"}catch{Xa="unknown_service"}}return Xa}const Qa=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";class tc{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,e){const i=new tc({},e);i._rawAttributes=rc(t);i._asyncAttributesPending=t.filter((([t,e])=>Qa(e))).length>0;return i}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(Qa(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=rc(this._rawAttributes);this._schemaUrl=nc(e?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(!this.asyncAttributesPending){return}for(let t=0;t<this._rawAttributes.length;t++){const[e,i]=this._rawAttributes[t];this._rawAttributes[t]=[e,Qa(i)?await i:i]}this._asyncAttributesPending=false}get attributes(){if(this.asyncAttributesPending){Wt.error("Accessing resource attributes before async attributes settled")}if(this._memoizedAttributes){return this._memoizedAttributes}const t={};for(const[e,i]of this._rawAttributes){if(Qa(i)){Wt.debug(`Unsettled resource attribute ${e} skipped`);continue}if(i!=null){t[e]??=i}}if(!this._asyncAttributesPending){this._memoizedAttributes=t}return t}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;const e=sc(this,t);const i=e?{schemaUrl:e}:undefined;return tc.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],i)}}function ec(t,e){return tc.FromAttributeList(Object.entries(t),e)}function ic(){return ec({[qe]:Ya(),[He]:xa[He],[Ke]:xa[Ke],[Ze]:xa[Ze]})}function rc(t){return t.map((([t,e])=>{if(Qa(e)){return[t,e.catch((e=>{Wt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function nc(t){if(typeof t==="string"||t===undefined){return t}Wt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t);return undefined}function sc(t,e){const i=t?.schemaUrl;const r=e?.schemaUrl;const n=i===undefined||i==="";const s=r===undefined||r==="";if(n){return r}if(s){return i}if(i===r){return i}Wt.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',i,r);return undefined}class oc{_registeredViews=[];addView(t){this._registeredViews.push(t)}findViews(t,e){const i=this._registeredViews.filter((i=>this._matchInstrument(i.instrumentSelector,t)&&this._matchMeter(i.meterSelector,e)));return i}_matchInstrument(t,e){return(t.getType()===undefined||e.type===t.getType())&&t.getNameFilter().match(e.name)&&t.getUnitFilter().match(e.unit)}_matchMeter(t,e){return t.getNameFilter().match(e.name)&&(e.version===undefined||t.getVersionFilter().match(e.version))&&(e.schemaUrl===undefined||t.getSchemaUrlFilter().match(e.schemaUrl))}}function ac(t,e,i){if(!fc(t)){Wt.warn(`Invalid metric name: "${t}". The metric name should be a ASCII string with a length no greater than 255 characters.`)}return{name:t,type:e,description:i?.description??"",unit:i?.unit??"",valueType:i?.valueType??ut.DOUBLE,advice:i?.advice??{}}}function cc(t,e){return{name:t.name??e.name,description:t.description??e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function uc(t,e){return Do(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}const lc=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function fc(t){return lc.test(t)}class hc{_writableMetricStorage;_descriptor;constructor(t,e){this._writableMetricStorage=t;this._descriptor=e}_record(t,e={},i=Zt.active()){if(typeof t!=="number"){Wt.warn(`non-number value provided to metric ${this._descriptor.name}: ${t}`);return}if(this._descriptor.valueType===ut.INT&&!Number.isInteger(t)){Wt.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`);t=Math.trunc(t);if(!Number.isInteger(t)){return}}this._writableMetricStorage.record(t,e,i,Ea(Date.now()))}}class dc extends hc{add(t,e,i){this._record(t,e,i)}}class pc extends hc{add(t,e,i){if(t<0){Wt.warn(`negative value provided to counter ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class mc extends hc{record(t,e,i){this._record(t,e,i)}}class bc extends hc{record(t,e,i){if(t<0){Wt.warn(`negative value provided to histogram ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class vc{_metricStorages;_descriptor;_observableRegistry;constructor(t,e,i){this._descriptor=t;this._metricStorages=e;this._observableRegistry=i}addCallback(t){this._observableRegistry.addCallback(t,this)}removeCallback(t){this._observableRegistry.removeCallback(t,this)}}class wc extends vc{}class gc extends vc{}class yc extends vc{}function xc(t){return t instanceof vc}class kc{_meterSharedState;constructor(t){this._meterSharedState=t}createGauge(t,e){const i=ac(t,Ao.GAUGE,e);const r=this._meterSharedState.registerMetricStorage(i);return new mc(r,i)}createHistogram(t,e){const i=ac(t,Ao.HISTOGRAM,e);const r=this._meterSharedState.registerMetricStorage(i);return new bc(r,i)}createCounter(t,e){const i=ac(t,Ao.COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new pc(r,i)}createUpDownCounter(t,e){const i=ac(t,Ao.UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new dc(r,i)}createObservableGauge(t,e){const i=ac(t,Ao.OBSERVABLE_GAUGE,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new gc(i,r,this._meterSharedState.observableRegistry)}createObservableCounter(t,e){const i=ac(t,Ao.OBSERVABLE_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new wc(i,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(t,e){const i=ac(t,Ao.OBSERVABLE_UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new yc(i,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.addBatchCallback(t,e)}removeBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.removeBatchCallback(t,e)}}class Sc{_instrumentDescriptor;constructor(t){this._instrumentDescriptor=t}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(t){this._instrumentDescriptor=ac(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:t,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class Ec{_valueMap=new Map;_keyMap=new Map;_hash;constructor(t){this._hash=t}get(t,e){e??=this._hash(t);return this._valueMap.get(e)}getOrDefault(t,e){const i=this._hash(t);if(this._valueMap.has(i)){return this._valueMap.get(i)}const r=e();if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,r);return r}set(t,e,i){i??=this._hash(t);if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,e)}has(t,e){e??=this._hash(t);return this._valueMap.has(e)}*keys(){const t=this._keyMap.entries();let e=t.next();while(e.done!==true){yield[e.value[1],e.value[0]];e=t.next()}}*entries(){const t=this._valueMap.entries();let e=t.next();while(e.done!==true){yield[this._keyMap.get(e.value[0]),e.value[1],e.value[0]];e=t.next()}}get size(){return this._valueMap.size}}class _c extends Ec{constructor(){super(Mo)}}class Ac{_activeCollectionStorage=new _c;_cumulativeMemoStorage=new _c;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":true};_overflowHashCode;_aggregator;constructor(t,e){this._aggregator=t;this._cardinalityLimit=(e??2e3)-1;this._overflowHashCode=Mo(this._overflowAttributes)}record(t,e,i,r){let n=this._activeCollectionStorage.get(e);if(!n){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const e=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,(()=>this._aggregator.createAccumulation(r)));e?.record(t);return}n=this._aggregator.createAccumulation(r);this._activeCollectionStorage.set(e,n)}n?.record(t)}batchCumulate(t,e){Array.from(t.entries()).forEach((([t,i,r])=>{const n=this._aggregator.createAccumulation(e);n?.record(i);let s=n;if(this._cumulativeMemoStorage.has(t,r)){const e=this._cumulativeMemoStorage.get(t,r);s=this._aggregator.diff(e,n)}else{if(this._cumulativeMemoStorage.size>=this._cardinalityLimit){t=this._overflowAttributes;r=this._overflowHashCode;if(this._cumulativeMemoStorage.has(t,r)){const e=this._cumulativeMemoStorage.get(t,r);s=this._aggregator.diff(e,n)}}}if(this._activeCollectionStorage.has(t,r)){const e=this._activeCollectionStorage.get(t,r);s=this._aggregator.merge(e,s)}this._cumulativeMemoStorage.set(t,n,r);this._activeCollectionStorage.set(t,s,r)}))}collect(){const t=this._activeCollectionStorage;this._activeCollectionStorage=new _c;return t}}class Tc{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(t,e){this._aggregator=t;e.forEach((t=>{this._unreportedAccumulations.set(t,[])}))}buildMetrics(t,e,i,r){this._stashAccumulations(i);const n=this._getMergedUnreportedAccumulations(t);let s=n;let o;if(this._reportHistory.has(t)){const e=this._reportHistory.get(t);const i=e.collectionTime;o=e.aggregationTemporality;if(o===_o.CUMULATIVE){s=Tc.merge(e.accumulations,n,this._aggregator)}else{s=Tc.calibrateStartTime(e.accumulations,n,i)}}else{o=t.selectAggregationTemporality(e.type)}this._reportHistory.set(t,{accumulations:s,collectionTime:r,aggregationTemporality:o});const a=Mc(s);if(a.length===0){return undefined}return this._aggregator.toMetricData(e,o,a,r)}_stashAccumulations(t){const e=this._unreportedAccumulations.keys();for(const i of e){let e=this._unreportedAccumulations.get(i);if(e===undefined){e=[];this._unreportedAccumulations.set(i,e)}e.push(t)}}_getMergedUnreportedAccumulations(t){let e=new _c;const i=this._unreportedAccumulations.get(t);this._unreportedAccumulations.set(t,[]);if(i===undefined){return e}for(const t of i){e=Tc.merge(e,t,this._aggregator)}return e}static merge(t,e,i){const r=t;const n=e.entries();let s=n.next();while(s.done!==true){const[e,o,a]=s.value;if(t.has(e,a)){const n=t.get(e,a);const s=i.merge(n,o);r.set(e,s,a)}else{r.set(e,o,a)}s=n.next()}return r}static calibrateStartTime(t,e,i){for(const[r,n]of t.keys()){const t=e.get(r,n);t?.setStartTime(i)}return e}}function Mc(t){return Array.from(t.entries())}class Cc extends Sc{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(t,e,i,r,n){super(t);this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new Ac(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new Tc(e,r);this._attributesProcessor=i}record(t,e){const i=new _c;Array.from(t.entries()).forEach((([t,e])=>{i.set(this._attributesProcessor.process(t),e)}));this._deltaMetricStorage.batchCumulate(i,e)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}function Oc(t,e){let i="";if(t.unit!==e.unit){i+=`\t- Unit '${t.unit}' does not match '${e.unit}'\n`}if(t.type!==e.type){i+=`\t- Type '${t.type}' does not match '${e.type}'\n`}if(t.valueType!==e.valueType){i+=`\t- Value Type '${t.valueType}' does not match '${e.valueType}'\n`}if(t.description!==e.description){i+=`\t- Description '${t.description}' does not match '${e.description}'\n`}return i}function Pc(t,e){return`\t- use valueType '${t.valueType}' on instrument creation or use an instrument name other than '${e.name}'`}function Ic(t,e){return`\t- use unit '${t.unit}' on instrument creation or use an instrument name other than '${e.name}'`}function Lc(t,e){const i={name:e.name,type:e.type,unit:e.unit};const r=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${r}'`}function Dc(t,e){const i={name:e.name,type:e.type,unit:e.unit};const r=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${r}'\n \t- OR - create a new view with the name ${t.name} and description '${t.description}' and InstrumentSelector ${r}\n \t- OR - create a new view with the name ${e.name} and description '${t.description}' and InstrumentSelector ${r}`}function Rc(t,e){if(t.valueType!==e.valueType){return Pc(t,e)}if(t.unit!==e.unit){return Ic(t,e)}if(t.type!==e.type){return Lc(t,e)}if(t.description!==e.description){return Dc(t,e)}return""}class Nc{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new Nc}getStorages(t){let e=[];for(const t of this._sharedRegistry.values()){e=e.concat(t)}const i=this._perCollectorRegistry.get(t);if(i!=null){for(const t of i.values()){e=e.concat(t)}}return e}register(t){this._registerStorage(t,this._sharedRegistry)}registerForCollector(t,e){let i=this._perCollectorRegistry.get(t);if(i==null){i=new Map;this._perCollectorRegistry.set(t,i)}this._registerStorage(e,i)}findOrUpdateCompatibleStorage(t){const e=this._sharedRegistry.get(t.name);if(e===undefined){return null}return this._findOrUpdateCompatibleStorage(t,e)}findOrUpdateCompatibleCollectorStorage(t,e){const i=this._perCollectorRegistry.get(t);if(i===undefined){return null}const r=i.get(e.name);if(r===undefined){return null}return this._findOrUpdateCompatibleStorage(e,r)}_registerStorage(t,e){const i=t.getInstrumentDescriptor();const r=e.get(i.name);if(r===undefined){e.set(i.name,[t]);return}r.push(t)}_findOrUpdateCompatibleStorage(t,e){let i=null;for(const r of e){const e=r.getInstrumentDescriptor();if(uc(e,t)){if(e.description!==t.description){if(t.description.length>e.description.length){r.updateDescription(t.description)}Wt.warn("A view or instrument with the name ",t.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",Oc(e,t),"The longer description will be used.\nTo resolve the conflict:",Rc(e,t))}i=r}else{Wt.warn("A view or instrument with the name ",t.name," has already been registered and is incompatible with another registered view.\n","Details:\n",Oc(e,t),"To resolve the conflict:\n",Rc(e,t))}}return i}}class jc{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,i,r){this._backingStorages.forEach((n=>{n.record(t,e,i,r)}))}}class Uc{_buffer=new _c;_instrumentName;_valueType;constructor(t,e){this._instrumentName=t;this._valueType=e}observe(t,e={}){if(typeof t!=="number"){Wt.warn(`non-number value provided to metric ${this._instrumentName}: ${t}`);return}if(this._valueType===ut.INT&&!Number.isInteger(t)){Wt.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`);t=Math.trunc(t);if(!Number.isInteger(t)){return}}this._buffer.set(e,t)}}class zc{_buffer=new Map;observe(t,e,i={}){if(!xc(t)){return}let r=this._buffer.get(t);if(r==null){r=new _c;this._buffer.set(t,r)}if(typeof e!=="number"){Wt.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}if(t._descriptor.valueType===ut.INT&&!Number.isInteger(e)){Wt.warn(`INT value type cannot accept a floating-point value for ${t._descriptor.name}, ignoring the fractional digits.`);e=Math.trunc(e);if(!Number.isInteger(e)){return}}r.set(i,e)}}class $c{_callbacks=[];_batchCallbacks=[];addCallback(t,e){const i=this._findCallback(t,e);if(i>=0){return}this._callbacks.push({callback:t,instrument:e})}removeCallback(t,e){const i=this._findCallback(t,e);if(i<0){return}this._callbacks.splice(i,1)}addBatchCallback(t,e){const i=new Set(e.filter(xc));if(i.size===0){Wt.error("BatchObservableCallback is not associated with valid instruments",e);return}const r=this._findBatchCallback(t,i);if(r>=0){return}this._batchCallbacks.push({callback:t,instruments:i})}removeBatchCallback(t,e){const i=new Set(e.filter(xc));const r=this._findBatchCallback(t,i);if(r<0){return}this._batchCallbacks.splice(r,1)}async observe(t,e){const i=this._observeCallbacks(t,e);const r=this._observeBatchCallbacks(t,e);const n=await Promise.allSettled([...i,...r]);const s=n.filter((t=>t.status==="rejected")).map((t=>t.reason));return s}_observeCallbacks(t,e){return this._callbacks.map((async({callback:i,instrument:r})=>{const n=new Uc(r._descriptor.name,r._descriptor.valueType);let s=Promise.resolve(i(n));if(e!=null){s=Po(s,e)}await s;r._metricStorages.forEach((e=>{e.record(n._buffer,t)}))}))}_observeBatchCallbacks(t,e){return this._batchCallbacks.map((async({callback:i,instruments:r})=>{const n=new zc;let s=Promise.resolve(i(n));if(e!=null){s=Po(s,e)}await s;r.forEach((e=>{const i=n._buffer.get(e);if(i==null){return}e._metricStorages.forEach((e=>{e.record(i,t)}))}))}))}_findCallback(t,e){return this._callbacks.findIndex((i=>i.callback===t&&i.instrument===e))}_findBatchCallback(t,e){return this._batchCallbacks.findIndex((i=>i.callback===t&&Io(i.instruments,e)))}}class Bc extends Sc{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(t,e,i,r,n){super(t);this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new Ac(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new Tc(e,r);this._attributesProcessor=i}record(t,e,i,r){e=this._attributesProcessor.process(e,i);this._deltaMetricStorage.record(t,e,i,r)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}class Fc{process(t,e){return t}}class Gc{_processors;constructor(t){this._processors=t}process(t,e){let i=t;for(const t of this._processors){i=t.process(i,e)}return i}}function Vc(){return Hc}function qc(t){return new Gc(t)}const Hc=new Fc;class Jc{metricStorageRegistry=new Nc;observableRegistry=new $c;meter;_meterProviderSharedState;_instrumentationScope;constructor(t,e){this.meter=new kc(this);this._meterProviderSharedState=t;this._instrumentationScope=e}registerMetricStorage(t){const e=this._registerMetricStorage(t,Bc);if(e.length===1){return e[0]}return new jc(e)}registerAsyncMetricStorage(t){const e=this._registerMetricStorage(t,Cc);return e}async collect(t,e,i){const r=await this.observableRegistry.observe(e,i?.timeoutMillis);const n=this.metricStorageRegistry.getStorages(t);if(n.length===0){return null}const s=[];n.forEach((i=>{const r=i.collect(t,e);if(r!=null){s.push(r)}}));if(s.length===0){return{errors:r}}return{scopeMetrics:{scope:this._instrumentationScope,metrics:s},errors:r}}_registerMetricStorage(t,e){const i=this._meterProviderSharedState.viewRegistry.findViews(t,this._instrumentationScope);let r=i.map((i=>{const r=cc(i,t);const n=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(n!=null){return n}const s=i.aggregation.createAggregator(r);const o=new e(r,s,i.attributesProcessor,this._meterProviderSharedState.metricCollectors,i.aggregationCardinalityLimit);this.metricStorageRegistry.register(o);return o}));if(r.length===0){const i=this._meterProviderSharedState.selectAggregations(t.type);const n=i.map((([i,r])=>{const n=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(i,t);if(n!=null){return n}const s=r.createAggregator(t);const o=i.selectCardinalityLimit(t.type);const a=new e(t,s,Vc(),[i],o);this.metricStorageRegistry.registerForCollector(i,a);return a}));r=r.concat(n)}return r}}class Kc{viewRegistry=new oc;metricCollectors=[];meterSharedStates=new Map;resource;constructor(t){this.resource=t}getMeterSharedState(t){const e=Co(t);let i=this.meterSharedStates.get(e);if(i==null){i=new Jc(this,t);this.meterSharedStates.set(e,i)}return i}selectAggregations(t){const e=[];for(const i of this.metricCollectors){e.push([i,Ha(i.selectAggregation(t))])}return e}}class Zc{_sharedState;_metricReader;constructor(t,e){this._sharedState=t;this._metricReader=e}async collect(t){const e=Ea(Date.now());const i=[];const r=[];const n=Array.from(this._sharedState.meterSharedStates.values()).map((async n=>{const s=await n.collect(this,e,t);if(s?.scopeMetrics!=null){i.push(s.scopeMetrics)}if(s?.errors!=null){r.push(...s.errors)}}));await Promise.all(n);return{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:i},errors:r}}async forceFlush(t){await this._metricReader.forceFlush(t)}async shutdown(t){await this._metricReader.shutdown(t)}selectAggregationTemporality(t){return this._metricReader.selectAggregationTemporality(t)}selectAggregation(t){return this._metricReader.selectAggregation(t)}selectCardinalityLimit(t){return this._metricReader.selectCardinalityLimit?.(t)??2e3}}const Wc=/[\^$\\.+?()[\]{}|]/g;class Xc{_matchAll;_regexp;constructor(t){if(t==="*"){this._matchAll=true;this._regexp=/.*/}else{this._matchAll=false;this._regexp=new RegExp(Xc.escapePattern(t))}}match(t){if(this._matchAll){return true}return this._regexp.test(t)}static escapePattern(t){return`^${t.replace(Wc,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}}class Yc{_matchAll;_pattern;constructor(t){this._matchAll=t===undefined;this._pattern=t}match(t){if(this._matchAll){return true}if(t===this._pattern){return true}return false}}class Qc{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new Xc(t?.name??"*");this._type=t?.type;this._unitFilter=new Yc(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class tu{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new Yc(t?.name);this._versionFilter=new Yc(t?.version);this._schemaUrlFilter=new Yc(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function eu(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}function iu(t){if(eu(t)){throw new Error("Cannot create view with no selector arguments supplied")}if(t.name!=null&&(t?.instrumentName==null||Xc.hasWildcard(t.instrumentName))){throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}}class ru{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){iu(t);if(t.attributesProcessors!=null){this.attributesProcessor=qc(t.attributesProcessors)}else{this.attributesProcessor=Vc()}this.name=t.name;this.description=t.description;this.aggregation=Ha(t.aggregation??{type:qa.DEFAULT});this.instrumentSelector=new Qc({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit});this.meterSelector=new tu({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl});this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}}class nu{_sharedState;_shutdown=false;constructor(t){this._sharedState=new Kc(t?.resource??ic());if(t?.views!=null&&t.views.length>0){for(const e of t.views){this._sharedState.viewRegistry.addView(new ru(e))}}if(t?.readers!=null&&t.readers.length>0){for(const e of t.readers){const t=new Zc(this._sharedState,e);e.setMetricProducer(t);this._sharedState.metricCollectors.push(t)}}}getMeter(t,e="",i={}){if(this._shutdown){Wt.warn("A shutdown MeterProvider cannot provide a Meter");return ct()}return this._sharedState.getMeterSharedState({name:t,version:e,schemaUrl:i.schemaUrl}).meter}async shutdown(t){if(this._shutdown){Wt.warn("shutdown may only be called once per MeterProvider");return}this._shutdown=true;await Promise.all(this._sharedState.metricCollectors.map((e=>e.shutdown(t))))}async forceFlush(t){if(this._shutdown){Wt.warn("invalid attempt to force flush after MeterProvider shutdown");return}await Promise.all(this._sharedState.metricCollectors.map((e=>e.forceFlush(t))))}}var su;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(su||(su={}));var ou;(function(t){t["COUNTER"]="COUNTER";t["GAUGE"]="GAUGE";t["HISTOGRAM"]="HISTOGRAM";t["UP_DOWN_COUNTER"]="UP_DOWN_COUNTER";t["OBSERVABLE_COUNTER"]="OBSERVABLE_COUNTER";t["OBSERVABLE_GAUGE"]="OBSERVABLE_GAUGE";t["OBSERVABLE_UP_DOWN_COUNTER"]="OBSERVABLE_UP_DOWN_COUNTER"})(ou||(ou={}));var au;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(au||(au={}));var cu;(function(t){t[t["DEFAULT"]=0]="DEFAULT";t[t["DROP"]=1]="DROP";t[t["SUM"]=2]="SUM";t[t["LAST_VALUE"]=3]="LAST_VALUE";t[t["EXPLICIT_BUCKET_HISTOGRAM"]=4]="EXPLICIT_BUCKET_HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=5]="EXPONENTIAL_HISTOGRAM"})(cu||(cu={}));var uu;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE";t[t["LOWMEMORY"]=2]="LOWMEMORY"})(uu||(uu={}));const lu=()=>su.CUMULATIVE;const fu=t=>{switch(t){case ou.COUNTER:case ou.OBSERVABLE_COUNTER:case ou.GAUGE:case ou.HISTOGRAM:case ou.OBSERVABLE_GAUGE:return su.DELTA;case ou.UP_DOWN_COUNTER:case ou.OBSERVABLE_UP_DOWN_COUNTER:return su.CUMULATIVE}};const hu=t=>{switch(t){case ou.COUNTER:case ou.HISTOGRAM:return su.DELTA;case ou.GAUGE:case ou.UP_DOWN_COUNTER:case ou.OBSERVABLE_UP_DOWN_COUNTER:case ou.OBSERVABLE_COUNTER:case ou.OBSERVABLE_GAUGE:return su.CUMULATIVE}};function du(){const t="cumulative".toLowerCase();if(t==="cumulative"){return lu}if(t==="delta"){return fu}if(t==="lowmemory"){return hu}Wt.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${t}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);return lu}function pu(t){if(t!=null){if(t===uu.DELTA){return fu}else if(t===uu.LOWMEMORY){return hu}return lu}return du()}const mu=Object.freeze({type:cu.DEFAULT});function bu(t){return t?.aggregationPreference??(()=>mu)}class vu extends Xr{_aggregationTemporalitySelector;_aggregationSelector;constructor(t,e){super(t);this._aggregationSelector=bu(e);this._aggregationTemporalitySelector=pu(e?.temporalityPreference)}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}}class wu extends vu{constructor(t){super(Es(t??{},Wn,"v1/metrics",{"Content-Type":"application/json"}),t)}}class gu{meterProvider=null;meter=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;exportIntervalMillis;metricReader=null;captureCounter=null;errorCounter=null;modelLoadCounter=null;userInteractionCounter=null;captureLatencyHistogram=null;modelLoadLatencyHistogram=null;detectionLatencyHistogram=null;imageSizeHistogram=null;activeSessionsGauge=null;memoryUsageGauge=null;activeSessions=0;gaugeValues=new Map;constructor(t={}){this.collectorUrl=t.collectorUrl||"https://collector.jaak.ai/v1/metrics";this.serviceName=t.serviceName||"jaak-stamps-webcomponent";this.serviceVersion=t.serviceVersion||"2.1.0";this.debug=t.debug||false;this.customerId=t.customerId;this.tenantId=t.tenantId;this.environment=t.environment||"production";this.exportIntervalMillis=t.exportIntervalMillis||6e4}initialize(){try{const t=new wu({url:this.collectorUrl,headers:{"Content-Type":"application/json"}});this.metricReader=new Wa({exporter:t,exportIntervalMillis:this.exportIntervalMillis,exportTimeoutMillis:3e4});this.meterProvider=new nu({readers:[this.metricReader]});this.meter=this.meterProvider.getMeter(this.serviceName,this.serviceVersion);this.initializeMetrics();if(this.debug){console.log("[MetricsService] Initialized successfully",{collectorUrl:this.collectorUrl,serviceName:this.serviceName,serviceVersion:this.serviceVersion,environment:this.environment,customerId:this.customerId,tenantId:this.tenantId,exportIntervalMillis:this.exportIntervalMillis})}}catch(t){console.error("[MetricsService] Failed to initialize:",t)}}initializeMetrics(){if(!this.meter)return;const t=this.getBaseAttributes();try{this.captureCounter=this.meter.createCounter("jaak.captures.total",{description:"Total number of document captures",unit:"1"});this.errorCounter=this.meter.createCounter("jaak.errors.total",{description:"Total number of errors",unit:"1"});this.modelLoadCounter=this.meter.createCounter("jaak.model.loads.total",{description:"Total number of model loads",unit:"1"});this.userInteractionCounter=this.meter.createCounter("jaak.user.interactions.total",{description:"Total user interactions (clicks, etc.)",unit:"1"});this.captureLatencyHistogram=this.meter.createHistogram("jaak.capture.duration",{description:"Duration of capture operations",unit:"ms"});this.modelLoadLatencyHistogram=this.meter.createHistogram("jaak.model.load.duration",{description:"Duration of model loading",unit:"ms"});this.detectionLatencyHistogram=this.meter.createHistogram("jaak.detection.duration",{description:"Duration of detection inference",unit:"ms"});this.imageSizeHistogram=this.meter.createHistogram("jaak.image.size",{description:"Size of captured images",unit:"bytes"});this.activeSessionsGauge=this.meter.createObservableGauge("jaak.sessions.active",{description:"Number of active capture sessions",unit:"1"});this.activeSessionsGauge.addCallback((e=>{e.observe(this.activeSessions,t)}));if("memory"in performance){this.memoryUsageGauge=this.meter.createObservableGauge("jaak.memory.usage",{description:"JavaScript heap memory usage",unit:"bytes"});this.memoryUsageGauge.addCallback((e=>{const i=performance.memory;if(i){e.observe(i.usedJSHeapSize,t)}}))}if(this.debug){console.log("[MetricsService] Business metrics initialized")}}catch(t){console.error("[MetricsService] Failed to initialize metrics:",t)}}getBaseAttributes(){const t={"service.name":this.serviceName,"service.version":this.serviceVersion,"deployment.environment":this.environment};if(this.customerId){t["customer.id"]=this.customerId}if(this.tenantId){t["tenant.id"]=this.tenantId}return t}incrementCounter(t,e=1,i){try{const r=this.getBaseAttributes();const n={...r,...i};switch(t){case"captures":this.captureCounter?.add(e,n);break;case"errors":this.errorCounter?.add(e,n);break;case"model_loads":this.modelLoadCounter?.add(e,n);break;case"user_interactions":this.userInteractionCounter?.add(e,n);break;default:if(this.meter){const i=this.meter.createCounter(`jaak.${t}.total`,{description:`Total ${t}`,unit:"1"});i.add(e,n)}}if(this.debug){console.log(`[MetricsService] Counter incremented: ${t} += ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to increment counter:",t)}}recordHistogram(t,e,i){try{const r=this.getBaseAttributes();const n={...r,...i};switch(t){case"capture_duration":this.captureLatencyHistogram?.record(e,n);break;case"model_load_duration":this.modelLoadLatencyHistogram?.record(e,n);break;case"detection_duration":this.detectionLatencyHistogram?.record(e,n);break;case"image_size":this.imageSizeHistogram?.record(e,n);break;default:if(this.meter){const i=this.meter.createHistogram(`jaak.${t}`,{description:`Distribution of ${t}`,unit:"ms"});i.record(e,n)}}if(this.debug){console.log(`[MetricsService] Histogram recorded: ${t} = ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to record histogram:",t)}}setGauge(t,e,i){try{this.gaugeValues.set(t,e);if(t==="active_sessions"){this.activeSessions=e}if(this.debug){console.log(`[MetricsService] Gauge set: ${t} = ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to set gauge:",t)}}async measureDuration(t,e,i){const r=performance.now();try{const n=await e();const s=performance.now()-r;this.recordHistogram(t,s,i);return n}catch(e){const n=performance.now()-r;this.recordHistogram(t,n,{...i,error:true});throw e}}async flush(){try{if(this.metricReader){await this.metricReader.forceFlush()}if(this.debug){console.log("[MetricsService] Metrics flushed")}}catch(t){console.error("[MetricsService] Failed to flush metrics:",t)}}async cleanup(){try{if(this.metricReader){await this.metricReader.forceFlush();await this.metricReader.shutdown()}if(this.meterProvider){await this.meterProvider.shutdown()}if(this.debug){console.log("[MetricsService] Cleaned up successfully")}}catch(t){console.error("[MetricsService] Failed to cleanup:",t)}}recordCapture(t,e,i){this.incrementCounter("captures",1,{side:t,mode:e});this.recordHistogram("capture_duration",i,{side:t,mode:e})}recordError(t,e){this.incrementCounter("errors",1,{error_type:t,operation:e})}recordModelLoad(t,e,i){this.incrementCounter("model_loads",1,{model_type:t,cached:i});this.recordHistogram("model_load_duration",e,{model_type:t,cached:i})}recordDetection(t,e){this.recordHistogram("detection_duration",t,{detections_found:e})}recordImageSize(t,e){this.recordHistogram("image_size",e,{side:t})}updateActiveSessions(t){this.setGauge("active_sessions",t)}recordUserInteraction(t){this.incrementCounter("user_interactions",1,{interaction_type:t})}}class yu{services=new Map;constructor(t){this.initializeServices(t)}initializeServices(t){const e=new n;const i=new s(e);const r=new o(e,t.preferredCamera);const a=new f(t.debug,t.useDocumentClassification,t.useDocumentDetector);let c=null;if(t.enableTelemetry!==false){c=new Eo({collectorUrl:t.telemetryCollectorUrl||"https://collector.jaak.ai/v1/traces",serviceName:"jaak-stamps-webcomponent",serviceVersion:"2.1.0",debug:t.debug,customerId:t.customerId,tenantId:t.tenantId,environment:t.environment||"production",propagateTraceHeaderCorsUrls:t.propagateTraceHeaderCorsUrls||[],enableAutoInstrumentation:true});c.initialize()}let u=null;if(t.enableMetrics!==false){u=new gu({collectorUrl:t.metricsCollectorUrl||"https://collector.jaak.ai/v1/metrics",serviceName:"jaak-stamps-webcomponent",serviceVersion:"2.1.0",debug:t.debug,customerId:t.customerId,tenantId:t.tenantId,environment:t.environment||"production",exportIntervalMillis:t.metricsExportIntervalMillis||6e4});u.initialize()}this.services.set("eventBus",e);this.services.set("stateManager",i);this.services.set("cameraService",r);this.services.set("detectionService",a);if(c){this.services.set("tracingService",c)}if(u){this.services.set("metricsService",u)}}get(t){const e=this.services.get(t);if(!e){throw new Error(`Service ${t} not found`)}return e}getEventBus(){return this.get("eventBus")}getStateManager(){return this.get("stateManager")}getCameraService(){return this.get("cameraService")}getDetectionService(){return this.get("detectionService")}getTracingService(){try{return this.get("tracingService")}catch{return null}}getMetricsService(){try{return this.get("metricsService")}catch{return null}}updateConfig(t){}async cleanup(){this.getDetectionService().cleanup();const t=this.getMetricsService();if(t){await t.cleanup()}const e=this.getTracingService();if(e){await e.cleanup()}this.getEventBus().clear();this.services.clear()}}class xu{apiEndpoint="/api/v1/license/validate";baseUrl;static ENVIRONMENT_URLS={dev:"https://api.dev.jaak.ai",qa:"https://api.qa.jaak.ai",sandbox:"https://api.sandbox.jaak.ai",prod:"https://services.api.jaak.ai"};constructor(t="prod"){this.baseUrl=xu.ENVIRONMENT_URLS[t]}async validateLicense(t,e,i="jaak-stamps-web"){const r=e||this.generateTraceId();const n={license:e?`L${r}`:t,origin:"web",app_id:i,product:"kyc",metadata:{sdk_version:"2.1.0"}};const s={"Content-Type":"application/json"};s["traceparent"]=`00-${r}-${this.generateSpanId()}-01`;try{const t=await fetch(`${this.baseUrl}${this.apiEndpoint}`,{method:"POST",headers:s,body:JSON.stringify(n)});if(!t.ok){const e=await t.json().catch((()=>({})));throw{error:e.error||"license_validation_failed",error_description:e.error_description||`HTTP ${t.status}: ${t.statusText}`,status_code:t.status}}const e=await t.json();return{...e,traceId:r}}catch(t){if(t.error){throw t}throw{error:"network_error",error_description:"Failed to connect to license validation service",status_code:0}}}generateTraceId(){const t=new Uint8Array(16);crypto.getRandomValues(t);return Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("")}generateSpanId(){const t=new Uint8Array(8);crypto.getRandomValues(t);return Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("")}static extractTraceIdFromLicense(t){if(!t||typeof t!=="string"){return null}const e=t.startsWith("L")?t.slice(1):t;if(e.length===32&&/^[a-f0-9]{32}$/i.test(e)){return e.toLowerCase()}console.warn("[LicenseValidationService] Invalid license format for trace ID:",t);return null}}const ku=":host{display:block;width:100%;height:100%;font-family:system-ui, -apple-system, sans-serif;color:#1a1a1a}.detector-container{display:flex;flex-direction:column;align-items:center;width:100%;height:100%}h1{font-size:24px;font-weight:500;color:#333;margin:0 0 24px 0}.video-container{position:relative;width:100%;height:100%;background-color:#000;border:none;border-radius:8px;overflow:hidden}video,.detection-overlay{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,.detection-overlay.mirror{transform:rotateY(180deg)}.detection-overlay{z-index:1;pointer-events:none}video{z-index:0}video::-webkit-media-controls{display:none !important}video::-webkit-media-controls-panel{display:none !important}video::-webkit-media-controls-play-button{display:none !important}video::-webkit-media-controls-start-playback-button{display:none !important}video::-webkit-media-controls-enclosure{display:none !important}.detection-box{transition:opacity 0.2s ease}.status{margin-top:16px;font-size:12px;color:#666}.overlay-mask{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10;display:block;pointer-events:none}.card-outline{position:absolute;top:var(--mask-center-y, 50%);left:var(--mask-center-x, 50%);transform:translate(-50%, -50%);width:var(--mask-width, 88%);height:var(--mask-height, 55%);border:none;border-radius:4px;background:transparent;opacity:0.8}.side{position:absolute;background:#999;transition:background-color 0.3s ease;border-radius:1px}.side-top.aligned{border-left-color:#28a745;border-top-color:#28a745}.side-right.aligned{border-right-color:#28a745;border-top-color:#28a745}.side-bottom.aligned{border-left-color:#28a745;border-bottom-color:#28a745}.side-left.aligned{border-right-color:#28a745;border-bottom-color:#28a745}.side-top{top:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-right{top:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-bottom{bottom:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.side-left{bottom:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);color:#ffffff;font-size:12px;font-weight:500;text-align:center;white-space:normal;padding:13px;max-width:300px;z-index:20;height:fit-content;width:fit-content;animation:slideInFromTopCentered 0.3s ease-out}.quality-indicator{position:absolute;top:20px;right:20px;display:flex;align-items:center;gap:8px;background:rgba(0, 0, 0, 0.8);padding:8px 12px;border-radius:20px;z-index:25;transition:all 0.3s ease}.quality-indicator.warning{background:rgba(255, 152, 0, 0.9)}.quality-indicator.good{background:rgba(76, 175, 80, 0.9)}.quality-score{color:#fff;font-size:12px;font-weight:600;min-width:30px;text-align:center}.quality-status{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:bold;color:#fff;transition:all 0.3s ease}.quality-status.ready{background:#4CAF50}.quality-status.not-ready{background:#f44336}.card-outline.quality-warning{animation:qualityWarning 1s ease-in-out infinite alternate}@keyframes qualityWarning{0%{box-shadow:0 0 0 3px rgba(255, 152, 0, 0.6)}100%{box-shadow:0 0 0 6px rgba(255, 152, 0, 0.3)}}.capture-animation{position:absolute;top:0;left:0;width:100%;height:100%;background:#fff;opacity:0;z-index:30;pointer-events:none;animation:captureFlash 0.6s ease-out}@keyframes captureFlash{0%{opacity:0}15%{opacity:0.8}30%{opacity:0}45%{opacity:0.4}60%{opacity:0}100%{opacity:0}}.card-outline.capturing{animation:pulseGreen 0.6s ease-out}@keyframes pulseGreen{0%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}}.flip-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showFlipInstruction 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.id-card-icon{width:80px;height:50px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:8px;position:relative;animation:flipCard 2s ease-in-out infinite;box-shadow:0 4px 12px rgba(0, 0, 0, 0.3)}.id-card-icon::before{content:'';position:absolute;top:8px;left:8px;width:16px;height:12px;background:rgba(255, 255, 255, 0.9);border-radius:2px}.id-card-icon::after{content:'';position:absolute;top:25px;left:8px;width:64px;height:3px;background:rgba(255, 255, 255, 0.7);border-radius:1px;box-shadow:0 6px 0 rgba(255, 255, 255, 0.7), 0 12px 0 rgba(255, 255, 255, 0.7)}.flip-text{margin-top:12px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px}@keyframes showFlipInstruction{0%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}}@keyframes flipCard{0%{transform:rotateY(0deg)}50%{transform:rotateY(180deg)}100%{transform:rotateY(360deg)}}.success-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showSuccessMessage 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.check-icon{width:80px;height:80px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:50%;position:relative;animation:bounceSuccess 0.6s ease-out;box-shadow:0 4px 16px rgba(108, 117, 125, 0.4);display:flex;align-items:center;justify-content:center}.check-icon::before{content:'';position:absolute;width:20px;height:35px;border:4px solid #fff;border-top:none;border-left:none;transform:rotate(45deg);}.success-text{margin-top:16px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;animation:fadeInUp 0.5s ease-out 0.4s both}@keyframes showSuccessMessage{0%{opacity:0;transform:translate(-50%, -50%) scale(0.5)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.9)}}@keyframes bounceSuccess{0%{transform:scale(0)}50%{transform:scale(1.1)}100%{transform:scale(1)}}@keyframes drawCheck{0%{width:0;height:0}50%{width:20px;height:0}100%{width:20px;height:35px}}@keyframes fadeInUp{0%{opacity:0;transform:translateY(20px)}100%{opacity:1;transform:translateY(0)}}.skip-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.back-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:320px}.back-capture-buttons{display:flex;gap:12px;align-items:center;justify-content:center;flex-wrap:wrap}.capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.capture-button:hover{background:#f8f9fa}.capture-button:active{background:#e9ecef;transform:translateY(1px)}.capture-button:disabled,.capture-button.primary-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}@media (max-width: 480px){.back-capture-section{bottom:16px;max-width:300px}.back-capture-buttons{flex-direction:column;gap:8px;width:100%}.capture-button,.back-capture-buttons .skip-button{width:100%;max-width:200px;padding:10px 20px;font-size:13px}.capture-button:disabled,.capture-button.primary-button:disabled,.skip-button:disabled{opacity:0.7 !important;cursor:not-allowed !important}}.skip-explanation{background:rgba(0, 0, 0, 0.5);color:#ffffff;padding:10px 16px;border-radius:8px;font-size:14px;font-weight:500;text-align:center;margin-bottom:12px;box-shadow:0 2px 8px rgba(0, 0, 0, 0.2);backdrop-filter:blur(12px);border:1px solid rgba(255, 255, 255, 0.1);animation:fadeIn 0.3s ease-in-out}@keyframes fadeIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.guide-text.performance-warning-text{animation:gentlePulse 2s ease-in-out infinite;background:rgba(255, 107, 107, 0.3);border:1px solid rgba(255, 107, 107, 0.5)}@keyframes gentlePulse{0%,100%{transform:translate(-50%, -50%) scale(1);background:rgba(255, 107, 107, 0.3)}50%{transform:translate(-50%, -50%) scale(1.02);background:rgba(255, 107, 107, 0.4)}}.skip-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.skip-button:hover{background:#f8f9fa}.skip-button:active{background:#e9ecef;transform:translateY(1px)}.skip-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}.camera-controls{position:absolute;top:16px;right:16px;z-index:25;display:flex;gap:8px;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}.camera-selector-button{height:32px;padding:0 10px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(12px);color:#ffffff;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s ease;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255, 255, 255, 0.1);white-space:nowrap;min-width:fit-content}.camera-selector-button:hover{background:rgba(0, 0, 0, 0.8);border-color:rgba(255, 255, 255, 0.2);transform:translateY(-1px)}.camera-selector-button:active{transform:translateY(0);background:rgba(0, 0, 0, 0.9)}.camera-selector-button:disabled,.camera-selector-button.loading{opacity:0.7;cursor:not-allowed;pointer-events:none}.camera-selector-button:disabled:hover,.camera-selector-button.loading:hover{transform:none;background:rgba(0, 0, 0, 0.6);border-color:rgba(255, 255, 255, 0.1)}.button-spinner{width:16px;height:16px;border:2px solid rgba(0, 0, 0, 0.2);border-top:2px solid #333333;border-radius:50%;animation:spin 1s linear infinite;display:inline-block;margin-right:8px;vertical-align:middle}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.camera-selector-dropdown{position:absolute;top:56px;right:16px;z-index:30;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;min-width:260px;max-width:300px;border:1px solid rgba(255, 255, 255, 0.1);overflow:hidden;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-8px) scale(0.95)}100%{opacity:1;transform:translateY(0) scale(1)}}@keyframes slideInFromTopCentered{0%{opacity:0;transform:translate(-50%, -50%) translateY(-8px) scale(0.95)}100%{opacity:1;transform:translate(-50%, -50%) translateY(0) scale(1)}}.camera-selector-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid rgba(255, 255, 255, 0.1)}.camera-selector-header span{font-weight:500;color:#ffffff;font-size:13px;opacity:0.9}.close-selector{width:20px;height:20px;border:none;background:none;color:rgba(255, 255, 255, 0.7);font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all 0.2s ease}.close-selector:hover{background:rgba(255, 255, 255, 0.1);color:#ffffff}.camera-list{padding:4px 0;max-height:240px;overflow-y:auto}.camera-option{width:100%;padding:8px 12px;border:none;background:none;text-align:left;cursor:pointer;transition:all 0.2s ease;display:flex;justify-content:flex-start;align-items:center;gap:8px;color:rgba(255, 255, 255, 0.9)}.camera-option:hover{background:rgba(255, 255, 255, 0.08)}.camera-option.selected{background:rgba(255, 255, 255, 0.12);color:#ffffff}.camera-label{font-size:13px;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-right:0;font-weight:400;display:flex;align-items:center;gap:6px}.camera-label .autofocus-icon{font-size:12px;color:#ffffff !important;opacity:0.8;flex-shrink:0}.selected-indicator{font-size:14px;color:#ffffff;opacity:0.9;flex-shrink:0}.device-info{padding:6px 12px;border-top:1px solid rgba(255, 255, 255, 0.1);background:rgba(255, 255, 255, 0.05)}.device-info small{color:rgba(255, 255, 255, 0.6);font-size:11px;text-transform:capitalize;font-weight:400}@media (max-width: 480px){.camera-controls{top:12px;right:12px;gap:6px}.camera-selector-button{height:36px;padding:0 12px;font-size:11px;border-radius:6px}.camera-selector-dropdown{right:12px;top:48px;min-width:240px;max-width:calc(100vw - 24px)}.camera-selector-header{padding:6px 10px}.camera-option{padding:6px 10px}.device-info{padding:4px 10px}}.watermark{position:absolute;bottom:12px;right:12px;z-index:15;pointer-events:none;opacity:0.7}.watermark img{height:24px;width:auto;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))}.component-status{position:absolute;top:16px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);display:flex;align-items:center;gap:6px;padding:6px 10px;z-index:40;height:32px;width:fit-content;animation:slideInFromTop 0.3s ease-out}.status-spinner{width:16px;height:16px;border:1px solid rgba(255, 255, 255, 0.3);border-top:1px solid #ffffff;border-radius:50%;animation:statusSpin 1s linear infinite;flex-shrink:0}.status-content{display:flex;flex-direction:column;gap:1px}.status-message{color:#ffffff;font-size:12px;font-weight:500;margin:0}.status-description{color:rgba(255, 255, 255, 0.7);font-size:10px;line-height:1.2;margin:0}@keyframes statusSpin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@media (max-width: 480px){.component-status{top:12px;left:12px;padding:4px 8px;gap:4px;height:28px;border-radius:8px}.status-spinner{width:14px;height:14px}.status-message{font-size:11px}.status-description{font-size:9px}.guide-text{font-size:11px;padding:4px 8px;border-radius:8px}}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.85);backdrop-filter:blur(4px);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:8px}.loading-spinner{width:50px;height:50px;border:3px solid rgba(255, 255, 255, 0.15);border-top:3px solid #28a745;border-radius:50%;animation:spin 1s ease-in-out infinite;margin-bottom:16px}.loading-text{color:#ffffff;font-size:14px;font-weight:500;text-align:center;opacity:0.9;margin-bottom:4px}.loading-description{color:rgba(255, 255, 255, 0.7);font-size:12px;text-align:center;opacity:0.8}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.performance-monitor{position:absolute;top:70px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromTop 0.3s ease-out;transition:all 0.3s ease}@keyframes slideInFromLeft{0%{opacity:0;transform:translateX(-20px) scale(0.95)}100%{opacity:1;transform:translateX(0) scale(1)}}.performance-expanded{padding:6px 10px}.metrics-row{display:flex;gap:8px;margin-bottom:4px}.metrics-row:last-child{margin-bottom:0}.metric-compact{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:50px}.metric-label{font-size:9px;color:rgba(255, 255, 255, 0.6);font-weight:500;text-transform:uppercase;letter-spacing:0.3px}.metric-value{font-size:10px;font-weight:600;font-family:'Monaco', 'Menlo', 'Consolas', monospace;padding:2px 4px;border-radius:3px;text-align:center;white-space:nowrap}.metric-value.good{color:#4ade80;background:rgba(74, 222, 128, 0.1);border:1px solid rgba(74, 222, 128, 0.2)}.metric-value.warning{color:#fbbf24;background:rgba(251, 191, 36, 0.1);border:1px solid rgba(251, 191, 36, 0.2)}.metric-value.danger{color:#f87171;background:rgba(248, 113, 113, 0.1);border:1px solid rgba(248, 113, 113, 0.2)}@media (max-width: 480px){.performance-monitor{top:60px;left:12px;width:fit-content}.performance-expanded{padding:4px 8px}.metrics-row{gap:6px;margin-bottom:3px}.metric-compact{min-width:45px;gap:1px}.metric-label{font-size:8px}.metric-value{font-size:9px;padding:1px 3px}}.quality-monitor{position:absolute;top:200px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromLeft 0.3s ease-out;transition:all 0.3s ease}.quality-text{padding:6px 10px;font-size:11px;color:white;font-family:'Monaco', 'Menlo', 'Consolas', monospace;line-height:1.4}.quality-fail{color:#ff9999}@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.7}}.metric-value.danger{animation:pulse 2s infinite}@media (max-width: 480px){.quality-monitor{top:160px;left:12px}.quality-text{padding:4px 8px;font-size:10px}}.manual-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.manual-capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.manual-capture-button:hover{background:#f8f9fa}.manual-capture-button:active{background:#e9ecef;transform:translateY(1px)}.manual-capture-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}@media (max-width: 480px){.manual-capture-section{bottom:16px;max-width:280px}.manual-capture-button{padding:10px 20px;font-size:13px}.manual-capture-button:disabled{opacity:0.7 !important;cursor:not-allowed !important}}.license-error-container{display:flex;align-items:center;justify-content:center;padding:40px 20px;height:100%;width:100%;background:#f5f7fa;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif}.license-error-card{background:#ffffff;border-radius:8px;box-shadow:0 2px 12px rgba(0, 0, 0, 0.1);max-width:480px;width:100%;padding:48px 32px;text-align:center}.license-error-icon{color:#dc3545;margin-bottom:24px}.license-error-title{color:#2c3e50;font-size:24px;font-weight:600;margin:0 0 16px 0}.license-error-message{color:#495057;font-size:16px;line-height:1.6;margin:0 0 24px 0}.license-error-help{color:#6c757d;font-size:14px;margin:0 0 32px 0}.license-error-help a{color:#007bff;text-decoration:none;font-weight:500}.license-error-help a:hover{text-decoration:underline}.license-error-footer{color:#adb5bd;font-size:12px;font-weight:500;padding-top:24px;border-top:1px solid #e9ecef}@media (max-width: 640px){.license-error-card{padding:32px 24px}.license-error-title{font-size:20px}.license-error-message{font-size:14px}}";const Su=class{constructor(i){t(this,i);this.captureCompleted=e(this,"captureCompleted");this.isReady=e(this,"isReady");this.traceIdGenerated=e(this,"traceIdGenerated")}get el(){return i(this)}debug=false;alignmentTolerance=15;maskSize=90;cropMargin=20;useDocumentClassification=false;useDocumentDetector=true;preferredCamera="auto";captureDelay=1500;enableBackDocumentTimer=false;backDocumentTimerDuration=20;telemetryCollectorUrl="https://collector.jaak.ai/v1/traces";metricsCollectorUrl="https://collector.jaak.ai/v1/metrics";enableTelemetry=true;enableMetrics=true;customerId;tenantId;environment="production";propagateTraceHeaderCorsUrls;metricsExportIntervalMillis=6e4;license;licenseEnvironment="prod";traceId;appId="jaak-stamps-web";captureCompleted;isReady;traceIdGenerated;detectionBoxes=[];sideAlignment={top:false,right:false,bottom:false,left:false};isMaskReady=false;shouldMirrorVideo=true;showCameraSelector=false;isSwitchingCamera=false;hasDocumentDetected=false;cameraInfoWithAutofocus={availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null};currentStatus={message:"Preparando capturador...",description:"Configurando herramientas de captura",type:"initializing",isInitialized:false};performanceData={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0};backDocumentTimerRemaining=0;showManualCaptureButton=false;performanceDegradedMode=false;showPerformanceMessage=false;captureStateVersion=0;processingButton=null;licenseValid=true;licenseError=null;classificationDisabled=false;licenseValidationService=null;serviceContainer;eventBus;stateManager;cameraService;detectionService;tracingService;metricsService;videoRef;detectionContainer;videoStream;animationId;lastDetectedBox;startTime;hasScreenshotTaken=false;alignmentStartTime;alignmentTimer;backDocumentTimer;orientationTimer;performanceMetrics={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0,lastUpdateTime:0};performanceUpdateInterval;frameSkipCounter=0;BASE_FRAME_SKIP=2;MAX_FRAME_SKIP=8;consecutiveFailures=0;MAX_FAILURES=30;lastInferenceTime=0;MIN_INFERENCE_INTERVAL=50;MOBILE_MIN_INFERENCE_INTERVAL=100;performanceHistory=[];PERFORMANCE_HISTORY_SIZE=10;PERFORMANCE_THRESHOLD_MS=2e3;SLOW_FRAMES_TO_TRIGGER=2;slowFrameCount=0;processedFramesCount=0;hasAutoSwitchedToManual=false;_manualModeLoggedOnce=false;canvasPool=[];MAX_CANVAS_POOL_SIZE=3;async componentWillLoad(){if(this.debug){console.log("[JAAK-DEBUG] componentWillLoad() - Props at initialization:");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector,"(type:",typeof this.useDocumentDetector,")");console.log("[JAAK-DEBUG] useDocumentClassification:",this.useDocumentClassification);console.log("[JAAK-DEBUG] debug:",this.debug);console.log("[JAAK-DEBUG] license:",this.license?this.license.substring(0,8)+"...":"EMPTY");console.log("[JAAK-DEBUG] licenseEnvironment:",this.licenseEnvironment);console.log("[JAAK-DEBUG] alignmentTolerance:",this.alignmentTolerance);console.log("[JAAK-DEBUG] maskSize:",this.maskSize);console.log("[JAAK-DEBUG] captureDelay:",this.captureDelay);console.log("[JAAK-DEBUG] preferredCamera:",this.preferredCamera);console.log("[JAAK-DEBUG] appId:",this.appId)}await new Promise((t=>setTimeout(t,50)));if(this.debug){console.log("[JAAK-DEBUG] Props AFTER 50ms wait:");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector,"(type:",typeof this.useDocumentDetector,")")}this.updateStatus("Validando licencia...","Verificando autorización de uso","initializing");await this.validateLicense();if(!this.licenseValid){if(this.debug){console.error("[JAAK-DEBUG] License validation FAILED. Stopping initialization.")}return}if(this.debug){console.log("[JAAK-DEBUG] License validation OK")}}async componentDidLoad(){try{if(!this.licenseValid){return}this.updateStatus("Preparando capturador...","Configurando herramientas de captura","initializing");await this.initializeServices();this.updateStatus("Preparando funciones...","Configurando herramientas de trabajo","initializing");await this.setupEventListeners();this.updateStatus("Configurando cámara...","Detectando dispositivos disponibles","initializing");await this.initializeComponent();if(this.debug){this.initializePerformanceMonitor()}}catch(t){this.updateStatus("Error de inicialización",t.message,"error")}}async initializeServices(){const t=this.propagateTraceHeaderCorsUrls?this.propagateTraceHeaderCorsUrls.split(",").map((t=>t.trim())):[];const e={debug:this.debug,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,cropMargin:this.cropMargin,useDocumentClassification:this.useDocumentClassification,useDocumentDetector:this.useDocumentDetector,preferredCamera:this.preferredCamera,captureDelay:this.captureDelay,telemetryCollectorUrl:this.telemetryCollectorUrl,metricsCollectorUrl:this.metricsCollectorUrl,enableTelemetry:this.enableTelemetry,enableMetrics:this.enableMetrics,customerId:this.customerId,tenantId:this.tenantId,environment:this.environment,propagateTraceHeaderCorsUrls:t,metricsExportIntervalMillis:this.metricsExportIntervalMillis};this.serviceContainer=new yu(e);this.eventBus=this.serviceContainer.getEventBus();this.stateManager=this.serviceContainer.getStateManager();this.cameraService=this.serviceContainer.getCameraService();this.detectionService=this.serviceContainer.getDetectionService();this.tracingService=this.serviceContainer.getTracingService();this.metricsService=this.serviceContainer.getMetricsService();if(this.tracingService&&this.traceId){this.tracingService.setSessionTraceId(this.traceId)}if(this.tracingService){const t=this.tracingService.startSpan("component.initialize",{"component.debug":this.debug,"component.useDocumentDetector":this.useDocumentDetector,"component.useDocumentClassification":this.useDocumentClassification});this.tracingService.endSpan(t)}}async validateLicense(){if(!this.license){console.error("❌ No license provided for JAAK Stamps component");this.licenseError='Este componente requiere una licencia válida. Por favor, proporcione una licencia usando el atributo "license".';this.licenseValid=false;this.updateStatus("Error de licencia","Licencia no proporcionada","error");return}try{console.log("🔑 Validating license for JAAK Stamps...");this.licenseValidationService=new xu(this.licenseEnvironment);const t=await this.licenseValidationService.validateLicense(this.license,this.traceId,this.appId);if(t&&t.access_token){this.licenseValid=true;this.licenseError=null;console.log("✅ License validated successfully for JAAK Stamps");if(t.traceId){this.traceIdGenerated.emit({traceId:t.traceId});console.log("📋 TraceId:",t.traceId)}}else{this.licenseValid=false;this.licenseError="La licencia proporcionada no es válida. Por favor, verifique su licencia e intente nuevamente.";this.updateStatus("Error de licencia","Licencia inválida","error");console.error("❌ Invalid license for JAAK Stamps")}}catch(t){this.licenseValid=false;const e=t;this.licenseError=e.error_description||"Error al validar la licencia. Por favor, verifique su conexión e intente nuevamente.";this.updateStatus("Error de licencia","Fallo en la validación","error");console.error("❌ License validation failed for JAAK Stamps:",t)}}async setupEventListeners(){this.eventBus.on("state-changed",(()=>{this.handleStateChange()}))}async initializeComponent(){this.validateProps();if(this.debug){this.stateManager.updateCaptureState({isLoading:true});await new Promise((t=>setTimeout(t,500)))}this.updateStatus("Detectando cámaras...","Buscando dispositivos de captura","initializing");await this.cameraService.detectDeviceType();await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","initializing");await this.loadOnnxRuntime();this.initializeResizeObserver()}validateProps(){if(this.maskSize<50||this.maskSize>100){this.maskSize=90}if(this.cropMargin<0||this.cropMargin>100){this.cropMargin=0}const t=["auto","front","back"];if(!t.includes(this.preferredCamera)){this.preferredCamera="auto"}if(this.captureDelay<0||this.captureDelay>1e4){this.captureDelay=1500}}async loadOnnxRuntime(){if(!window.ort){this.updateStatus("Preparando herramientas...","Configurando funciones de captura","initializing");const t=document.createElement("script");const e=navigator.userAgent;const i=/iPad|iPhone|iPod/.test(e);if(i){t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.wasm.min.js"}else{t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"}document.head.appendChild(t);await new Promise((e=>{t.onload=()=>{if(i&&window.ort?.env){const t=window.ort;t.env.wasm.simd=false;t.env.wasm.numThreads=1;t.env.wasm.proxy=false}setTimeout((async()=>{await this.finalizeInitialization();e(undefined)}),300)}}))}else{setTimeout((async()=>{await this.finalizeInitialization()}),300)}}async finalizeInitialization(){this.stateManager.updateCaptureState({isLoading:false});const t=await this.checkCameraPermissions();if(t){this.currentStatus={message:"Listo para capturar",description:"",type:"ready",isInitialized:true}}else{this.currentStatus={message:"Permisos de cámara requeridos",description:"Por favor, otorgue permisos de cámara para continuar",type:"error",isInitialized:true}}this.emitReadyEvent()}updateStatus(t,e,i="loading"){this.currentStatus={message:t,description:e,type:i,isInitialized:this.currentStatus.isInitialized}}emitReadyEvent(){const t=!!window.ort&&this.detectionService.isModelLoaded();this.isReady.emit(t)}async checkCameraPermissions(){try{if(!navigator.permissions){try{const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()));return true}catch{return false}}const t=await navigator.permissions.query({name:"camera"});return t.state==="granted"}catch(t){return false}}handleStateChange(){}initializeResizeObserver(){if("ResizeObserver"in window&&this.detectionContainer){const t=new ResizeObserver((()=>{this.handleResize()}));t.observe(this.detectionContainer.parentElement)}window.addEventListener("orientationchange",(()=>{if(this.orientationTimer){clearTimeout(this.orientationTimer)}this.orientationTimer=window.setTimeout((()=>{this.handleResize();this.orientationTimer=undefined}),300)}))}handleResize(){if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}}triggerRerender(){this.captureStateVersion=this.captureStateVersion+1}getGuideText(t){if(t==="completed"){return"Proceso completado"}if(this.showPerformanceMessage&&t==="front"){return"Modo manual activado por rendimiento. Use el botón para capturar."}if(t==="front"){if(this.showManualCaptureButton){return"Posicione el frente de su documento en el marco y presione el botón para capturar"}return"Alinee su identificación con el marco"}else if(t==="back"){if(this.useDocumentDetector){return"Si tu documento no tiene lado trasero, da clic en el botón para continuar con el proceso"}else{return"Posicione el reverso de su documento en el marco y capture, o salte este paso"}}return"Alinee su identificación con el marco"}updateMaskDimensions(t){if(!this.videoRef)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;if(e===0||i===0)return;const r=e/i;const n=t.width/t.height;let s,o;let a=0,c=0;if(r>n){s=t.width;o=t.width/r;c=(t.height-o)/2}else{o=t.height;s=t.height*r;a=(t.width-s)/2}const u=85.6/53.98;const l=o*u;let f,h;const d=this.maskSize/100;if(l<=s){h=o*d;f=h*u}else{f=s*d;h=f/u}const p=f/t.width*100;const m=h/t.height*100;const b=a+s/2;const v=c+o/2;const w=b/t.width*100;const g=v/t.height*100;this.el.style.setProperty("--mask-width",`${p}%`);this.el.style.setProperty("--mask-height",`${m}%`);this.el.style.setProperty("--mask-center-x",`${w}%`);this.el.style.setProperty("--mask-center-y",`${g}%`);this.isMaskReady=true}isComponentReady(){if(!this.currentStatus.isInitialized){return{ready:false,message:"El componente aún se está inicializando",status:"initializing"}}if(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing"){return{ready:false,message:"El componente está cargando recursos",status:"loading"}}if(!this.serviceContainer||!this.stateManager||!this.cameraService||!this.detectionService){return{ready:false,message:"Los servicios del componente no están disponibles",status:"error"}}return{ready:true}}async getCapturedImages(){const t=this.isComponentReady();if(!t.ready){throw new Error(t.message)}const e=this.stateManager.getCaptureState();if(e.step!=="completed"){throw new Error("El proceso de captura no ha sido completado")}return this.stateManager.getCapturedImages()}async isProcessCompleted(){const t=this.isComponentReady();if(!t.ready){return false}return this.stateManager.isProcessCompleted()}async startCapture(){const t=this.tracingService?.startSpan("capture.start");const e=this.isComponentReady();if(!e.ready){this.updateStatus(e.message,"Espere a que termine la inicialización",e.status);if(t){this.tracingService?.setSpanAttribute(t,"error",true);this.tracingService?.setSpanAttribute(t,"error.message",e.message);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}try{await this.startDetection();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true}}catch(e){this.updateStatus("Error al iniciar captura",e.message,"error");if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async stopCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.exitSession();return{success:true}}catch(t){return{success:false,error:t.message}}}async resetCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.resetDetection();return{success:true}}catch(t){return{success:false,error:t.message}}}async skipBackCapture(){console.log("🟡 Botón clicked: Saltar reverso");this.processingButton="skip-back";await new Promise((t=>setTimeout(t,100)));const t=this.isComponentReady();if(!t.ready){this.processingButton=null;return{success:false,error:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();if(t.step==="back"&&e.front.fullFrame){this.completeProcess(true);return{success:true}}else{return{success:false,error:"No se puede saltar el reverso en el estado actual"}}}catch(t){return{success:false,error:t.message}}finally{this.processingButton=null}}async getStatus(){const t=this.isComponentReady();if(!t.ready){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:t.status,componentMessage:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();return{isVideoActive:t.isVideoActive,captureStep:t.step,hasImages:!!(e.front.fullFrame||e.back.fullFrame),isProcessCompleted:this.stateManager.isProcessCompleted(),isModelPreloaded:this.detectionService.isModelLoaded(),componentStatus:"ready"}}catch(t){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:"error",componentMessage:t.message}}}async preloadModel(){const t=this.tracingService?.startSpan("model.preload");const e=this.isComponentReady();if(!e.ready){this.updateStatus(e.message,"Espere a que termine la inicialización",e.status);if(t){this.tracingService?.setSpanAttribute(t,"error",true);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}if(this.detectionService.isModelLoaded()){this.updateStatus("Reconocimiento listo","","ready");if(t){this.tracingService?.setSpanAttribute(t,"cached",true);this.tracingService?.endSpan(t)}return{success:true,message:"Model already loaded"}}try{const e=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:true})}try{const t=performance.now();const e=this.tracingService?.startSpan("model.detection.load");await this.detectionService.loadModel();if(e)this.tracingService?.endSpan(e);const i=performance.now()-t;this.metricsService?.recordModelLoad("detection",i,false)}catch(t){this.metricsService?.recordError("model_load_failed","detection");this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");try{const t=performance.now();const e=this.tracingService?.startSpan("model.classification.load");await this.detectionService.loadClassificationModel();if(e)this.tracingService?.endSpan(e);const i=performance.now()-t;this.metricsService?.recordModelLoad("classification",i,false)}catch(t){this.metricsService?.recordError("model_load_failed","classification");this.switchToManualModeWithError("Error al cargar modelo de clasificación");throw t}const i=performance.now();const r=i-e;if(this.debug){this.recordOnnxPerformance(r,0)}if(t){this.tracingService?.setSpanAttribute(t,"loadTime",r)}this.updateStatus("Finalizando configuración...","Preparando herramientas para captura","loading");await new Promise((t=>setTimeout(t,300)));this.updateStatus("Reconocimiento preparado","","ready");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}this.emitReadyEvent();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true,message:"Models preloaded successfully"}}catch(e){this.updateStatus("Error de configuración","No se pudieron preparar las herramientas necesarias","error");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async getCameraInfo(){const t=this.isComponentReady();if(!t.ready){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}try{return await this.cameraService.getCameraInfo()}catch(t){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}}async setPreferredCamera(t){const e=this.isComponentReady();if(!e.ready){return{success:false,error:e.message,selectedCamera:null,availableCameras:0}}try{this.preferredCamera=t;this.serviceContainer.updateConfig({preferredCamera:t});await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();const e=this.stateManager.getCaptureState();if(e.isVideoActive){const t=this.cameraService.getSelectedCameraId();if(t){await this.cameraService.switchCamera(t)}}return{success:true,selectedCamera:this.cameraService.getSelectedCameraId(),availableCameras:this.cameraService.getAvailableCameras().length}}catch(t){return{success:false,error:t.message,selectedCamera:null,availableCameras:0}}}async setCaptureDelay(t){if(t<0||t>1e4){return{success:false,error:"Capture delay must be between 0 and 10000 milliseconds",captureDelay:this.captureDelay}}this.captureDelay=t;if(this.serviceContainer){this.serviceContainer.updateConfig({captureDelay:t})}return{success:true,captureDelay:this.captureDelay}}async getCaptureDelay(){return this.captureDelay}checkDeviceCapabilities(){const t=navigator.deviceMemory;return{canUseML:true,reason:"Dispositivo compatible con detección automática.",memoryMB:t?t*1024:null}}async startDetection(){try{if(this.debug){console.log("[JAAK-DEBUG] startDetection() called");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector);console.log("[JAAK-DEBUG] useDocumentClassification:",this.useDocumentClassification)}const t=this.checkDeviceCapabilities();if(this.debug){console.log("[JAAK-DEBUG] Device capabilities:",JSON.stringify(t))}if(!t.canUseML&&this.useDocumentDetector){if(this.debug){console.warn("[JAAK-DEBUG] MANUAL MODE: Device cannot use ML. Reason:",t.reason)}this.switchToManualModeWithWarning(t.reason);return}if(!this.detectionService.isModelLoaded()){const t=performance.now();if(this.debug){console.log("[JAAK-DEBUG] Loading detection model...")}this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");this.stateManager.updateCaptureState({isLoading:true});try{await this.detectionService.loadModel();if(this.debug){console.log("[JAAK-DEBUG] Detection model loaded successfully in",(performance.now()-t).toFixed(0),"ms")}}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";if(this.debug){console.warn("[JAAK-DEBUG] MANUAL MODE: Out of memory loading detection model.",t)}this.switchToManualModeWithWarning(`Memoria insuficiente para detección automática ${t}. Modo manual activado - funciona igual de bien!`);return}else{if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Error loading detection model:",t.message)}this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");if(this.debug){console.log("[JAAK-DEBUG] Loading classification model...")}try{await this.detectionService.loadClassificationModel();if(this.debug){console.log("[JAAK-DEBUG] Classification model loaded successfully")}}catch(t){if(this.debug){console.warn("[JAAK-DEBUG] Classification model failed to load, disabling classification. Error:",t.message)}this.classificationDisabled=true}const e=performance.now();const i=e-t;if(this.debug){console.log("[JAAK-DEBUG] All models loaded in",i.toFixed(0),"ms");this.recordOnnxPerformance(i,0)}}else{if(this.debug){console.log("[JAAK-DEBUG] Models already loaded, skipping load")}}this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}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()){if(this.debug){console.log("[JAAK-DEBUG] detectFrame() skipped: videoRef=",!!this.videoRef,"detectionContainer=",!!this.detectionContainer,"modelLoaded=",this.detectionService.isModelLoaded())}return}if(!this.useDocumentDetector||this.performanceDegradedMode){if(this.debug&&!this._manualModeLoggedOnce){console.warn("[JAAK-DEBUG] detectFrame() in MANUAL MODE: useDocumentDetector=",this.useDocumentDetector,"performanceDegradedMode=",this.performanceDegradedMode);this._manualModeLoggedOnce=true}this.showManualCaptureButton=true;if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}else if(!this.performanceDegradedMode){this.showManualCaptureButton=false}if(e.isDetectionPaused){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter++;const i=this.getAdaptiveFrameSkip();if(this.frameSkipCounter<=i){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter=0;const r=Date.now();const n=this.cameraInfoWithAutofocus.deviceType==="mobile"||/Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);const s=this.cameraInfoWithAutofocus.deviceType==="tablet"||/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const o=n&&!s?this.MOBILE_MIN_INFERENCE_INTERVAL:this.MIN_INFERENCE_INTERVAL;if(r-this.lastInferenceTime<o){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.lastInferenceTime=r;const a=performance.now();let c;let u;let l;try{c=this.detectionService.preprocess(this.videoRef)}catch(t){if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Preprocess error:",t.message)}this.switchToManualModeWithError("Error al procesar imagen");return}try{u=await this.detectionService.runInference(c);l=performance.now()-a}catch(t){if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Inference error:",t.message)}this.switchToManualModeWithError("Error en detección automática");return}this.processedFramesCount++;if(this.debug){this.recordOnnxPerformance(0,l)}if(this.startTime&&Date.now()-this.startTime<5e3){u.forEach((t=>{const i=this.detectionService.isCardInFrame(t);const r=i?t.score*1.2:t.score;if(r>e.bestScore){this.stateManager.updateCaptureState({bestScore:r})}}))}const f=this.hasDocumentDetected;this.hasDocumentDetected=u.length>0;if(!f&&this.hasDocumentDetected&&e.step==="back"&&this.enableBackDocumentTimer){this.startBackDocumentTimer()}if(u.length===0){this.consecutiveFailures++}else{this.consecutiveFailures=0}if(this.debug){this.updateDetectionBoxes(u)}else{this.detectionBoxes=[]}this.updateMaskColor(u);const h=performance.now();const d=h-t;if(this.useDocumentDetector&&!this.hasAutoSwitchedToManual){if(this.debug){console.log(`[JAAK-DEBUG] Frame #${this.processedFramesCount} time: ${d.toFixed(0)}ms (threshold: ${this.PERFORMANCE_THRESHOLD_MS}ms) | inference: ${l.toFixed(0)}ms | slowFrames: ${this.slowFrameCount}/${this.SLOW_FRAMES_TO_TRIGGER}`)}if(d>=this.PERFORMANCE_THRESHOLD_MS){this.slowFrameCount++;if(this.debug){console.warn(`[JAAK-DEBUG] SLOW FRAME detected: ${d.toFixed(0)}ms >= ${this.PERFORMANCE_THRESHOLD_MS}ms | slowFrameCount: ${this.slowFrameCount}/${this.SLOW_FRAMES_TO_TRIGGER}`)}if(this.slowFrameCount>=this.SLOW_FRAMES_TO_TRIGGER){if(this.debug){console.error(`[JAAK-DEBUG] MANUAL MODE: Performance degraded. ${this.slowFrameCount} slow frames (>= ${this.PERFORMANCE_THRESHOLD_MS}ms) exceeded threshold of ${this.SLOW_FRAMES_TO_TRIGGER}`)}this.switchToManualMode()}}else{if(this.slowFrameCount>0){if(this.debug){console.log(`[JAAK-DEBUG] Fast frame, resetting slowFrameCount from ${this.slowFrameCount} to 0`)}this.slowFrameCount=0}}if(this.processedFramesCount===2){this.updateStatus("Captura activa","Buscando documento en el marco de captura","active")}}if(this.debug){this.recordFrameProcessing(d,u.length)}if(e.step!=="completed"){if(this.consecutiveFailures>this.MAX_FAILURES){setTimeout((()=>this.detectFrame()),200)}else{this.animationId=requestAnimationFrame((()=>this.detectFrame()))}}}catch(t){const e=this.stateManager.getCaptureState();if(e.step!=="completed"){setTimeout((()=>this.detectFrame()),100)}}}disconnectedCallback(){this.cleanup()}cleanup(){if(this.animationId){cancelAnimationFrame(this.animationId)}if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(this.orientationTimer){clearTimeout(this.orientationTimer);this.orientationTimer=undefined}this.releaseOnnxResources();if(this.performanceUpdateInterval){clearInterval(this.performanceUpdateInterval);this.performanceUpdateInterval=undefined}this.canvasPool=[];this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.serviceContainer?.cleanup()}render(){const t=this.stateManager?.getCaptureState()||{isVideoActive:false,showFlipAnimation:false,showSuccessAnimation:false,step:"front",isCapturing:false};const e=this.cameraInfoWithAutofocus;return r("div",{key:"9f2c1f21e7c18a77f519444bad87d29b2dfd2e6c",class:"detector-container"},!this.licenseValid&&this.licenseError&&r("div",{key:"d2965c6d859e8dd36f6a883288f086b9a39f236d",class:"license-error-container"},r("div",{key:"0db457c58ba390892ecc1046f410f35781d534fb",class:"license-error-card"},r("svg",{key:"9d5bb7a635157c8515323e0506f5f5add50e07dc",class:"license-error-icon",width:"64",height:"64",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r("path",{key:"938b6fd1b4c3f574c47d1678a87db8db7053945c",d:"M12 22C12 22 20 18 20 12V5L12 2L4 5V12C4 18 12 22 12 22Z",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}),r("path",{key:"8e5eb1966fa88e7f0a6f799cd8ce96fc86f0c291",d:"M12 8V12",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"}),r("circle",{key:"d4f798caf065b269d9d246cd099499f9a9e86008",cx:"12",cy:"16",r:"0.5",fill:"currentColor",stroke:"currentColor","stroke-width":"1"})),r("h2",{key:"109fcd76d9b0c27f33f037ed1c16031a3e9a7966",class:"license-error-title"},"Licencia Requerida"),r("p",{key:"c4d582a8e950498c80980faf25d50d3dea71ee8e",class:"license-error-message"},this.licenseError),r("p",{key:"6b15b08047124e4cec49f8b6b02d5938c2071c9b",class:"license-error-help"},"Contacte a soporte: ",r("a",{key:"0a6fd5acce763c068fe2ae929e16a3b90223a4b5",href:"mailto:support@jaak.ai"},"support@jaak.ai")),r("div",{key:"bb7a438b6d8f506334086ee511c7deaa37ab59aa",class:"license-error-footer"},"JAAK Stamps"))),this.licenseValid&&r("div",{key:"1fd31d4721feb0c4cd8ff1621646d2b20211b22f",class:"video-container"},r("video",{key:"ec228d91b0e2a8e18a0acb898198983685c97572",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{display:t.isVideoActive?"block":"none"}}),r("div",{key:"e1711ea66777df0e482d93a82b82bff63c9fe9f0",ref:t=>this.detectionContainer=t,class:`detection-overlay ${this.shouldMirrorVideo?"mirror":""}`},this.debug&&this.detectionBoxes.map(((t,e)=>r("div",{key:e,class:"detection-box",style:{position:"absolute",left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,border:"2px solid #32406C",pointerEvents:"none",boxSizing:"border-box"}})))),this.isMaskReady&&r("div",{key:"00e7b7a30d95f72fff38d37dbad7715262f4bcbc",class:"overlay-mask"},r("div",{key:"7f2cefac16306c4db77145ff4a2e0c36bbf71b41",class:"card-outline"},r("div",{key:"6a160a7be2fa6b39a01af7e7ac26612439726a0d",class:"side side-top"}),r("div",{key:"33317ed5d33142557198e315796fe472915988e5",class:"side side-right"}),r("div",{key:"15428b208d96c70da90540ade83ea736829b6cfc",class:"side side-bottom"}),r("div",{key:"615e5c6cd8861921a314372aa522ce678b035297",class:"side side-left"})),!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"786fdc87ffc5977ccab04e201b68cca6624a3a75",class:`guide-text ${this.showPerformanceMessage?"performance-warning-text":""}`},this.getGuideText(t.step)),t.step==="back"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"87a0b3460776e267a6288800b4c27d790f874555",class:"back-capture-section"},r("div",{key:"f75551d152bc5f1b41d56daaa44c360d42b3c6d7",class:"back-capture-buttons"},(!this.useDocumentDetector||this.performanceDegradedMode||this.showManualCaptureButton)&&r("button",{key:"798801b00d7be739db78267224193a64813c92be",class:"capture-button primary-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-back"&&r("span",{key:"14ecf72110b1583bd8c4e75f669cd8c71c01d074",class:"button-spinner"}),"Capturar Reverso"),r("button",{key:"ed12d7774f8399244913c468e118a6a9d9a6888b",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button",disabled:this.processingButton!==null},this.processingButton==="skip-back"&&r("span",{key:"e75d2a3da9167050fd315b27871eff612f6954ff",class:"button-spinner"}),this.enableBackDocumentTimer&&this.backDocumentTimerRemaining>0?`Saltar reverso (${this.backDocumentTimerRemaining}s)`:"Saltar reverso"))),t.isVideoActive&&r("div",{key:"019fdafddac5d9ad093f7d0adaf0f9dda29c8944",class:"camera-controls"},r("button",{key:"dbdeac63de4cf5f09f12b1757e87fc5c5c21fc29",class:`camera-selector-button ${this.isSwitchingCamera?"loading":""}`,onClick:()=>this.toggleCameraSelector(),type:"button",title:"Seleccionar cámara",disabled:this.isSwitchingCamera},this.isSwitchingCamera?r("div",{class:"button-spinner"}):"Cámaras")),this.showCameraSelector&&e.availableCameras.length>0&&r("div",{key:"c62b8914fba9dec18ddcecfeccb1cbe0ec59fae2",class:"camera-selector-dropdown"},r("div",{key:"9a1861c72c2ae75cced3a13b4e3cce28f2f2eff3",class:"camera-selector-header"},r("span",{key:"f4d20f3efe85bf727d3cc7bb380b9fa53bfd00e8"},"Seleccionar Cámara"),r("button",{key:"2cae8c595fff51108c9a17786350cc42a129bb88",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),r("div",{key:"643dbb27c6f52372819b9d2daf4b5f2ed67b5dc3",class:"camera-list"},e.availableCameras.map((t=>r("button",{key:t.id,class:`camera-option ${e.selectedCameraId===t.id?"selected":""}`,onClick:()=>this.handleCameraSwitch(t.id),type:"button"},r("span",{class:"camera-label"},t.label||`Cámara ${e.availableCameras.indexOf(t)+1}`,t.hasAutofocus&&r("span",{class:"autofocus-icon",title:"Autofoco disponible"},"⦿")),e.selectedCameraId===t.id&&r("span",{class:"selected-indicator"},"✓"))))),r("div",{key:"750fe47a0ae0eb1802b3126d8e49e6b8ad536879",class:"device-info"},r("small",{key:"a6fa21c1ae530708f830c17774e226c8f06d8b96"},"Dispositivo: ",e.deviceType))),this.showManualCaptureButton&&t.step==="front"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"a2f91224f2166eb3a8962ba581196d64c7cec2cb",class:"manual-capture-section"},r("button",{key:"4ce9090a4ed8e0346463ab0a77502a25990a2512",class:"manual-capture-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-front"&&r("span",{key:"4e9b12bdc735e86faadcf521083d42080f230183",class:"button-spinner"}),"Capturar Frente"))),t.isCapturing&&r("div",{key:"d275dd3d3f62cfa943efd2e69d6898981c34f547",class:"capture-animation"}),t.showFlipAnimation&&r("div",{key:"038cc4f1b245ff6fad917efb8d558e216de1771b",class:"flip-animation"},r("div",{key:"61d9097585ed53d9b2798d826aac274b9ea42390",class:"id-card-icon"}),r("div",{key:"90db95f234a9f25aae40d3b2c480e6dc1a580a84",class:"flip-text"},"¡Voltea tu identificación!")),t.showSuccessAnimation&&r("div",{key:"586ac9d2e89fdd4bf13610e31c43142c84f4d8c3",class:"success-animation"},r("div",{key:"8ed80578d1deacd808988d80d9677fb849267b1e",class:"check-icon"}),r("div",{key:"124615b15175f16946c0b3722fcf5a39b9ad4631",class:"success-text"},"¡Proceso completado!")),r("div",{key:"e587fd78705e91f5f3885e514f556288724bbc57",class:`component-status status-${this.currentStatus.type}`},(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing")&&r("div",{key:"a9a8afa7f3653586778acc95ccecd6927a0350c8",class:"status-spinner"}),r("div",{key:"db30d1bf772920b111e60ca22ff2fc8150e5d51f",class:"status-content"},r("div",{key:"3dc8912cc18fc61d2f42173e2605ef9e3b7f906a",class:"status-message"},this.currentStatus.message),this.currentStatus.description&&r("div",{key:"9025868961082897f19b1c230346a985ea3e0ca2",class:"status-description"},this.currentStatus.description))),this.debug&&r("div",{key:"8f18ba02911a3605ed88cb6f93926f9412289e56",class:"performance-monitor"},r("div",{key:"5531d873b7baed61d17f7b94106a7dd953e079c1",class:"performance-expanded"},r("div",{key:"af62b9f0dcfa3f4ecdc1925fe26d36a221d74afd",class:"metrics-row"},r("div",{key:"230c75005a1c8608d97486063b23897da676f9d6",class:"metric-compact"},r("span",{key:"48a28744a884124517e5ce55e0e47dd16c207a6f",class:"metric-label"},"FPS"),r("span",{key:"e6504c0075f9c730898dc5597a91475e99a5550f",class:`metric-value ${this.performanceData.fps<15?"warning":this.performanceData.fps<10?"danger":"good"}`},this.performanceData.fps)),r("div",{key:"df732632425cb06d47f14d18f2d87900f2ff293b",class:"metric-compact"},r("span",{key:"f32737c081480760714c3224749d67b4dffd6756",class:"metric-label"},"MEM"),r("span",{key:"d2d2ff4ed6721bfbc15bf20e41ea452b0a6f6670",class:`metric-value ${this.performanceData.memoryUsage>100?"warning":this.performanceData.memoryUsage>200?"danger":"good"}`},this.performanceData.memoryUsage,"MB"))),r("div",{key:"7d6333691cf92a12c8b2974b68756d2d59df4301",class:"metrics-row"},r("div",{key:"63f1b39293780e01c6119c14b46febf67ff58a89",class:"metric-compact"},r("span",{key:"84f4ed08009d3a2414c3a6e097c78b69d8854a3b",class:"metric-label"},"INF"),r("span",{key:"5512948dcebaadc442fe9161bc4ad05ae0960dbf",class:`metric-value ${this.performanceData.inferenceTime>100?"warning":this.performanceData.inferenceTime>200?"danger":"good"}`},this.performanceData.inferenceTime,"ms")),r("div",{key:"9e523d2a51c36d08748a4fa3c88f0aa48ad4482e",class:"metric-compact"},r("span",{key:"38593b6e84eadc87f129bfc3d5494845063c936a",class:"metric-label"},"FRAME"),r("span",{key:"5fcddc82c511360870875c1be5eaaedd1523eb20",class:`metric-value ${this.performanceData.frameProcessingTime>50?"warning":this.performanceData.frameProcessingTime>100?"danger":"good"}`},this.performanceData.frameProcessingTime,"ms"))),r("div",{key:"ea0ff4f807a7c70fce1938dd9b8036362855b547",class:"metrics-row"},r("div",{key:"929c04a5bee635a8de0e79208cd4c6fb47fb4120",class:"metric-compact"},r("span",{key:"5f3b500ede8ffcaf1c824cb0760f18d441dd4c1b",class:"metric-label"},"DET"),r("span",{key:"050ae9a0f52bc4614f35f16cf8d4f47e96b5d55b",class:"metric-value good"},this.performanceData.successfulDetections,"/",this.performanceData.totalDetections)),r("div",{key:"8cbee2808ec4355007a9c441495579235415f47b",class:"metric-compact"},r("span",{key:"769941a75abbc120289c6663d69d3f73c783d79e",class:"metric-label"},"RATE"),r("span",{key:"64b9954fd29a39bbf560833fdde393e4778fc6ec",class:`metric-value ${this.performanceData.detectionRate<30?"danger":this.performanceData.detectionRate<60?"warning":"good"}`},this.performanceData.detectionRate,"%"))))),r("div",{key:"bc87799947f87213ff5f781353aa948882bfdce3",class:"watermark"},r("img",{key:"8ddf884a54af69e548eea8619340ca83cc736acc",src:"https://static.jaak.ai/commons/powered-by-jaak.png",alt:"Powered by Jaak"}))))}updateDetectionBoxes(t){if(!this.videoRef||!this.detectionContainer)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;const r=this.detectionContainer.parentElement;const n=r.getBoundingClientRect();const s=n.width;const o=n.height;if(e===0||i===0)return;const a=e/i;const c=s/o;let u,l;let f=0,h=0;if(a>c){u=s;l=s/a;h=(o-l)/2}else{l=o;u=o*a;f=(s-u)/2}const d=320;const p=u/d;const m=l/d;this.detectionBoxes=t.map((t=>({x:t.x*p+f,y:t.y*m+h,w:t.w*p,h:t.h*m,score:t.score})))}updateMaskColor(t){const e=this.el.shadowRoot?.querySelector(".card-outline");const i=this.el.shadowRoot?.querySelectorAll(".corner");const r=this.el.shadowRoot?.querySelector(".side-top");const n=this.el.shadowRoot?.querySelector(".side-right");const s=this.el.shadowRoot?.querySelector(".side-bottom");const o=this.el.shadowRoot?.querySelector(".side-left");let a=null;let c={top:false,right:false,bottom:false,left:false};if(t.length>0){a=t.reduce(((t,e)=>e.score>t.score?e:t));const e={INPUT_SIZE:320,ID1_ASPECT_RATIO:85.6/53.98,shouldMirrorVideo:this.shouldMirrorVideo,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,videoRef:this.videoRef};c=this.detectionService.checkSideAlignment(a,e);this.sideAlignment=c}else{this.sideAlignment={top:false,right:false,bottom:false,left:false}}r?.classList.toggle("aligned",c.top);n?.classList.toggle("aligned",c.right);s?.classList.toggle("aligned",c.bottom);o?.classList.toggle("aligned",c.left);const u=this.detectionService.areAllSidesAligned(c);const l=this.stateManager.getCaptureState();if(l.step==="back"&&this.enableBackDocumentTimer&&a){const t=c.top||c.right||c.bottom||c.left;if(t){this.startBackDocumentTimer()}}if(u&&a){e?.classList.add("perfect-match");i?.forEach((t=>t.classList.add("perfect-match")));if(!this.hasScreenshotTaken){const t=Date.now();if(!this.alignmentStartTime){this.alignmentStartTime=t}const e=t-this.alignmentStartTime;if(e>=this.captureDelay){this.lastDetectedBox=a;this.takeScreenshot().catch((()=>{}));this.hasScreenshotTaken=true;this.alignmentStartTime=undefined;setTimeout((()=>{this.hasScreenshotTaken=false}),2e3)}}}else{e?.classList.remove("perfect-match");i?.forEach((t=>t.classList.remove("perfect-match")));if(this.alignmentStartTime){this.alignmentStartTime=undefined}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}}}async takeManualScreenshot(){console.log("🔵 Botón clicked: Capturar (Frente/Reverso)");const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.manual");const i=this.stateManager?.getCaptureState();const r=i?.step==="front"?"front":"back";if(i?.step==="front"){this.processingButton="capture-front";if(e)this.tracingService?.setSpanAttribute(e,"side","front")}else if(i?.step==="back"){this.processingButton="capture-back";if(e)this.tracingService?.setSpanAttribute(e,"side","back")}this.metricsService?.recordUserInteraction("manual_capture_button");console.log("🔵 processingButton set to:",this.processingButton);await new Promise((t=>setTimeout(t,100)));if(!this.videoRef){this.processingButton=null;if(e){this.tracingService?.setSpanAttribute(e,"error","no_video_ref");this.tracingService?.endSpan(e)}return}await this.takeScreenshotWithMaskCoordinates();const n=performance.now()-t;this.metricsService?.recordCapture(r,"manual",n);if(e){this.tracingService?.setSpanAttribute(e,"success",true);this.tracingService?.endSpan(e)}}async takeScreenshotWithMaskCoordinates(){if(!this.videoRef||!this.detectionContainer)return;this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const t=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const e=t.getContext("2d",{alpha:false});e.clearRect(0,0,t.width,t.height);e.drawImage(this.videoRef,0,0,t.width,t.height);const i=this.detectionContainer.parentElement;const r=i.getBoundingClientRect();const n=parseFloat(this.el.style.getPropertyValue("--mask-width").replace("%",""))||90;const s=parseFloat(this.el.style.getPropertyValue("--mask-height").replace("%",""))||56.25;const o=parseFloat(this.el.style.getPropertyValue("--mask-center-x").replace("%",""))||50;const a=parseFloat(this.el.style.getPropertyValue("--mask-center-y").replace("%",""))||50;const c=this.videoRef.videoWidth;const u=this.videoRef.videoHeight;const l=c/u;const f=r.width/r.height;let h,d;let p=0,m=0;if(l>f){h=r.width;d=r.width/l;m=(r.height-d)/2}else{d=r.height;h=r.height*l;p=(r.width-h)/2}const b=n/100*r.width;const v=s/100*r.height;const w=o/100*r.width;const g=a/100*r.height;const y=c/h;const x=u/d;const k=(w-p)*y;const S=(g-m)*x;const E=b*y;const _=v*x;const A=Math.max(0,k-E/2-this.cropMargin);const T=Math.max(0,S-_/2-this.cropMargin);const M=Math.min(E+2*this.cropMargin,c-A);const C=Math.min(_+2*this.cropMargin,u-T);const O=this.getPooledCanvas(M,C);const P=O.getContext("2d",{alpha:false});P.clearRect(0,0,O.width,O.height);P.drawImage(this.videoRef,A,T,M,C,0,0,M,C);const I=this.stateManager.getCaptureState();if(I.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/jpeg"),cropped:O.toDataURL("image/jpeg")}});if(this.useDocumentClassification&&!this.classificationDisabled){try{const e=await this.detectionService.classifyDocument(O);if(e&&e.class==="passport"){this.completeProcess(true);this.returnCanvasToPool(t);this.returnCanvasToPool(O);this.processingButton=null;return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});this.triggerRerender();setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.triggerRerender();this.startBackDocumentTimer();this.processingButton=null}),3e3)}else if(I.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/jpeg"),cropped:O.toDataURL("image/jpeg")}});this.completeProcess(false);this.processingButton=null}this.returnCanvasToPool(t);this.returnCanvasToPool(O)}async takeScreenshot(){if(!this.videoRef||!this.lastDetectedBox)return;const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.auto");this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const i=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const r=i.getContext("2d",{alpha:false});r.clearRect(0,0,i.width,i.height);r.drawImage(this.videoRef,0,0,i.width,i.height);const n=320;const s=this.videoRef.videoWidth/n;const o=this.videoRef.videoHeight/n;const a=Math.max(0,this.lastDetectedBox.x*s-this.cropMargin);const c=Math.max(0,this.lastDetectedBox.y*o-this.cropMargin);const u=Math.min(this.lastDetectedBox.w*s+2*this.cropMargin,this.videoRef.videoWidth-a);const l=Math.min(this.lastDetectedBox.h*o+2*this.cropMargin,this.videoRef.videoHeight-c);const f=this.getPooledCanvas(u,l);const h=f.getContext("2d",{alpha:false});h.clearRect(0,0,f.width,f.height);h.drawImage(this.videoRef,a,c,u,l,0,0,u,l);const d=this.stateManager.getCaptureState();if(d.step==="front"){const r=i.toDataURL("image/jpeg");const n=f.toDataURL("image/jpeg");this.stateManager.setCapturedImages({front:{fullFrame:r,cropped:n}});const s=performance.now()-t;this.metricsService?.recordCapture("front","auto",s);this.metricsService?.recordImageSize("front",r.length);if(e){this.tracingService?.setSpanAttribute(e,"side","front")}if(this.useDocumentClassification&&!this.classificationDisabled){try{const t=await this.detectionService.classifyDocument(f);if(t&&t.class==="passport"){if(e){this.tracingService?.setSpanAttribute(e,"document.type","passport");this.tracingService?.endSpan(e)}this.completeProcess(true);return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});if(e){this.tracingService?.endSpan(e)}setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.startBackDocumentTimer()}),3e3)}else if(d.step==="back"){const r=i.toDataURL("image/jpeg");const n=f.toDataURL("image/jpeg");this.stateManager.setCapturedImages({back:{fullFrame:r,cropped:n}});const s=performance.now()-t;this.metricsService?.recordCapture("back","auto",s);this.metricsService?.recordImageSize("back",r.length);if(e){this.tracingService?.setSpanAttribute(e,"side","back");this.tracingService?.endSpan(e)}this.completeProcess(false)}this.returnCanvasToPool(i);this.returnCanvasToPool(f)}triggerCaptureAnimation(){const t=this.el.shadowRoot?.querySelector(".card-outline");t?.classList.add("capturing");setTimeout((()=>{this.stateManager.updateCaptureState({isCapturing:false});t?.classList.remove("capturing")}),600)}switchToManualMode(){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}if(this.debug){console.warn("[JAAK-DEBUG] switchToManualMode() called - PERFORMANCE DEGRADED");console.warn("[JAAK-DEBUG] Cause: Slow frames exceeded threshold");console.warn("[JAAK-DEBUG] slowFrameCount:",this.slowFrameCount,"| threshold:",this.PERFORMANCE_THRESHOLD_MS,"ms | trigger:",this.SLOW_FRAMES_TO_TRIGGER)}this.stopPerformanceMonitoring();this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.showPerformanceMessage=true;setTimeout((()=>{this.showPerformanceMessage=false}),5e3)}switchToManualModeWithWarning(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}if(this.debug){console.warn("[JAAK-DEBUG] switchToManualModeWithWarning() called");console.warn("[JAAK-DEBUG] Cause:",t);console.warn("[JAAK-DEBUG] deviceMemory:",navigator.deviceMemory,"| hardwareConcurrency:",navigator.hardwareConcurrency)}this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.updateStatus("Modo manual activado",t,"active");this.continueWithCameraSetup()}async continueWithCameraSetup(){try{this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus()}catch(t){throw new Error(`Error al actualizar información de cámara: ${t.message}`)}this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");let t;try{t=await this.cameraService.setupCamera()}catch(t){throw new Error(`Error al configurar cámara: ${t.message}`)}this.updateStatus("Captura manual","Posicione su documento y use el botón para capturar","active");try{await this.initializeVideoStream(t)}catch(t){throw new Error(`Error al inicializar video: ${t.message}`)}if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});this.showManualCaptureButton=true}catch(t){this.updateStatus("Error de cámara",t.message,"error");throw t}}switchToManualModeWithError(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}if(this.debug){console.error("[JAAK-DEBUG] switchToManualModeWithError() called");console.error("[JAAK-DEBUG] Cause:",t);console.error("[JAAK-DEBUG] deviceMemory:",navigator.deviceMemory,"| hardwareConcurrency:",navigator.hardwareConcurrency)}this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.updateStatus("Modo manual activado",t,"error");this.continueWithCameraSetup().catch((()=>{setTimeout((()=>{this.updateStatus("Captura manual","Use el botón para capturar","ready")}),5e3)}))}stopPerformanceMonitoring(){}releaseOnnxResources(){try{if(this.detectionService){this.detectionService.cleanup()}}catch(t){}}async completeProcess(t=false){this.stateManager.updateCaptureState({step:"completed",showSuccessAnimation:true});const e=this.stateManager.getCapturedImages();e.metadata.processCompleted=true;e.metadata.backCaptureSkipped=t;this.stateManager.setCapturedImages(e);this.stopDetection();this.updateStatus("Proceso completado",`Imágenes capturadas exitosamente`,"ready");const i={...e,timestamp:(new Date).toISOString()};if(this.tracingService){try{await this.tracingService.flush()}catch(t){console.error("[my-component] Failed to flush traces:",t)}}this.captureCompleted.emit(i);setTimeout((()=>{this.stateManager.updateCaptureState({showSuccessAnimation:false})}),3e3)}stopDetection(){if(this.animationId){cancelAnimationFrame(this.animationId);this.animationId=undefined}this.clearBackDocumentTimer();this.detectionBoxes=[]}startBackDocumentTimer(){if(!this.enableBackDocumentTimer)return;if(this.backDocumentTimer){clearInterval(this.backDocumentTimer)}this.backDocumentTimerRemaining=this.backDocumentTimerDuration;this.backDocumentTimer=window.setInterval((()=>{this.backDocumentTimerRemaining--;if(this.backDocumentTimerRemaining<=0){this.clearBackDocumentTimer();this.skipBackCapture()}}),1e3)}clearBackDocumentTimer(){if(this.backDocumentTimer){clearInterval(this.backDocumentTimer);this.backDocumentTimer=undefined}this.backDocumentTimerRemaining=0}toggleCameraSelector(){if(this.isSwitchingCamera)return;this.showCameraSelector=!this.showCameraSelector}async updateCameraInfoWithAutofocus(){try{const t=await this.cameraService.getCameraInfo();this.cameraInfoWithAutofocus=t}catch(t){}}async handleCameraSwitch(t){if(this.isSwitchingCamera)return;try{this.showCameraSelector=false;const e=this.cameraService.getSelectedCameraId();if(e===t){return}this.isSwitchingCamera=true;if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}await this.cameraService.switchCamera(t);const i=await this.cameraService.setupCamera();await this.initializeVideoStream(i);await this.updateCameraInfoWithAutofocus()}catch(t){try{const t=await this.cameraService.setupCamera();await this.initializeVideoStream(t)}catch(t){this.updateStatus("Error al cambiar cámara","No se pudo cambiar el dispositivo","error")}}finally{this.isSwitchingCamera=false}}resetDetection(){const t=this.stateManager.getCaptureState();const e=t.isVideoActive;this.stateManager.reset();if(e){this.stateManager.updateCaptureState({isVideoActive:true})}this.hasScreenshotTaken=false;this.startTime=Date.now();this.frameSkipCounter=0;this.consecutiveFailures=0;this.lastInferenceTime=0;this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.processedFramesCount=0;this.slowFrameCount=0;this.hasAutoSwitchedToManual=false;this.performanceDegradedMode=false;this.showPerformanceMessage=false;if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(e&&this.detectionService.isModelLoaded()){this.updateStatus("Captura reiniciada","Buscando documento en el marco de captura","active");this.detectFrame()}else{this.updateStatus("Listo para capturar","","ready")}}exitSession(){if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()));this.videoStream=undefined;this.stateManager.updateCaptureState({isVideoActive:false,isLoading:false})}this.isMaskReady=false;this.updateStatus("Captura finalizada","","ready");this.detectionBoxes=[];this.cleanup()}initializePerformanceMonitor(){this.performanceMetrics.lastUpdateTime=performance.now();this.performanceUpdateInterval=window.setInterval((()=>{this.updatePerformanceMetrics()}),500)}updatePerformanceMetrics(){const t=performance.now();const e=t-this.performanceMetrics.lastUpdateTime;if(e>0){this.performanceMetrics.fps=Math.round(1e3/(e/this.frameSkipCounter||1))}if("memory"in performance){const t=performance.memory;this.performanceMetrics.memoryUsage=Math.round(t.usedJSHeapSize/1048576)}if(this.performanceMetrics.totalDetections>0){this.performanceMetrics.successfulDetections=this.performanceMetrics.successfulDetections;const t=this.performanceMetrics.successfulDetections/this.performanceMetrics.totalDetections*100;this.performanceMetrics.detectionRate=Math.round(t)}this.performanceData={fps:this.performanceMetrics.fps,inferenceTime:this.performanceMetrics.inferenceTime,memoryUsage:this.performanceMetrics.memoryUsage,onnxLoadTime:this.performanceMetrics.onnxLoadTime,frameProcessingTime:this.performanceMetrics.frameProcessingTime,totalDetections:this.performanceMetrics.totalDetections,successfulDetections:this.performanceMetrics.successfulDetections,detectionRate:this.performanceMetrics.detectionRate};this.performanceMetrics.lastUpdateTime=t}recordOnnxPerformance(t,e){this.performanceMetrics.onnxLoadTime=Math.round(t);this.performanceMetrics.inferenceTime=Math.round(e)}recordFrameProcessing(t,e){this.performanceMetrics.frameProcessingTime=Math.round(t);this.performanceMetrics.totalDetections++;if(e>0){this.performanceMetrics.successfulDetections++}this.performanceHistory.push(t);if(this.performanceHistory.length>this.PERFORMANCE_HISTORY_SIZE){this.performanceHistory.shift()}}getAdaptiveFrameSkip(){const t=this.cameraInfoWithAutofocus.deviceType==="mobile"||/Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);const e=this.cameraInfoWithAutofocus.deviceType==="tablet"||/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const i=t&&!e?4:this.BASE_FRAME_SKIP;if(this.consecutiveFailures>20)return this.MAX_FRAME_SKIP;if(this.performanceMetrics.inferenceTime>200)return Math.max(6,i);if(this.performanceMetrics.memoryUsage>200)return Math.max(5,i);if(this.performanceHistory.length>0){const t=this.performanceHistory.reduce(((t,e)=>t+e),0)/this.performanceHistory.length;if(t>100)return Math.max(4,i);if(t>80)return Math.max(3,i);if(t>60)return Math.max(this.BASE_FRAME_SKIP+1,i)}if(this.performanceMetrics.memoryUsage>150)return Math.max(4,i);return i}resetMaskToWhite(){const t=this.el.shadowRoot?.querySelector(".card-outline");const e=this.el.shadowRoot?.querySelectorAll(".corner");const i=this.el.shadowRoot?.querySelector(".side-top");const r=this.el.shadowRoot?.querySelector(".side-right");const n=this.el.shadowRoot?.querySelector(".side-bottom");const s=this.el.shadowRoot?.querySelector(".side-left");t?.classList.remove("perfect-match");e?.forEach((t=>t.classList.remove("perfect-match")));i?.classList.remove("aligned");r?.classList.remove("aligned");n?.classList.remove("aligned");s?.classList.remove("aligned");this.sideAlignment={top:false,right:false,bottom:false,left:false}}getPooledCanvas(t,e){const i=this.canvasPool.findIndex((i=>i.width===t&&i.height===e));if(i!==-1){return this.canvasPool.splice(i,1)[0]}if(this.canvasPool.length>0){const i=this.canvasPool.pop();i.width=t;i.height=e;return i}const r=document.createElement("canvas");r.width=t;r.height=e;return r}returnCanvasToPool(t){if(this.canvasPool.length<this.MAX_CANVAS_POOL_SIZE){const e=t.getContext("2d");e.clearRect(0,0,t.width,t.height);this.canvasPool.push(t)}}};Su.style=ku;export{Su as jaak_stamps};
|
|
7
|
-
//# sourceMappingURL=p-
|
|
6
|
+
*/(function(t){t()})((function(){var e=globalThis;function i(t){var i=e["__Zone_symbol_prefix"]||"__zone_symbol__";return i+t}function r(){var t=e["performance"];function r(e){t&&t["mark"]&&t["mark"](e)}function n(e,i){t&&t["measure"]&&t["measure"](e,i)}r("Zone");var s=function(){function t(t,e){this._parent=t;this._name=e?e.name||"unnamed":"<root>";this._properties=e&&e.properties||{};this._zoneDelegate=new a(this,this._parent&&this._parent._zoneDelegate,e)}t.assertZonePatched=function(){if(e["Promise"]!==M["ZoneAwarePromise"]){throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` "+"has been overwritten.\n"+"Most likely cause is that a Promise polyfill has been loaded "+"after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. "+"If you must load one, do so before loading zone.js.)")}};Object.defineProperty(t,"root",{get:function(){var e=t.current;while(e.parent){e=e.parent}return e},enumerable:false,configurable:true});Object.defineProperty(t,"current",{get:function(){return O.zone},enumerable:false,configurable:true});Object.defineProperty(t,"currentTask",{get:function(){return P},enumerable:false,configurable:true});t.__load_patch=function(s,o,a){if(a===void 0){a=false}if(M.hasOwnProperty(s)){var c=e[i("forceDuplicateZoneCheck")]===true;if(!a&&c){throw Error("Already loaded patch: "+s)}}else if(!e["__Zone_disable_"+s]){var u="Zone:"+s;r(u);M[s]=o(e,t,C);n(u,u)}};Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},enumerable:false,configurable:true});Object.defineProperty(t.prototype,"name",{get:function(){return this._name},enumerable:false,configurable:true});t.prototype.get=function(t){var e=this.getZoneWith(t);if(e)return e._properties[t]};t.prototype.getZoneWith=function(t){var e=this;while(e){if(e._properties.hasOwnProperty(t)){return e}e=e._parent}return null};t.prototype.fork=function(t){if(!t)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,t)};t.prototype.wrap=function(t,e){if(typeof t!=="function"){throw new Error("Expecting function got: "+t)}var i=this._zoneDelegate.intercept(this,t,e);var r=this;return function(){return r.runGuarded(i,this,arguments,e)}};t.prototype.run=function(t,e,i,r){O={parent:O,zone:this};try{return this._zoneDelegate.invoke(this,t,e,i,r)}finally{O=O.parent}};t.prototype.runGuarded=function(t,e,i,r){if(e===void 0){e=null}O={parent:O,zone:this};try{try{return this._zoneDelegate.invoke(this,t,e,i,r)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{O=O.parent}};t.prototype.runTask=function(t,e,i){if(t.zone!=this){throw new Error("A task can only be run in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")")}var r=t;var n=t.type,s=t.data,o=s===void 0?{}:s,a=o.isPeriodic,c=a===void 0?false:a,u=o.isRefreshable,l=u===void 0?false:u;if(t.state===g&&(n===T||n===A)){return}var f=t.state!=k;f&&r._transitionTo(k,x);var h=P;P=r;O={parent:O,zone:this};try{if(n==A&&t.data&&!c&&!l){t.cancelFn=undefined}try{return this._zoneDelegate.invokeTask(this,r,e,i)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{var d=t.state;if(d!==g&&d!==E){if(n==T||c||l&&d===y){f&&r._transitionTo(x,k,y)}else{var p=r._zoneDelegates;this._updateTaskCount(r,-1);f&&r._transitionTo(g,k,g);if(l){r._zoneDelegates=p}}}O=O.parent;P=h}};t.prototype.scheduleTask=function(t){if(t.zone&&t.zone!==this){var e=this;while(e){if(e===t.zone){throw Error("can not reschedule task to ".concat(this.name," which is descendants of the original zone ").concat(t.zone.name))}e=e.parent}}t._transitionTo(y,g);var i=[];t._zoneDelegates=i;t._zone=this;try{t=this._zoneDelegate.scheduleTask(this,t)}catch(e){t._transitionTo(E,y,g);this._zoneDelegate.handleError(this,e);throw e}if(t._zoneDelegates===i){this._updateTaskCount(t,1)}if(t.state==y){t._transitionTo(x,y)}return t};t.prototype.scheduleMicroTask=function(t,e,i,r){return this.scheduleTask(new c(_,t,e,i,r,undefined))};t.prototype.scheduleMacroTask=function(t,e,i,r,n){return this.scheduleTask(new c(A,t,e,i,r,n))};t.prototype.scheduleEventTask=function(t,e,i,r,n){return this.scheduleTask(new c(T,t,e,i,r,n))};t.prototype.cancelTask=function(t){if(t.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")");if(t.state!==x&&t.state!==k){return}t._transitionTo(S,x,k);try{this._zoneDelegate.cancelTask(this,t)}catch(e){t._transitionTo(E,S);this._zoneDelegate.handleError(this,e);throw e}this._updateTaskCount(t,-1);t._transitionTo(g,S);t.runCount=-1;return t};t.prototype._updateTaskCount=function(t,e){var i=t._zoneDelegates;if(e==-1){t._zoneDelegates=null}for(var r=0;r<i.length;r++){i[r]._updateTaskCount(t.type,e)}};t.__symbol__=i;return t}();var o={name:"",onHasTask:function(t,e,i,r){return t.hasTask(i,r)},onScheduleTask:function(t,e,i,r){return t.scheduleTask(i,r)},onInvokeTask:function(t,e,i,r,n,s){return t.invokeTask(i,r,n,s)},onCancelTask:function(t,e,i,r){return t.cancelTask(i,r)}};var a=function(){function t(t,e,i){this._taskCounts={microTask:0,macroTask:0,eventTask:0};this._zone=t;this._parentDelegate=e;this._forkZS=i&&(i&&i.onFork?i:e._forkZS);this._forkDlgt=i&&(i.onFork?e:e._forkDlgt);this._forkCurrZone=i&&(i.onFork?this._zone:e._forkCurrZone);this._interceptZS=i&&(i.onIntercept?i:e._interceptZS);this._interceptDlgt=i&&(i.onIntercept?e:e._interceptDlgt);this._interceptCurrZone=i&&(i.onIntercept?this._zone:e._interceptCurrZone);this._invokeZS=i&&(i.onInvoke?i:e._invokeZS);this._invokeDlgt=i&&(i.onInvoke?e:e._invokeDlgt);this._invokeCurrZone=i&&(i.onInvoke?this._zone:e._invokeCurrZone);this._handleErrorZS=i&&(i.onHandleError?i:e._handleErrorZS);this._handleErrorDlgt=i&&(i.onHandleError?e:e._handleErrorDlgt);this._handleErrorCurrZone=i&&(i.onHandleError?this._zone:e._handleErrorCurrZone);this._scheduleTaskZS=i&&(i.onScheduleTask?i:e._scheduleTaskZS);this._scheduleTaskDlgt=i&&(i.onScheduleTask?e:e._scheduleTaskDlgt);this._scheduleTaskCurrZone=i&&(i.onScheduleTask?this._zone:e._scheduleTaskCurrZone);this._invokeTaskZS=i&&(i.onInvokeTask?i:e._invokeTaskZS);this._invokeTaskDlgt=i&&(i.onInvokeTask?e:e._invokeTaskDlgt);this._invokeTaskCurrZone=i&&(i.onInvokeTask?this._zone:e._invokeTaskCurrZone);this._cancelTaskZS=i&&(i.onCancelTask?i:e._cancelTaskZS);this._cancelTaskDlgt=i&&(i.onCancelTask?e:e._cancelTaskDlgt);this._cancelTaskCurrZone=i&&(i.onCancelTask?this._zone:e._cancelTaskCurrZone);this._hasTaskZS=null;this._hasTaskDlgt=null;this._hasTaskDlgtOwner=null;this._hasTaskCurrZone=null;var r=i&&i.onHasTask;var n=e&&e._hasTaskZS;if(r||n){this._hasTaskZS=r?i:o;this._hasTaskDlgt=e;this._hasTaskDlgtOwner=this;this._hasTaskCurrZone=this._zone;if(!i.onScheduleTask){this._scheduleTaskZS=o;this._scheduleTaskDlgt=e;this._scheduleTaskCurrZone=this._zone}if(!i.onInvokeTask){this._invokeTaskZS=o;this._invokeTaskDlgt=e;this._invokeTaskCurrZone=this._zone}if(!i.onCancelTask){this._cancelTaskZS=o;this._cancelTaskDlgt=e;this._cancelTaskCurrZone=this._zone}}}Object.defineProperty(t.prototype,"zone",{get:function(){return this._zone},enumerable:false,configurable:true});t.prototype.fork=function(t,e){return this._forkZS?this._forkZS.onFork(this._forkDlgt,this.zone,t,e):new s(t,e)};t.prototype.intercept=function(t,e,i){return this._interceptZS?this._interceptZS.onIntercept(this._interceptDlgt,this._interceptCurrZone,t,e,i):e};t.prototype.invoke=function(t,e,i,r,n){return this._invokeZS?this._invokeZS.onInvoke(this._invokeDlgt,this._invokeCurrZone,t,e,i,r,n):e.apply(i,r)};t.prototype.handleError=function(t,e){return this._handleErrorZS?this._handleErrorZS.onHandleError(this._handleErrorDlgt,this._handleErrorCurrZone,t,e):true};t.prototype.scheduleTask=function(t,e){var i=e;if(this._scheduleTaskZS){if(this._hasTaskZS){i._zoneDelegates.push(this._hasTaskDlgtOwner)}i=this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt,this._scheduleTaskCurrZone,t,e);if(!i)i=e}else{if(e.scheduleFn){e.scheduleFn(e)}else if(e.type==_){b(e)}else{throw new Error("Task is missing scheduleFn.")}}return i};t.prototype.invokeTask=function(t,e,i,r){return this._invokeTaskZS?this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt,this._invokeTaskCurrZone,t,e,i,r):e.callback.apply(i,r)};t.prototype.cancelTask=function(t,e){var i;if(this._cancelTaskZS){i=this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt,this._cancelTaskCurrZone,t,e)}else{if(!e.cancelFn){throw Error("Task is not cancelable")}i=e.cancelFn(e)}return i};t.prototype.hasTask=function(t,e){try{this._hasTaskZS&&this._hasTaskZS.onHasTask(this._hasTaskDlgt,this._hasTaskCurrZone,t,e)}catch(e){this.handleError(t,e)}};t.prototype._updateTaskCount=function(t,e){var i=this._taskCounts;var r=i[t];var n=i[t]=r+e;if(n<0){throw new Error("More tasks executed then were scheduled.")}if(r==0||n==0){var s={microTask:i["microTask"]>0,macroTask:i["macroTask"]>0,eventTask:i["eventTask"]>0,change:t};this.hasTask(this._zone,s)}};return t}();var c=function(){function t(i,r,n,s,o,a){this._zone=null;this.runCount=0;this._zoneDelegates=null;this._state="notScheduled";this.type=i;this.source=r;this.data=s;this.scheduleFn=o;this.cancelFn=a;if(!n){throw new Error("callback is not defined")}this.callback=n;var c=this;if(i===T&&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 l=i("Promise");var f=i("then");var h=[];var d=false;var p;function m(t){if(!p){if(e[l]){p=e[l].resolve(0)}}if(p){var i=p[f];if(!i){i=p["then"]}i.call(p,t)}else{e[u](t,0)}}function b(t){if(I===0&&h.length===0){m(v)}t&&h.push(t)}function v(){if(!d){d=true;while(h.length){var t=h;h=[];for(var e=0;e<t.length;e++){var i=t[e];try{i.zone.runTask(i,null,null)}catch(t){C.onUnhandledError(t)}}}C.microtaskDrainDone();d=false}}var w={name:"NO ZONE"};var g="notScheduled",y="scheduling",x="scheduled",k="running",S="canceling",E="unknown";var _="microTask",A="macroTask",T="eventTask";var M={};var C={symbol:i,currentZoneFrame:function(){return O},onUnhandledError:L,microtaskDrainDone:L,scheduleMicroTask:b,showUncaughtError:function(){return!s[i("ignoreConsoleErrorUncaughtError")]},patchEventTarget:function(){return[]},patchOnProperties:L,patchMethod:function(){return L},bindArguments:function(){return[]},patchThen:function(){return L},patchMacroTask:function(){return L},patchEventPrototype:function(){return L},isIEOrEdge:function(){return false},getGlobalObjects:function(){return undefined},ObjectDefineProperty:function(){return L},ObjectGetOwnPropertyDescriptor:function(){return undefined},ObjectCreate:function(){return undefined},ArraySlice:function(){return[]},patchClass:function(){return L},wrapWithCurrentZone:function(){return L},filterProperties:function(){return[]},attachOriginToPatched:function(){return L},_redefineProperty:function(){return L},patchCallbacks:function(){return L},nativeScheduleMicroTask:m};var O={parent:null,zone:new s(null,null)};var P=null;var I=0;function L(){}n("Zone","Zone");return s}function n(){var t;var e=globalThis;var n=e[i("forceDuplicateZoneCheck")]===true;if(e["Zone"]&&(n||typeof e["Zone"].__symbol__!=="function")){throw new Error("Zone already loaded.")}(t=e["Zone"])!==null&&t!==void 0?t:e["Zone"]=r();return e["Zone"]}var s=Object.getOwnPropertyDescriptor;var o=Object.defineProperty;var a=Object.getPrototypeOf;var c=Object.create;var u=Array.prototype.slice;var l="addEventListener";var f="removeEventListener";var h=i(l);var d=i(f);var p="true";var m="false";var b=i("");function v(t,e){return Zone.current.wrap(t,e)}function w(t,e,i,r,n){return Zone.current.scheduleMacroTask(t,e,i,r,n)}var g=i;var y=typeof window!=="undefined";var x=y?window:undefined;var k=y&&x||globalThis;var S="removeAttribute";function E(t,e){for(var i=t.length-1;i>=0;i--){if(typeof t[i]==="function"){t[i]=v(t[i],e+"_"+i)}}return t}function _(t,e){var i=t.constructor["name"];var r=function(r){var n=e[r];var o=t[n];if(o){var a=s(t,n);if(!A(a)){return"continue"}t[n]=function(t){var e=function(){return t.apply(this,E(arguments,i+"."+n))};$(e,t);return e}(o)}};for(var n=0;n<e.length;n++){r(n)}}function A(t){if(!t){return true}if(t.writable===false){return false}return!(typeof t.get==="function"&&typeof t.set==="undefined")}var T=typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope;var M=!("nw"in k)&&typeof k.process!=="undefined"&&k.process.toString()==="[object process]";var C=!M&&!T&&!!(y&&x["HTMLElement"]);var O=typeof k.process!=="undefined"&&k.process.toString()==="[object process]"&&!T&&!!(y&&x["HTMLElement"]);var P={};var I=g("enable_beforeunload");var L=function(t){t=t||k.event;if(!t){return}var e=P[t.type];if(!e){e=P[t.type]=g("ON_PROPERTY"+t.type)}var i=this||t.target||k;var r=i[e];var n;if(C&&i===x&&t.type==="error"){var s=t;n=r&&r.call(this,s.message,s.filename,s.lineno,s.colno,s.error);if(n===true){t.preventDefault()}}else{n=r&&r.apply(this,arguments);if(t.type==="beforeunload"&&k[I]&&typeof n==="string"){t.returnValue=n}else if(n!=undefined&&!n){t.preventDefault()}}return n};function D(t,e,i){var r=s(t,e);if(!r&&i){var n=s(i,e);if(n){r={enumerable:true,configurable:true}}}if(!r||!r.configurable){return}var a=g("on"+e+"patched");if(t.hasOwnProperty(a)&&t[a]){return}delete r.writable;delete r.value;var c=r.get;var u=r.set;var l=e.slice(2);var f=P[l];if(!f){f=P[l]=g("ON_PROPERTY"+l)}r.set=function(e){var i=this;if(!i&&t===k){i=k}if(!i){return}var r=i[f];if(typeof r==="function"){i.removeEventListener(l,L)}u===null||u===void 0?void 0:u.call(i,null);i[f]=e;if(typeof e==="function"){i.addEventListener(l,L,false)}};r.get=function(){var i=this;if(!i&&t===k){i=k}if(!i){return null}var n=i[f];if(n){return n}else if(c){var s=c.call(this);if(s){r.set.call(this,s);if(typeof i[S]==="function"){i.removeAttribute(e)}return s}}return null};o(t,e,r);t[a]=true}function R(t,e,i){if(e){for(var r=0;r<e.length;r++){D(t,"on"+e[r],i)}}else{var n=[];for(var s in t){if(s.slice(0,2)=="on"){n.push(s)}}for(var o=0;o<n.length;o++){D(t,n[o],i)}}}var N=g("originalInstance");function j(t){var e=k[t];if(!e)return;k[g(t)]=e;k[t]=function(){var i=E(arguments,t);switch(i.length){case 0:this[N]=new e;break;case 1:this[N]=new e(i[0]);break;case 2:this[N]=new e(i[0],i[1]);break;case 3:this[N]=new e(i[0],i[1],i[2]);break;case 4:this[N]=new e(i[0],i[1],i[2],i[3]);break;default:throw new Error("Arg list too long.")}};$(k[t],e);var i=new e((function(){}));var r;for(r in i){if(t==="XMLHttpRequest"&&r==="responseBlob")continue;(function(e){if(typeof i[e]==="function"){k[t].prototype[e]=function(){return this[N][e].apply(this[N],arguments)}}else{o(k[t].prototype,e,{set:function(i){if(typeof i==="function"){this[N][e]=v(i,t+"."+e);$(this[N][e],i)}else{this[N][e]=i}},get:function(){return this[N][e]}})}})(r)}for(r in e){if(r!=="prototype"&&e.hasOwnProperty(r)){k[t][r]=e[r]}}}function U(t,e,i){var r=t;while(r&&!r.hasOwnProperty(e)){r=a(r)}if(!r&&t[e]){r=t}var n=g(e);var o=null;if(r&&(!(o=r[n])||!r.hasOwnProperty(n))){o=r[n]=r[e];var c=r&&s(r,e);if(A(c)){var u=i(o,n,e);r[e]=function(){return u(this,arguments)};$(r[e],o)}}return o}function z(t,e,i){var r=null;function n(t){var e=t.data;e.args[e.cbIdx]=function(){t.invoke.apply(this,arguments)};r.apply(e.target,e.args);return t}r=U(t,e,(function(t){return function(e,r){var s=i(e,r);if(s.cbIdx>=0&&typeof r[s.cbIdx]==="function"){return w(s.name,r[s.cbIdx],s,n)}else{return t.apply(e,r)}}}))}function $(t,e){t[g("OriginalDelegate")]=e}var B=false;var F=false;function G(){if(B){return F}B=true;try{var t=x.navigator.userAgent;if(t.indexOf("MSIE ")!==-1||t.indexOf("Trident/")!==-1||t.indexOf("Edge/")!==-1){F=true}}catch(t){}return F}function V(t){return typeof t==="function"}function q(t){return typeof t==="number"}var H={useG:true};var J={};var K={};var Z=new RegExp("^"+b+"(\\w+)(true|false)$");var W=g("propagationStopped");function X(t,e){var i=(e?e(t):t)+m;var r=(e?e(t):t)+p;var n=b+i;var s=b+r;J[t]={};J[t][m]=n;J[t][p]=s}function Y(e,i,r,n){var s=n&&n.add||l;var o=n&&n.rm||f;var c=n&&n.listeners||"eventListeners";var u=n&&n.rmAll||"removeAllListeners";var h=g(s);var d="."+s+":";var v="prependListener";var w="."+v+":";var y=function(t,e,i){if(t.isRemoved){return}var r=t.callback;if(typeof r==="object"&&r.handleEvent){t.callback=function(t){return r.handleEvent(t)};t.originalDelegate=r}var n;try{t.invoke(t,e,[i])}catch(t){n=t}var s=t.options;if(s&&typeof s==="object"&&s.once){var a=t.originalDelegate?t.originalDelegate:t.callback;e[o].call(e,i.type,a,s)}return n};function x(t,r,n){r=r||e.event;if(!r){return}var s=t||r.target||e;var o=s[J[r.type][n?p:m]];if(o){var a=[];if(o.length===1){var c=y(o[0],s,r);c&&a.push(c)}else{var u=o.slice();for(var l=0;l<u.length;l++){if(r&&r[W]===true){break}var c=y(u[l],s,r);c&&a.push(c)}}if(a.length===1){throw a[0]}else{var f=function(t){var e=a[t];i.nativeScheduleMicroTask((function(){throw e}))};for(var l=0;l<a.length;l++){f(l)}}}}var k=function(t){return x(this,t,false)};var S=function(t){return x(this,t,true)};function E(i,r){if(!i){return false}var n=true;if(r&&r.useG!==undefined){n=r.useG}var l=r&&r.vh;var f=true;if(r&&r.chkDup!==undefined){f=r.chkDup}var y=false;if(r&&r.rt!==undefined){y=r.rt}var x=i;while(x&&!x.hasOwnProperty(s)){x=a(x)}if(!x&&i[s]){x=i}if(!x){return false}if(x[h]){return false}var E=r&&r.eventNameToString;var _={};var A=x[h]=x[s];var T=x[g(o)]=x[o];var C=x[g(c)]=x[c];var O=x[g(u)]=x[u];var P;if(r&&r.prepend){P=x[g(r.prepend)]=x[r.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(_.isExisting){return}return A.call(_.target,_.eventName,_.capture?S:k,_.options)};var D=function(t){if(!t.isRemoved){var e=J[t.eventName];var i=void 0;if(e){i=e[t.capture?p:m]}var r=i&&t.target[i];if(r){for(var n=0;n<r.length;n++){var s=r[n];if(s===t){r.splice(n,1);t.isRemoved=true;if(t.removeAbortListener){t.removeAbortListener();t.removeAbortListener=null}if(r.length===0){t.allRemoved=true;t.target[i]=null}break}}}}if(!t.allRemoved){return}return T.call(t.target,t.eventName,t.capture?S:k,t.options)};var R=function(t){return A.call(_.target,_.eventName,t.invoke,_.options)};var N=function(t){return P.call(_.target,_.eventName,t.invoke,_.options)};var j=function(t){return T.call(t.target,t.eventName,t.invoke,t.options)};var U=n?L:R;var z=n?D:j;var B=function(t,e){var i=typeof e;return i==="function"&&t.callback===e||i==="object"&&t.originalDelegate===e};var F=(r===null||r===void 0?void 0:r.diff)||B;var G=Zone[g("UNPATCHED_EVENTS")];var V=e[g("PASSIVE_EVENTS")];function q(e){if(typeof e==="object"&&e!==null){var i=t({},e);if(e.signal){i.signal=e.signal}return i}return e}var W=function(t,i,s,o,a,c){if(a===void 0){a=false}if(c===void 0){c=false}return function(){var u=this||e;var h=arguments[0];if(r&&r.transferEventName){h=r.transferEventName(h)}var d=arguments[1];if(!d){return t.apply(this,arguments)}if(M&&h==="uncaughtException"){return t.apply(this,arguments)}var b=false;if(typeof d!=="function"){if(!d.handleEvent){return t.apply(this,arguments)}b=true}if(l&&!l(t,d,u,arguments)){return}var v=!!V&&V.indexOf(h)!==-1;var w=q(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(G){for(var y=0;y<G.length;y++){if(h===G[y]){if(v){return t.call(u,h,d,w)}else{return t.apply(this,arguments)}}}}var x=!w?false:typeof w==="boolean"?true:w.capture;var k=w&&typeof w==="object"?w.once:false;var S=Zone.current;var A=J[h];if(!A){X(h,E);A=J[h]}var T=A[x?p:m];var C=u[T];var O=false;if(C){O=true;if(f){for(var y=0;y<C.length;y++){if(F(C[y],d)){return}}}}else{C=u[T]=[]}var P;var L=u.constructor["name"];var D=K[L];if(D){P=D[h]}if(!P){P=L+i+(E?E(h):h)}_.options=w;if(k){_.options.once=false}_.target=u;_.capture=x;_.eventName=h;_.isExisting=O;var R=n?H:undefined;if(R){R.taskData=_}if(g){_.options.signal=undefined}var N=S.scheduleEventTask(P,d,R,s,o);if(g){_.options.signal=g;var j=function(){return N.zone.cancelTask(N)};t.call(g,"abort",j,{once:true});N.removeAbortListener=function(){return g.removeEventListener("abort",j)}}_.target=null;if(R){R.taskData=null}if(k){_.options.once=true}if(typeof N.options!=="boolean"){N.options=w}N.target=u;N.capture=x;N.eventName=h;if(b){N.originalDelegate=d}if(!c){C.push(N)}else{C.unshift(N)}if(a){return u}}};x[s]=W(A,d,U,z,y);if(P){x[v]=W(P,w,N,z,y,true)}x[o]=function(){var t=this||e;var i=arguments[0];if(r&&r.transferEventName){i=r.transferEventName(i)}var n=arguments[2];var s=!n?false:typeof n==="boolean"?true:n.capture;var o=arguments[1];if(!o){return T.apply(this,arguments)}if(l&&!l(T,o,t,arguments)){return}var a=J[i];var c;if(a){c=a[s?p:m]}var u=c&&t[c];if(u){for(var f=0;f<u.length;f++){var h=u[f];if(F(h,o)){u.splice(f,1);h.isRemoved=true;if(u.length===0){h.allRemoved=true;t[c]=null;if(!s&&typeof i==="string"){var d=b+"ON_PROPERTY"+i;t[d]=null}}h.zone.cancelTask(h);if(y){return t}return}}}return T.apply(this,arguments)};x[c]=function(){var t=this||e;var i=arguments[0];if(r&&r.transferEventName){i=r.transferEventName(i)}var n=[];var s=Q(t,E?E(i):i);for(var o=0;o<s.length;o++){var a=s[o];var c=a.originalDelegate?a.originalDelegate:a.callback;n.push(c)}return n};x[u]=function(){var t=this||e;var i=arguments[0];if(!i){var n=Object.keys(t);for(var s=0;s<n.length;s++){var a=n[s];var c=Z.exec(a);var l=c&&c[1];if(l&&l!=="removeListener"){this[u].call(this,l)}}this[u].call(this,"removeListener")}else{if(r&&r.transferEventName){i=r.transferEventName(i)}var f=J[i];if(f){var h=f[m];var d=f[p];var b=t[h];var v=t[d];if(b){var w=b.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}if(v){var w=v.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}}}if(y){return this}};$(x[s],A);$(x[o],T);if(O){$(x[u],O)}if(C){$(x[c],C)}return true}var _=[];for(var A=0;A<r.length;A++){_[A]=E(r[A],n)}return _}function Q(t,e){if(!e){var i=[];for(var r in t){var n=Z.exec(r);var s=n&&n[1];if(s&&(!e||s===e)){var o=t[r];if(o){for(var a=0;a<o.length;a++){i.push(o[a])}}}}return i}var c=J[e];if(!c){X(e);c=J[e]}var u=t[c[m]];var l=t[c[p]];if(!u){return l?l.slice():[]}else{return l?u.concat(l):u.slice()}}function tt(t,e){var i=t["Event"];if(i&&i.prototype){e.patchMethod(i.prototype,"stopImmediatePropagation",(function(t){return function(e,i){e[W]=true;t&&t.apply(e,i)}}))}}function et(t,e){e.patchMethod(t,"queueMicrotask",(function(t){return function(t,e){Zone.current.scheduleMicroTask("queueMicrotask",e[0])}}))}var it=g("zoneTask");function rt(t,e,i,r){var n=null;var s=null;e+=r;i+=r;var o={};function a(e){var i=e.data;i.args[0]=function(){return e.invoke.apply(this,arguments)};var r=n.apply(t,i.args);if(q(r)){i.handleId=r}else{i.handle=r;i.isRefreshable=V(r.refresh)}return e}function c(e){var i=e.data,r=i.handle,n=i.handleId;return s.call(t,r!==null&&r!==void 0?r:n)}n=U(t,e,(function(i){return function(n,s){var u;if(V(s[0])){var l={isRefreshable:false,isPeriodic:r==="Interval",delay:r==="Timeout"||r==="Interval"?s[1]||0:undefined,args:s};var f=s[0];s[0]=function t(){try{return f.apply(this,arguments)}finally{var e=l.handle,i=l.handleId,r=l.isPeriodic,n=l.isRefreshable;if(!r&&!n){if(i){delete o[i]}else if(e){e[it]=null}}}};var h=w(e,s[0],l,a,c);if(!h){return h}var d=h.data,p=d.handleId,m=d.handle,b=d.isRefreshable,v=d.isPeriodic;if(p){o[p]=h}else if(m){m[it]=h;if(b&&!v){var g=m.refresh;m.refresh=function(){var t=h.zone,e=h.state;if(e==="notScheduled"){h._state="scheduled";t._updateTaskCount(h,1)}else if(e==="running"){h._state="scheduling"}return g.call(this)}}}return(u=m!==null&&m!==void 0?m:p)!==null&&u!==void 0?u:h}else{return i.apply(t,s)}}}));s=U(t,i,(function(e){return function(i,r){var n=r[0];var s;if(q(n)){s=o[n];delete o[n]}else{s=n===null||n===void 0?void 0:n[it];if(s){n[it]=null}else{s=n}}if(s===null||s===void 0?void 0:s.type){if(s.cancelFn){s.zone.cancelTask(s)}}else{e.apply(t,r)}}}))}function nt(t,e){var i=e.getGlobalObjects(),r=i.isBrowser,n=i.isMix;if(!r&&!n||!t["customElements"]||!("customElements"in t)){return}var s=["connectedCallback","disconnectedCallback","adoptedCallback","attributeChangedCallback","formAssociatedCallback","formDisabledCallback","formResetCallback","formStateRestoreCallback"];e.patchCallbacks(e,t.customElements,"customElements","define",s)}function st(t,e){if(Zone[e.symbol("patchEventTarget")]){return}var i=e.getGlobalObjects(),r=i.eventNames,n=i.zoneSymbolEventNames,s=i.TRUE_STR,o=i.FALSE_STR,a=i.ZONE_SYMBOL_PREFIX;for(var c=0;c<r.length;c++){var u=r[c];var l=u+o;var f=u+s;var h=a+l;var d=a+f;n[u]={};n[u][o]=h;n[u][s]=d}var p=t["EventTarget"];if(!p||!p.prototype){return}e.patchEventTarget(t,e,[p&&p.prototype]);return true}function ot(t,e){e.patchEventPrototype(t,e)}function at(t,e,i){if(!i||i.length===0){return e}var r=i.filter((function(e){return e.target===t}));if(r.length===0){return e}var n=r[0].ignoreProperties;return e.filter((function(t){return n.indexOf(t)===-1}))}function ct(t,e,i,r){if(!t){return}var n=at(t,e,i);R(t,n,r)}function ut(t){return Object.getOwnPropertyNames(t).filter((function(t){return t.startsWith("on")&&t.length>2})).map((function(t){return t.substring(2)}))}function lt(t,e){if(M&&!O){return}if(Zone[t.symbol("patchEvents")]){return}var i=e["__Zone_ignore_on_properties"];var r=[];if(C){var n=window;r=r.concat(["Document","SVGElement","Element","HTMLElement","HTMLBodyElement","HTMLMediaElement","HTMLFrameSetElement","HTMLFrameElement","HTMLIFrameElement","HTMLMarqueeElement","Worker"]);var s=[];ct(n,ut(n),i?i.concat(s):i,a(n))}r=r.concat(["XMLHttpRequest","XMLHttpRequestEventTarget","IDBIndex","IDBRequest","IDBOpenDBRequest","IDBDatabase","IDBTransaction","IDBCursor","WebSocket"]);for(var o=0;o<r.length;o++){var c=e[r[o]];(c===null||c===void 0?void 0:c.prototype)&&ct(c.prototype,ut(c.prototype),i)}}function ft(t){t.__load_patch("legacy",(function(e){var i=e[t.__symbol__("legacyPatch")];if(i){i()}}));t.__load_patch("timers",(function(t){var e="set";var i="clear";rt(t,e,i,"Timeout");rt(t,e,i,"Interval");rt(t,e,i,"Immediate")}));t.__load_patch("requestAnimationFrame",(function(t){rt(t,"request","cancel","AnimationFrame");rt(t,"mozRequest","mozCancel","AnimationFrame");rt(t,"webkitRequest","webkitCancel","AnimationFrame")}));t.__load_patch("blocking",(function(t,e){var i=["alert","prompt","confirm"];for(var r=0;r<i.length;r++){var n=i[r];U(t,n,(function(i,r,n){return function(r,s){return e.current.run(i,t,s,n)}}))}}));t.__load_patch("EventTarget",(function(t,e,i){ot(t,i);st(t,i);var r=t["XMLHttpRequestEventTarget"];if(r&&r.prototype){i.patchEventTarget(t,i,[r.prototype])}}));t.__load_patch("MutationObserver",(function(t,e,i){j("MutationObserver");j("WebKitMutationObserver")}));t.__load_patch("IntersectionObserver",(function(t,e,i){j("IntersectionObserver")}));t.__load_patch("FileReader",(function(t,e,i){j("FileReader")}));t.__load_patch("on_property",(function(t,e,i){lt(i,t)}));t.__load_patch("customElements",(function(t,e,i){nt(t,i)}));t.__load_patch("XHR",(function(t,e){c(t);var i=g("xhrTask");var r=g("xhrSync");var n=g("xhrListener");var s=g("xhrScheduled");var o=g("xhrURL");var a=g("xhrErrorBeforeScheduled");function c(t){var c=t["XMLHttpRequest"];if(!c){return}var u=c.prototype;function l(t){return t[i]}var f=u[h];var p=u[d];if(!f){var m=t["XMLHttpRequestEventTarget"];if(m){var b=m.prototype;f=b[h];p=b[d]}}var v="readystatechange";var y="scheduled";function x(t){var r=t.data;var o=r.target;o[s]=false;o[a]=false;var c=o[n];if(!f){f=o[h];p=o[d]}if(c){p.call(o,v,c)}var u=o[n]=function(){if(o.readyState===o.DONE){if(!r.aborted&&o[s]&&t.state===y){var i=o[e.__symbol__("loadfalse")];if(o.status!==0&&i&&i.length>0){var n=t.invoke;t.invoke=function(){var i=o[e.__symbol__("loadfalse")];for(var s=0;s<i.length;s++){if(i[s]===t){i.splice(s,1)}}if(!r.aborted&&t.state===y){n.call(t)}};i.push(t)}else{t.invoke()}}else if(!r.aborted&&o[s]===false){o[a]=true}}};f.call(o,v,u);var l=o[i];if(!l){o[i]=t}M.apply(o,r.args);o[s]=true;return t}function k(){}function S(t){var e=t.data;e.aborted=true;return C.apply(e.target,e.args)}var E=U(u,"open",(function(){return function(t,e){t[r]=e[2]==false;t[o]=e[1];return E.apply(t,e)}}));var _="XMLHttpRequest.send";var A=g("fetchTaskAborting");var T=g("fetchTaskScheduling");var M=U(u,"send",(function(){return function(t,i){if(e.current[T]===true){return M.apply(t,i)}if(t[r]){return M.apply(t,i)}else{var n={target:t,url:t[o],isPeriodic:false,args:i,aborted:false};var s=w(_,k,n,x,S);if(t&&t[a]===true&&!n.aborted&&s.state===y){s.invoke()}}}}));var C=U(u,"abort",(function(){return function(t,i){var r=l(t);if(r&&typeof r.type=="string"){if(r.cancelFn==null||r.data&&r.data.aborted){return}r.zone.cancelTask(r)}else if(e.current[A]===true){return C.apply(t,i)}}}))}}));t.__load_patch("geolocation",(function(t){if(t["navigator"]&&t["navigator"].geolocation){_(t["navigator"].geolocation,["getCurrentPosition","watchPosition"])}}));t.__load_patch("PromiseRejectionEvent",(function(t,e){function i(e){return function(i){var r=Q(t,e);r.forEach((function(r){var n=t["PromiseRejectionEvent"];if(n){var s=new n(e,{promise:i.promise,reason:i.rejection});r.invoke(s)}}))}}if(t["PromiseRejectionEvent"]){e[g("unhandledPromiseRejectionHandler")]=i("unhandledrejection");e[g("rejectionHandledHandler")]=i("rejectionhandled")}}));t.__load_patch("queueMicrotask",(function(t,e,i){et(t,i)}))}function ht(t){t.__load_patch("ZoneAwarePromise",(function(t,e,i){var r=Object.getOwnPropertyDescriptor;var n=Object.defineProperty;function s(t){if(t&&t.toString===Object.prototype.toString){var e=t.constructor&&t.constructor.name;return(e?e:"")+": "+JSON.stringify(t)}return t?t.toString():Object.prototype.toString.call(t)}var o=i.symbol;var a=[];var c=t[o("DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION")]!==false;var u=o("Promise");var l=o("then");var f="__creationTrace__";i.onUnhandledError=function(t){if(i.showUncaughtError()){var e=t&&t.rejection;if(e){console.error("Unhandled Promise rejection:",e instanceof Error?e.message:e,"; Zone:",t.zone.name,"; Task:",t.task&&t.task.source,"; Value:",e,e instanceof Error?e.stack:undefined)}else{console.error(t)}}};i.microtaskDrainDone=function(){var t=function(){var t=a.shift();try{t.zone.runGuarded((function(){if(t.throwOriginal){throw t.rejection}throw t}))}catch(t){d(t)}};while(a.length){t()}};var h=o("unhandledPromiseRejectionHandler");function d(t){i.onUnhandledError(t);try{var r=e[h];if(typeof r==="function"){r.call(this,t)}}catch(t){}}function p(t){return t&&typeof t.then==="function"}function m(t){return t}function b(t){return z.reject(t)}var v=o("state");var w=o("value");var g=o("finally");var y=o("parentPromiseValue");var x=o("parentPromiseState");var k="Promise.then";var S=null;var E=true;var _=false;var A=0;function T(t,e){return function(i){try{P(t,e,i)}catch(e){P(t,false,e)}}}var M=function(){var t=false;return function e(i){return function(){if(t){return}t=true;i.apply(null,arguments)}}};var C="Promise resolved with itself";var O=o("currentTaskTrace");function P(t,r,o){var u=M();if(t===o){throw new TypeError(C)}if(t[v]===S){var l=null;try{if(typeof o==="object"||typeof o==="function"){l=o&&o.then}}catch(e){u((function(){P(t,false,e)}))();return t}if(r!==_&&o instanceof z&&o.hasOwnProperty(v)&&o.hasOwnProperty(w)&&o[v]!==S){L(o);P(t,o[v],o[w])}else if(r!==_&&typeof l==="function"){try{l.call(o,u(T(t,r)),u(T(t,false)))}catch(e){u((function(){P(t,false,e)}))()}}else{t[v]=r;var h=t[w];t[w]=o;if(t[g]===g){if(r===E){t[v]=t[x];t[w]=t[y]}}if(r===_&&o instanceof Error){var d=e.currentTask&&e.currentTask.data&&e.currentTask.data[f];if(d){n(o,O,{configurable:true,enumerable:false,writable:true,value:d})}}for(var p=0;p<h.length;){D(t,h[p++],h[p++],h[p++],h[p++])}if(h.length==0&&r==_){t[v]=A;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]===A){try{var i=e[I];if(i&&typeof i==="function"){i.call(this,{rejection:t[w],promise:t})}}catch(t){}t[v]=_;for(var r=0;r<a.length;r++){if(t===a[r].promise){a.splice(r,1)}}}}function D(t,e,i,r,n){L(t);var s=t[v];var o=s?typeof r==="function"?r:m:typeof n==="function"?n:b;e.scheduleMicroTask(k,(function(){try{var r=t[w];var n=!!i&&g===i[g];if(n){i[y]=r;i[x]=s}var a=e.run(o,undefined,n&&o!==b&&o!==m?[]:[r]);P(i,true,a)}catch(t){P(i,false,t)}}),i)}var R="function ZoneAwarePromise() { [native code] }";var N=function(){};var j=t.AggregateError;var z=function(){function t(e){var i=this;if(!(i instanceof t)){throw new Error("Must be an instanceof Promise.")}i[v]=S;i[w]=[];try{var r=M();e&&e(r(T(i,E)),r(T(i,_)))}catch(t){P(i,false,t)}}t.toString=function(){return R};t.resolve=function(e){if(e instanceof t){return e}return P(new this(null),E,e)};t.reject=function(t){return P(new this(null),_,t)};t.withResolvers=function(){var e={};e.promise=new t((function(t,i){e.resolve=t;e.reject=i}));return e};t.any=function(e){if(!e||typeof e[Symbol.iterator]!=="function"){return Promise.reject(new j([],"All promises were rejected"))}var i=[];var r=0;try{for(var n=0,s=e;n<s.length;n++){var o=s[n];r++;i.push(t.resolve(o))}}catch(t){return Promise.reject(new j([],"All promises were rejected"))}if(r===0){return Promise.reject(new j([],"All promises were rejected"))}var a=false;var c=[];return new t((function(t,e){for(var n=0;n<i.length;n++){i[n].then((function(e){if(a){return}a=true;t(e)}),(function(t){c.push(t);r--;if(r===0){a=true;e(new j(c,"All promises were rejected"))}}))}}))};t.race=function(t){var e;var i;var r=new this((function(t,r){e=t;i=r}));function n(t){e(t)}function s(t){i(t)}for(var o=0,a=t;o<a.length;o++){var c=a[o];if(!p(c)){c=this.resolve(c)}c.then(n,s)}return r};t.all=function(e){return t.allWithCallback(e)};t.allSettled=function(e){var i=this&&this.prototype instanceof t?this:t;return i.allWithCallback(e,{thenCallback:function(t){return{status:"fulfilled",value:t}},errorCallback:function(t){return{status:"rejected",reason:t}}})};t.allWithCallback=function(t,e){var i;var r;var n=new this((function(t,e){i=t;r=e}));var s=2;var o=0;var a=[];var c=function(t){if(!p(t)){t=u.resolve(t)}var n=o;try{t.then((function(t){a[n]=e?e.thenCallback(t):t;s--;if(s===0){i(a)}}),(function(t){if(!e){r(t)}else{a[n]=e.errorCallback(t);s--;if(s===0){i(a)}}}))}catch(t){r(t)}s++;o++};var u=this;for(var l=0,f=t;l<f.length;l++){var h=f[l];c(h)}s-=2;if(s===0){i(a)}return n};Object.defineProperty(t.prototype,Symbol.toStringTag,{get:function(){return"Promise"},enumerable:false,configurable:true});Object.defineProperty(t.prototype,Symbol.species,{get:function(){return t},enumerable:false,configurable:true});t.prototype.then=function(i,r){var n;var s=(n=this.constructor)===null||n===void 0?void 0:n[Symbol.species];if(!s||typeof s!=="function"){s=this.constructor||t}var o=new s(N);var a=e.current;if(this[v]==S){this[w].push(a,o,i,r)}else{D(this,a,o,i,r)}return o};t.prototype.catch=function(t){return this.then(null,t)};t.prototype.finally=function(i){var r;var n=(r=this.constructor)===null||r===void 0?void 0:r[Symbol.species];if(!n||typeof n!=="function"){n=t}var s=new n(N);s[g]=g;var o=e.current;if(this[v]==S){this[w].push(o,s,i,i)}else{D(this,o,s,i,i)}return s};return t}();z["resolve"]=z.resolve;z["reject"]=z.reject;z["race"]=z.race;z["all"]=z.all;var $=t[u]=t["Promise"];t["Promise"]=z;var B=o("thenPatched");function F(t){var e=t.prototype;var i=r(e,"then");if(i&&(i.writable===false||!i.configurable)){return}var n=e.then;e[l]=n;t.prototype.then=function(t,e){var i=this;var r=new z((function(t,e){n.call(i,t,e)}));return r.then(t,e)};t[B]=true}i.patchThen=F;function G(t){return function(e,i){var r=t.apply(e,i);if(r instanceof z){return r}var n=r.constructor;if(!n[B]){F(n)}return r}}if($){F($);U(t,"fetch",(function(t){return G(t)}))}Promise[e.__symbol__("uncaughtPromiseErrors")]=a;return z}))}function dt(t){t.__load_patch("toString",(function(t){var e=Function.prototype.toString;var i=g("OriginalDelegate");var r=g("Promise");var n=g("Error");var s=function s(){if(typeof this==="function"){var o=this[i];if(o){if(typeof o==="function"){return e.call(o)}else{return Object.prototype.toString.call(o)}}if(this===Promise){var a=t[r];if(a){return e.call(a)}}if(this===Error){var c=t[n];if(c){return e.call(c)}}}return e.call(this)};s[i]=e;Function.prototype.toString=s;var o=Object.prototype.toString;var a="[object Promise]";Object.prototype.toString=function(){if(typeof Promise==="function"&&this instanceof Promise){return a}return o.call(this)}}))}function pt(t,e,i,r,n){var s=Zone.__symbol__(r);if(e[s]){return}var o=e[s]=e[r];e[r]=function(s,a,c){if(a&&a.prototype){n.forEach((function(e){var n="".concat(i,".").concat(r,"::")+e;var s=a.prototype;try{if(s.hasOwnProperty(e)){var o=t.ObjectGetOwnPropertyDescriptor(s,e);if(o&&o.value){o.value=t.wrapWithCurrentZone(o.value,n);t._redefineProperty(a.prototype,e,o)}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],n)}}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],n)}}catch(t){}}))}return o.call(e,s,a,c)};t.attachOriginToPatched(e[r],o)}function mt(t){t.__load_patch("util",(function(t,e,i){var r=ut(t);i.patchOnProperties=R;i.patchMethod=U;i.bindArguments=E;i.patchMacroTask=z;var n=e.__symbol__("BLACK_LISTED_EVENTS");var a=e.__symbol__("UNPATCHED_EVENTS");if(t[a]){t[n]=t[a]}if(t[n]){e[n]=e[a]=t[n]}i.patchEventPrototype=tt;i.patchEventTarget=Y;i.isIEOrEdge=G;i.ObjectDefineProperty=o;i.ObjectGetOwnPropertyDescriptor=s;i.ObjectCreate=c;i.ArraySlice=u;i.patchClass=j;i.wrapWithCurrentZone=v;i.filterProperties=at;i.attachOriginToPatched=$;i._redefineProperty=Object.defineProperty;i.patchCallbacks=pt;i.getGlobalObjects=function(){return{globalSources:K,zoneSymbolEventNames:J,eventNames:r,isBrowser:C,isMix:O,isNode:M,TRUE_STR:p,FALSE_STR:m,ZONE_SYMBOL_PREFIX:b,ADD_EVENT_LISTENER_STR:l,REMOVE_EVENT_LISTENER_STR:f}}}))}function bt(t){ht(t);dt(t);mt(t)}var vt=n();bt(vt);ft(vt)}));return Os}Is();class Ls{emit(t){}}const Ds=new Ls;class Rs{getLogger(t,e,i){return new Ls}}const Ns=new Rs;class js{constructor(t,e,i,r){this._provider=t;this.name=e;this.version=i;this.options=r}emit(t){this._getLogger().emit(t)}_getLogger(){if(this._delegate){return this._delegate}const t=this._provider._getDelegateLogger(this.name,this.version,this.options);if(!t){return Ds}this._delegate=t;return this._delegate}}class Us{getLogger(t,e,i){var r;return(r=this._getDelegateLogger(t,e,i))!==null&&r!==void 0?r:new js(this,t,e,i)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Ns}_setDelegate(t){this._delegate=t}_getDelegateLogger(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getLogger(t,e,i)}}const zs=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};const $s=Symbol.for("io.opentelemetry.js.api.logs");const Bs=zs;function Fs(t,e,i){return r=>r===t?e:i}const Gs=1;class Vs{constructor(){this._proxyLoggerProvider=new Us}static getInstance(){if(!this._instance){this._instance=new Vs}return this._instance}setGlobalLoggerProvider(t){if(Bs[$s]){return this.getLoggerProvider()}Bs[$s]=Fs(Gs,t,Ns);this._proxyLoggerProvider._setDelegate(t);return t}getLoggerProvider(){var t,e;return(e=(t=Bs[$s])===null||t===void 0?void 0:t.call(Bs,Gs))!==null&&e!==void 0?e:this._proxyLoggerProvider}getLogger(t,e,i){return this.getLoggerProvider().getLogger(t,e,i)}disable(){delete Bs[$s];this._proxyLoggerProvider=new Us}}const qs=Vs.getInstance();function Hs(t,e,i,r){for(let n=0,s=t.length;n<s;n++){const s=t[n];if(e){s.setTracerProvider(e)}if(i){s.setMeterProvider(i)}if(r&&s.setLoggerProvider){s.setLoggerProvider(r)}if(!s.getConfig().enabled){s.enable()}}}function Js(t){t.forEach((t=>t.disable()))}function Ks(t){const e=t.tracerProvider||pe.getTracerProvider();const i=t.meterProvider||ee.getMeterProvider();const r=t.loggerProvider||qs.getLoggerProvider();const n=t.instrumentations?.flat()??[];Hs(n,e,i,r);return()=>{Js(n)}}let Zs=console.error.bind(console);function Ws(t,e,i){const r=!!t[e]&&Object.prototype.propertyIsEnumerable.call(t,e);Object.defineProperty(t,e,{configurable:true,enumerable:r,writable:true,value:i})}const Xs=(t,e,i)=>{if(!t||!t[e]){Zs("no original function "+String(e)+" to wrap");return}if(!i){Zs("no wrapper function");Zs((new Error).stack);return}const r=t[e];if(typeof r!=="function"||typeof i!=="function"){Zs("original object and wrapper must be functions");return}const n=i(r,e);Ws(n,"__original",r);Ws(n,"__unwrap",(()=>{if(t[e]===n){Ws(t,e,r)}}));Ws(n,"__wrapped",true);Ws(t,e,n);return n};const Ys=(t,e,i)=>{if(!t){Zs("must provide one or more modules to patch");Zs((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Zs("must provide one or more functions to wrap on modules");return}t.forEach((t=>{e.forEach((e=>{Xs(t,e,i)}))}))};const Qs=(t,e)=>{if(!t||!t[e]){Zs("no function to unwrap.");Zs((new Error).stack);return}const i=t[e];if(!i.__unwrap){Zs("no original to unwrap to -- has "+String(e)+" already been unwrapped?")}else{i.__unwrap();return}};const to=(t,e)=>{if(!t){Zs("must provide one or more modules to patch");Zs((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){Zs("must provide one or more functions to unwrap on modules");return}t.forEach((t=>{e.forEach((e=>{Qs(t,e)}))}))};class eo{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(t,e,i){this.instrumentationName=t;this.instrumentationVersion=e;this.setConfig(i);this._diag=Wt.createComponentLogger({namespace:t});this._tracer=pe.getTracer(t,e);this._meter=ee.getMeter(t,e);this._logger=qs.getLogger(t,e);this._updateMetricInstruments()}_wrap=Xs;_unwrap=Qs;_massWrap=Ys;_massUnwrap=to;get meter(){return this._meter}setMeterProvider(t){this._meter=t.getMeter(this.instrumentationName,this.instrumentationVersion);this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(t){this._logger=t.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const t=this.init()??[];if(!Array.isArray(t)){return[t]}return t}_updateMetricInstruments(){return}getConfig(){return this._config}setConfig(t){this._config={enabled:true,...t}}setTracerProvider(t){this._tracer=t.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(t,e,i,r){if(!t){return}try{t(i,r)}catch(t){this._diag.error(`Error running span customization hook due to exception in handler`,{triggerName:e},t)}}}class io extends eo{constructor(t,e,i){super(t,e,i);if(this._config.enabled){this.enable()}}}function ro(t){return typeof t==="function"&&typeof t.__original==="function"&&typeof t.__unwrap==="function"&&t.__wrapped===true}var no;(function(t){t["EVENT_TYPE"]="event_type";t["TARGET_ELEMENT"]="target_element";t["TARGET_XPATH"]="target_xpath";t["HTTP_URL"]="http.url"})(no||(no={}));const so="0.53.0";const oo="@opentelemetry/instrumentation-user-interaction";const ao="OT_ZONE_CONTEXT";const co="Navigation:";const uo=["click"];function lo(){return false}class fo extends io{version=so;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(t={}){super(oo,so,t);this._eventNames=new Set(t?.eventNames??uo);this._shouldPreventSpanCreation=typeof t?.shouldPreventSpanCreation==="function"?t.shouldPreventSpanCreation:lo}init(){}_checkForTimeout(t,e){const i=this._spansData.get(e);if(i){if(t.source==="setTimeout"){i.hrTimeLastTimeout=ni()}else if(t.source!=="Promise.then"&&t.source!=="setTimeout"){i.hrTimeLastTimeout=undefined}}}_allowEventName(t){return this._eventNames.has(t)}_createSpan(t,e,i){if(!(t instanceof HTMLElement)){return undefined}if(!t.getAttribute){return undefined}if(t.hasAttribute("disabled")){return undefined}if(!this._allowEventName(e)){return undefined}const r=Kr(t,true);try{const n=this.tracer.startSpan(e,{attributes:{[no.EVENT_TYPE]:e,[no.TARGET_ELEMENT]:t.tagName,[no.TARGET_XPATH]:r,[no.HTTP_URL]:window.location.href}},i?pe.setSpan(Zt.active(),i):undefined);if(this._shouldPreventSpanCreation(e,t,n)===true){return undefined}this._spansData.set(n,{taskCount:0});return n}catch(t){this._diag.error("failed to start create new user interaction span",t)}return undefined}_decrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount--;if(e.taskCount===0){this._tryToEndSpan(t,e.hrTimeLastTimeout)}}}_getCurrentSpan(t){const e=t.get(ao);if(e){return pe.getSpan(e)}return e}_incrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount++}}addPatchedListener(t,e,i,r){let n=this._wrappedListeners.get(i);if(!n){n=new Map;this._wrappedListeners.set(i,n)}let s=n.get(e);if(!s){s=new Map;n.set(e,s)}if(s.has(t)){return false}s.set(t,r);return true}removePatchedListener(t,e,i){const r=this._wrappedListeners.get(i);if(!r){return undefined}const n=r.get(e);if(!n){return undefined}const s=n.get(t);if(s){n.delete(t);if(n.size===0){r.delete(e);if(r.size===0){this._wrappedListeners.delete(i)}}}return s}_invokeListener(t,e,i){if(typeof t==="function"){return t.apply(e,i)}else{return t.handleEvent(i[0])}}_patchAddEventListener(){const t=this;return e=>function i(r,n,s){if(!n){return e.call(this,r,n,s)}const o=s&&typeof s==="object"&&s.once;const a=function(...e){let i;const s=e[0];const a=s?.target;if(s){i=t._eventsSpanMap.get(s)}if(o){t.removePatchedListener(this,r,n)}const c=t._createSpan(a,r,i);if(c){if(s){t._eventsSpanMap.set(s,c)}return Zt.with(pe.setSpan(Zt.active(),c),(()=>{const i=t._invokeListener(n,this,e);c.end();return i}))}else{return t._invokeListener(n,this,e)}};if(t.addPatchedListener(this,r,n,a)){return e.call(this,r,a,s)}}}_patchRemoveEventListener(){const t=this;return e=>function i(r,n,s){const o=t.removePatchedListener(this,r,n);if(o){return e.call(this,r,o,s)}else{return e.call(this,r,n,s)}}}_getPatchableEventTargets(){return window.EventTarget?[EventTarget.prototype]:[Node.prototype,Window.prototype]}_patchHistoryApi(){this._unpatchHistoryApi();this._wrap(history,"replaceState",this._patchHistoryMethod());this._wrap(history,"pushState",this._patchHistoryMethod());this._wrap(history,"back",this._patchHistoryMethod());this._wrap(history,"forward",this._patchHistoryMethod());this._wrap(history,"go",this._patchHistoryMethod())}_patchHistoryMethod(){const t=this;return e=>function i(...r){const n=`${location.pathname}${location.hash}${location.search}`;const s=e.apply(this,r);const o=`${location.pathname}${location.hash}${location.search}`;if(n!==o){t._updateInteractionName(o)}return s}}_unpatchHistoryApi(){if(ro(history.replaceState))this._unwrap(history,"replaceState");if(ro(history.pushState))this._unwrap(history,"pushState");if(ro(history.back))this._unwrap(history,"back");if(ro(history.forward))this._unwrap(history,"forward");if(ro(history.go))this._unwrap(history,"go")}_updateInteractionName(t){const e=pe.getSpan(Zt.active());if(e&&typeof e.updateName==="function"){e.updateName(`${co} ${t}`)}}_patchZoneCancelTask(){const t=this;return e=>function i(r){const n=Zone.current;const s=t._getCurrentSpan(n);if(s&&t._shouldCountTask(r,n)){t._decrementTask(s)}return e.call(this,r)}}_patchZoneScheduleTask(){const t=this;return e=>function i(r){const n=Zone.current;const s=t._getCurrentSpan(n);if(s&&t._shouldCountTask(r,n)){t._incrementTask(s);t._checkForTimeout(r,s)}return e.call(this,r)}}_patchZoneRunTask(){const t=this;return e=>function i(r,n,s){const o=Array.isArray(s)&&s[0]instanceof Event?s[0]:undefined;const a=o?.target;let c;const u=this;if(a){c=t._createSpan(a,r.eventName);if(c){t._incrementTask(c);return u.run((()=>{try{return Zt.with(pe.setSpan(Zt.active(),c),(()=>{const t=Zone.current;r._zone=t;return e.call(t,r,n,s)}))}finally{t._decrementTask(c)}}))}}else{c=t._getCurrentSpan(u)}try{return e.call(u,r,n,s)}finally{if(c&&t._shouldCountTask(r,u)){t._decrementTask(c)}}}}_shouldCountTask(t,e){if(t._zone){e=t._zone}if(!e||!t.data||t.data.isPeriodic){return false}const i=this._getCurrentSpan(e);if(!i){return false}if(!this._spansData.get(i)){return false}return t.type==="macroTask"||t.type==="microTask"}_tryToEndSpan(t,e){if(t){const i=this._spansData.get(t);if(i){t.end(e);this._spansData.delete(t)}}}enable(){const t=this._getZoneWithPrototype();this._diag.debug("applying patch to",this.moduleName,this.version,"zone:",!!t);if(t){if(ro(t.prototype.runTask)){this._unwrap(t.prototype,"runTask");this._diag.debug("removing previous patch from method runTask")}if(ro(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask");this._diag.debug("removing previous patch from method scheduleTask")}if(ro(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask");this._diag.debug("removing previous patch from method cancelTask")}this._zonePatched=true;this._wrap(t.prototype,"runTask",this._patchZoneRunTask());this._wrap(t.prototype,"scheduleTask",this._patchZoneScheduleTask());this._wrap(t.prototype,"cancelTask",this._patchZoneCancelTask())}else{this._zonePatched=false;const t=this._getPatchableEventTargets();t.forEach((t=>{if(ro(t.addEventListener)){this._unwrap(t,"addEventListener");this._diag.debug("removing previous patch from method addEventListener")}if(ro(t.removeEventListener)){this._unwrap(t,"removeEventListener");this._diag.debug("removing previous patch from method removeEventListener")}this._wrap(t,"addEventListener",this._patchAddEventListener());this._wrap(t,"removeEventListener",this._patchRemoveEventListener())}))}this._patchHistoryApi()}disable(){const t=this._getZoneWithPrototype();this._diag.debug("removing patch from",this.moduleName,this.version,"zone:",!!t);if(t&&this._zonePatched){if(ro(t.prototype.runTask)){this._unwrap(t.prototype,"runTask")}if(ro(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask")}if(ro(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask")}}else{const t=this._getPatchableEventTargets();t.forEach((t=>{if(ro(t.addEventListener)){this._unwrap(t,"addEventListener")}if(ro(t.removeEventListener)){this._unwrap(t,"removeEventListener")}}))}this._unpatchHistoryApi()}_getZoneWithPrototype(){const t=window;return t.Zone}}var ho={exports:{}};var po=ho.exports;var mo;function bo(){if(mo)return ho.exports;mo=1;(function(t,e){(function(i,r){var n="1.0.41",s="",o="?",a="function",c="undefined",u="object",l="string",f="major",h="model",d="name",p="type",m="vendor",b="version",v="architecture",w="console",g="mobile",y="tablet",x="smarttv",k="wearable",S="embedded",E=500;var _="Amazon",A="Apple",T="ASUS",M="BlackBerry",C="Browser",O="Chrome",P="Edge",I="Firefox",L="Google",D="Honor",R="Huawei",N="Lenovo",j="LG",U="Microsoft",z="Motorola",$="Nvidia",B="OnePlus",F="Opera",G="OPPO",V="Samsung",q="Sharp",H="Sony",J="Xiaomi",K="Zebra",Z="Facebook",W="Chromium OS",X="Mac OS",Y=" Browser";var Q=function(t,e){var i={};for(var r in t){if(e[r]&&e[r].length%2===0){i[r]=e[r].concat(t[r])}else{i[r]=t[r]}}return i},tt=function(t){var e={};for(var i=0;i<t.length;i++){e[t[i].toUpperCase()]=t[i]}return e},et=function(t,e){return typeof t===l?it(e).indexOf(it(t))!==-1:false},it=function(t){return t.toLowerCase()},rt=function(t){return typeof t===l?t.replace(/[^\d\.]/g,s).split(".")[0]:r},nt=function(t,e){if(typeof t===l){t=t.replace(/^\s\s*/,s);return typeof e===c?t:t.substring(0,E)}};var st=function(t,e){var i=0,n,s,o,c,l,f;while(i<e.length&&!l){var h=e[i],d=e[i+1];n=s=0;while(n<h.length&&!l){if(!h[n]){break}l=h[n++].exec(t);if(!!l){for(o=0;o<d.length;o++){f=l[++s];c=d[o];if(typeof c===u&&c.length>0){if(c.length===2){if(typeof c[1]==a){this[c[0]]=c[1].call(this,f)}else{this[c[0]]=c[1]}}else if(c.length===3){if(typeof c[1]===a&&!(c[1].exec&&c[1].test)){this[c[0]]=f?c[1].call(this,f,c[2]):r}else{this[c[0]]=f?f.replace(c[1],c[2]):r}}else if(c.length===4){this[c[0]]=f?c[3].call(this,f.replace(c[1],c[2])):r}}else{this[c]=f?f:r}}}}i+=2}},ot=function(t,e){for(var i in e){if(typeof e[i]===u&&e[i].length>0){for(var n=0;n<e[i].length;n++){if(et(e[i][n],t)){return i===o?r:i}}}else if(et(e[i],t)){return i===o?r:i}}return e.hasOwnProperty("*")?e["*"]:t};var at={"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},ct={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"};var ut={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[b,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[b,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,b],[/opios[\/ ]+([\w\.]+)/i],[b,[d,F+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[b,[d,F+" GX"]],[/\bopr\/([\w\.]+)/i],[b,[d,F]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[b,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[b,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,b],[/quark(?:pc)?\/([-\w\.]+)/i],[b,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[b,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[b,[d,"UC"+C]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[b,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[b,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[b,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[b,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[b,[d,"Smart Lenovo "+C]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+C],b],[/\bfocus\/([\w\.]+)/i],[b,[d,I+" Focus"]],[/\bopt\/([\w\.]+)/i],[b,[d,F+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[b,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[b,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[b,[d,F+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[b,[d,"MIUI"+Y]],[/fxios\/([\w\.-]+)/i],[b,[d,I]],[/\bqihoobrowser\/?([\w\.]*)/i],[b,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],b],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+Y],b],[/samsungbrowser\/([\w\.]+)/i],[b,[d,V+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[b,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],b],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,b],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[b,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,Z],b],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,b],[/\bgsa\/([\w\.]+) .*safari\//i],[b,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[b,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[b,[d,O+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,O+" WebView"],b],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[b,[d,"Android "+C]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,b],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[b,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[b,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[b,ot,at]],[/(webkit|khtml)\/([\w\.]+)/i],[d,b],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],b],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,b],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[b,[d,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],[h,[m,V],[p,y]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[h,[m,V],[p,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[h,[m,A],[p,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[h,[m,A],[p,y]],[/(macintosh);/i],[h,[m,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[h,[m,q],[p,g]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[h,[m,D],[p,y]],[/honor([-\w ]+)[;\)]/i],[h,[m,D],[p,g]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[h,[m,R],[p,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[h,[m,R],[p,g]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[h,/_/g," "],[m,J],[p,y]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[h,/_/g," "],[m,J],[p,g]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[h,[m,G],[p,g]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[h,[m,ot,{OnePlus:["304","403","203"],"*":G}],[p,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[h,[m,"Vivo"],[p,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[h,[m,"Realme"],[p,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[h,[m,z],[p,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[h,[m,z],[p,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[h,[m,j],[p,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[h,[m,j],[p,g]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[h,[m,N],[p,y]],[/(nokia) (t[12][01])/i],[m,h,[p,y]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[h,/_/g," "],[p,g],[m,"Nokia"]],[/(pixel (c|tablet))\b/i],[h,[m,L],[p,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[h,[m,L],[p,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[h,[m,H],[p,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[h,"Xperia Tablet"],[m,H],[p,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[h,[m,B],[p,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[h,[m,_],[p,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[h,/(.+)/g,"Fire Phone $1"],[m,_],[p,g]],[/(playbook);[-\w\),; ]+(rim)/i],[h,m,[p,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[h,[m,M],[p,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[h,[m,T],[p,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[h,[m,T],[p,g]],[/(nexus 9)/i],[h,[m,"HTC"],[p,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[m,[h,/_/g," "],[p,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[h,[m,"TCL"],[p,y]],[/(itel) ((\w+))/i],[[m,it],h,[p,ot,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[h,[m,"Acer"],[p,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[h,[m,"Meizu"],[p,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[h,[m,"Ulefone"],[p,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[h,[m,"Energizer"],[p,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[h,[m,"Cat"],[p,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[h,[m,"Smartfren"],[p,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[h,[m,"Nothing"],[p,g]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[h,[m,"Archos"],[p,y]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[h,[m,"Archos"],[p,g]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[m,h,[p,y]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[m,h,[p,g]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[m,h,[p,y]],[/(surface duo)/i],[h,[m,U],[p,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[h,[m,"Fairphone"],[p,g]],[/(u304aa)/i],[h,[m,"AT&T"],[p,g]],[/\bsie-(\w*)/i],[h,[m,"Siemens"],[p,g]],[/\b(rct\w+) b/i],[h,[m,"RCA"],[p,y]],[/\b(venue[\d ]{2,7}) b/i],[h,[m,"Dell"],[p,y]],[/\b(q(?:mv|ta)\w+) b/i],[h,[m,"Verizon"],[p,y]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[h,[m,"Barnes & Noble"],[p,y]],[/\b(tm\d{3}\w+) b/i],[h,[m,"NuVision"],[p,y]],[/\b(k88) b/i],[h,[m,"ZTE"],[p,y]],[/\b(nx\d{3}j) b/i],[h,[m,"ZTE"],[p,g]],[/\b(gen\d{3}) b.+49h/i],[h,[m,"Swiss"],[p,g]],[/\b(zur\d{3}) b/i],[h,[m,"Swiss"],[p,y]],[/\b((zeki)?tb.*\b) b/i],[h,[m,"Zeki"],[p,y]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[m,"Dragon Touch"],h,[p,y]],[/\b(ns-?\w{0,9}) b/i],[h,[m,"Insignia"],[p,y]],[/\b((nxa|next)-?\w{0,9}) b/i],[h,[m,"NextBook"],[p,y]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[m,"Voice"],h,[p,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[m,"LvTel"],h,[p,g]],[/\b(ph-1) /i],[h,[m,"Essential"],[p,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[h,[m,"Envizen"],[p,y]],[/\b(trio[-\w\. ]+) b/i],[h,[m,"MachSpeed"],[p,y]],[/\btu_(1491) b/i],[h,[m,"Rotor"],[p,y]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[h,[m,$],[p,y]],[/(sprint) (\w+)/i],[m,h,[p,g]],[/(kin\.[onetw]{3})/i],[[h,/\./g," "],[m,U],[p,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[h,[m,K],[p,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[h,[m,K],[p,g]],[/smart-tv.+(samsung)/i],[m,[p,x]],[/hbbtv.+maple;(\d+)/i],[[h,/^/,"SmartTV"],[m,V],[p,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[m,j],[p,x]],[/(apple) ?tv/i],[m,[h,A+" TV"],[p,x]],[/crkey/i],[[h,O+"cast"],[m,L],[p,x]],[/droid.+aft(\w+)( bui|\))/i],[h,[m,_],[p,x]],[/(shield \w+ tv)/i],[h,[m,$],[p,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[h,[m,q],[p,x]],[/(bravia[\w ]+)( bui|\))/i],[h,[m,H],[p,x]],[/(mi(tv|box)-?\w+) bui/i],[h,[m,J],[p,x]],[/Hbbtv.*(technisat) (.*);/i],[m,h,[p,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[m,nt],[h,nt],[p,x]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[h,[p,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[p,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[m,h,[p,w]],[/droid.+; (shield)( bui|\))/i],[h,[m,$],[p,w]],[/(playstation \w+)/i],[h,[m,H],[p,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[h,[m,U],[p,w]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[h,[m,V],[p,k]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[m,h,[p,k]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[h,[m,G],[p,k]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[h,[m,A],[p,k]],[/(opwwe\d{3})/i],[h,[m,B],[p,k]],[/(moto 360)/i],[h,[m,z],[p,k]],[/(smartwatch 3)/i],[h,[m,H],[p,k]],[/(g watch r)/i],[h,[m,j],[p,k]],[/droid.+; (wt63?0{2,3})\)/i],[h,[m,K],[p,k]],[/droid.+; (glass) \d/i],[h,[m,L],[p,k]],[/(pico) (4|neo3(?: link|pro)?)/i],[m,h,[p,k]],[/; (quest( \d| pro)?)/i],[h,[m,Z],[p,k]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[m,[p,S]],[/(aeobc)\b/i],[h,[m,_],[p,S]],[/(homepod).+mac os/i],[h,[m,A],[p,S]],[/windows iot/i],[[p,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[h,[p,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[h,[p,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[p,y]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[p,g]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[h,[m,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[b,[d,P+"HTML"]],[/(arkweb)\/([\w\.]+)/i],[d,b],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[b,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,b],[/ladybird\//i],[[d,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[b,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,b],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[d,[b,ot,ct]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[b,ot,ct],[d,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[b,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,X],[b,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[b,d],[/(ubuntu) ([\w\.]+) like android/i],[[d,/(.+)/,"$1 Touch"],b],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[d,b],[/\(bb(10);/i],[b,[d,M]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[b,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[b,[d,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,O+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,W],b],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,b],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],b],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,b]]};var lt=function(t,e){if(typeof t===u){e=t;t=r}if(!(this instanceof lt)){return new lt(t,e).getResult()}var n=typeof i!==c&&i.navigator?i.navigator:r;var o=t||(n&&n.userAgent?n.userAgent:s);var w=n&&n.userAgentData?n.userAgentData:r;var x=e?Q(ut,e):ut;var k=n&&n.userAgent==o;this.getBrowser=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.browser);t[f]=rt(t[b]);if(k&&n&&n.brave&&typeof n.brave.isBrave==a){t[d]="Brave"}return t};this.getCPU=function(){var t={};t[v]=r;st.call(t,o,x.cpu);return t};this.getDevice=function(){var t={};t[m]=r;t[h]=r;t[p]=r;st.call(t,o,x.device);if(k&&!t[p]&&w&&w.mobile){t[p]=g}if(k&&t[h]=="Macintosh"&&n&&typeof n.standalone!==c&&n.maxTouchPoints&&n.maxTouchPoints>2){t[h]="iPad";t[p]=y}return t};this.getEngine=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.engine);return t};this.getOS=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.os);if(k&&!t[d]&&w&&w.platform&&w.platform!="Unknown"){t[d]=w.platform.replace(/chrome os/i,W).replace(/macos/i,X)}return t};this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}};this.getUA=function(){return o};this.setUA=function(t){o=typeof t===l&&t.length>E?nt(t,E):t;return this};this.setUA(o);return this};lt.VERSION=n;lt.BROWSER=tt([d,b,f]);lt.CPU=tt([v]);lt.DEVICE=tt([h,m,p,w,g,x,y,k,S]);lt.ENGINE=lt.OS=tt([d,b]);{if(t.exports){e=t.exports=lt}e.UAParser=lt}var ft=typeof i!==c&&(i.jQuery||i.Zepto);if(ft&&!ft.ua){var ht=new lt;ft.ua=ht.getResult();ft.ua.get=function(){return ht.getUA()};ft.ua.set=function(t){ht.setUA(t);var e=ht.getResult();for(var i in e){ft.ua[i]=e[i]}}}})(typeof window==="object"?window:po)})(ho,ho.exports);return ho.exports}var vo=bo();var wo=fn(vo);const go="service.name";const yo="service.version";const xo="eAzROSTiqNd3i+M9Jw6q5Tld0jarZc617sJB//pvb5c=";let ko=false;function So(){if(ko){return}ko=true;const t=window.XMLHttpRequest;if(!t){console.error("[TracingService] XMLHttpRequest not available");return}window.XMLHttpRequest=function(){const e=new t;const i=e.open;const r=e.send;let n=false;e.open=function(t,e,...r){const s=typeof e==="string"?e:e.toString();n=s.includes("collector.jaak.ai");return i.apply(this,[t,e,...r])};e.send=function(...t){if(n){this.setRequestHeader("Authorization",`Bearer ${xo}`)}return r.apply(this,t)};return e};for(const e in t){if(t.hasOwnProperty(e)){window.XMLHttpRequest[e]=t[e]}}const e=window.fetch;window.fetch=function(t,i){const r=typeof t==="string"?t:t instanceof URL?t.href:t.url;if(r.includes("collector.jaak.ai")){const t=new Headers(i?.headers||{});t.set("Authorization",`Bearer ${xo}`);i={...i,headers:t}}return e.call(this,t,i)};navigator.sendBeacon=function(){return false}}class Eo{provider=null;tracer=null;sessionTraceId=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;enableAutoInstrumentation;spanProcessor=null;parser;geoCache=null;geoCacheTimestamp=0;GEO_CACHE_DURATION_MS=60*60*1e3;constructor(t={}){this.collectorUrl=t.collectorUrl||"https://collector.jaak.ai/v1/traces";this.serviceName=t.serviceName||"jaak-stamps-webcomponent";this.serviceVersion=t.serviceVersion||"2.1.0";this.debug=t.debug||false;this.customerId=t.customerId;this.tenantId=t.tenantId;this.environment=t.environment||"production";this.enableAutoInstrumentation=t.enableAutoInstrumentation??false;this.parser=new wo}initialize(){try{So();const t=new As({url:this.collectorUrl,headers:{"Content-Type":"application/json",Authorization:`Bearer ${xo}`},useSendBeacon:false});const e={export:(e,i)=>{if(this.debug){console.log("[TracingService] 📤 Exporting",e.length,"spans to collector")}t.export(e,(t=>{if(t.code!==0){console.error("[TracingService] ❌ Export failed:",t)}i(t)}))},shutdown:async()=>t.shutdown(),forceFlush:async()=>t.forceFlush()};this.spanProcessor=new Dr(e,{maxQueueSize:100,maxExportBatchSize:10,scheduledDelayMillis:5e3,exportTimeoutMillis:3e4});this.provider=new Jr({spanProcessors:[this.spanProcessor]});const i=new Cs;const r=new Di;this.provider.register({contextManager:i,propagator:r});this.tracer=pe.getTracer(this.serviceName,this.serviceVersion);if(this.enableAutoInstrumentation){this.initializeAutoInstrumentation()}}catch(t){console.error("[TracingService] Failed to initialize:",t)}}initializeAutoInstrumentation(){try{Ks({instrumentations:[new fo({eventNames:["click","submit"],shouldPreventSpanCreation:(t,e)=>e.tagName==="BUTTON"||e.tagName==="A"||e.tagName==="FORM"})]})}catch(t){console.error("[TracingService] Failed to initialize auto-instrumentation:",t)}}getDeviceInfo(){const t=this.parser.getResult();return{type:t.device.type||"desktop",vendor:t.device.vendor||"unknown",model:t.device.model||"unknown"}}getBrowserInfo(){const t=this.parser.getResult();return{name:t.browser.name||"unknown",version:t.browser.version||"unknown",major:t.browser.major||"unknown"}}getOSInfo(){const t=this.parser.getResult();return{name:t.os.name||"unknown",version:t.os.version||"unknown"}}setSessionTraceId(t){if(t&&t.length===32&&/^[a-f0-9]{32}$/i.test(t)){this.sessionTraceId=t.toLowerCase();if(this.debug){console.log("[TracingService] Session trace ID set:",this.sessionTraceId)}}else if(t){console.warn("[TracingService] Invalid trace ID format. Must be 32 hex characters:",t)}}getSessionTraceId(){return this.sessionTraceId}generateSpanId(){const t=new Uint8Array(8);crypto.getRandomValues(t);return Array.from(t).map((t=>t.toString(16).padStart(2,"0"))).join("")}async getGeoLocation(){const t=Date.now();if(this.geoCache&&t-this.geoCacheTimestamp<this.GEO_CACHE_DURATION_MS){return this.geoCache}try{const e=await fetch("https://ipapi.co/json/",{signal:AbortSignal.timeout(5e3)});if(!e.ok){return{}}const i=await e.json();this.geoCache={country:i.country_name,region:i.region,city:i.city,latitude:i.latitude,longitude:i.longitude};this.geoCacheTimestamp=t;return this.geoCache}catch(t){console.warn("[TracingService] Failed to fetch geo location:",t);return this.geoCache||{}}}startSpan(t,e){if(!this.tracer){console.warn("[TracingService] Tracer not initialized, returning no-op span");return pe.getTracer("noop").startSpan("noop")}try{let i=Zt.active();if(this.sessionTraceId&&!pe.getSpan(i)){const t={traceId:this.sessionTraceId,spanId:this.generateSpanId(),traceFlags:yt.SAMPLED,isRemote:true};const e=pe.wrapSpanContext(t);i=pe.setSpan(i,e)}const r=this.getDeviceInfo();const n=this.getBrowserInfo();const s=this.getOSInfo();const o=this.tracer.startSpan(t,{attributes:{...e,component:this.serviceName.includes("stamps")?"jaak-stamps":"jaak-visage",[go]:this.serviceName,[yo]:this.serviceVersion,"deployment.environment":this.environment,"trace.id":this.sessionTraceId||"auto-generated","device.type":r.type,"device.vendor":r.vendor,"device.model":r.model,"browser.name":n.name,"browser.version":n.version,"browser.major":n.major,"os.name":s.name,"os.version":s.version,user_agent:navigator.userAgent,...this.customerId&&{"customer.id":this.customerId},...this.tenantId&&{"tenant.id":this.tenantId}}},i);this.getGeoLocation().then((t=>{if(t.country)o.setAttribute("geo.country",t.country);if(t.region)o.setAttribute("geo.region",t.region);if(t.city)o.setAttribute("geo.city",t.city)})).catch((t=>console.warn("Failed to add geo attributes:",t)));if(this.debug){console.log(`[TracingService] Started span: ${t}`,{traceId:o.spanContext().traceId,spanId:o.spanContext().spanId,sessionTraceId:this.sessionTraceId,attributes:e})}return o}catch(t){console.error("[TracingService] Failed to start span:",t);return pe.getTracer("noop").startSpan("noop")}}endSpan(t){if(!t){console.warn("[TracingService] endSpan called with null/undefined span");return}try{t.end()}catch(t){console.error("[TracingService] ❌ Failed to end span:",t)}}addSpanEvent(t,e,i){if(!t)return;try{t.addEvent(e,i);if(this.debug){console.log(`[TracingService] Added event to span: ${e}`,i)}}catch(t){console.error("[TracingService] Failed to add span event:",t)}}recordException(t,e){if(!t)return;try{t.recordException(e);t.setStatus({code:Kt.ERROR,message:e.message})}catch(t){console.error("[TracingService] Failed to record exception:",t)}}setSpanAttribute(t,e,i){if(!t)return;try{t.setAttribute(e,i);if(this.debug){console.log(`[TracingService] Set attribute: ${e} = ${i}`)}}catch(t){console.error("[TracingService] Failed to set span attribute:",t)}}async trace(t,e,i){const r=this.startSpan(t,i);try{const t=await Zt.with(pe.setSpan(Zt.active(),r),(async()=>await e()));r.setStatus({code:Kt.OK});return t}catch(t){this.recordException(r,t);throw t}finally{this.endSpan(r)}}async traceAsync(t,e,i){return this.trace(t,e,i)}async flush(){try{if(!this.spanProcessor){console.warn("[TracingService] No span processor available to flush");return}await this.spanProcessor.forceFlush()}catch(t){console.error("[TracingService] ❌ Failed to flush spans:",t);throw t}}async cleanup(){try{if(this.spanProcessor){await this.spanProcessor.forceFlush();await this.spanProcessor.shutdown()}if(this.provider){await this.provider.shutdown()}}catch(t){console.error("[TracingService] Failed to cleanup:",t)}}getCurrentTraceId(){try{const t=pe.getSpan(Zt.active());return t?.spanContext().traceId}catch{return undefined}}getCurrentSpanId(){try{const t=pe.getSpan(Zt.active());return t?.spanContext().spanId}catch{return undefined}}}var _o;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(_o||(_o={}));var Ao;(function(t){t["COUNTER"]="COUNTER";t["GAUGE"]="GAUGE";t["HISTOGRAM"]="HISTOGRAM";t["UP_DOWN_COUNTER"]="UP_DOWN_COUNTER";t["OBSERVABLE_COUNTER"]="OBSERVABLE_COUNTER";t["OBSERVABLE_GAUGE"]="OBSERVABLE_GAUGE";t["OBSERVABLE_UP_DOWN_COUNTER"]="OBSERVABLE_UP_DOWN_COUNTER"})(Ao||(Ao={}));var To;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(To||(To={}));function Mo(t){let e=Object.keys(t);if(e.length===0)return"";e=e.sort();return JSON.stringify(e.map((e=>[e,t[e]])))}function Co(t){return`${t.name}:${t.version??""}:${t.schemaUrl??""}`}class Oo extends Error{constructor(t){super(t);Object.setPrototypeOf(this,Oo.prototype)}}function Po(t,e){let i;const r=new Promise((function t(r,n){i=setTimeout((function t(){n(new Oo("Operation timed out."))}),e)}));return Promise.race([t,r]).then((t=>{clearTimeout(i);return t}),(t=>{clearTimeout(i);throw t}))}function Io(t,e){if(t.size!==e.size){return false}for(const i of t){if(!e.has(i)){return false}}return true}function Lo(t,e){let i=0;let r=t.length-1;let n=t.length;while(r>=i){const s=i+Math.trunc((r-i)/2);if(t[s]<e){i=s+1}else{n=s;r=s-1}}return n}function Do(t,e){return t.toLowerCase()===e.toLowerCase()}var Ro;(function(t){t[t["DROP"]=0]="DROP";t[t["SUM"]=1]="SUM";t[t["LAST_VALUE"]=2]="LAST_VALUE";t[t["HISTOGRAM"]=3]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=4]="EXPONENTIAL_HISTOGRAM"})(Ro||(Ro={}));class No{kind=Ro.DROP;createAccumulation(){return undefined}merge(t,e){return undefined}diff(t,e){return undefined}toMetricData(t,e,i,r){return undefined}}function jo(t){const e=t.map((()=>0));e.push(0);return{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:false,min:Infinity,max:-Infinity}}class Uo{startTime;_boundaries;_recordMinMax;_current;constructor(t,e,i=true,r=jo(e)){this.startTime=t;this._boundaries=e;this._recordMinMax=i;this._current=r}record(t){if(Number.isNaN(t)){return}this._current.count+=1;this._current.sum+=t;if(this._recordMinMax){this._current.min=Math.min(t,this._current.min);this._current.max=Math.max(t,this._current.max);this._current.hasMinMax=true}const e=Lo(this._boundaries,t);this._current.buckets.counts[e]+=1}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class zo{kind=Ro.HISTOGRAM;_boundaries;_recordMinMax;constructor(t,e){this._boundaries=t;this._recordMinMax=e}createAccumulation(t){return new Uo(t,this._boundaries,this._recordMinMax)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();const n=i.buckets.counts;const s=r.buckets.counts;const o=new Array(n.length);for(let t=0;t<n.length;t++){o[t]=n[t]+s[t]}let a=Infinity;let c=-Infinity;if(this._recordMinMax){if(i.hasMinMax&&r.hasMinMax){a=Math.min(i.min,r.min);c=Math.max(i.max,r.max)}else if(i.hasMinMax){a=i.min;c=i.max}else if(r.hasMinMax){a=r.min;c=r.max}}return new Uo(t.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:i.count+r.count,sum:i.sum+r.sum,hasMinMax:this._recordMinMax&&(i.hasMinMax||r.hasMinMax),min:a,max:c})}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();const n=i.buckets.counts;const s=r.buckets.counts;const o=new Array(n.length);for(let t=0;t<n.length;t++){o[t]=s[t]-n[t]}return new Uo(e.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:r.count-i.count,sum:r.sum-i.sum,hasMinMax:false,min:Infinity,max:-Infinity})}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:To.HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===Ao.GAUGE||t.type===Ao.UP_DOWN_COUNTER||t.type===Ao.OBSERVABLE_GAUGE||t.type===Ao.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:r,value:{min:n.hasMinMax?n.min:undefined,max:n.hasMinMax?n.max:undefined,sum:!s?n.sum:undefined,buckets:n.buckets,count:n.count}}}))}}}class $o{backing;indexBase;indexStart;indexEnd;constructor(t=new Bo,e=0,i=0,r=0){this.backing=t;this.indexBase=e;this.indexStart=i;this.indexEnd=r}get offset(){return this.indexStart}get length(){if(this.backing.length===0){return 0}if(this.indexEnd===this.indexStart&&this.at(0)===0){return 0}return this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},((t,e)=>this.at(e)))}at(t){const e=this.indexBase-this.indexStart;if(t<e){t+=this.backing.length}t-=e;return this.backing.countAt(t)}incrementBucket(t,e){this.backing.increment(t,e)}decrementBucket(t,e){this.backing.decrement(t,e)}trim(){for(let t=0;t<this.length;t++){if(this.at(t)!==0){this.indexStart+=t;break}else if(t===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}}for(let t=this.length-1;t>=0;t--){if(this.at(t)!==0){this.indexEnd-=this.length-t-1;break}}this._rotate()}downscale(t){this._rotate();const e=1+this.indexEnd-this.indexStart;const i=1<<t;let r=0;let n=0;for(let t=this.indexStart;t<=this.indexEnd;){let s=t%i;if(s<0){s+=i}for(let o=s;o<i&&r<e;o++){this._relocateBucket(n,r);r++;t++}n++}this.indexStart>>=t;this.indexEnd>>=t;this.indexBase=this.indexStart}clone(){return new $o(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const t=this.indexBase-this.indexStart;if(t===0){return}else if(t>0){this.backing.reverse(0,this.backing.length);this.backing.reverse(0,t);this.backing.reverse(t,this.backing.length)}else{this.backing.reverse(0,this.backing.length);this.backing.reverse(0,this.backing.length+t)}this.indexBase=this.indexStart}_relocateBucket(t,e){if(t===e){return}this.incrementBucket(t,this.backing.emptyBucket(e))}}class Bo{_counts;constructor(t=[0]){this._counts=t}get length(){return this._counts.length}countAt(t){return this._counts[t]}growTo(t,e,i){const r=new Array(t).fill(0);r.splice(i,this._counts.length-e,...this._counts.slice(e));r.splice(0,e,...this._counts.slice(0,e));this._counts=r}reverse(t,e){const i=Math.floor((t+e)/2)-t;for(let r=0;r<i;r++){const i=this._counts[t+r];this._counts[t+r]=this._counts[e-r-1];this._counts[e-r-1]=i}}emptyBucket(t){const e=this._counts[t];this._counts[t]=0;return e}increment(t,e){this._counts[t]+=e}decrement(t,e){if(this._counts[t]>=e){this._counts[t]-=e}else{this._counts[t]=0}}clone(){return new Bo([...this._counts])}}const Fo=52;const Go=2146435072;const Vo=1048575;const qo=1023;const Ho=-1023+1;const Jo=qo;const Ko=Math.pow(2,-1022);function Zo(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=(i&Go)>>20;return r-qo}function Wo(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=e.getUint32(4);const n=(i&Vo)*Math.pow(2,32);return n+r}function Xo(t,e){if(t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)){return t}return t*Math.pow(2,e)}function Yo(t){t--;t|=t>>1;t|=t>>2;t|=t>>4;t|=t>>8;t|=t>>16;t++;return t}class Qo extends Error{}class ta{_shift;constructor(t){this._shift=-t}mapToIndex(t){if(t<Ko){return this._minNormalLowerBoundaryIndex()}const e=Zo(t);const i=this._rightShift(Wo(t)-1,Fo);return e+i>>this._shift}lowerBoundary(t){const e=this._minNormalLowerBoundaryIndex();if(t<e){throw new Qo(`underflow: ${t} is < minimum lower boundary: ${e}`)}const i=this._maxNormalLowerBoundaryIndex();if(t>i){throw new Qo(`overflow: ${t} is > maximum lower boundary: ${i}`)}return Xo(1,t<<this._shift)}get scale(){if(this._shift===0){return 0}return-this._shift}_minNormalLowerBoundaryIndex(){let t=Ho>>this._shift;if(this._shift<2){t--}return t}_maxNormalLowerBoundaryIndex(){return Jo>>this._shift}_rightShift(t,e){return Math.floor(t*Math.pow(2,-e))}}class ea{_scale;_scaleFactor;_inverseFactor;constructor(t){this._scale=t;this._scaleFactor=Xo(Math.LOG2E,t);this._inverseFactor=Xo(Math.LN2,-t)}mapToIndex(t){if(t<=Ko){return this._minNormalLowerBoundaryIndex()-1}if(Wo(t)===0){const e=Zo(t);return(e<<this._scale)-1}const e=Math.floor(Math.log(t)*this._scaleFactor);const i=this._maxNormalLowerBoundaryIndex();if(e>=i){return i}return e}lowerBoundary(t){const e=this._maxNormalLowerBoundaryIndex();if(t>=e){if(t===e){return 2*Math.exp((t-(1<<this._scale))/this._scaleFactor)}throw new Qo(`overflow: ${t} is > maximum lower boundary: ${e}`)}const i=this._minNormalLowerBoundaryIndex();if(t<=i){if(t===i){return Ko}else if(t===i-1){return Math.exp((t+(1<<this._scale))/this._scaleFactor)/2}throw new Qo(`overflow: ${t} is < minimum lower boundary: ${i}`)}return Math.exp(t*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Ho<<this._scale}_maxNormalLowerBoundaryIndex(){return(Jo+1<<this._scale)-1}}const ia=-10;const ra=20;const na=Array.from({length:31},((t,e)=>{if(e>10){return new ea(e-10)}return new ta(e-10)}));function sa(t){if(t>ra||t<ia){throw new Qo(`expected scale >= ${ia} && <= ${ra}, got: ${t}`)}return na[t+10]}class oa{static combine(t,e){return new oa(Math.min(t.low,e.low),Math.max(t.high,e.high))}low;high;constructor(t,e){this.low=t;this.high=e}}const aa=20;const ca=160;const ua=2;class la{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(t,e=ca,i=true,r=0,n=0,s=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new $o,u=new $o,l=sa(aa)){this.startTime=t;this._maxSize=e;this._recordMinMax=i;this._sum=r;this._count=n;this._zeroCount=s;this._min=o;this._max=a;this._positive=c;this._negative=u;this._mapping=l;if(this._maxSize<ua){Wt.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${ua}`);this._maxSize=ua}}record(t){this.updateByIncrement(t,1)}setStartTime(t){this.startTime=t}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){if(this._count===this._zeroCount){return 0}return this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(t,e){if(Number.isNaN(t)){return}if(t>this._max){this._max=t}if(t<this._min){this._min=t}this._count+=e;if(t===0){this._zeroCount+=e;return}this._sum+=t*e;if(t>0){this._updateBuckets(this._positive,t,e)}else{this._updateBuckets(this._negative,-t,e)}}merge(t){if(this._count===0){this._min=t.min;this._max=t.max}else if(t.count!==0){if(t.min<this.min){this._min=t.min}if(t.max>this.max){this._max=t.max}}this.startTime=t.startTime;this._sum+=t.sum;this._count+=t.count;this._zeroCount+=t.zeroCount;const e=this._minScale(t);this._downscale(this.scale-e);this._mergeBuckets(this.positive,t,t.positive,e);this._mergeBuckets(this.negative,t,t.negative,e)}diff(t){this._min=Infinity;this._max=-Infinity;this._sum-=t.sum;this._count-=t.count;this._zeroCount-=t.zeroCount;const e=this._minScale(t);this._downscale(this.scale-e);this._diffBuckets(this.positive,t,t.positive,e);this._diffBuckets(this.negative,t,t.negative,e)}clone(){return new la(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(t,e,i){let r=this._mapping.mapToIndex(e);let n=false;let s=0;let o=0;if(t.length===0){t.indexStart=r;t.indexEnd=t.indexStart;t.indexBase=t.indexStart}else if(r<t.indexStart&&t.indexEnd-r>=this._maxSize){n=true;o=r;s=t.indexEnd}else if(r>t.indexEnd&&r-t.indexStart>=this._maxSize){n=true;o=t.indexStart;s=r}if(n){const t=this._changeScale(s,o);this._downscale(t);r=this._mapping.mapToIndex(e)}this._incrementIndexBy(t,r,i)}_incrementIndexBy(t,e,i){if(i===0){return}if(t.length===0){t.indexStart=t.indexEnd=t.indexBase=e}if(e<t.indexStart){const i=t.indexEnd-e;if(i>=t.backing.length){this._grow(t,i+1)}t.indexStart=e}else if(e>t.indexEnd){const i=e-t.indexStart;if(i>=t.backing.length){this._grow(t,i+1)}t.indexEnd=e}let r=e-t.indexBase;if(r<0){r+=t.backing.length}t.incrementBucket(r,i)}_grow(t,e){const i=t.backing.length;const r=t.indexBase-t.indexStart;const n=i-r;let s=Yo(e);if(s>this._maxSize){s=this._maxSize}const o=s-r;t.backing.growTo(s,n,o)}_changeScale(t,e){let i=0;while(t-e>=this._maxSize){t>>=1;e>>=1;i++}return i}_downscale(t){if(t===0){return}if(t<0){throw new Error(`impossible change of scale: ${this.scale}`)}const e=this._mapping.scale-t;this._positive.downscale(t);this._negative.downscale(t);this._mapping=sa(e)}_minScale(t){const e=Math.min(this.scale,t.scale);const i=oa.combine(this._highLowAtScale(this.positive,this.scale,e),this._highLowAtScale(t.positive,t.scale,e));const r=oa.combine(this._highLowAtScale(this.negative,this.scale,e),this._highLowAtScale(t.negative,t.scale,e));return Math.min(e-this._changeScale(i.high,i.low),e-this._changeScale(r.high,r.low))}_highLowAtScale(t,e,i){if(t.length===0){return new oa(0,-1)}const r=e-i;return new oa(t.indexStart>>r,t.indexEnd>>r)}_mergeBuckets(t,e,i,r){const n=i.offset;const s=e.scale-r;for(let e=0;e<i.length;e++){this._incrementIndexBy(t,n+e>>s,i.at(e))}}_diffBuckets(t,e,i,r){const n=i.offset;const s=e.scale-r;for(let e=0;e<i.length;e++){const r=n+e>>s;let o=r-t.indexBase;if(o<0){o+=t.backing.length}t.decrementBucket(o,i.at(e))}t.trim()}}class fa{kind=Ro.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(t,e){this._maxSize=t;this._recordMinMax=e}createAccumulation(t){return new la(t,this._maxSize,this._recordMinMax)}merge(t,e){const i=e.clone();i.merge(t);return i}diff(t,e){const i=e.clone();i.diff(t);return i}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:To.EXPONENTIAL_HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===Ao.GAUGE||t.type===Ao.UP_DOWN_COUNTER||t.type===Ao.OBSERVABLE_GAUGE||t.type===Ao.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:r,value:{min:n.hasMinMax?n.min:undefined,max:n.hasMinMax?n.max:undefined,sum:!s?n.sum:undefined,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},count:n.count,scale:n.scale,zeroCount:n.zeroCount}}}))}}}const ha=$("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function da(t){return t.setValue(ha,true)}function pa(){return t=>{Wt.error(ma(t))}}function ma(t){if(typeof t==="string"){return t}else{return JSON.stringify(ba(t))}}function ba(t){const e={};let i=t;while(i!==null){Object.getOwnPropertyNames(i).forEach((t=>{if(e[t])return;const r=i[t];if(r){e[t]=String(r)}}));i=Object.getPrototypeOf(i)}return e}let va=pa();function wa(t){try{va(t)}catch{}}const ga="2.6.0";const ya="process.runtime.name";const xa={[Ke]:"opentelemetry",[ya]:"browser",[He]:Je,[Ze]:ga};const ka=6;const Sa=Math.pow(10,ka);function Ea(t){const e=t/1e3;const i=Math.trunc(e);const r=Math.round(t%1e3*Sa);return[i,r]}function _a(t){return t[0]*1e6+t[1]/1e3}var Aa;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(Aa||(Aa={}));function Ta(t,e){return new Promise((i=>{Zt.with(da(Zt.active()),(()=>{t.export(e,i)}))}))}const Ma={_export:Ta};class Ca{startTime;_current;sampleTime;constructor(t,e=0,i=[0,0]){this.startTime=t;this._current=e;this.sampleTime=i}record(t){this._current=t;this.sampleTime=Ea(Date.now())}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Oa{kind=Ro.LAST_VALUE;createAccumulation(t){return new Ca(t)}merge(t,e){const i=_a(e.sampleTime)>=_a(t.sampleTime)?e:t;return new Ca(t.startTime,i.toPointValue(),i.sampleTime)}diff(t,e){const i=_a(e.sampleTime)>=_a(t.sampleTime)?e:t;return new Ca(e.startTime,i.toPointValue(),i.sampleTime)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:To.GAUGE,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()})))}}}class Pa{startTime;monotonic;_current;reset;constructor(t,e,i=0,r=false){this.startTime=t;this.monotonic=e;this._current=i;this.reset=r}record(t){if(this.monotonic&&t<0){return}this._current+=t}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Ia{kind=Ro.SUM;monotonic;constructor(t){this.monotonic=t}createAccumulation(t){return new Pa(t,this.monotonic)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();if(e.reset){return new Pa(e.startTime,this.monotonic,r,e.reset)}return new Pa(t.startTime,this.monotonic,i+r)}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();if(this.monotonic&&i>r){return new Pa(e.startTime,this.monotonic,r,true)}return new Pa(e.startTime,this.monotonic,r-i)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:To.SUM,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()}))),isMonotonic:this.monotonic}}}class La{static DEFAULT_INSTANCE=new No;createAggregator(t){return La.DEFAULT_INSTANCE}}class Da{static MONOTONIC_INSTANCE=new Ia(true);static NON_MONOTONIC_INSTANCE=new Ia(false);createAggregator(t){switch(t.type){case Ao.COUNTER:case Ao.OBSERVABLE_COUNTER:case Ao.HISTOGRAM:{return Da.MONOTONIC_INSTANCE}default:{return Da.NON_MONOTONIC_INSTANCE}}}}class Ra{static DEFAULT_INSTANCE=new Oa;createAggregator(t){return Ra.DEFAULT_INSTANCE}}class Na{static DEFAULT_INSTANCE=new zo([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],true);createAggregator(t){return Na.DEFAULT_INSTANCE}}class ja{_boundaries;_recordMinMax;constructor(t,e=true){if(t==null){throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array")}t=t.concat();t=t.sort(((t,e)=>t-e));const i=t.lastIndexOf(-Infinity);let r=t.indexOf(Infinity);if(r===-1){r=undefined}this._boundaries=t.slice(i+1,r);this._recordMinMax=e}createAggregator(t){return new zo(this._boundaries,this._recordMinMax)}}class Ua{_maxSize;_recordMinMax;constructor(t=160,e=true){this._maxSize=t;this._recordMinMax=e}createAggregator(t){return new fa(this._maxSize,this._recordMinMax)}}class za{_resolve(t){switch(t.type){case Ao.COUNTER:case Ao.UP_DOWN_COUNTER:case Ao.OBSERVABLE_COUNTER:case Ao.OBSERVABLE_UP_DOWN_COUNTER:{return Ba}case Ao.GAUGE:case Ao.OBSERVABLE_GAUGE:{return Fa}case Ao.HISTOGRAM:{if(t.advice.explicitBucketBoundaries){return new ja(t.advice.explicitBucketBoundaries)}return Ga}}Wt.warn(`Unable to recognize instrument type: ${t.type}`);return $a}createAggregator(t){return this._resolve(t).createAggregator(t)}}const $a=new La;const Ba=new Da;const Fa=new Ra;const Ga=new Na;const Va=new za;var qa;(function(t){t[t["DEFAULT"]=0]="DEFAULT";t[t["DROP"]=1]="DROP";t[t["SUM"]=2]="SUM";t[t["LAST_VALUE"]=3]="LAST_VALUE";t[t["EXPLICIT_BUCKET_HISTOGRAM"]=4]="EXPLICIT_BUCKET_HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=5]="EXPONENTIAL_HISTOGRAM"})(qa||(qa={}));function Ha(t){switch(t.type){case qa.DEFAULT:return Va;case qa.DROP:return $a;case qa.SUM:return Ba;case qa.LAST_VALUE:return Fa;case qa.EXPONENTIAL_HISTOGRAM:{const e=t;return new Ua(e.options?.maxSize,e.options?.recordMinMax)}case qa.EXPLICIT_BUCKET_HISTOGRAM:{const e=t;if(e.options==null){return Ga}else{return new ja(e.options?.boundaries,e.options?.recordMinMax)}}default:throw new Error("Unsupported Aggregation")}}const Ja=t=>({type:qa.DEFAULT});const Ka=t=>_o.CUMULATIVE;class Za{_shutdown=false;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(t){this._aggregationSelector=t?.aggregationSelector??Ja;this._aggregationTemporalitySelector=t?.aggregationTemporalitySelector??Ka;this._metricProducers=t?.metricProducers??[];this._cardinalitySelector=t?.cardinalitySelector}setMetricProducer(t){if(this._sdkMetricProducer){throw new Error("MetricReader can not be bound to a MeterProvider again.")}this._sdkMetricProducer=t;this.onInitialized()}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}selectCardinalityLimit(t){return this._cardinalitySelector?this._cardinalitySelector(t):2e3}onInitialized(){}async collect(t){if(this._sdkMetricProducer===undefined){throw new Error("MetricReader is not bound to a MetricProducer")}if(this._shutdown){throw new Error("MetricReader is shutdown")}const[e,...i]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:t?.timeoutMillis}),...this._metricProducers.map((e=>e.collect({timeoutMillis:t?.timeoutMillis})))]);const r=e.errors.concat(i.flatMap((t=>t.errors)));const n=e.resourceMetrics.resource;const s=e.resourceMetrics.scopeMetrics.concat(i.flatMap((t=>t.resourceMetrics.scopeMetrics)));return{resourceMetrics:{resource:n,scopeMetrics:s},errors:r}}async shutdown(t){if(this._shutdown){Wt.error("Cannot call shutdown twice.");return}if(t?.timeoutMillis==null){await this.onShutdown()}else{await Po(this.onShutdown(),t.timeoutMillis)}this._shutdown=true}async forceFlush(t){if(this._shutdown){Wt.warn("Cannot forceFlush on already shutdown MetricReader.");return}if(t?.timeoutMillis==null){await this.onForceFlush();return}await Po(this.onForceFlush(),t.timeoutMillis)}}class Wa extends Za{_interval;_exporter;_exportInterval;_exportTimeout;constructor(t){const{exporter:e,exportIntervalMillis:i=6e4,metricProducers:r}=t;let{exportTimeoutMillis:n=3e4}=t;super({aggregationSelector:e.selectAggregation?.bind(e),aggregationTemporalitySelector:e.selectAggregationTemporality?.bind(e),metricProducers:r});if(i<=0){throw Error("exportIntervalMillis must be greater than 0")}if(n<=0){throw Error("exportTimeoutMillis must be greater than 0")}if(i<n){if("exportIntervalMillis"in t&&"exportTimeoutMillis"in t){throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis")}else{Wt.info(`Timeout of ${n} exceeds the interval of ${i}. Clamping timeout to interval duration.`);n=i}}this._exportInterval=i;this._exportTimeout=n;this._exporter=e}async _runOnce(){try{await Po(this._doRun(),this._exportTimeout)}catch(t){if(t instanceof Oo){Wt.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);return}wa(t)}}async _doRun(){const{resourceMetrics:t,errors:e}=await this.collect({timeoutMillis:this._exportTimeout});if(e.length>0){Wt.error("PeriodicExportingMetricReader: metrics collection errors",...e)}if(t.resource.asyncAttributesPending){try{await(t.resource.waitForAsyncAttributes?.())}catch(t){Wt.debug("Error while resolving async portion of resource: ",t);wa(t)}}if(t.scopeMetrics.length===0){return}const i=await Ma._export(this._exporter,t);if(i.code!==Aa.SUCCESS){throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${i.error})`)}}onInitialized(){this._interval=setInterval((()=>{void this._runOnce()}),this._exportInterval);if(typeof this._interval!=="number"){this._interval.unref()}}async onForceFlush(){await this._runOnce();await this._exporter.forceFlush()}async onShutdown(){if(this._interval){clearInterval(this._interval)}await this.onForceFlush();await this._exporter.shutdown()}}let Xa;function Ya(){if(Xa===undefined){try{const t=globalThis.process.argv0;Xa=t?`unknown_service:${t}`:"unknown_service"}catch{Xa="unknown_service"}}return Xa}const Qa=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";class tc{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,e){const i=new tc({},e);i._rawAttributes=rc(t);i._asyncAttributesPending=t.filter((([t,e])=>Qa(e))).length>0;return i}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(Qa(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=rc(this._rawAttributes);this._schemaUrl=nc(e?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(!this.asyncAttributesPending){return}for(let t=0;t<this._rawAttributes.length;t++){const[e,i]=this._rawAttributes[t];this._rawAttributes[t]=[e,Qa(i)?await i:i]}this._asyncAttributesPending=false}get attributes(){if(this.asyncAttributesPending){Wt.error("Accessing resource attributes before async attributes settled")}if(this._memoizedAttributes){return this._memoizedAttributes}const t={};for(const[e,i]of this._rawAttributes){if(Qa(i)){Wt.debug(`Unsettled resource attribute ${e} skipped`);continue}if(i!=null){t[e]??=i}}if(!this._asyncAttributesPending){this._memoizedAttributes=t}return t}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;const e=sc(this,t);const i=e?{schemaUrl:e}:undefined;return tc.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],i)}}function ec(t,e){return tc.FromAttributeList(Object.entries(t),e)}function ic(){return ec({[qe]:Ya(),[He]:xa[He],[Ke]:xa[Ke],[Ze]:xa[Ze]})}function rc(t){return t.map((([t,e])=>{if(Qa(e)){return[t,e.catch((e=>{Wt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function nc(t){if(typeof t==="string"||t===undefined){return t}Wt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t);return undefined}function sc(t,e){const i=t?.schemaUrl;const r=e?.schemaUrl;const n=i===undefined||i==="";const s=r===undefined||r==="";if(n){return r}if(s){return i}if(i===r){return i}Wt.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',i,r);return undefined}class oc{_registeredViews=[];addView(t){this._registeredViews.push(t)}findViews(t,e){const i=this._registeredViews.filter((i=>this._matchInstrument(i.instrumentSelector,t)&&this._matchMeter(i.meterSelector,e)));return i}_matchInstrument(t,e){return(t.getType()===undefined||e.type===t.getType())&&t.getNameFilter().match(e.name)&&t.getUnitFilter().match(e.unit)}_matchMeter(t,e){return t.getNameFilter().match(e.name)&&(e.version===undefined||t.getVersionFilter().match(e.version))&&(e.schemaUrl===undefined||t.getSchemaUrlFilter().match(e.schemaUrl))}}function ac(t,e,i){if(!fc(t)){Wt.warn(`Invalid metric name: "${t}". The metric name should be a ASCII string with a length no greater than 255 characters.`)}return{name:t,type:e,description:i?.description??"",unit:i?.unit??"",valueType:i?.valueType??ut.DOUBLE,advice:i?.advice??{}}}function cc(t,e){return{name:t.name??e.name,description:t.description??e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function uc(t,e){return Do(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}const lc=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function fc(t){return lc.test(t)}class hc{_writableMetricStorage;_descriptor;constructor(t,e){this._writableMetricStorage=t;this._descriptor=e}_record(t,e={},i=Zt.active()){if(typeof t!=="number"){Wt.warn(`non-number value provided to metric ${this._descriptor.name}: ${t}`);return}if(this._descriptor.valueType===ut.INT&&!Number.isInteger(t)){Wt.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`);t=Math.trunc(t);if(!Number.isInteger(t)){return}}this._writableMetricStorage.record(t,e,i,Ea(Date.now()))}}class dc extends hc{add(t,e,i){this._record(t,e,i)}}class pc extends hc{add(t,e,i){if(t<0){Wt.warn(`negative value provided to counter ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class mc extends hc{record(t,e,i){this._record(t,e,i)}}class bc extends hc{record(t,e,i){if(t<0){Wt.warn(`negative value provided to histogram ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class vc{_metricStorages;_descriptor;_observableRegistry;constructor(t,e,i){this._descriptor=t;this._metricStorages=e;this._observableRegistry=i}addCallback(t){this._observableRegistry.addCallback(t,this)}removeCallback(t){this._observableRegistry.removeCallback(t,this)}}class wc extends vc{}class gc extends vc{}class yc extends vc{}function xc(t){return t instanceof vc}class kc{_meterSharedState;constructor(t){this._meterSharedState=t}createGauge(t,e){const i=ac(t,Ao.GAUGE,e);const r=this._meterSharedState.registerMetricStorage(i);return new mc(r,i)}createHistogram(t,e){const i=ac(t,Ao.HISTOGRAM,e);const r=this._meterSharedState.registerMetricStorage(i);return new bc(r,i)}createCounter(t,e){const i=ac(t,Ao.COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new pc(r,i)}createUpDownCounter(t,e){const i=ac(t,Ao.UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new dc(r,i)}createObservableGauge(t,e){const i=ac(t,Ao.OBSERVABLE_GAUGE,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new gc(i,r,this._meterSharedState.observableRegistry)}createObservableCounter(t,e){const i=ac(t,Ao.OBSERVABLE_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new wc(i,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(t,e){const i=ac(t,Ao.OBSERVABLE_UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new yc(i,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.addBatchCallback(t,e)}removeBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.removeBatchCallback(t,e)}}class Sc{_instrumentDescriptor;constructor(t){this._instrumentDescriptor=t}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(t){this._instrumentDescriptor=ac(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:t,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class Ec{_valueMap=new Map;_keyMap=new Map;_hash;constructor(t){this._hash=t}get(t,e){e??=this._hash(t);return this._valueMap.get(e)}getOrDefault(t,e){const i=this._hash(t);if(this._valueMap.has(i)){return this._valueMap.get(i)}const r=e();if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,r);return r}set(t,e,i){i??=this._hash(t);if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,e)}has(t,e){e??=this._hash(t);return this._valueMap.has(e)}*keys(){const t=this._keyMap.entries();let e=t.next();while(e.done!==true){yield[e.value[1],e.value[0]];e=t.next()}}*entries(){const t=this._valueMap.entries();let e=t.next();while(e.done!==true){yield[this._keyMap.get(e.value[0]),e.value[1],e.value[0]];e=t.next()}}get size(){return this._valueMap.size}}class _c extends Ec{constructor(){super(Mo)}}class Ac{_activeCollectionStorage=new _c;_cumulativeMemoStorage=new _c;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":true};_overflowHashCode;_aggregator;constructor(t,e){this._aggregator=t;this._cardinalityLimit=(e??2e3)-1;this._overflowHashCode=Mo(this._overflowAttributes)}record(t,e,i,r){let n=this._activeCollectionStorage.get(e);if(!n){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const e=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,(()=>this._aggregator.createAccumulation(r)));e?.record(t);return}n=this._aggregator.createAccumulation(r);this._activeCollectionStorage.set(e,n)}n?.record(t)}batchCumulate(t,e){Array.from(t.entries()).forEach((([t,i,r])=>{const n=this._aggregator.createAccumulation(e);n?.record(i);let s=n;if(this._cumulativeMemoStorage.has(t,r)){const e=this._cumulativeMemoStorage.get(t,r);s=this._aggregator.diff(e,n)}else{if(this._cumulativeMemoStorage.size>=this._cardinalityLimit){t=this._overflowAttributes;r=this._overflowHashCode;if(this._cumulativeMemoStorage.has(t,r)){const e=this._cumulativeMemoStorage.get(t,r);s=this._aggregator.diff(e,n)}}}if(this._activeCollectionStorage.has(t,r)){const e=this._activeCollectionStorage.get(t,r);s=this._aggregator.merge(e,s)}this._cumulativeMemoStorage.set(t,n,r);this._activeCollectionStorage.set(t,s,r)}))}collect(){const t=this._activeCollectionStorage;this._activeCollectionStorage=new _c;return t}}class Tc{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(t,e){this._aggregator=t;e.forEach((t=>{this._unreportedAccumulations.set(t,[])}))}buildMetrics(t,e,i,r){this._stashAccumulations(i);const n=this._getMergedUnreportedAccumulations(t);let s=n;let o;if(this._reportHistory.has(t)){const e=this._reportHistory.get(t);const i=e.collectionTime;o=e.aggregationTemporality;if(o===_o.CUMULATIVE){s=Tc.merge(e.accumulations,n,this._aggregator)}else{s=Tc.calibrateStartTime(e.accumulations,n,i)}}else{o=t.selectAggregationTemporality(e.type)}this._reportHistory.set(t,{accumulations:s,collectionTime:r,aggregationTemporality:o});const a=Mc(s);if(a.length===0){return undefined}return this._aggregator.toMetricData(e,o,a,r)}_stashAccumulations(t){const e=this._unreportedAccumulations.keys();for(const i of e){let e=this._unreportedAccumulations.get(i);if(e===undefined){e=[];this._unreportedAccumulations.set(i,e)}e.push(t)}}_getMergedUnreportedAccumulations(t){let e=new _c;const i=this._unreportedAccumulations.get(t);this._unreportedAccumulations.set(t,[]);if(i===undefined){return e}for(const t of i){e=Tc.merge(e,t,this._aggregator)}return e}static merge(t,e,i){const r=t;const n=e.entries();let s=n.next();while(s.done!==true){const[e,o,a]=s.value;if(t.has(e,a)){const n=t.get(e,a);const s=i.merge(n,o);r.set(e,s,a)}else{r.set(e,o,a)}s=n.next()}return r}static calibrateStartTime(t,e,i){for(const[r,n]of t.keys()){const t=e.get(r,n);t?.setStartTime(i)}return e}}function Mc(t){return Array.from(t.entries())}class Cc extends Sc{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(t,e,i,r,n){super(t);this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new Ac(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new Tc(e,r);this._attributesProcessor=i}record(t,e){const i=new _c;Array.from(t.entries()).forEach((([t,e])=>{i.set(this._attributesProcessor.process(t),e)}));this._deltaMetricStorage.batchCumulate(i,e)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}function Oc(t,e){let i="";if(t.unit!==e.unit){i+=`\t- Unit '${t.unit}' does not match '${e.unit}'\n`}if(t.type!==e.type){i+=`\t- Type '${t.type}' does not match '${e.type}'\n`}if(t.valueType!==e.valueType){i+=`\t- Value Type '${t.valueType}' does not match '${e.valueType}'\n`}if(t.description!==e.description){i+=`\t- Description '${t.description}' does not match '${e.description}'\n`}return i}function Pc(t,e){return`\t- use valueType '${t.valueType}' on instrument creation or use an instrument name other than '${e.name}'`}function Ic(t,e){return`\t- use unit '${t.unit}' on instrument creation or use an instrument name other than '${e.name}'`}function Lc(t,e){const i={name:e.name,type:e.type,unit:e.unit};const r=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${r}'`}function Dc(t,e){const i={name:e.name,type:e.type,unit:e.unit};const r=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${r}'\n \t- OR - create a new view with the name ${t.name} and description '${t.description}' and InstrumentSelector ${r}\n \t- OR - create a new view with the name ${e.name} and description '${t.description}' and InstrumentSelector ${r}`}function Rc(t,e){if(t.valueType!==e.valueType){return Pc(t,e)}if(t.unit!==e.unit){return Ic(t,e)}if(t.type!==e.type){return Lc(t,e)}if(t.description!==e.description){return Dc(t,e)}return""}class Nc{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new Nc}getStorages(t){let e=[];for(const t of this._sharedRegistry.values()){e=e.concat(t)}const i=this._perCollectorRegistry.get(t);if(i!=null){for(const t of i.values()){e=e.concat(t)}}return e}register(t){this._registerStorage(t,this._sharedRegistry)}registerForCollector(t,e){let i=this._perCollectorRegistry.get(t);if(i==null){i=new Map;this._perCollectorRegistry.set(t,i)}this._registerStorage(e,i)}findOrUpdateCompatibleStorage(t){const e=this._sharedRegistry.get(t.name);if(e===undefined){return null}return this._findOrUpdateCompatibleStorage(t,e)}findOrUpdateCompatibleCollectorStorage(t,e){const i=this._perCollectorRegistry.get(t);if(i===undefined){return null}const r=i.get(e.name);if(r===undefined){return null}return this._findOrUpdateCompatibleStorage(e,r)}_registerStorage(t,e){const i=t.getInstrumentDescriptor();const r=e.get(i.name);if(r===undefined){e.set(i.name,[t]);return}r.push(t)}_findOrUpdateCompatibleStorage(t,e){let i=null;for(const r of e){const e=r.getInstrumentDescriptor();if(uc(e,t)){if(e.description!==t.description){if(t.description.length>e.description.length){r.updateDescription(t.description)}Wt.warn("A view or instrument with the name ",t.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",Oc(e,t),"The longer description will be used.\nTo resolve the conflict:",Rc(e,t))}i=r}else{Wt.warn("A view or instrument with the name ",t.name," has already been registered and is incompatible with another registered view.\n","Details:\n",Oc(e,t),"To resolve the conflict:\n",Rc(e,t))}}return i}}class jc{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,i,r){this._backingStorages.forEach((n=>{n.record(t,e,i,r)}))}}class Uc{_buffer=new _c;_instrumentName;_valueType;constructor(t,e){this._instrumentName=t;this._valueType=e}observe(t,e={}){if(typeof t!=="number"){Wt.warn(`non-number value provided to metric ${this._instrumentName}: ${t}`);return}if(this._valueType===ut.INT&&!Number.isInteger(t)){Wt.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`);t=Math.trunc(t);if(!Number.isInteger(t)){return}}this._buffer.set(e,t)}}class zc{_buffer=new Map;observe(t,e,i={}){if(!xc(t)){return}let r=this._buffer.get(t);if(r==null){r=new _c;this._buffer.set(t,r)}if(typeof e!=="number"){Wt.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}if(t._descriptor.valueType===ut.INT&&!Number.isInteger(e)){Wt.warn(`INT value type cannot accept a floating-point value for ${t._descriptor.name}, ignoring the fractional digits.`);e=Math.trunc(e);if(!Number.isInteger(e)){return}}r.set(i,e)}}class $c{_callbacks=[];_batchCallbacks=[];addCallback(t,e){const i=this._findCallback(t,e);if(i>=0){return}this._callbacks.push({callback:t,instrument:e})}removeCallback(t,e){const i=this._findCallback(t,e);if(i<0){return}this._callbacks.splice(i,1)}addBatchCallback(t,e){const i=new Set(e.filter(xc));if(i.size===0){Wt.error("BatchObservableCallback is not associated with valid instruments",e);return}const r=this._findBatchCallback(t,i);if(r>=0){return}this._batchCallbacks.push({callback:t,instruments:i})}removeBatchCallback(t,e){const i=new Set(e.filter(xc));const r=this._findBatchCallback(t,i);if(r<0){return}this._batchCallbacks.splice(r,1)}async observe(t,e){const i=this._observeCallbacks(t,e);const r=this._observeBatchCallbacks(t,e);const n=await Promise.allSettled([...i,...r]);const s=n.filter((t=>t.status==="rejected")).map((t=>t.reason));return s}_observeCallbacks(t,e){return this._callbacks.map((async({callback:i,instrument:r})=>{const n=new Uc(r._descriptor.name,r._descriptor.valueType);let s=Promise.resolve(i(n));if(e!=null){s=Po(s,e)}await s;r._metricStorages.forEach((e=>{e.record(n._buffer,t)}))}))}_observeBatchCallbacks(t,e){return this._batchCallbacks.map((async({callback:i,instruments:r})=>{const n=new zc;let s=Promise.resolve(i(n));if(e!=null){s=Po(s,e)}await s;r.forEach((e=>{const i=n._buffer.get(e);if(i==null){return}e._metricStorages.forEach((e=>{e.record(i,t)}))}))}))}_findCallback(t,e){return this._callbacks.findIndex((i=>i.callback===t&&i.instrument===e))}_findBatchCallback(t,e){return this._batchCallbacks.findIndex((i=>i.callback===t&&Io(i.instruments,e)))}}class Bc extends Sc{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(t,e,i,r,n){super(t);this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new Ac(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new Tc(e,r);this._attributesProcessor=i}record(t,e,i,r){e=this._attributesProcessor.process(e,i);this._deltaMetricStorage.record(t,e,i,r)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}class Fc{process(t,e){return t}}class Gc{_processors;constructor(t){this._processors=t}process(t,e){let i=t;for(const t of this._processors){i=t.process(i,e)}return i}}function Vc(){return Hc}function qc(t){return new Gc(t)}const Hc=new Fc;class Jc{metricStorageRegistry=new Nc;observableRegistry=new $c;meter;_meterProviderSharedState;_instrumentationScope;constructor(t,e){this.meter=new kc(this);this._meterProviderSharedState=t;this._instrumentationScope=e}registerMetricStorage(t){const e=this._registerMetricStorage(t,Bc);if(e.length===1){return e[0]}return new jc(e)}registerAsyncMetricStorage(t){const e=this._registerMetricStorage(t,Cc);return e}async collect(t,e,i){const r=await this.observableRegistry.observe(e,i?.timeoutMillis);const n=this.metricStorageRegistry.getStorages(t);if(n.length===0){return null}const s=[];n.forEach((i=>{const r=i.collect(t,e);if(r!=null){s.push(r)}}));if(s.length===0){return{errors:r}}return{scopeMetrics:{scope:this._instrumentationScope,metrics:s},errors:r}}_registerMetricStorage(t,e){const i=this._meterProviderSharedState.viewRegistry.findViews(t,this._instrumentationScope);let r=i.map((i=>{const r=cc(i,t);const n=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(n!=null){return n}const s=i.aggregation.createAggregator(r);const o=new e(r,s,i.attributesProcessor,this._meterProviderSharedState.metricCollectors,i.aggregationCardinalityLimit);this.metricStorageRegistry.register(o);return o}));if(r.length===0){const i=this._meterProviderSharedState.selectAggregations(t.type);const n=i.map((([i,r])=>{const n=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(i,t);if(n!=null){return n}const s=r.createAggregator(t);const o=i.selectCardinalityLimit(t.type);const a=new e(t,s,Vc(),[i],o);this.metricStorageRegistry.registerForCollector(i,a);return a}));r=r.concat(n)}return r}}class Kc{viewRegistry=new oc;metricCollectors=[];meterSharedStates=new Map;resource;constructor(t){this.resource=t}getMeterSharedState(t){const e=Co(t);let i=this.meterSharedStates.get(e);if(i==null){i=new Jc(this,t);this.meterSharedStates.set(e,i)}return i}selectAggregations(t){const e=[];for(const i of this.metricCollectors){e.push([i,Ha(i.selectAggregation(t))])}return e}}class Zc{_sharedState;_metricReader;constructor(t,e){this._sharedState=t;this._metricReader=e}async collect(t){const e=Ea(Date.now());const i=[];const r=[];const n=Array.from(this._sharedState.meterSharedStates.values()).map((async n=>{const s=await n.collect(this,e,t);if(s?.scopeMetrics!=null){i.push(s.scopeMetrics)}if(s?.errors!=null){r.push(...s.errors)}}));await Promise.all(n);return{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:i},errors:r}}async forceFlush(t){await this._metricReader.forceFlush(t)}async shutdown(t){await this._metricReader.shutdown(t)}selectAggregationTemporality(t){return this._metricReader.selectAggregationTemporality(t)}selectAggregation(t){return this._metricReader.selectAggregation(t)}selectCardinalityLimit(t){return this._metricReader.selectCardinalityLimit?.(t)??2e3}}const Wc=/[\^$\\.+?()[\]{}|]/g;class Xc{_matchAll;_regexp;constructor(t){if(t==="*"){this._matchAll=true;this._regexp=/.*/}else{this._matchAll=false;this._regexp=new RegExp(Xc.escapePattern(t))}}match(t){if(this._matchAll){return true}return this._regexp.test(t)}static escapePattern(t){return`^${t.replace(Wc,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}}class Yc{_matchAll;_pattern;constructor(t){this._matchAll=t===undefined;this._pattern=t}match(t){if(this._matchAll){return true}if(t===this._pattern){return true}return false}}class Qc{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new Xc(t?.name??"*");this._type=t?.type;this._unitFilter=new Yc(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class tu{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new Yc(t?.name);this._versionFilter=new Yc(t?.version);this._schemaUrlFilter=new Yc(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function eu(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}function iu(t){if(eu(t)){throw new Error("Cannot create view with no selector arguments supplied")}if(t.name!=null&&(t?.instrumentName==null||Xc.hasWildcard(t.instrumentName))){throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}}class ru{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){iu(t);if(t.attributesProcessors!=null){this.attributesProcessor=qc(t.attributesProcessors)}else{this.attributesProcessor=Vc()}this.name=t.name;this.description=t.description;this.aggregation=Ha(t.aggregation??{type:qa.DEFAULT});this.instrumentSelector=new Qc({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit});this.meterSelector=new tu({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl});this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}}class nu{_sharedState;_shutdown=false;constructor(t){this._sharedState=new Kc(t?.resource??ic());if(t?.views!=null&&t.views.length>0){for(const e of t.views){this._sharedState.viewRegistry.addView(new ru(e))}}if(t?.readers!=null&&t.readers.length>0){for(const e of t.readers){const t=new Zc(this._sharedState,e);e.setMetricProducer(t);this._sharedState.metricCollectors.push(t)}}}getMeter(t,e="",i={}){if(this._shutdown){Wt.warn("A shutdown MeterProvider cannot provide a Meter");return ct()}return this._sharedState.getMeterSharedState({name:t,version:e,schemaUrl:i.schemaUrl}).meter}async shutdown(t){if(this._shutdown){Wt.warn("shutdown may only be called once per MeterProvider");return}this._shutdown=true;await Promise.all(this._sharedState.metricCollectors.map((e=>e.shutdown(t))))}async forceFlush(t){if(this._shutdown){Wt.warn("invalid attempt to force flush after MeterProvider shutdown");return}await Promise.all(this._sharedState.metricCollectors.map((e=>e.forceFlush(t))))}}var su;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(su||(su={}));var ou;(function(t){t["COUNTER"]="COUNTER";t["GAUGE"]="GAUGE";t["HISTOGRAM"]="HISTOGRAM";t["UP_DOWN_COUNTER"]="UP_DOWN_COUNTER";t["OBSERVABLE_COUNTER"]="OBSERVABLE_COUNTER";t["OBSERVABLE_GAUGE"]="OBSERVABLE_GAUGE";t["OBSERVABLE_UP_DOWN_COUNTER"]="OBSERVABLE_UP_DOWN_COUNTER"})(ou||(ou={}));var au;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(au||(au={}));var cu;(function(t){t[t["DEFAULT"]=0]="DEFAULT";t[t["DROP"]=1]="DROP";t[t["SUM"]=2]="SUM";t[t["LAST_VALUE"]=3]="LAST_VALUE";t[t["EXPLICIT_BUCKET_HISTOGRAM"]=4]="EXPLICIT_BUCKET_HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=5]="EXPONENTIAL_HISTOGRAM"})(cu||(cu={}));var uu;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE";t[t["LOWMEMORY"]=2]="LOWMEMORY"})(uu||(uu={}));const lu=()=>su.CUMULATIVE;const fu=t=>{switch(t){case ou.COUNTER:case ou.OBSERVABLE_COUNTER:case ou.GAUGE:case ou.HISTOGRAM:case ou.OBSERVABLE_GAUGE:return su.DELTA;case ou.UP_DOWN_COUNTER:case ou.OBSERVABLE_UP_DOWN_COUNTER:return su.CUMULATIVE}};const hu=t=>{switch(t){case ou.COUNTER:case ou.HISTOGRAM:return su.DELTA;case ou.GAUGE:case ou.UP_DOWN_COUNTER:case ou.OBSERVABLE_UP_DOWN_COUNTER:case ou.OBSERVABLE_COUNTER:case ou.OBSERVABLE_GAUGE:return su.CUMULATIVE}};function du(){const t="cumulative".toLowerCase();if(t==="cumulative"){return lu}if(t==="delta"){return fu}if(t==="lowmemory"){return hu}Wt.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${t}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);return lu}function pu(t){if(t!=null){if(t===uu.DELTA){return fu}else if(t===uu.LOWMEMORY){return hu}return lu}return du()}const mu=Object.freeze({type:cu.DEFAULT});function bu(t){return t?.aggregationPreference??(()=>mu)}class vu extends Xr{_aggregationTemporalitySelector;_aggregationSelector;constructor(t,e){super(t);this._aggregationSelector=bu(e);this._aggregationTemporalitySelector=pu(e?.temporalityPreference)}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}}class wu extends vu{constructor(t){super(Es(t??{},Wn,"v1/metrics",{"Content-Type":"application/json"}),t)}}class gu{meterProvider=null;meter=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;exportIntervalMillis;metricReader=null;captureCounter=null;errorCounter=null;modelLoadCounter=null;userInteractionCounter=null;captureLatencyHistogram=null;modelLoadLatencyHistogram=null;detectionLatencyHistogram=null;imageSizeHistogram=null;activeSessionsGauge=null;memoryUsageGauge=null;activeSessions=0;gaugeValues=new Map;constructor(t={}){this.collectorUrl=t.collectorUrl||"https://collector.jaak.ai/v1/metrics";this.serviceName=t.serviceName||"jaak-stamps-webcomponent";this.serviceVersion=t.serviceVersion||"2.1.0";this.debug=t.debug||false;this.customerId=t.customerId;this.tenantId=t.tenantId;this.environment=t.environment||"production";this.exportIntervalMillis=t.exportIntervalMillis||6e4}initialize(){try{const t=new wu({url:this.collectorUrl,headers:{"Content-Type":"application/json"}});this.metricReader=new Wa({exporter:t,exportIntervalMillis:this.exportIntervalMillis,exportTimeoutMillis:3e4});this.meterProvider=new nu({readers:[this.metricReader]});this.meter=this.meterProvider.getMeter(this.serviceName,this.serviceVersion);this.initializeMetrics();if(this.debug){console.log("[MetricsService] Initialized successfully",{collectorUrl:this.collectorUrl,serviceName:this.serviceName,serviceVersion:this.serviceVersion,environment:this.environment,customerId:this.customerId,tenantId:this.tenantId,exportIntervalMillis:this.exportIntervalMillis})}}catch(t){console.error("[MetricsService] Failed to initialize:",t)}}initializeMetrics(){if(!this.meter)return;const t=this.getBaseAttributes();try{this.captureCounter=this.meter.createCounter("jaak.captures.total",{description:"Total number of document captures",unit:"1"});this.errorCounter=this.meter.createCounter("jaak.errors.total",{description:"Total number of errors",unit:"1"});this.modelLoadCounter=this.meter.createCounter("jaak.model.loads.total",{description:"Total number of model loads",unit:"1"});this.userInteractionCounter=this.meter.createCounter("jaak.user.interactions.total",{description:"Total user interactions (clicks, etc.)",unit:"1"});this.captureLatencyHistogram=this.meter.createHistogram("jaak.capture.duration",{description:"Duration of capture operations",unit:"ms"});this.modelLoadLatencyHistogram=this.meter.createHistogram("jaak.model.load.duration",{description:"Duration of model loading",unit:"ms"});this.detectionLatencyHistogram=this.meter.createHistogram("jaak.detection.duration",{description:"Duration of detection inference",unit:"ms"});this.imageSizeHistogram=this.meter.createHistogram("jaak.image.size",{description:"Size of captured images",unit:"bytes"});this.activeSessionsGauge=this.meter.createObservableGauge("jaak.sessions.active",{description:"Number of active capture sessions",unit:"1"});this.activeSessionsGauge.addCallback((e=>{e.observe(this.activeSessions,t)}));if("memory"in performance){this.memoryUsageGauge=this.meter.createObservableGauge("jaak.memory.usage",{description:"JavaScript heap memory usage",unit:"bytes"});this.memoryUsageGauge.addCallback((e=>{const i=performance.memory;if(i){e.observe(i.usedJSHeapSize,t)}}))}if(this.debug){console.log("[MetricsService] Business metrics initialized")}}catch(t){console.error("[MetricsService] Failed to initialize metrics:",t)}}getBaseAttributes(){const t={"service.name":this.serviceName,"service.version":this.serviceVersion,"deployment.environment":this.environment};if(this.customerId){t["customer.id"]=this.customerId}if(this.tenantId){t["tenant.id"]=this.tenantId}return t}incrementCounter(t,e=1,i){try{const r=this.getBaseAttributes();const n={...r,...i};switch(t){case"captures":this.captureCounter?.add(e,n);break;case"errors":this.errorCounter?.add(e,n);break;case"model_loads":this.modelLoadCounter?.add(e,n);break;case"user_interactions":this.userInteractionCounter?.add(e,n);break;default:if(this.meter){const i=this.meter.createCounter(`jaak.${t}.total`,{description:`Total ${t}`,unit:"1"});i.add(e,n)}}if(this.debug){console.log(`[MetricsService] Counter incremented: ${t} += ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to increment counter:",t)}}recordHistogram(t,e,i){try{const r=this.getBaseAttributes();const n={...r,...i};switch(t){case"capture_duration":this.captureLatencyHistogram?.record(e,n);break;case"model_load_duration":this.modelLoadLatencyHistogram?.record(e,n);break;case"detection_duration":this.detectionLatencyHistogram?.record(e,n);break;case"image_size":this.imageSizeHistogram?.record(e,n);break;default:if(this.meter){const i=this.meter.createHistogram(`jaak.${t}`,{description:`Distribution of ${t}`,unit:"ms"});i.record(e,n)}}if(this.debug){console.log(`[MetricsService] Histogram recorded: ${t} = ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to record histogram:",t)}}setGauge(t,e,i){try{this.gaugeValues.set(t,e);if(t==="active_sessions"){this.activeSessions=e}if(this.debug){console.log(`[MetricsService] Gauge set: ${t} = ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to set gauge:",t)}}async measureDuration(t,e,i){const r=performance.now();try{const n=await e();const s=performance.now()-r;this.recordHistogram(t,s,i);return n}catch(e){const n=performance.now()-r;this.recordHistogram(t,n,{...i,error:true});throw e}}async flush(){try{if(this.metricReader){await this.metricReader.forceFlush()}if(this.debug){console.log("[MetricsService] Metrics flushed")}}catch(t){console.error("[MetricsService] Failed to flush metrics:",t)}}async cleanup(){try{if(this.metricReader){await this.metricReader.forceFlush();await this.metricReader.shutdown()}if(this.meterProvider){await this.meterProvider.shutdown()}if(this.debug){console.log("[MetricsService] Cleaned up successfully")}}catch(t){console.error("[MetricsService] Failed to cleanup:",t)}}recordCapture(t,e,i){this.incrementCounter("captures",1,{side:t,mode:e});this.recordHistogram("capture_duration",i,{side:t,mode:e})}recordError(t,e){this.incrementCounter("errors",1,{error_type:t,operation:e})}recordModelLoad(t,e,i){this.incrementCounter("model_loads",1,{model_type:t,cached:i});this.recordHistogram("model_load_duration",e,{model_type:t,cached:i})}recordDetection(t,e){this.recordHistogram("detection_duration",t,{detections_found:e})}recordImageSize(t,e){this.recordHistogram("image_size",e,{side:t})}updateActiveSessions(t){this.setGauge("active_sessions",t)}recordUserInteraction(t){this.incrementCounter("user_interactions",1,{interaction_type:t})}}class yu{services=new Map;cleanedUp=false;constructor(t){this.initializeServices(t)}initializeServices(t){const e=new n;const i=new s(e);const r=new o(e,t.preferredCamera);const a=new f(t.debug,t.useDocumentClassification,t.useDocumentDetector);let c=null;if(t.enableTelemetry!==false){c=new Eo({collectorUrl:t.telemetryCollectorUrl||"https://collector.jaak.ai/v1/traces",serviceName:"jaak-stamps-webcomponent",serviceVersion:"2.1.0",debug:t.debug,customerId:t.customerId,tenantId:t.tenantId,environment:t.environment||"production",propagateTraceHeaderCorsUrls:t.propagateTraceHeaderCorsUrls||[],enableAutoInstrumentation:true});c.initialize()}let u=null;if(t.enableMetrics!==false){u=new gu({collectorUrl:t.metricsCollectorUrl||"https://collector.jaak.ai/v1/metrics",serviceName:"jaak-stamps-webcomponent",serviceVersion:"2.1.0",debug:t.debug,customerId:t.customerId,tenantId:t.tenantId,environment:t.environment||"production",exportIntervalMillis:t.metricsExportIntervalMillis||6e4});u.initialize()}this.services.set("eventBus",e);this.services.set("stateManager",i);this.services.set("cameraService",r);this.services.set("detectionService",a);if(c){this.services.set("tracingService",c)}if(u){this.services.set("metricsService",u)}}get(t){const e=this.services.get(t);if(!e){throw new Error(`Service ${t} not found`)}return e}getEventBus(){return this.get("eventBus")}getStateManager(){return this.get("stateManager")}getCameraService(){return this.get("cameraService")}getDetectionService(){return this.get("detectionService")}getTracingService(){try{return this.get("tracingService")}catch{return null}}getMetricsService(){try{return this.get("metricsService")}catch{return null}}updateConfig(t){}async cleanup(){if(this.cleanedUp){return}this.cleanedUp=true;this.getDetectionService().cleanup();const t=this.getMetricsService();if(t){await t.cleanup()}const e=this.getTracingService();if(e){await e.cleanup()}this.getEventBus().clear();this.services.clear()}}class xu{apiEndpoint="/api/v1/license/validate";baseUrl;static ENVIRONMENT_URLS={dev:"https://api.dev.jaak.ai",qa:"https://api.qa.jaak.ai",sandbox:"https://api.sandbox.jaak.ai",prod:"https://services.api.jaak.ai"};constructor(t="prod"){this.baseUrl=xu.ENVIRONMENT_URLS[t]}async validateLicense(t,e,i="jaak-stamps-web"){const r=e||this.generateTraceId();const n={license:e?`L${r}`:t,origin:"web",app_id:i,product:"kyc",metadata:{sdk_version:"2.1.0"}};const s={"Content-Type":"application/json"};s["traceparent"]=`00-${r}-${this.generateSpanId()}-01`;try{const t=await fetch(`${this.baseUrl}${this.apiEndpoint}`,{method:"POST",headers:s,body:JSON.stringify(n)});if(!t.ok){const e=await t.json().catch((()=>({})));throw{error:e.error||"license_validation_failed",error_description:e.error_description||`HTTP ${t.status}: ${t.statusText}`,status_code:t.status}}const e=await t.json();return{...e,traceId:r}}catch(t){if(t.error){throw t}throw{error:"network_error",error_description:"Failed to connect to license validation service",status_code:0}}}generateTraceId(){const t=new Uint8Array(16);crypto.getRandomValues(t);return Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("")}generateSpanId(){const t=new Uint8Array(8);crypto.getRandomValues(t);return Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("")}static extractTraceIdFromLicense(t){if(!t||typeof t!=="string"){return null}const e=t.startsWith("L")?t.slice(1):t;if(e.length===32&&/^[a-f0-9]{32}$/i.test(e)){return e.toLowerCase()}console.warn("[LicenseValidationService] Invalid license format for trace ID:",t);return null}}const ku=":host{display:block;width:100%;height:100%;font-family:system-ui, -apple-system, sans-serif;color:#1a1a1a}.detector-container{display:flex;flex-direction:column;align-items:center;width:100%;height:100%}h1{font-size:24px;font-weight:500;color:#333;margin:0 0 24px 0}.video-container{position:relative;width:100%;height:100%;background-color:#000;border:none;border-radius:8px;overflow:hidden}video,.detection-overlay{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,.detection-overlay.mirror{transform:rotateY(180deg)}.detection-overlay{z-index:1;pointer-events:none}video{z-index:0}video::-webkit-media-controls{display:none !important}video::-webkit-media-controls-panel{display:none !important}video::-webkit-media-controls-play-button{display:none !important}video::-webkit-media-controls-start-playback-button{display:none !important}video::-webkit-media-controls-enclosure{display:none !important}.detection-box{transition:opacity 0.2s ease}.status{margin-top:16px;font-size:12px;color:#666}.overlay-mask{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10;display:block;pointer-events:none}.card-outline{position:absolute;top:var(--mask-center-y, 50%);left:var(--mask-center-x, 50%);transform:translate(-50%, -50%);width:var(--mask-width, 88%);height:var(--mask-height, 55%);border:none;border-radius:4px;background:transparent;opacity:0.8}.side{position:absolute;background:#999;transition:background-color 0.3s ease;border-radius:1px}.side-top.aligned{border-left-color:#28a745;border-top-color:#28a745}.side-right.aligned{border-right-color:#28a745;border-top-color:#28a745}.side-bottom.aligned{border-left-color:#28a745;border-bottom-color:#28a745}.side-left.aligned{border-right-color:#28a745;border-bottom-color:#28a745}.side-top{top:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-right{top:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-bottom{bottom:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.side-left{bottom:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);color:#ffffff;font-size:12px;font-weight:500;text-align:center;white-space:normal;padding:13px;max-width:300px;z-index:20;height:fit-content;width:fit-content;animation:slideInFromTopCentered 0.3s ease-out}.quality-indicator{position:absolute;top:20px;right:20px;display:flex;align-items:center;gap:8px;background:rgba(0, 0, 0, 0.8);padding:8px 12px;border-radius:20px;z-index:25;transition:all 0.3s ease}.quality-indicator.warning{background:rgba(255, 152, 0, 0.9)}.quality-indicator.good{background:rgba(76, 175, 80, 0.9)}.quality-score{color:#fff;font-size:12px;font-weight:600;min-width:30px;text-align:center}.quality-status{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:bold;color:#fff;transition:all 0.3s ease}.quality-status.ready{background:#4CAF50}.quality-status.not-ready{background:#f44336}.card-outline.quality-warning{animation:qualityWarning 1s ease-in-out infinite alternate}@keyframes qualityWarning{0%{box-shadow:0 0 0 3px rgba(255, 152, 0, 0.6)}100%{box-shadow:0 0 0 6px rgba(255, 152, 0, 0.3)}}.capture-animation{position:absolute;top:0;left:0;width:100%;height:100%;background:#fff;opacity:0;z-index:30;pointer-events:none;animation:captureFlash 0.6s ease-out}@keyframes captureFlash{0%{opacity:0}15%{opacity:0.8}30%{opacity:0}45%{opacity:0.4}60%{opacity:0}100%{opacity:0}}.card-outline.capturing{animation:pulseGreen 0.6s ease-out}@keyframes pulseGreen{0%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}}.flip-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showFlipInstruction 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.id-card-icon{width:80px;height:50px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:8px;position:relative;animation:flipCard 2s ease-in-out infinite;box-shadow:0 4px 12px rgba(0, 0, 0, 0.3)}.id-card-icon::before{content:'';position:absolute;top:8px;left:8px;width:16px;height:12px;background:rgba(255, 255, 255, 0.9);border-radius:2px}.id-card-icon::after{content:'';position:absolute;top:25px;left:8px;width:64px;height:3px;background:rgba(255, 255, 255, 0.7);border-radius:1px;box-shadow:0 6px 0 rgba(255, 255, 255, 0.7), 0 12px 0 rgba(255, 255, 255, 0.7)}.flip-text{margin-top:12px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px}@keyframes showFlipInstruction{0%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}}@keyframes flipCard{0%{transform:rotateY(0deg)}50%{transform:rotateY(180deg)}100%{transform:rotateY(360deg)}}.success-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showSuccessMessage 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.check-icon{width:80px;height:80px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:50%;position:relative;animation:bounceSuccess 0.6s ease-out;box-shadow:0 4px 16px rgba(108, 117, 125, 0.4);display:flex;align-items:center;justify-content:center}.check-icon::before{content:'';position:absolute;width:20px;height:35px;border:4px solid #fff;border-top:none;border-left:none;transform:rotate(45deg);}.success-text{margin-top:16px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;animation:fadeInUp 0.5s ease-out 0.4s both}@keyframes showSuccessMessage{0%{opacity:0;transform:translate(-50%, -50%) scale(0.5)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.9)}}@keyframes bounceSuccess{0%{transform:scale(0)}50%{transform:scale(1.1)}100%{transform:scale(1)}}@keyframes drawCheck{0%{width:0;height:0}50%{width:20px;height:0}100%{width:20px;height:35px}}@keyframes fadeInUp{0%{opacity:0;transform:translateY(20px)}100%{opacity:1;transform:translateY(0)}}.skip-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.back-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:320px}.back-capture-buttons{display:flex;gap:12px;align-items:center;justify-content:center;flex-wrap:wrap}.capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.capture-button:hover{background:#f8f9fa}.capture-button:active{background:#e9ecef;transform:translateY(1px)}.capture-button:disabled,.capture-button.primary-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}@media (max-width: 480px){.back-capture-section{bottom:16px;max-width:300px}.back-capture-buttons{flex-direction:column;gap:8px;width:100%}.capture-button,.back-capture-buttons .skip-button{width:100%;max-width:200px;padding:10px 20px;font-size:13px}.capture-button:disabled,.capture-button.primary-button:disabled,.skip-button:disabled{opacity:0.7 !important;cursor:not-allowed !important}}.skip-explanation{background:rgba(0, 0, 0, 0.5);color:#ffffff;padding:10px 16px;border-radius:8px;font-size:14px;font-weight:500;text-align:center;margin-bottom:12px;box-shadow:0 2px 8px rgba(0, 0, 0, 0.2);backdrop-filter:blur(12px);border:1px solid rgba(255, 255, 255, 0.1);animation:fadeIn 0.3s ease-in-out}@keyframes fadeIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.guide-text.performance-warning-text{animation:gentlePulse 2s ease-in-out infinite;background:rgba(255, 107, 107, 0.3);border:1px solid rgba(255, 107, 107, 0.5)}@keyframes gentlePulse{0%,100%{transform:translate(-50%, -50%) scale(1);background:rgba(255, 107, 107, 0.3)}50%{transform:translate(-50%, -50%) scale(1.02);background:rgba(255, 107, 107, 0.4)}}.skip-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.skip-button:hover{background:#f8f9fa}.skip-button:active{background:#e9ecef;transform:translateY(1px)}.skip-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}.camera-controls{position:absolute;top:16px;right:16px;z-index:25;display:flex;gap:8px;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}.camera-selector-button{height:32px;padding:0 10px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(12px);color:#ffffff;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s ease;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255, 255, 255, 0.1);white-space:nowrap;min-width:fit-content}.camera-selector-button:hover{background:rgba(0, 0, 0, 0.8);border-color:rgba(255, 255, 255, 0.2);transform:translateY(-1px)}.camera-selector-button:active{transform:translateY(0);background:rgba(0, 0, 0, 0.9)}.camera-selector-button:disabled,.camera-selector-button.loading{opacity:0.7;cursor:not-allowed;pointer-events:none}.camera-selector-button:disabled:hover,.camera-selector-button.loading:hover{transform:none;background:rgba(0, 0, 0, 0.6);border-color:rgba(255, 255, 255, 0.1)}.button-spinner{width:16px;height:16px;border:2px solid rgba(0, 0, 0, 0.2);border-top:2px solid #333333;border-radius:50%;animation:spin 1s linear infinite;display:inline-block;margin-right:8px;vertical-align:middle}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.camera-selector-dropdown{position:absolute;top:56px;right:16px;z-index:30;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;min-width:260px;max-width:300px;border:1px solid rgba(255, 255, 255, 0.1);overflow:hidden;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-8px) scale(0.95)}100%{opacity:1;transform:translateY(0) scale(1)}}@keyframes slideInFromTopCentered{0%{opacity:0;transform:translate(-50%, -50%) translateY(-8px) scale(0.95)}100%{opacity:1;transform:translate(-50%, -50%) translateY(0) scale(1)}}.camera-selector-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid rgba(255, 255, 255, 0.1)}.camera-selector-header span{font-weight:500;color:#ffffff;font-size:13px;opacity:0.9}.close-selector{width:20px;height:20px;border:none;background:none;color:rgba(255, 255, 255, 0.7);font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all 0.2s ease}.close-selector:hover{background:rgba(255, 255, 255, 0.1);color:#ffffff}.camera-list{padding:4px 0;max-height:240px;overflow-y:auto}.camera-option{width:100%;padding:8px 12px;border:none;background:none;text-align:left;cursor:pointer;transition:all 0.2s ease;display:flex;justify-content:flex-start;align-items:center;gap:8px;color:rgba(255, 255, 255, 0.9)}.camera-option:hover{background:rgba(255, 255, 255, 0.08)}.camera-option.selected{background:rgba(255, 255, 255, 0.12);color:#ffffff}.camera-label{font-size:13px;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-right:0;font-weight:400;display:flex;align-items:center;gap:6px}.camera-label .autofocus-icon{font-size:12px;color:#ffffff !important;opacity:0.8;flex-shrink:0}.selected-indicator{font-size:14px;color:#ffffff;opacity:0.9;flex-shrink:0}.device-info{padding:6px 12px;border-top:1px solid rgba(255, 255, 255, 0.1);background:rgba(255, 255, 255, 0.05)}.device-info small{color:rgba(255, 255, 255, 0.6);font-size:11px;text-transform:capitalize;font-weight:400}@media (max-width: 480px){.camera-controls{top:12px;right:12px;gap:6px}.camera-selector-button{height:36px;padding:0 12px;font-size:11px;border-radius:6px}.camera-selector-dropdown{right:12px;top:48px;min-width:240px;max-width:calc(100vw - 24px)}.camera-selector-header{padding:6px 10px}.camera-option{padding:6px 10px}.device-info{padding:4px 10px}}.watermark{position:absolute;bottom:12px;right:12px;z-index:15;pointer-events:none;opacity:0.7}.watermark img{height:24px;width:auto;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))}.component-status{position:absolute;top:16px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);display:flex;align-items:center;gap:6px;padding:6px 10px;z-index:40;height:32px;width:fit-content;animation:slideInFromTop 0.3s ease-out}.status-spinner{width:16px;height:16px;border:1px solid rgba(255, 255, 255, 0.3);border-top:1px solid #ffffff;border-radius:50%;animation:statusSpin 1s linear infinite;flex-shrink:0}.status-content{display:flex;flex-direction:column;gap:1px}.status-message{color:#ffffff;font-size:12px;font-weight:500;margin:0}.status-description{color:rgba(255, 255, 255, 0.7);font-size:10px;line-height:1.2;margin:0}@keyframes statusSpin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@media (max-width: 480px){.component-status{top:12px;left:12px;padding:4px 8px;gap:4px;height:28px;border-radius:8px}.status-spinner{width:14px;height:14px}.status-message{font-size:11px}.status-description{font-size:9px}.guide-text{font-size:11px;padding:4px 8px;border-radius:8px}}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.85);backdrop-filter:blur(4px);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:8px}.loading-spinner{width:50px;height:50px;border:3px solid rgba(255, 255, 255, 0.15);border-top:3px solid #28a745;border-radius:50%;animation:spin 1s ease-in-out infinite;margin-bottom:16px}.loading-text{color:#ffffff;font-size:14px;font-weight:500;text-align:center;opacity:0.9;margin-bottom:4px}.loading-description{color:rgba(255, 255, 255, 0.7);font-size:12px;text-align:center;opacity:0.8}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.performance-monitor{position:absolute;top:70px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromTop 0.3s ease-out;transition:all 0.3s ease}@keyframes slideInFromLeft{0%{opacity:0;transform:translateX(-20px) scale(0.95)}100%{opacity:1;transform:translateX(0) scale(1)}}.performance-expanded{padding:6px 10px}.metrics-row{display:flex;gap:8px;margin-bottom:4px}.metrics-row:last-child{margin-bottom:0}.metric-compact{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:50px}.metric-label{font-size:9px;color:rgba(255, 255, 255, 0.6);font-weight:500;text-transform:uppercase;letter-spacing:0.3px}.metric-value{font-size:10px;font-weight:600;font-family:'Monaco', 'Menlo', 'Consolas', monospace;padding:2px 4px;border-radius:3px;text-align:center;white-space:nowrap}.metric-value.good{color:#4ade80;background:rgba(74, 222, 128, 0.1);border:1px solid rgba(74, 222, 128, 0.2)}.metric-value.warning{color:#fbbf24;background:rgba(251, 191, 36, 0.1);border:1px solid rgba(251, 191, 36, 0.2)}.metric-value.danger{color:#f87171;background:rgba(248, 113, 113, 0.1);border:1px solid rgba(248, 113, 113, 0.2)}@media (max-width: 480px){.performance-monitor{top:60px;left:12px;width:fit-content}.performance-expanded{padding:4px 8px}.metrics-row{gap:6px;margin-bottom:3px}.metric-compact{min-width:45px;gap:1px}.metric-label{font-size:8px}.metric-value{font-size:9px;padding:1px 3px}}.quality-monitor{position:absolute;top:200px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromLeft 0.3s ease-out;transition:all 0.3s ease}.quality-text{padding:6px 10px;font-size:11px;color:white;font-family:'Monaco', 'Menlo', 'Consolas', monospace;line-height:1.4}.quality-fail{color:#ff9999}@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.7}}.metric-value.danger{animation:pulse 2s infinite}@media (max-width: 480px){.quality-monitor{top:160px;left:12px}.quality-text{padding:4px 8px;font-size:10px}}.manual-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.manual-capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.manual-capture-button:hover{background:#f8f9fa}.manual-capture-button:active{background:#e9ecef;transform:translateY(1px)}.manual-capture-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}@media (max-width: 480px){.manual-capture-section{bottom:16px;max-width:280px}.manual-capture-button{padding:10px 20px;font-size:13px}.manual-capture-button:disabled{opacity:0.7 !important;cursor:not-allowed !important}}.license-error-container{display:flex;align-items:center;justify-content:center;padding:40px 20px;height:100%;width:100%;background:#f5f7fa;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif}.license-error-card{background:#ffffff;border-radius:8px;box-shadow:0 2px 12px rgba(0, 0, 0, 0.1);max-width:480px;width:100%;padding:48px 32px;text-align:center}.license-error-icon{color:#dc3545;margin-bottom:24px}.license-error-title{color:#2c3e50;font-size:24px;font-weight:600;margin:0 0 16px 0}.license-error-message{color:#495057;font-size:16px;line-height:1.6;margin:0 0 24px 0}.license-error-help{color:#6c757d;font-size:14px;margin:0 0 32px 0}.license-error-help a{color:#007bff;text-decoration:none;font-weight:500}.license-error-help a:hover{text-decoration:underline}.license-error-footer{color:#adb5bd;font-size:12px;font-weight:500;padding-top:24px;border-top:1px solid #e9ecef}@media (max-width: 640px){.license-error-card{padding:32px 24px}.license-error-title{font-size:20px}.license-error-message{font-size:14px}}";const Su=class{constructor(i){t(this,i);this.captureCompleted=e(this,"captureCompleted");this.isReady=e(this,"isReady");this.traceIdGenerated=e(this,"traceIdGenerated")}get el(){return i(this)}debug=false;alignmentTolerance=15;maskSize=90;cropMargin=20;useDocumentClassification=false;useDocumentDetector=true;preferredCamera="auto";captureDelay=1500;enableBackDocumentTimer=false;backDocumentTimerDuration=20;telemetryCollectorUrl="https://collector.jaak.ai/v1/traces";metricsCollectorUrl="https://collector.jaak.ai/v1/metrics";enableTelemetry=true;enableMetrics=true;customerId;tenantId;environment="production";propagateTraceHeaderCorsUrls;metricsExportIntervalMillis=6e4;license;licenseEnvironment="prod";traceId;appId="jaak-stamps-web";captureCompleted;isReady;traceIdGenerated;detectionBoxes=[];sideAlignment={top:false,right:false,bottom:false,left:false};isMaskReady=false;shouldMirrorVideo=true;showCameraSelector=false;isSwitchingCamera=false;hasDocumentDetected=false;cameraInfoWithAutofocus={availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null};currentStatus={message:"Preparando capturador...",description:"Configurando herramientas de captura",type:"initializing",isInitialized:false};performanceData={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0};backDocumentTimerRemaining=0;showManualCaptureButton=false;performanceDegradedMode=false;showPerformanceMessage=false;captureStateVersion=0;processingButton=null;licenseValid=true;licenseError=null;classificationDisabled=false;licenseValidationService=null;serviceContainer;eventBus;stateManager;cameraService;detectionService;tracingService;metricsService;videoRef;detectionContainer;videoStream;animationId;lastDetectedBox;startTime;hasScreenshotTaken=false;alignmentStartTime;alignmentTimer;backDocumentTimer;orientationTimer;performanceMetrics={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0,lastUpdateTime:0};performanceUpdateInterval;frameSkipCounter=0;BASE_FRAME_SKIP=2;MAX_FRAME_SKIP=8;consecutiveFailures=0;MAX_FAILURES=30;lastInferenceTime=0;MIN_INFERENCE_INTERVAL=50;MOBILE_MIN_INFERENCE_INTERVAL=100;performanceHistory=[];PERFORMANCE_HISTORY_SIZE=10;PERFORMANCE_THRESHOLD_MS=2e3;SLOW_FRAMES_TO_TRIGGER=2;slowFrameCount=0;processedFramesCount=0;hasAutoSwitchedToManual=false;_manualModeLoggedOnce=false;canvasPool=[];MAX_CANVAS_POOL_SIZE=3;async componentWillLoad(){if(this.debug){console.log("[JAAK-DEBUG] componentWillLoad() - Props at initialization:");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector,"(type:",typeof this.useDocumentDetector,")");console.log("[JAAK-DEBUG] useDocumentClassification:",this.useDocumentClassification);console.log("[JAAK-DEBUG] debug:",this.debug);console.log("[JAAK-DEBUG] license:",this.license?this.license.substring(0,8)+"...":"EMPTY");console.log("[JAAK-DEBUG] licenseEnvironment:",this.licenseEnvironment);console.log("[JAAK-DEBUG] alignmentTolerance:",this.alignmentTolerance);console.log("[JAAK-DEBUG] maskSize:",this.maskSize);console.log("[JAAK-DEBUG] captureDelay:",this.captureDelay);console.log("[JAAK-DEBUG] preferredCamera:",this.preferredCamera);console.log("[JAAK-DEBUG] appId:",this.appId)}await new Promise((t=>setTimeout(t,50)));if(this.debug){console.log("[JAAK-DEBUG] Props AFTER 50ms wait:");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector,"(type:",typeof this.useDocumentDetector,")")}this.updateStatus("Validando licencia...","Verificando autorización de uso","initializing");await this.validateLicense();if(!this.licenseValid){if(this.debug){console.error("[JAAK-DEBUG] License validation FAILED. Stopping initialization.")}return}if(this.debug){console.log("[JAAK-DEBUG] License validation OK")}}async componentDidLoad(){try{if(!this.licenseValid){return}this.updateStatus("Preparando capturador...","Configurando herramientas de captura","initializing");await this.initializeServices();this.updateStatus("Preparando funciones...","Configurando herramientas de trabajo","initializing");await this.setupEventListeners();this.updateStatus("Configurando cámara...","Detectando dispositivos disponibles","initializing");await this.initializeComponent();if(this.debug){this.initializePerformanceMonitor()}}catch(t){this.updateStatus("Error de inicialización",t.message,"error")}}async initializeServices(){const t=this.propagateTraceHeaderCorsUrls?this.propagateTraceHeaderCorsUrls.split(",").map((t=>t.trim())):[];const e={debug:this.debug,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,cropMargin:this.cropMargin,useDocumentClassification:this.useDocumentClassification,useDocumentDetector:this.useDocumentDetector,preferredCamera:this.preferredCamera,captureDelay:this.captureDelay,telemetryCollectorUrl:this.telemetryCollectorUrl,metricsCollectorUrl:this.metricsCollectorUrl,enableTelemetry:this.enableTelemetry,enableMetrics:this.enableMetrics,customerId:this.customerId,tenantId:this.tenantId,environment:this.environment,propagateTraceHeaderCorsUrls:t,metricsExportIntervalMillis:this.metricsExportIntervalMillis};this.serviceContainer=new yu(e);this.eventBus=this.serviceContainer.getEventBus();this.stateManager=this.serviceContainer.getStateManager();this.cameraService=this.serviceContainer.getCameraService();this.detectionService=this.serviceContainer.getDetectionService();this.tracingService=this.serviceContainer.getTracingService();this.metricsService=this.serviceContainer.getMetricsService();if(this.tracingService&&this.traceId){this.tracingService.setSessionTraceId(this.traceId)}if(this.tracingService){const t=this.tracingService.startSpan("component.initialize",{"component.debug":this.debug,"component.useDocumentDetector":this.useDocumentDetector,"component.useDocumentClassification":this.useDocumentClassification});this.tracingService.endSpan(t)}}async validateLicense(){if(!this.license){console.error("❌ No license provided for JAAK Stamps component");this.licenseError='Este componente requiere una licencia válida. Por favor, proporcione una licencia usando el atributo "license".';this.licenseValid=false;this.updateStatus("Error de licencia","Licencia no proporcionada","error");return}try{console.log("🔑 Validating license for JAAK Stamps...");this.licenseValidationService=new xu(this.licenseEnvironment);const t=await this.licenseValidationService.validateLicense(this.license,this.traceId,this.appId);if(t&&t.access_token){this.licenseValid=true;this.licenseError=null;console.log("✅ License validated successfully for JAAK Stamps");if(t.traceId){this.traceIdGenerated.emit({traceId:t.traceId});console.log("📋 TraceId:",t.traceId)}}else{this.licenseValid=false;this.licenseError="La licencia proporcionada no es válida. Por favor, verifique su licencia e intente nuevamente.";this.updateStatus("Error de licencia","Licencia inválida","error");console.error("❌ Invalid license for JAAK Stamps")}}catch(t){this.licenseValid=false;const e=t;this.licenseError=e.error_description||"Error al validar la licencia. Por favor, verifique su conexión e intente nuevamente.";this.updateStatus("Error de licencia","Fallo en la validación","error");console.error("❌ License validation failed for JAAK Stamps:",t)}}async setupEventListeners(){this.eventBus.on("state-changed",(()=>{this.handleStateChange()}))}async initializeComponent(){this.validateProps();if(this.debug){this.stateManager.updateCaptureState({isLoading:true});await new Promise((t=>setTimeout(t,500)))}this.updateStatus("Detectando cámaras...","Buscando dispositivos de captura","initializing");await this.cameraService.detectDeviceType();await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","initializing");await this.loadOnnxRuntime();this.initializeResizeObserver()}validateProps(){if(this.maskSize<50||this.maskSize>100){this.maskSize=90}if(this.cropMargin<0||this.cropMargin>100){this.cropMargin=0}const t=["auto","front","back"];if(!t.includes(this.preferredCamera)){this.preferredCamera="auto"}if(this.captureDelay<0||this.captureDelay>1e4){this.captureDelay=1500}}async loadOnnxRuntime(){if(!window.ort){this.updateStatus("Preparando herramientas...","Configurando funciones de captura","initializing");const t=document.createElement("script");const e=navigator.userAgent;const i=/iPad|iPhone|iPod/.test(e);if(i){t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.wasm.min.js"}else{t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"}document.head.appendChild(t);await new Promise((e=>{t.onload=()=>{if(i&&window.ort?.env){const t=window.ort;t.env.wasm.simd=false;t.env.wasm.numThreads=1;t.env.wasm.proxy=false}setTimeout((async()=>{await this.finalizeInitialization();e(undefined)}),300)}}))}else{setTimeout((async()=>{await this.finalizeInitialization()}),300)}}async finalizeInitialization(){this.stateManager.updateCaptureState({isLoading:false});const t=await this.checkCameraPermissions();if(t){this.currentStatus={message:"Listo para capturar",description:"",type:"ready",isInitialized:true}}else{this.currentStatus={message:"Permisos de cámara requeridos",description:"Por favor, otorgue permisos de cámara para continuar",type:"error",isInitialized:true}}this.emitReadyEvent()}updateStatus(t,e,i="loading"){this.currentStatus={message:t,description:e,type:i,isInitialized:this.currentStatus.isInitialized}}emitReadyEvent(){const t=!!window.ort&&this.detectionService.isModelLoaded();this.isReady.emit(t)}async checkCameraPermissions(){try{if(!navigator.permissions){try{const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()));return true}catch{return false}}const t=await navigator.permissions.query({name:"camera"});return t.state==="granted"}catch(t){return false}}handleStateChange(){}initializeResizeObserver(){if("ResizeObserver"in window&&this.detectionContainer){const t=new ResizeObserver((()=>{this.handleResize()}));t.observe(this.detectionContainer.parentElement)}window.addEventListener("orientationchange",(()=>{if(this.orientationTimer){clearTimeout(this.orientationTimer)}this.orientationTimer=window.setTimeout((()=>{this.handleResize();this.orientationTimer=undefined}),300)}))}handleResize(){if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}}triggerRerender(){this.captureStateVersion=this.captureStateVersion+1}getGuideText(t){if(t==="completed"){return"Proceso completado"}if(this.showPerformanceMessage&&t==="front"){return"Modo manual activado por rendimiento. Use el botón para capturar."}if(t==="front"){if(this.showManualCaptureButton){return"Posicione el frente de su documento en el marco y presione el botón para capturar"}return"Alinee su identificación con el marco"}else if(t==="back"){if(this.useDocumentDetector){return"Si tu documento no tiene lado trasero, da clic en el botón para continuar con el proceso"}else{return"Posicione el reverso de su documento en el marco y capture, o salte este paso"}}return"Alinee su identificación con el marco"}updateMaskDimensions(t){if(!this.videoRef)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;if(e===0||i===0)return;const r=e/i;const n=t.width/t.height;let s,o;let a=0,c=0;if(r>n){s=t.width;o=t.width/r;c=(t.height-o)/2}else{o=t.height;s=t.height*r;a=(t.width-s)/2}const u=85.6/53.98;const l=o*u;let f,h;const d=this.maskSize/100;if(l<=s){h=o*d;f=h*u}else{f=s*d;h=f/u}const p=f/t.width*100;const m=h/t.height*100;const b=a+s/2;const v=c+o/2;const w=b/t.width*100;const g=v/t.height*100;this.el.style.setProperty("--mask-width",`${p}%`);this.el.style.setProperty("--mask-height",`${m}%`);this.el.style.setProperty("--mask-center-x",`${w}%`);this.el.style.setProperty("--mask-center-y",`${g}%`);this.isMaskReady=true}isComponentReady(){if(!this.currentStatus.isInitialized){return{ready:false,message:"El componente aún se está inicializando",status:"initializing"}}if(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing"){return{ready:false,message:"El componente está cargando recursos",status:"loading"}}if(!this.serviceContainer||!this.stateManager||!this.cameraService||!this.detectionService){return{ready:false,message:"Los servicios del componente no están disponibles",status:"error"}}return{ready:true}}async getCapturedImages(){const t=this.isComponentReady();if(!t.ready){throw new Error(t.message)}const e=this.stateManager.getCaptureState();if(e.step!=="completed"){throw new Error("El proceso de captura no ha sido completado")}return this.stateManager.getCapturedImages()}async isProcessCompleted(){const t=this.isComponentReady();if(!t.ready){return false}return this.stateManager.isProcessCompleted()}async startCapture(){const t=this.tracingService?.startSpan("capture.start");const e=this.isComponentReady();if(!e.ready){this.updateStatus(e.message,"Espere a que termine la inicialización",e.status);if(t){this.tracingService?.setSpanAttribute(t,"error",true);this.tracingService?.setSpanAttribute(t,"error.message",e.message);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}try{await this.startDetection();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true}}catch(e){this.updateStatus("Error al iniciar captura",e.message,"error");if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async stopCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.exitSession();return{success:true}}catch(t){return{success:false,error:t.message}}}async resetCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.resetDetection();return{success:true}}catch(t){return{success:false,error:t.message}}}async skipBackCapture(){console.log("🟡 Botón clicked: Saltar reverso");this.processingButton="skip-back";await new Promise((t=>setTimeout(t,100)));const t=this.isComponentReady();if(!t.ready){this.processingButton=null;return{success:false,error:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();if(t.step==="back"&&e.front.fullFrame){this.completeProcess(true);return{success:true}}else{return{success:false,error:"No se puede saltar el reverso en el estado actual"}}}catch(t){return{success:false,error:t.message}}finally{this.processingButton=null}}async getStatus(){const t=this.isComponentReady();if(!t.ready){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:t.status,componentMessage:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();return{isVideoActive:t.isVideoActive,captureStep:t.step,hasImages:!!(e.front.fullFrame||e.back.fullFrame),isProcessCompleted:this.stateManager.isProcessCompleted(),isModelPreloaded:this.detectionService.isModelLoaded(),componentStatus:"ready"}}catch(t){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:"error",componentMessage:t.message}}}async preloadModel(){const t=this.tracingService?.startSpan("model.preload");const e=this.isComponentReady();if(!e.ready){this.updateStatus(e.message,"Espere a que termine la inicialización",e.status);if(t){this.tracingService?.setSpanAttribute(t,"error",true);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}if(this.detectionService.isModelLoaded()){this.updateStatus("Reconocimiento listo","","ready");if(t){this.tracingService?.setSpanAttribute(t,"cached",true);this.tracingService?.endSpan(t)}return{success:true,message:"Model already loaded"}}try{const e=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:true})}try{const t=performance.now();const e=this.tracingService?.startSpan("model.detection.load");await this.detectionService.loadModel();if(e)this.tracingService?.endSpan(e);const i=performance.now()-t;this.metricsService?.recordModelLoad("detection",i,false)}catch(t){this.metricsService?.recordError("model_load_failed","detection");this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");try{const t=performance.now();const e=this.tracingService?.startSpan("model.classification.load");await this.detectionService.loadClassificationModel();if(e)this.tracingService?.endSpan(e);const i=performance.now()-t;this.metricsService?.recordModelLoad("classification",i,false)}catch(t){this.metricsService?.recordError("model_load_failed","classification");this.switchToManualModeWithError("Error al cargar modelo de clasificación");throw t}const i=performance.now();const r=i-e;if(this.debug){this.recordOnnxPerformance(r,0)}if(t){this.tracingService?.setSpanAttribute(t,"loadTime",r)}this.updateStatus("Finalizando configuración...","Preparando herramientas para captura","loading");await new Promise((t=>setTimeout(t,300)));this.updateStatus("Reconocimiento preparado","","ready");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}this.emitReadyEvent();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true,message:"Models preloaded successfully"}}catch(e){this.updateStatus("Error de configuración","No se pudieron preparar las herramientas necesarias","error");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async getCameraInfo(){const t=this.isComponentReady();if(!t.ready){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}try{return await this.cameraService.getCameraInfo()}catch(t){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}}async setPreferredCamera(t){const e=this.isComponentReady();if(!e.ready){return{success:false,error:e.message,selectedCamera:null,availableCameras:0}}try{this.preferredCamera=t;this.serviceContainer.updateConfig({preferredCamera:t});await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();const e=this.stateManager.getCaptureState();if(e.isVideoActive){const t=this.cameraService.getSelectedCameraId();if(t){await this.cameraService.switchCamera(t)}}return{success:true,selectedCamera:this.cameraService.getSelectedCameraId(),availableCameras:this.cameraService.getAvailableCameras().length}}catch(t){return{success:false,error:t.message,selectedCamera:null,availableCameras:0}}}async setCaptureDelay(t){if(t<0||t>1e4){return{success:false,error:"Capture delay must be between 0 and 10000 milliseconds",captureDelay:this.captureDelay}}this.captureDelay=t;if(this.serviceContainer){this.serviceContainer.updateConfig({captureDelay:t})}return{success:true,captureDelay:this.captureDelay}}async getCaptureDelay(){return this.captureDelay}checkDeviceCapabilities(){const t=navigator.deviceMemory;return{canUseML:true,reason:"Dispositivo compatible con detección automática.",memoryMB:t?t*1024:null}}async startDetection(){try{if(this.debug){console.log("[JAAK-DEBUG] startDetection() called");console.log("[JAAK-DEBUG] useDocumentDetector:",this.useDocumentDetector);console.log("[JAAK-DEBUG] useDocumentClassification:",this.useDocumentClassification)}const t=this.checkDeviceCapabilities();if(this.debug){console.log("[JAAK-DEBUG] Device capabilities:",JSON.stringify(t))}if(!t.canUseML&&this.useDocumentDetector){if(this.debug){console.warn("[JAAK-DEBUG] MANUAL MODE: Device cannot use ML. Reason:",t.reason)}this.switchToManualModeWithWarning(t.reason);return}if(!this.detectionService.isModelLoaded()){const t=performance.now();if(this.debug){console.log("[JAAK-DEBUG] Loading detection model...")}this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");this.stateManager.updateCaptureState({isLoading:true});try{await this.detectionService.loadModel();if(this.debug){console.log("[JAAK-DEBUG] Detection model loaded successfully in",(performance.now()-t).toFixed(0),"ms")}}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";if(this.debug){console.warn("[JAAK-DEBUG] MANUAL MODE: Out of memory loading detection model.",t)}this.switchToManualModeWithWarning(`Memoria insuficiente para detección automática ${t}. Modo manual activado - funciona igual de bien!`);return}else{if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Error loading detection model:",t.message)}this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");if(this.debug){console.log("[JAAK-DEBUG] Loading classification model...")}try{await this.detectionService.loadClassificationModel();if(this.debug){console.log("[JAAK-DEBUG] Classification model loaded successfully")}}catch(t){if(this.debug){console.warn("[JAAK-DEBUG] Classification model failed to load, disabling classification. Error:",t.message)}this.classificationDisabled=true}const e=performance.now();const i=e-t;if(this.debug){console.log("[JAAK-DEBUG] All models loaded in",i.toFixed(0),"ms");this.recordOnnxPerformance(i,0)}}else{if(this.debug){console.log("[JAAK-DEBUG] Models already loaded, skipping load")}}this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}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()){if(this.debug){console.log("[JAAK-DEBUG] detectFrame() skipped: videoRef=",!!this.videoRef,"detectionContainer=",!!this.detectionContainer,"modelLoaded=",this.detectionService.isModelLoaded())}return}if(!this.useDocumentDetector||this.performanceDegradedMode){if(this.debug&&!this._manualModeLoggedOnce){console.warn("[JAAK-DEBUG] detectFrame() in MANUAL MODE: useDocumentDetector=",this.useDocumentDetector,"performanceDegradedMode=",this.performanceDegradedMode);this._manualModeLoggedOnce=true}this.showManualCaptureButton=true;if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}else if(!this.performanceDegradedMode){this.showManualCaptureButton=false}if(e.isDetectionPaused){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter++;const i=this.getAdaptiveFrameSkip();if(this.frameSkipCounter<=i){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter=0;const r=Date.now();const n=this.cameraInfoWithAutofocus.deviceType==="mobile"||/Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);const s=this.cameraInfoWithAutofocus.deviceType==="tablet"||/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const o=n&&!s?this.MOBILE_MIN_INFERENCE_INTERVAL:this.MIN_INFERENCE_INTERVAL;if(r-this.lastInferenceTime<o){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.lastInferenceTime=r;const a=performance.now();let c;let u;let l;try{c=this.detectionService.preprocess(this.videoRef)}catch(t){if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Preprocess error:",t.message)}this.switchToManualModeWithError("Error al procesar imagen");return}try{u=await this.detectionService.runInference(c);l=performance.now()-a}catch(t){if(this.debug){console.error("[JAAK-DEBUG] MANUAL MODE: Inference error:",t.message)}this.switchToManualModeWithError("Error en detección automática");return}this.processedFramesCount++;if(this.debug){this.recordOnnxPerformance(0,l)}if(this.startTime&&Date.now()-this.startTime<5e3){u.forEach((t=>{const i=this.detectionService.isCardInFrame(t);const r=i?t.score*1.2:t.score;if(r>e.bestScore){this.stateManager.updateCaptureState({bestScore:r})}}))}const f=this.hasDocumentDetected;this.hasDocumentDetected=u.length>0;if(!f&&this.hasDocumentDetected&&e.step==="back"&&this.enableBackDocumentTimer){this.startBackDocumentTimer()}if(u.length===0){this.consecutiveFailures++}else{this.consecutiveFailures=0}if(this.debug){this.updateDetectionBoxes(u)}else{this.detectionBoxes=[]}this.updateMaskColor(u);const h=performance.now();const d=h-t;if(this.useDocumentDetector&&!this.hasAutoSwitchedToManual){if(this.debug){console.log(`[JAAK-DEBUG] Frame #${this.processedFramesCount} time: ${d.toFixed(0)}ms (threshold: ${this.PERFORMANCE_THRESHOLD_MS}ms) | inference: ${l.toFixed(0)}ms | slowFrames: ${this.slowFrameCount}/${this.SLOW_FRAMES_TO_TRIGGER}`)}if(d>=this.PERFORMANCE_THRESHOLD_MS){this.slowFrameCount++;if(this.debug){console.warn(`[JAAK-DEBUG] SLOW FRAME detected: ${d.toFixed(0)}ms >= ${this.PERFORMANCE_THRESHOLD_MS}ms | slowFrameCount: ${this.slowFrameCount}/${this.SLOW_FRAMES_TO_TRIGGER}`)}if(this.slowFrameCount>=this.SLOW_FRAMES_TO_TRIGGER){if(this.debug){console.error(`[JAAK-DEBUG] MANUAL MODE: Performance degraded. ${this.slowFrameCount} slow frames (>= ${this.PERFORMANCE_THRESHOLD_MS}ms) exceeded threshold of ${this.SLOW_FRAMES_TO_TRIGGER}`)}this.switchToManualMode()}}else{if(this.slowFrameCount>0){if(this.debug){console.log(`[JAAK-DEBUG] Fast frame, resetting slowFrameCount from ${this.slowFrameCount} to 0`)}this.slowFrameCount=0}}if(this.processedFramesCount===2){this.updateStatus("Captura activa","Buscando documento en el marco de captura","active")}}if(this.debug){this.recordFrameProcessing(d,u.length)}if(e.step!=="completed"){if(this.consecutiveFailures>this.MAX_FAILURES){setTimeout((()=>this.detectFrame()),200)}else{this.animationId=requestAnimationFrame((()=>this.detectFrame()))}}}catch(t){const e=this.stateManager.getCaptureState();if(e.step!=="completed"){setTimeout((()=>this.detectFrame()),100)}}}disconnectedCallback(){this.cleanup()}cleanup(){if(this.animationId){cancelAnimationFrame(this.animationId)}if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(this.orientationTimer){clearTimeout(this.orientationTimer);this.orientationTimer=undefined}this.releaseOnnxResources();if(this.performanceUpdateInterval){clearInterval(this.performanceUpdateInterval);this.performanceUpdateInterval=undefined}this.canvasPool=[];this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.serviceContainer?.cleanup()}render(){const t=this.stateManager?.getCaptureState()||{isVideoActive:false,showFlipAnimation:false,showSuccessAnimation:false,step:"front",isCapturing:false};const e=this.cameraInfoWithAutofocus;return r("div",{key:"9f2c1f21e7c18a77f519444bad87d29b2dfd2e6c",class:"detector-container"},!this.licenseValid&&this.licenseError&&r("div",{key:"d2965c6d859e8dd36f6a883288f086b9a39f236d",class:"license-error-container"},r("div",{key:"0db457c58ba390892ecc1046f410f35781d534fb",class:"license-error-card"},r("svg",{key:"9d5bb7a635157c8515323e0506f5f5add50e07dc",class:"license-error-icon",width:"64",height:"64",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r("path",{key:"938b6fd1b4c3f574c47d1678a87db8db7053945c",d:"M12 22C12 22 20 18 20 12V5L12 2L4 5V12C4 18 12 22 12 22Z",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}),r("path",{key:"8e5eb1966fa88e7f0a6f799cd8ce96fc86f0c291",d:"M12 8V12",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"}),r("circle",{key:"d4f798caf065b269d9d246cd099499f9a9e86008",cx:"12",cy:"16",r:"0.5",fill:"currentColor",stroke:"currentColor","stroke-width":"1"})),r("h2",{key:"109fcd76d9b0c27f33f037ed1c16031a3e9a7966",class:"license-error-title"},"Licencia Requerida"),r("p",{key:"c4d582a8e950498c80980faf25d50d3dea71ee8e",class:"license-error-message"},this.licenseError),r("p",{key:"6b15b08047124e4cec49f8b6b02d5938c2071c9b",class:"license-error-help"},"Contacte a soporte: ",r("a",{key:"0a6fd5acce763c068fe2ae929e16a3b90223a4b5",href:"mailto:support@jaak.ai"},"support@jaak.ai")),r("div",{key:"bb7a438b6d8f506334086ee511c7deaa37ab59aa",class:"license-error-footer"},"JAAK Stamps"))),this.licenseValid&&r("div",{key:"1fd31d4721feb0c4cd8ff1621646d2b20211b22f",class:"video-container"},r("video",{key:"ec228d91b0e2a8e18a0acb898198983685c97572",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{display:t.isVideoActive?"block":"none"}}),r("div",{key:"e1711ea66777df0e482d93a82b82bff63c9fe9f0",ref:t=>this.detectionContainer=t,class:`detection-overlay ${this.shouldMirrorVideo?"mirror":""}`},this.debug&&this.detectionBoxes.map(((t,e)=>r("div",{key:e,class:"detection-box",style:{position:"absolute",left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,border:"2px solid #32406C",pointerEvents:"none",boxSizing:"border-box"}})))),this.isMaskReady&&r("div",{key:"00e7b7a30d95f72fff38d37dbad7715262f4bcbc",class:"overlay-mask"},r("div",{key:"7f2cefac16306c4db77145ff4a2e0c36bbf71b41",class:"card-outline"},r("div",{key:"6a160a7be2fa6b39a01af7e7ac26612439726a0d",class:"side side-top"}),r("div",{key:"33317ed5d33142557198e315796fe472915988e5",class:"side side-right"}),r("div",{key:"15428b208d96c70da90540ade83ea736829b6cfc",class:"side side-bottom"}),r("div",{key:"615e5c6cd8861921a314372aa522ce678b035297",class:"side side-left"})),!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"786fdc87ffc5977ccab04e201b68cca6624a3a75",class:`guide-text ${this.showPerformanceMessage?"performance-warning-text":""}`},this.getGuideText(t.step)),t.step==="back"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"87a0b3460776e267a6288800b4c27d790f874555",class:"back-capture-section"},r("div",{key:"f75551d152bc5f1b41d56daaa44c360d42b3c6d7",class:"back-capture-buttons"},(!this.useDocumentDetector||this.performanceDegradedMode||this.showManualCaptureButton)&&r("button",{key:"798801b00d7be739db78267224193a64813c92be",class:"capture-button primary-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-back"&&r("span",{key:"14ecf72110b1583bd8c4e75f669cd8c71c01d074",class:"button-spinner"}),"Capturar Reverso"),r("button",{key:"ed12d7774f8399244913c468e118a6a9d9a6888b",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button",disabled:this.processingButton!==null},this.processingButton==="skip-back"&&r("span",{key:"e75d2a3da9167050fd315b27871eff612f6954ff",class:"button-spinner"}),this.enableBackDocumentTimer&&this.backDocumentTimerRemaining>0?`Saltar reverso (${this.backDocumentTimerRemaining}s)`:"Saltar reverso"))),t.isVideoActive&&r("div",{key:"019fdafddac5d9ad093f7d0adaf0f9dda29c8944",class:"camera-controls"},r("button",{key:"dbdeac63de4cf5f09f12b1757e87fc5c5c21fc29",class:`camera-selector-button ${this.isSwitchingCamera?"loading":""}`,onClick:()=>this.toggleCameraSelector(),type:"button",title:"Seleccionar cámara",disabled:this.isSwitchingCamera},this.isSwitchingCamera?r("div",{class:"button-spinner"}):"Cámaras")),this.showCameraSelector&&e.availableCameras.length>0&&r("div",{key:"c62b8914fba9dec18ddcecfeccb1cbe0ec59fae2",class:"camera-selector-dropdown"},r("div",{key:"9a1861c72c2ae75cced3a13b4e3cce28f2f2eff3",class:"camera-selector-header"},r("span",{key:"f4d20f3efe85bf727d3cc7bb380b9fa53bfd00e8"},"Seleccionar Cámara"),r("button",{key:"2cae8c595fff51108c9a17786350cc42a129bb88",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),r("div",{key:"643dbb27c6f52372819b9d2daf4b5f2ed67b5dc3",class:"camera-list"},e.availableCameras.map((t=>r("button",{key:t.id,class:`camera-option ${e.selectedCameraId===t.id?"selected":""}`,onClick:()=>this.handleCameraSwitch(t.id),type:"button"},r("span",{class:"camera-label"},t.label||`Cámara ${e.availableCameras.indexOf(t)+1}`,t.hasAutofocus&&r("span",{class:"autofocus-icon",title:"Autofoco disponible"},"⦿")),e.selectedCameraId===t.id&&r("span",{class:"selected-indicator"},"✓"))))),r("div",{key:"750fe47a0ae0eb1802b3126d8e49e6b8ad536879",class:"device-info"},r("small",{key:"a6fa21c1ae530708f830c17774e226c8f06d8b96"},"Dispositivo: ",e.deviceType))),this.showManualCaptureButton&&t.step==="front"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"a2f91224f2166eb3a8962ba581196d64c7cec2cb",class:"manual-capture-section"},r("button",{key:"4ce9090a4ed8e0346463ab0a77502a25990a2512",class:"manual-capture-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-front"&&r("span",{key:"4e9b12bdc735e86faadcf521083d42080f230183",class:"button-spinner"}),"Capturar Frente"))),t.isCapturing&&r("div",{key:"d275dd3d3f62cfa943efd2e69d6898981c34f547",class:"capture-animation"}),t.showFlipAnimation&&r("div",{key:"038cc4f1b245ff6fad917efb8d558e216de1771b",class:"flip-animation"},r("div",{key:"61d9097585ed53d9b2798d826aac274b9ea42390",class:"id-card-icon"}),r("div",{key:"90db95f234a9f25aae40d3b2c480e6dc1a580a84",class:"flip-text"},"¡Voltea tu identificación!")),t.showSuccessAnimation&&r("div",{key:"586ac9d2e89fdd4bf13610e31c43142c84f4d8c3",class:"success-animation"},r("div",{key:"8ed80578d1deacd808988d80d9677fb849267b1e",class:"check-icon"}),r("div",{key:"124615b15175f16946c0b3722fcf5a39b9ad4631",class:"success-text"},"¡Proceso completado!")),r("div",{key:"e587fd78705e91f5f3885e514f556288724bbc57",class:`component-status status-${this.currentStatus.type}`},(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing")&&r("div",{key:"a9a8afa7f3653586778acc95ccecd6927a0350c8",class:"status-spinner"}),r("div",{key:"db30d1bf772920b111e60ca22ff2fc8150e5d51f",class:"status-content"},r("div",{key:"3dc8912cc18fc61d2f42173e2605ef9e3b7f906a",class:"status-message"},this.currentStatus.message),this.currentStatus.description&&r("div",{key:"9025868961082897f19b1c230346a985ea3e0ca2",class:"status-description"},this.currentStatus.description))),this.debug&&r("div",{key:"8f18ba02911a3605ed88cb6f93926f9412289e56",class:"performance-monitor"},r("div",{key:"5531d873b7baed61d17f7b94106a7dd953e079c1",class:"performance-expanded"},r("div",{key:"af62b9f0dcfa3f4ecdc1925fe26d36a221d74afd",class:"metrics-row"},r("div",{key:"230c75005a1c8608d97486063b23897da676f9d6",class:"metric-compact"},r("span",{key:"48a28744a884124517e5ce55e0e47dd16c207a6f",class:"metric-label"},"FPS"),r("span",{key:"e6504c0075f9c730898dc5597a91475e99a5550f",class:`metric-value ${this.performanceData.fps<15?"warning":this.performanceData.fps<10?"danger":"good"}`},this.performanceData.fps)),r("div",{key:"df732632425cb06d47f14d18f2d87900f2ff293b",class:"metric-compact"},r("span",{key:"f32737c081480760714c3224749d67b4dffd6756",class:"metric-label"},"MEM"),r("span",{key:"d2d2ff4ed6721bfbc15bf20e41ea452b0a6f6670",class:`metric-value ${this.performanceData.memoryUsage>100?"warning":this.performanceData.memoryUsage>200?"danger":"good"}`},this.performanceData.memoryUsage,"MB"))),r("div",{key:"7d6333691cf92a12c8b2974b68756d2d59df4301",class:"metrics-row"},r("div",{key:"63f1b39293780e01c6119c14b46febf67ff58a89",class:"metric-compact"},r("span",{key:"84f4ed08009d3a2414c3a6e097c78b69d8854a3b",class:"metric-label"},"INF"),r("span",{key:"5512948dcebaadc442fe9161bc4ad05ae0960dbf",class:`metric-value ${this.performanceData.inferenceTime>100?"warning":this.performanceData.inferenceTime>200?"danger":"good"}`},this.performanceData.inferenceTime,"ms")),r("div",{key:"9e523d2a51c36d08748a4fa3c88f0aa48ad4482e",class:"metric-compact"},r("span",{key:"38593b6e84eadc87f129bfc3d5494845063c936a",class:"metric-label"},"FRAME"),r("span",{key:"5fcddc82c511360870875c1be5eaaedd1523eb20",class:`metric-value ${this.performanceData.frameProcessingTime>50?"warning":this.performanceData.frameProcessingTime>100?"danger":"good"}`},this.performanceData.frameProcessingTime,"ms"))),r("div",{key:"ea0ff4f807a7c70fce1938dd9b8036362855b547",class:"metrics-row"},r("div",{key:"929c04a5bee635a8de0e79208cd4c6fb47fb4120",class:"metric-compact"},r("span",{key:"5f3b500ede8ffcaf1c824cb0760f18d441dd4c1b",class:"metric-label"},"DET"),r("span",{key:"050ae9a0f52bc4614f35f16cf8d4f47e96b5d55b",class:"metric-value good"},this.performanceData.successfulDetections,"/",this.performanceData.totalDetections)),r("div",{key:"8cbee2808ec4355007a9c441495579235415f47b",class:"metric-compact"},r("span",{key:"769941a75abbc120289c6663d69d3f73c783d79e",class:"metric-label"},"RATE"),r("span",{key:"64b9954fd29a39bbf560833fdde393e4778fc6ec",class:`metric-value ${this.performanceData.detectionRate<30?"danger":this.performanceData.detectionRate<60?"warning":"good"}`},this.performanceData.detectionRate,"%"))))),r("div",{key:"bc87799947f87213ff5f781353aa948882bfdce3",class:"watermark"},r("img",{key:"8ddf884a54af69e548eea8619340ca83cc736acc",src:"https://static.jaak.ai/commons/powered-by-jaak.png",alt:"Powered by Jaak"}))))}updateDetectionBoxes(t){if(!this.videoRef||!this.detectionContainer)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;const r=this.detectionContainer.parentElement;const n=r.getBoundingClientRect();const s=n.width;const o=n.height;if(e===0||i===0)return;const a=e/i;const c=s/o;let u,l;let f=0,h=0;if(a>c){u=s;l=s/a;h=(o-l)/2}else{l=o;u=o*a;f=(s-u)/2}const d=320;const p=u/d;const m=l/d;this.detectionBoxes=t.map((t=>({x:t.x*p+f,y:t.y*m+h,w:t.w*p,h:t.h*m,score:t.score})))}updateMaskColor(t){const e=this.el.shadowRoot?.querySelector(".card-outline");const i=this.el.shadowRoot?.querySelectorAll(".corner");const r=this.el.shadowRoot?.querySelector(".side-top");const n=this.el.shadowRoot?.querySelector(".side-right");const s=this.el.shadowRoot?.querySelector(".side-bottom");const o=this.el.shadowRoot?.querySelector(".side-left");let a=null;let c={top:false,right:false,bottom:false,left:false};if(t.length>0){a=t.reduce(((t,e)=>e.score>t.score?e:t));const e={INPUT_SIZE:320,ID1_ASPECT_RATIO:85.6/53.98,shouldMirrorVideo:this.shouldMirrorVideo,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,videoRef:this.videoRef};c=this.detectionService.checkSideAlignment(a,e);this.sideAlignment=c}else{this.sideAlignment={top:false,right:false,bottom:false,left:false}}r?.classList.toggle("aligned",c.top);n?.classList.toggle("aligned",c.right);s?.classList.toggle("aligned",c.bottom);o?.classList.toggle("aligned",c.left);const u=this.detectionService.areAllSidesAligned(c);const l=this.stateManager.getCaptureState();if(l.step==="back"&&this.enableBackDocumentTimer&&a){const t=c.top||c.right||c.bottom||c.left;if(t){this.startBackDocumentTimer()}}if(u&&a){e?.classList.add("perfect-match");i?.forEach((t=>t.classList.add("perfect-match")));if(!this.hasScreenshotTaken){const t=Date.now();if(!this.alignmentStartTime){this.alignmentStartTime=t}const e=t-this.alignmentStartTime;if(e>=this.captureDelay){this.lastDetectedBox=a;this.takeScreenshot().catch((()=>{}));this.hasScreenshotTaken=true;this.alignmentStartTime=undefined;setTimeout((()=>{this.hasScreenshotTaken=false}),2e3)}}}else{e?.classList.remove("perfect-match");i?.forEach((t=>t.classList.remove("perfect-match")));if(this.alignmentStartTime){this.alignmentStartTime=undefined}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}}}async takeManualScreenshot(){console.log("🔵 Botón clicked: Capturar (Frente/Reverso)");const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.manual");const i=this.stateManager?.getCaptureState();const r=i?.step==="front"?"front":"back";if(i?.step==="front"){this.processingButton="capture-front";if(e)this.tracingService?.setSpanAttribute(e,"side","front")}else if(i?.step==="back"){this.processingButton="capture-back";if(e)this.tracingService?.setSpanAttribute(e,"side","back")}this.metricsService?.recordUserInteraction("manual_capture_button");console.log("🔵 processingButton set to:",this.processingButton);await new Promise((t=>setTimeout(t,100)));if(!this.videoRef){this.processingButton=null;if(e){this.tracingService?.setSpanAttribute(e,"error","no_video_ref");this.tracingService?.endSpan(e)}return}await this.takeScreenshotWithMaskCoordinates();const n=performance.now()-t;this.metricsService?.recordCapture(r,"manual",n);if(e){this.tracingService?.setSpanAttribute(e,"success",true);this.tracingService?.endSpan(e)}}async takeScreenshotWithMaskCoordinates(){if(!this.videoRef||!this.detectionContainer)return;this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const t=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const e=t.getContext("2d",{alpha:false});e.clearRect(0,0,t.width,t.height);e.drawImage(this.videoRef,0,0,t.width,t.height);const i=this.detectionContainer.parentElement;const r=i.getBoundingClientRect();const n=parseFloat(this.el.style.getPropertyValue("--mask-width").replace("%",""))||90;const s=parseFloat(this.el.style.getPropertyValue("--mask-height").replace("%",""))||56.25;const o=parseFloat(this.el.style.getPropertyValue("--mask-center-x").replace("%",""))||50;const a=parseFloat(this.el.style.getPropertyValue("--mask-center-y").replace("%",""))||50;const c=this.videoRef.videoWidth;const u=this.videoRef.videoHeight;const l=c/u;const f=r.width/r.height;let h,d;let p=0,m=0;if(l>f){h=r.width;d=r.width/l;m=(r.height-d)/2}else{d=r.height;h=r.height*l;p=(r.width-h)/2}const b=n/100*r.width;const v=s/100*r.height;const w=o/100*r.width;const g=a/100*r.height;const y=c/h;const x=u/d;const k=(w-p)*y;const S=(g-m)*x;const E=b*y;const _=v*x;const A=Math.max(0,k-E/2-this.cropMargin);const T=Math.max(0,S-_/2-this.cropMargin);const M=Math.min(E+2*this.cropMargin,c-A);const C=Math.min(_+2*this.cropMargin,u-T);const O=this.getPooledCanvas(M,C);const P=O.getContext("2d",{alpha:false});P.clearRect(0,0,O.width,O.height);P.drawImage(this.videoRef,A,T,M,C,0,0,M,C);const I=this.stateManager.getCaptureState();if(I.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/jpeg"),cropped:O.toDataURL("image/jpeg")}});if(this.useDocumentClassification&&!this.classificationDisabled){try{const e=await this.detectionService.classifyDocument(O);if(e&&e.class==="passport"){this.completeProcess(true);this.returnCanvasToPool(t);this.returnCanvasToPool(O);this.processingButton=null;return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});this.triggerRerender();setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.triggerRerender();this.startBackDocumentTimer();this.processingButton=null}),3e3)}else if(I.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/jpeg"),cropped:O.toDataURL("image/jpeg")}});this.completeProcess(false);this.processingButton=null}this.returnCanvasToPool(t);this.returnCanvasToPool(O)}async takeScreenshot(){if(!this.videoRef||!this.lastDetectedBox)return;const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.auto");this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const i=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const r=i.getContext("2d",{alpha:false});r.clearRect(0,0,i.width,i.height);r.drawImage(this.videoRef,0,0,i.width,i.height);const n=320;const s=this.videoRef.videoWidth/n;const o=this.videoRef.videoHeight/n;const a=Math.max(0,this.lastDetectedBox.x*s-this.cropMargin);const c=Math.max(0,this.lastDetectedBox.y*o-this.cropMargin);const u=Math.min(this.lastDetectedBox.w*s+2*this.cropMargin,this.videoRef.videoWidth-a);const l=Math.min(this.lastDetectedBox.h*o+2*this.cropMargin,this.videoRef.videoHeight-c);const f=this.getPooledCanvas(u,l);const h=f.getContext("2d",{alpha:false});h.clearRect(0,0,f.width,f.height);h.drawImage(this.videoRef,a,c,u,l,0,0,u,l);const d=this.stateManager.getCaptureState();if(d.step==="front"){const r=i.toDataURL("image/jpeg");const n=f.toDataURL("image/jpeg");this.stateManager.setCapturedImages({front:{fullFrame:r,cropped:n}});const s=performance.now()-t;this.metricsService?.recordCapture("front","auto",s);this.metricsService?.recordImageSize("front",r.length);if(e){this.tracingService?.setSpanAttribute(e,"side","front")}if(this.useDocumentClassification&&!this.classificationDisabled){try{const t=await this.detectionService.classifyDocument(f);if(t&&t.class==="passport"){if(e){this.tracingService?.setSpanAttribute(e,"document.type","passport");this.tracingService?.endSpan(e)}this.completeProcess(true);return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});if(e){this.tracingService?.endSpan(e)}setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.startBackDocumentTimer()}),3e3)}else if(d.step==="back"){const r=i.toDataURL("image/jpeg");const n=f.toDataURL("image/jpeg");this.stateManager.setCapturedImages({back:{fullFrame:r,cropped:n}});const s=performance.now()-t;this.metricsService?.recordCapture("back","auto",s);this.metricsService?.recordImageSize("back",r.length);if(e){this.tracingService?.setSpanAttribute(e,"side","back");this.tracingService?.endSpan(e)}this.completeProcess(false)}this.returnCanvasToPool(i);this.returnCanvasToPool(f)}triggerCaptureAnimation(){const t=this.el.shadowRoot?.querySelector(".card-outline");t?.classList.add("capturing");setTimeout((()=>{this.stateManager.updateCaptureState({isCapturing:false});t?.classList.remove("capturing")}),600)}switchToManualMode(){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}if(this.debug){console.warn("[JAAK-DEBUG] switchToManualMode() called - PERFORMANCE DEGRADED");console.warn("[JAAK-DEBUG] Cause: Slow frames exceeded threshold");console.warn("[JAAK-DEBUG] slowFrameCount:",this.slowFrameCount,"| threshold:",this.PERFORMANCE_THRESHOLD_MS,"ms | trigger:",this.SLOW_FRAMES_TO_TRIGGER)}this.stopPerformanceMonitoring();this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.showPerformanceMessage=true;setTimeout((()=>{this.showPerformanceMessage=false}),5e3)}switchToManualModeWithWarning(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}if(this.debug){console.warn("[JAAK-DEBUG] switchToManualModeWithWarning() called");console.warn("[JAAK-DEBUG] Cause:",t);console.warn("[JAAK-DEBUG] deviceMemory:",navigator.deviceMemory,"| hardwareConcurrency:",navigator.hardwareConcurrency)}this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.updateStatus("Modo manual activado",t,"active");this.continueWithCameraSetup()}async continueWithCameraSetup(){try{this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus()}catch(t){throw new Error(`Error al actualizar información de cámara: ${t.message}`)}this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");let t;try{t=await this.cameraService.setupCamera()}catch(t){throw new Error(`Error al configurar cámara: ${t.message}`)}this.updateStatus("Captura manual","Posicione su documento y use el botón para capturar","active");try{await this.initializeVideoStream(t)}catch(t){throw new Error(`Error al inicializar video: ${t.message}`)}if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});this.showManualCaptureButton=true}catch(t){this.updateStatus("Error de cámara",t.message,"error");throw t}}switchToManualModeWithError(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}if(this.debug){console.error("[JAAK-DEBUG] switchToManualModeWithError() called");console.error("[JAAK-DEBUG] Cause:",t);console.error("[JAAK-DEBUG] deviceMemory:",navigator.deviceMemory,"| hardwareConcurrency:",navigator.hardwareConcurrency)}this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.updateStatus("Modo manual activado",t,"error");this.continueWithCameraSetup().catch((()=>{setTimeout((()=>{this.updateStatus("Captura manual","Use el botón para capturar","ready")}),5e3)}))}stopPerformanceMonitoring(){}releaseOnnxResources(){try{if(this.detectionService){this.detectionService.cleanup()}}catch(t){}}async completeProcess(t=false){this.stateManager.updateCaptureState({step:"completed",showSuccessAnimation:true});const e=this.stateManager.getCapturedImages();e.metadata.processCompleted=true;e.metadata.backCaptureSkipped=t;this.stateManager.setCapturedImages(e);this.stopDetection();this.updateStatus("Proceso completado",`Imágenes capturadas exitosamente`,"ready");const i={...e,timestamp:(new Date).toISOString()};if(this.tracingService){try{await this.tracingService.flush()}catch(t){console.error("[my-component] Failed to flush traces:",t)}}this.captureCompleted.emit(i);setTimeout((()=>{this.stateManager.updateCaptureState({showSuccessAnimation:false})}),3e3)}stopDetection(){if(this.animationId){cancelAnimationFrame(this.animationId);this.animationId=undefined}this.clearBackDocumentTimer();this.detectionBoxes=[]}startBackDocumentTimer(){if(!this.enableBackDocumentTimer)return;if(this.backDocumentTimer){clearInterval(this.backDocumentTimer)}this.backDocumentTimerRemaining=this.backDocumentTimerDuration;this.backDocumentTimer=window.setInterval((()=>{this.backDocumentTimerRemaining--;if(this.backDocumentTimerRemaining<=0){this.clearBackDocumentTimer();this.skipBackCapture()}}),1e3)}clearBackDocumentTimer(){if(this.backDocumentTimer){clearInterval(this.backDocumentTimer);this.backDocumentTimer=undefined}this.backDocumentTimerRemaining=0}toggleCameraSelector(){if(this.isSwitchingCamera)return;this.showCameraSelector=!this.showCameraSelector}async updateCameraInfoWithAutofocus(){try{const t=await this.cameraService.getCameraInfo();this.cameraInfoWithAutofocus=t}catch(t){}}async handleCameraSwitch(t){if(this.isSwitchingCamera)return;try{this.showCameraSelector=false;const e=this.cameraService.getSelectedCameraId();if(e===t){return}this.isSwitchingCamera=true;if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}await this.cameraService.switchCamera(t);const i=await this.cameraService.setupCamera();await this.initializeVideoStream(i);await this.updateCameraInfoWithAutofocus()}catch(t){try{const t=await this.cameraService.setupCamera();await this.initializeVideoStream(t)}catch(t){this.updateStatus("Error al cambiar cámara","No se pudo cambiar el dispositivo","error")}}finally{this.isSwitchingCamera=false}}resetDetection(){const t=this.stateManager.getCaptureState();const e=t.isVideoActive;this.stateManager.reset();if(e){this.stateManager.updateCaptureState({isVideoActive:true})}this.hasScreenshotTaken=false;this.startTime=Date.now();this.frameSkipCounter=0;this.consecutiveFailures=0;this.lastInferenceTime=0;this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.processedFramesCount=0;this.slowFrameCount=0;this.hasAutoSwitchedToManual=false;this.performanceDegradedMode=false;this.showPerformanceMessage=false;if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(e&&this.detectionService.isModelLoaded()){this.updateStatus("Captura reiniciada","Buscando documento en el marco de captura","active");this.detectFrame()}else{this.updateStatus("Listo para capturar","","ready")}}exitSession(){if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()));this.videoStream=undefined;this.stateManager.updateCaptureState({isVideoActive:false,isLoading:false})}this.isMaskReady=false;this.updateStatus("Captura finalizada","","ready");this.detectionBoxes=[];this.cleanup()}initializePerformanceMonitor(){this.performanceMetrics.lastUpdateTime=performance.now();this.performanceUpdateInterval=window.setInterval((()=>{this.updatePerformanceMetrics()}),500)}updatePerformanceMetrics(){const t=performance.now();const e=t-this.performanceMetrics.lastUpdateTime;if(e>0){this.performanceMetrics.fps=Math.round(1e3/(e/this.frameSkipCounter||1))}if("memory"in performance){const t=performance.memory;this.performanceMetrics.memoryUsage=Math.round(t.usedJSHeapSize/1048576)}if(this.performanceMetrics.totalDetections>0){this.performanceMetrics.successfulDetections=this.performanceMetrics.successfulDetections;const t=this.performanceMetrics.successfulDetections/this.performanceMetrics.totalDetections*100;this.performanceMetrics.detectionRate=Math.round(t)}this.performanceData={fps:this.performanceMetrics.fps,inferenceTime:this.performanceMetrics.inferenceTime,memoryUsage:this.performanceMetrics.memoryUsage,onnxLoadTime:this.performanceMetrics.onnxLoadTime,frameProcessingTime:this.performanceMetrics.frameProcessingTime,totalDetections:this.performanceMetrics.totalDetections,successfulDetections:this.performanceMetrics.successfulDetections,detectionRate:this.performanceMetrics.detectionRate};this.performanceMetrics.lastUpdateTime=t}recordOnnxPerformance(t,e){this.performanceMetrics.onnxLoadTime=Math.round(t);this.performanceMetrics.inferenceTime=Math.round(e)}recordFrameProcessing(t,e){this.performanceMetrics.frameProcessingTime=Math.round(t);this.performanceMetrics.totalDetections++;if(e>0){this.performanceMetrics.successfulDetections++}this.performanceHistory.push(t);if(this.performanceHistory.length>this.PERFORMANCE_HISTORY_SIZE){this.performanceHistory.shift()}}getAdaptiveFrameSkip(){const t=this.cameraInfoWithAutofocus.deviceType==="mobile"||/Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);const e=this.cameraInfoWithAutofocus.deviceType==="tablet"||/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const i=t&&!e?4:this.BASE_FRAME_SKIP;if(this.consecutiveFailures>20)return this.MAX_FRAME_SKIP;if(this.performanceMetrics.inferenceTime>200)return Math.max(6,i);if(this.performanceMetrics.memoryUsage>200)return Math.max(5,i);if(this.performanceHistory.length>0){const t=this.performanceHistory.reduce(((t,e)=>t+e),0)/this.performanceHistory.length;if(t>100)return Math.max(4,i);if(t>80)return Math.max(3,i);if(t>60)return Math.max(this.BASE_FRAME_SKIP+1,i)}if(this.performanceMetrics.memoryUsage>150)return Math.max(4,i);return i}resetMaskToWhite(){const t=this.el.shadowRoot?.querySelector(".card-outline");const e=this.el.shadowRoot?.querySelectorAll(".corner");const i=this.el.shadowRoot?.querySelector(".side-top");const r=this.el.shadowRoot?.querySelector(".side-right");const n=this.el.shadowRoot?.querySelector(".side-bottom");const s=this.el.shadowRoot?.querySelector(".side-left");t?.classList.remove("perfect-match");e?.forEach((t=>t.classList.remove("perfect-match")));i?.classList.remove("aligned");r?.classList.remove("aligned");n?.classList.remove("aligned");s?.classList.remove("aligned");this.sideAlignment={top:false,right:false,bottom:false,left:false}}getPooledCanvas(t,e){const i=this.canvasPool.findIndex((i=>i.width===t&&i.height===e));if(i!==-1){return this.canvasPool.splice(i,1)[0]}if(this.canvasPool.length>0){const i=this.canvasPool.pop();i.width=t;i.height=e;return i}const r=document.createElement("canvas");r.width=t;r.height=e;return r}returnCanvasToPool(t){if(this.canvasPool.length<this.MAX_CANVAS_POOL_SIZE){const e=t.getContext("2d");e.clearRect(0,0,t.width,t.height);this.canvasPool.push(t)}}};Su.style=ku;export{Su as jaak_stamps};
|
|
7
|
+
//# sourceMappingURL=p-85901267.entry.js.map
|