@overvio/sdk 1.0.0 → 1.0.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.
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Overvio=function(e){"use strict";var t,i=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,o=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__esm=(e,t)=>function(){return e&&(t=(0,e[s(e)[0]])(e=0)),t},__commonJS=(e,t)=>function(){return t||(0,e[s(e)[0]])((t={exports:{}}).exports,t),t.exports},__export=(e,t)=>{for(var i in t)r(e,i,{get:t[i],enumerable:!0})},__copyProps=(e,t,i,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of s(t))a.call(e,c)||c===i||r(e,c,{get:()=>t[c],enumerable:!(o=n(t,c))||o.enumerable});return e},__toESM=(e,t,n)=>(n=null!=e?i(o(e)):{},__copyProps(r(n,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(r({},"__esModule",{value:!0}),e),__publicField=(e,t,i)=>((e,t,i)=>t in e?r(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);function isGetRandomValuesAvailable(){return void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.getRandomValues}function secureRandomUUID(){if(void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID)return globalThis.crypto.randomUUID();if(isGetRandomValuesAvailable())return function(){const e=new Uint8Array(16);globalThis.crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20,32)].join("-")}();throw new t("Secure random generation unavailable. crypto.randomUUID() and crypto.getRandomValues() are both unavailable. This environment does not support secure ID generation. Ensure you are running in a modern browser (post-2015) or Node.js 15+.")}function secureRandomHex(e){if(!Number.isInteger(e)||e<=0)throw new RangeError(`Length must be a positive integer, got: ${e}`);const i=function(e){if(!Number.isInteger(e)||e<=0)throw new RangeError(`Length must be a positive integer, got: ${e}`);if(!isGetRandomValuesAvailable())throw new t("crypto.getRandomValues is not available. Secure random byte generation requires Web Crypto API. Ensure you are running in a modern browser or Node.js 15+.");const i=new Uint8Array(e);return globalThis.crypto.getRandomValues(i),i}(Math.ceil(e/2));return Array.from(i).map(e=>e.toString(16).padStart(2,"0")).join("").slice(0,e)}var c,l,u,d,h=__esm({"src/utils/secure-random.ts"(){t=class _SecureRandomUnavailableError extends Error{constructor(e){super(e),this.name="SecureRandomUnavailableError",Error.captureStackTrace&&Error.captureStackTrace(this,_SecureRandomUnavailableError)}}}}),g=__esm({"src/utils/correlation-id.ts"(){h(),l=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,u=(c="err_").length+36}});e.ErrorCode=void 0,e.ALL_ERROR_CODES=void 0;var p,m,f=__esm({"src/errors/codes.ts"(){e.ErrorCode=(e=>(e.NETWORK_ERROR="NETWORK_ERROR",e.VALIDATION_ERROR="VALIDATION_ERROR",e.CONFIGURATION_ERROR="CONFIGURATION_ERROR",e.RATE_LIMIT_ERROR="RATE_LIMIT_ERROR",e.CONSENT_REQUIRED="CONSENT_REQUIRED",e.PLUGIN_ERROR="PLUGIN_ERROR",e.QUEUE_FULL="QUEUE_FULL",e.TIMEOUT="TIMEOUT",e.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",e.AUTHORIZATION_ERROR="AUTHORIZATION_ERROR",e.NOT_FOUND="NOT_FOUND",e.DATABASE_ERROR="DATABASE_ERROR",e.EXTERNAL_SERVICE_ERROR="EXTERNAL_SERVICE_ERROR",e.INTERNAL_ERROR="INTERNAL_ERROR",e))(e.ErrorCode||{}),e.ALL_ERROR_CODES=Object.values(e.ErrorCode),d="https://docs.overvio.com/errors"}});function getSafeMessage(e,t){const i=p[e];return i?i.message:m}var y,v,b,S,w=__esm({"src/errors/messages.ts"(){p={NETWORK_ERROR:{message:"A connection error occurred. Please check your network and try again.",key:"error.network",actionable:!0},VALIDATION_ERROR:{message:"The provided data is invalid. Please review your input and try again.",key:"error.validation",actionable:!0},CONFIGURATION_ERROR:{message:"There is a configuration issue. Please contact support if this persists.",key:"error.configuration",actionable:!0},RATE_LIMIT_ERROR:{message:"Too many requests. Please wait a moment and try again.",key:"error.rateLimit",actionable:!0},CONSENT_REQUIRED:{message:"Your consent is required to proceed with this action.",key:"error.consentRequired",actionable:!0},PLUGIN_ERROR:{message:"A component encountered an error. Please try again.",key:"error.plugin",actionable:!0},QUEUE_FULL:{message:"The system is currently busy. Please try again shortly.",key:"error.queueFull",actionable:!0},TIMEOUT:{message:"The request timed out. Please check your connection and try again.",key:"error.timeout",actionable:!0},AUTHENTICATION_ERROR:{message:"Unable to authenticate. Please verify your credentials configuration.",key:"error.authentication",actionable:!0},AUTHORIZATION_ERROR:{message:"Access denied. Please contact support if you need permission for this action.",key:"error.authorization",actionable:!0},NOT_FOUND:{message:"The requested resource was not found. Please verify the resource exists.",key:"error.notFound",actionable:!0},DATABASE_ERROR:{message:"A temporary server issue occurred. Please try again shortly.",key:"error.database",actionable:!0},EXTERNAL_SERVICE_ERROR:{message:"An external service is temporarily unavailable. Please try again later.",key:"error.externalService",actionable:!0},INTERNAL_ERROR:{message:"A server issue occurred. Please try again.",key:"error.internal",actionable:!0}},m="An unexpected error occurred. Please try again."}});function sanitizeErrorMessage(e,t){if(!e||"string"!=typeof e)return"";let i=e;for(const e of S)i=i.replace(e,"[internal]");for(const e of b)i=i.replace(e,"[path]");if(null==t?void 0:t.customPatterns)for(const{pattern:e,replacement:r}of t.customPatterns)i=i.replace(e,r);return i=i.replace(/(\[(?:path|internal)\])+/g,"$1"),i}function isSensitiveKey(e,t){const i=e.toLowerCase();return t.some(e=>{const t=e.toLowerCase();return i===t||i.includes(t)||t.includes(i)})}function isAllowedKey(e,t){const i=e.toLowerCase();return t.some(e=>e.toLowerCase()===i)}function sanitizeValue(e,t,i){var r;const n=null!=(r=t.maxDepth)?r:5;return i>n?"[truncated]":null==e?e:"string"==typeof e?sanitizeErrorMessage(e,t):"number"==typeof e||"boolean"==typeof e?e:Array.isArray(e)?e.map(e=>sanitizeValue(e,t,i+1)):"object"==typeof e?sanitizeContextObject(e,t,i+1):"[redacted]"}function sanitizeContextObject(e,t,i){var r,n,s;if(i>(null!=(r=t.maxDepth)?r:5))return{_truncated:!0};const o=null!=(n=t.allowedContextKeys)?n:y,a=null!=(s=t.sensitiveContextKeys)?s:v,c={};for(const[r,n]of Object.entries(e))isSensitiveKey(r,a)?c[r]="[redacted]":isAllowedKey(r,o)?c[r]="string"==typeof n?sanitizeErrorMessage(n,t):n:c[r]=sanitizeValue(n,t,i);return c}var C=__esm({"src/errors/sanitizer.ts"(){y=["retryAfter","statusCode","errorCode","code","correlationId","timestamp","timeoutMs","queueSize","maxQueueSize","pluginName","method","operation","category"],v=["password","secret","token","apiKey","api_key","authorization","cookie","sessionId","session_id","credentials","privateKey","private_key","accessToken","access_token","refreshToken","refresh_token"],b=[/\/(?:Users|home|var|tmp|opt|usr|etc|root|mnt|media|srv)\/[^\s:'"`,;)[\]}>]+/gi,/[A-Z]:\\[^\s:'"`,;)[\]}>]+/gi,/(?:\.\.?\/)+(?:src|lib|dist|build|packages|apps?|components?|utils?|services?|modules?)\/[^\s:'"`,;)[\]}>]+/gi,/(?:\/|^)(?:src|lib|dist|build|packages|apps?|__tests__|test|spec)\/[^\s:'"`,;)[\]}>]+/gi],S=[/node_modules\/[^\s:'"`,;)[\]}>]+/gi,/(?:dist|build|\.next|\.nuxt)\/[^\s:'"`,;)[\]}>]+/gi,/webpack(?:-internal)?:\/\/[^\s:'"`,;)[\]}>]+/gi,/\/\/# sourceMappingURL=[^\s]+/gi]}});function isProductionEnvironment(){return("undefined"==typeof globalThis||!0!==globalThis.__OVERVIO_DEBUG__)&&(!("undefined"==typeof process||!process.env)||"undefined"!=typeof globalThis&&!0===globalThis.__PRODUCTION__)}e.OvervioError=void 0;var E,_,I,k,x=__esm({"src/errors/base.ts"(){g(),f(),w(),C(),e.OvervioError=class _OvervioError extends Error{constructor(e,t,i={},r,n){super(e),__publicField(this,"name","OvervioError"),__publicField(this,"code"),__publicField(this,"context"),__publicField(this,"cause"),__publicField(this,"timestamp"),__publicField(this,"correlationId"),this.code=t,this.context=i,this.cause=r,this.timestamp=new Date,n&&function(e){if("string"!=typeof e)return!1;if(e.length!==u)return!1;if(!e.startsWith(c))return!1;const t=e.slice(c.length);return l.test(t)}(n)?this.correlationId=n:this.correlationId=function(){const e=secureRandomUUID();return`${c}${e}`}(),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,new.target)}toJSON(){const e=isProductionEnvironment(),t={name:this.name,code:this.code,message:e?getSafeMessage(this.code):sanitizeErrorMessage(this.message),timestamp:this.timestamp.toISOString(),correlationId:this.correlationId,docUrl:(i=this.code,`${d.replace(/\/$/,"")}/${i}`)};var i;if(e)return t;const r={...t,context:(n=this.context,n&&"object"==typeof n?sanitizeContextObject(n,{},0):{})};var n;if(this.stack&&(r.stack=sanitizeErrorMessage(this.stack)),this.cause)if(this.cause instanceof _OvervioError)r.cause=this.cause.toJSON();else{const e={name:this.cause.name,message:sanitizeErrorMessage(this.cause.message)};void 0!==this.cause.stack&&(e.stack=sanitizeErrorMessage(this.cause.stack)),r.cause=e}return r}toString(){return`${this.name} [${this.code}]: ${this.message}`}static isOvervioError(e){return e instanceof _OvervioError}static from(e,t,i={}){return e instanceof _OvervioError?e.code===t?e:new _OvervioError(e.message,t,{...e.context,...i},e):e instanceof Error?new _OvervioError(e.message,t,i,e):"string"==typeof e?new _OvervioError(e,t,i):new _OvervioError("An unknown error occurred",t,{...i,originalValue:e})}}}});function validateNonEmptyString(e,t){if("string"!=typeof e)throw new Error(`${t} must be a string, received ${typeof e}`);if(0===e.length)throw new Error(`${t} cannot be an empty string`);return e}function createUserId(e){return validateNonEmptyString(e,"UserId")}function createSessionId(e){return validateNonEmptyString(e,"SessionId")}function isValidUserIdFormat(e){return function(e){return"string"!=typeof e?{valid:!1,reason:"ID must be a string, received "+typeof e}:e.length<I?{valid:!1,reason:"ID cannot be empty"}:e.length>_?{valid:!1,reason:`ID exceeds maximum length of ${_} characters`}:k.test(e)?{valid:!0}:{valid:!1,reason:"ID contains invalid characters. Only alphanumeric, underscore, hyphen, period, at, colon, and pipe are allowed."}}(e).valid}function createClientUuid(e){validateNonEmptyString(e,"ClientUuid");const t=e.toLowerCase();if(!E.test(t))throw new Error(`ClientUuid must be a valid UUID v4, received: ${e}`);return t}function createProductId(e){return validateNonEmptyString(e,"ProductId")}function createOrderId(e){return validateNonEmptyString(e,"OrderId")}function createIdempotencyKey(e){return validateNonEmptyString(e,"IdempotencyKey")}function isBrandedString(e){return"string"==typeof e&&e.length>0}function isUserId(e){return isValidUserIdFormat(e)}function isSessionId(e){return isValidUserIdFormat(e)}function isClientUuid(e){return isBrandedString(e)&&function(e){return E.test(e)}(e)}function isProductId(e){return isBrandedString(e)}function isOrderId(e){return isBrandedString(e)}function isIdempotencyKey(e){return isBrandedString(e)}function isAnyBrandedId(e){return isBrandedString(e)}var T,A=__esm({"src/types/branded.ts"(){E=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,_=256,I=1,k=/^[a-zA-Z0-9_\-.:@|]+$/}}),R=__esm({"src/core/emitter.ts"(){T=class{constructor(e={}){var t;__publicField(this,"listeners",new Map),__publicField(this,"maxListeners"),__publicField(this,"onListenerError"),this.maxListeners=null!=(t=e.maxListeners)?t:15,this.onListenerError=e.onListenerError}on(e,t){return this.addListener(e,t,!1)}off(e,t){const i=this.listeners.get(e);if(i){for(const e of i)if(e.listener===t){i.delete(e);break}0===i.size&&this.listeners.delete(e)}}once(e,t){return this.addListener(e,t,!0)}emit(e,...t){const i=this.listeners.get(e);if(!i||0===i.size)return;const r=t[0],n=Array.from(i);for(const t of n)t.once&&(i.delete(t),0===i.size&&this.listeners.delete(e)),this.invokeListener(e,t.listener,r)}removeAllListeners(e){void 0!==e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t;const i=this.listeners.get(e);return null!=(t=null==i?void 0:i.size)?t:0}eventNames(){return Array.from(this.listeners.keys())}addListener(e,t,i){let r=this.listeners.get(e);r||(r=new Set,this.listeners.set(e,r)),this.maxListeners>0&&r.size>=this.maxListeners&&console.warn(`TypedEventEmitter: Possible memory leak detected. ${r.size+1} listeners added for event "${String(e)}". Use removeAllListeners() to clean up or increase maxListeners.`);const n={listener:t,once:i};r.add(n);const s=r;return()=>{s.delete(n),0===s.size&&this.listeners.delete(e)}}invokeListener(e,t,i){try{const r=void 0===i?t():t(i);r instanceof Promise&&r.catch(i=>{this.handleListenerError(e,i,t)})}catch(i){this.handleListenerError(e,i,t)}}handleListenerError(e,t,i){if(this.onListenerError)try{this.onListenerError(String(e),t,i)}catch(i){console.error(`TypedEventEmitter: Error handler threw for event "${String(e)}":`,t)}else console.error(`TypedEventEmitter: Listener error for event "${String(e)}":`,t)}}}});function isBackendErrorResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!1!==t.success)return!1;const i=t.error;if("object"!=typeof i||null===i)return!1;const r=i;return"string"==typeof r.code&&"string"==typeof r.message}e.NetworkError=void 0;var P=__esm({"src/errors/network.ts"(){x(),e.NetworkError=class _NetworkError extends e.OvervioError{constructor(e,t={}){const{statusCode:i,retryable:r=!1,retryAfter:n,url:s,method:o,cause:a,context:c={},code:l="HTTP_ERROR"}=t,u={...c,networkErrorCode:l};void 0!==i&&(u.statusCode=i),void 0!==s&&(u.url=s),void 0!==o&&(u.method=o),void 0!==n&&(u.retryAfter=n),super(e,"NETWORK_ERROR",u,a),__publicField(this,"name","NetworkError"),__publicField(this,"statusCode"),__publicField(this,"retryable"),__publicField(this,"retryAfter"),__publicField(this,"url"),__publicField(this,"method"),__publicField(this,"networkErrorCode"),this.statusCode=i,this.retryable=r,this.retryAfter=n,this.url=s,this.method=o,this.networkErrorCode=l,Object.setPrototypeOf(this,new.target.prototype)}static fromResponse(e,t,i){const r=e.status,n=r>=500||429===r;let s;const o=e.headers.get("Retry-After");if(o){const e=parseInt(o,10);if(isNaN(e)){const e=new Date(o);isNaN(e.getTime())||(s=Math.max(0,Math.ceil((e.getTime()-Date.now())/1e3)))}else s=e}const a=`HTTP ${r}: ${e.statusText||"Request failed"}`,c={statusCode:r,retryable:n,url:null!=t?t:e.url};return void 0!==s&&(c.retryAfter=s),void 0!==i&&(c.method=i),new _NetworkError(a,c)}static async fromResponseAsync(e,t,i){const r=e.status,n=r>=500||429===r;let s;const o=e.headers.get("Retry-After");if(o){const e=parseInt(o,10);if(isNaN(e)){const e=new Date(o);isNaN(e.getTime())||(s=Math.max(0,Math.ceil((e.getTime()-Date.now())/1e3)))}else s=e}let a,c;try{const t=await e.clone().json();isBackendErrorResponse(t)&&(a=t.error.code,c=t.error.message,"retryAfter"in t&&"number"==typeof t.retryAfter&&(s=t.retryAfter))}catch(e){}const l=null!=c?c:`HTTP ${r}: ${e.statusText||"Request failed"}`,u={statusCode:r,retryable:n,url:null!=t?t:e.url,context:{}};return void 0!==s&&(u.retryAfter=s),void 0!==i&&(u.method=i),void 0!==a&&u.context&&(u.context.backendErrorCode=a),new _NetworkError(l,u)}static connectionError(e,t,i,r){const n={retryable:!0,code:"CONNECTION_ERROR"};return void 0!==t&&(n.url=t),void 0!==i&&(n.method=i),void 0!==r&&(n.cause=r),new _NetworkError(e,n)}static isNetworkError(e){return e instanceof _NetworkError}toJSON(){const e=super.toJSON();return isProductionEnvironment()?{...e,retryable:this.retryable,networkErrorCode:this.networkErrorCode,...void 0!==this.retryAfter&&{retryAfter:this.retryAfter}}:{...e,retryable:this.retryable,networkErrorCode:this.networkErrorCode,...void 0!==this.retryAfter&&{retryAfter:this.retryAfter},...void 0!==this.statusCode&&{statusCode:this.statusCode},...void 0!==this.url&&{url:this.url},...void 0!==this.method&&{method:this.method}}}}}});e.RateLimitError=void 0;var D=__esm({"src/errors/rate-limit.ts"(){x(),e.RateLimitError=class _RateLimitError extends e.OvervioError{constructor(e,t={}){const{retryAfter:i,limit:r,remaining:n,resetAt:s,endpoint:o,cause:a,context:c={}}=t,l={...c};void 0!==i&&(l.retryAfter=i),void 0!==r&&(l.limit=r),void 0!==n&&(l.remaining=n),void 0!==s&&(l.resetAt=s.toISOString()),void 0!==o&&(l.endpoint=o),super(e,"RATE_LIMIT_ERROR",l,a),__publicField(this,"name","RateLimitError"),__publicField(this,"retryAfter"),__publicField(this,"limit"),__publicField(this,"remaining"),__publicField(this,"resetAt"),__publicField(this,"endpoint"),this.retryAfter=i,this.limit=r,this.remaining=n,this.resetAt=s,this.endpoint=o,Object.setPrototypeOf(this,new.target.prototype)}static fromHeaders(e,t){var i,r,n,s;const o=null!=(i=e["retry-after"])?i:e["Retry-After"],a=null!=(r=e["x-ratelimit-limit"])?r:e["X-RateLimit-Limit"],c=null!=(n=e["x-ratelimit-remaining"])?n:e["X-RateLimit-Remaining"],l=null!=(s=e["x-ratelimit-reset"])?s:e["X-RateLimit-Reset"];let u;if(o){const e=parseInt(o,10);if(isNaN(e)){const e=new Date(o);isNaN(e.getTime())||(u=Math.max(0,Math.ceil((e.getTime()-Date.now())/1e3)))}else u=e}const d=a?parseInt(a,10):void 0,h=c?parseInt(c,10):void 0;let g;if(l){const e=parseInt(l,10);isNaN(e)||(g=new Date(1e3*e))}const p={};return void 0!==u&&(p.retryAfter=u),void 0===d||isNaN(d)||(p.limit=d),void 0===h||isNaN(h)||(p.remaining=h),void 0!==g&&(p.resetAt=g),void 0!==t&&(p.endpoint=t),new _RateLimitError("API rate limit exceeded",p)}static isRateLimitError(e){return e instanceof _RateLimitError}toJSON(){const e=super.toJSON();return isProductionEnvironment()?{...e,...void 0!==this.retryAfter&&{retryAfter:this.retryAfter}}:{...e,...void 0!==this.retryAfter&&{retryAfter:this.retryAfter},...void 0!==this.limit&&{limit:this.limit},...void 0!==this.remaining&&{remaining:this.remaining},...void 0!==this.resetAt&&{resetAt:this.resetAt.toISOString()},...void 0!==this.endpoint&&{endpoint:this.endpoint}}}}}});e.TimeoutError=void 0;var L=__esm({"src/errors/timeout.ts"(){x(),e.TimeoutError=class _TimeoutError extends e.OvervioError{constructor(e,t={}){const{timeoutMs:i,operation:r,retryable:n=!0,cause:s,context:o={}}=t,a={...o};void 0!==i&&(a.timeoutMs=i),void 0!==r&&(a.operation=r),a.retryable=n,super(e,"TIMEOUT",a,s),__publicField(this,"name","TimeoutError"),__publicField(this,"timeoutMs"),__publicField(this,"operation"),__publicField(this,"retryable"),this.timeoutMs=i,this.operation=r,this.retryable=n,Object.setPrototypeOf(this,new.target.prototype)}static httpRequest(e,t,i){return new _TimeoutError(`HTTP request timed out after ${t}ms`,{timeoutMs:t,operation:i?`${i} ${e}`:e,context:{url:e,method:i}})}static pluginOperation(e,t,i){return new _TimeoutError(`Plugin "${e}" timed out during ${t} after ${i}ms`,{timeoutMs:i,operation:`${e}.${t}`,context:{pluginName:e,method:t}})}static operation(e,t){return new _TimeoutError(`Operation "${e}" timed out after ${t}ms`,{timeoutMs:t,operation:e})}static isTimeoutError(e){return e instanceof _TimeoutError}toJSON(){const e=super.toJSON();return isProductionEnvironment()?{...e,...void 0!==this.timeoutMs&&{timeoutMs:this.timeoutMs},retryable:this.retryable}:{...e,...void 0!==this.timeoutMs&&{timeoutMs:this.timeoutMs},...void 0!==this.operation&&{operation:this.operation},retryable:this.retryable}}}}});e.ValidationError=void 0;var M=__esm({"src/errors/validation.ts"(){x(),e.ValidationError=class _ValidationError extends e.OvervioError{constructor(e,t={}){const{field:i,value:r,constraint:n,expected:s,received:o,cause:a,context:c={}}=t,l={...c};void 0!==i&&(l.field=i),void 0!==n&&(l.constraint=n),void 0!==s&&(l.expected=s),void 0!==o&&(l.received=o),super(e,"VALIDATION_ERROR",l,a),__publicField(this,"name","ValidationError"),__publicField(this,"field"),__publicField(this,"value"),__publicField(this,"constraint"),__publicField(this,"expected"),__publicField(this,"received"),this.field=i,this.value=r,this.constraint=n,this.expected=s,this.received=o,Object.setPrototypeOf(this,new.target.prototype)}static requiredField(e){return new _ValidationError(`${e} is required`,{field:e,value:void 0,constraint:"Field is required and cannot be undefined or null"})}static typeMismatch(e,t,i,r){return new _ValidationError(`${e} must be ${t}, received ${i}`,{field:e,value:r,expected:t,received:i,constraint:`Must be of type ${t}`})}static invalidFormat(e,t,i){return new _ValidationError(`${e} has invalid format`,{field:e,value:i,constraint:`Must be a ${t}`})}static outOfRange(e,t,i,r){let n;return n=void 0!==t&&void 0!==i?`Must be between ${t} and ${i}`:void 0!==t?`Must be at least ${t}`:void 0!==i?`Must be at most ${i}`:"Value is out of valid range",new _ValidationError(`${e} is out of range`,{field:e,value:r,constraint:n,context:{min:t,max:i}})}static isValidationError(e){return e instanceof _ValidationError}static fromResponse(e,t,i){var r;const n=null!=(r=e.error.details)?r:[],s=n[0],o={context:{validationDetails:n,errorCode:e.error.code}};return s&&(o.field=s.field,o.constraint=s.message),void 0!==t&&(o.context.url=t),void 0!==i&&(o.context.method=i),new _ValidationError(e.error.message,o)}toJSON(){const e=super.toJSON();return isProductionEnvironment()?{...e,...void 0!==this.field&&{field:this.field}}:{...e,...void 0!==this.field&&{field:this.field},...void 0!==this.constraint&&{constraint:this.constraint},...void 0!==this.expected&&{expected:this.expected},...void 0!==this.received&&{received:this.received}}}}}});e.EventType=void 0;var O=__esm({"src/events/types/constants.ts"(){e.EventType={PAGE_VIEW:"page_view",PRODUCT_VIEW:"product_view",ADD_TO_CART:"add_to_cart",REMOVE_FROM_CART:"remove_from_cart",VIEW_CART:"view_cart",VIEW_ITEM_LIST:"view_item_list",SELECT_ITEM:"select_item",ORDER_COMPLETED:"order_completed",SEARCH_PERFORMED:"search_performed",SEARCH_CLICK:"search_click",CUSTOM:"custom",SESSION_END:"session_end",BEGIN_CHECKOUT:"begin_checkout",ADD_SHIPPING_INFO:"add_shipping_info",ADD_PAYMENT_INFO:"add_payment_info",USER_LOGIN:"user_login",USER_SIGNUP:"user_signup",USER_LOGOUT:"user_logout",SESSION_START:"session_start",SCROLL_DEPTH:"scroll_depth",TIME_ON_PAGE:"time_on_page",POPUP_INTERACTION:"popup_interaction",VIEW_PROMOTION:"view_promotion",SELECT_PROMOTION:"select_promotion",COUPON_APPLIED:"coupon_applied",COUPON_FAILED:"coupon_failed",COUPON_REMOVED:"coupon_removed",ADD_TO_WISHLIST:"add_to_wishlist",REMOVE_FROM_WISHLIST:"remove_from_wishlist",SEARCH_AUTOCOMPLETE:"search_autocomplete",SEARCH_NO_RESULTS:"search_no_results",RAGE_CLICK:"rage_click",SEARCH_FILTER:"search_filter",SEARCH_SORT:"search_sort",ELEMENT_VISIBLE:"element_visible",SPELL_CORRECTION_SHOWN:"spell_correction_shown",SPELL_CORRECTION_ACCEPTED:"spell_correction_accepted",SPELL_CORRECTION_REJECTED:"spell_correction_rejected",QUERY_RELAXATION_SHOWN:"query_relaxation_shown",QUERY_RELAXATION_ACCEPTED:"query_relaxation_accepted",QUERY_RELAXATION_REJECTED:"query_relaxation_rejected",ZERO_RESULTS:"zero_results",ZERO_RESULTS_RECOVERY:"zero_results_recovery",SIMILAR_PRODUCTS_SHOWN:"similar_products_shown",SIMILAR_PRODUCT_CLICKED:"similar_product_clicked",FILTER_APPLIED:"filter_applied",FILTER_REMOVED:"filter_removed",FILTERS_CLEARED:"filters_cleared",VIEW_MODE_CHANGED:"view_mode_changed",SORT_CHANGED:"sort_changed"}}});function isBaseEvent(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&0!==t.type.length&&!("number"!=typeof t.timestamp||!Number.isFinite(t.timestamp))&&(void 0===t.context||"object"==typeof t.context&&null!==t.context)&&(void 0===t.idempotencyKey||"string"==typeof t.idempotencyKey&&0!==t.idempotencyKey.length)}function createBaseEvent(e,t){const i={type:e,timestamp:Date.now()};return void 0!==t&&(i.context=t),i}var $,N,F,q,U,z,H,V,B,j=__esm({"src/events/types/base.ts"(){}}),K=__esm({"src/events/types/index.ts"(){O(),j()}}),W=__esm({"src/events/types.ts"(){K()}});function validateUrl(e,t){const i={...$,...t};if("string"!=typeof e)return{valid:!1,reason:"URL must be a string"};if(0===e.length)return{valid:!1,reason:"URL cannot be empty"};const r=e.trim();if(r.length>i.maxUrlLength)return{valid:!1,reason:`URL exceeds maximum length of ${i.maxUrlLength} characters`};for(const e of U)if(e.test(r))return{valid:!1,reason:"URL contains dangerous protocol"};if(z.test(r))return{valid:!0,sanitized:r.replace(/\x00/g,"")};try{const e=new URL(r);return q.includes(e.protocol)?{valid:!0,sanitized:e.href}:{valid:!1,reason:"URL contains unsafe protocol"}}catch(e){if(i.autoAddProtocol)try{const e=`https://${r}`,t=new URL(e);if(t.hostname&&t.hostname.includes("."))return{valid:!0,sanitized:t.href}}catch(e){}return{valid:!1,reason:i.autoAddProtocol?"URL is malformed":"URL is malformed or missing protocol (http:// or https://)"}}}function sanitizeSearchQuery(e,t){const i={...$,...t};return e&&"string"==typeof e?e.replace(H,"").replace(V,"").replace(B," ").trim().slice(0,i.maxSearchQueryLength):""}var Q,G,Y,X,J,Z,ee=__esm({"src/utils/input-validation.ts"(){$={maxEmailLength:254,maxLocalPartLength:64,maxUrlLength:2048,maxSearchQueryLength:500,autoAddProtocol:!0},N=/[`\x00<>]/,F=/^[a-zA-Z0-9!#$%&'*+/=?^_'{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_'{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/,q=["http:","https:"],U=[/^javascript:/i,/^data:/i,/^vbscript:/i,/^file:/i],z=/^\.{0,2}\//,H=/<[^>]*>/g,V=/\x00/g,B=/\s+/g}});function isFilterRange(e){if("object"!=typeof e||null===e)return!1;const t=e,i="min"in t,r="max"in t;return!(!i&&!r||i&&"number"!=typeof t.min||r&&"number"!=typeof t.max)}function isSortOption(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.field&&0!==t.field.length&&("asc"===t.direction||"desc"===t.direction)}function isSortPreset(e){return"string"==typeof e&&Q.includes(e)}function isSearchOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.filters&&("object"!=typeof t.filters||null===t.filters)||void 0!==t.page&&("number"!=typeof t.page||t.page<1)||void 0!==t.limit&&("number"!=typeof t.limit||t.limit<1)||void 0!==t.sort&&!isSortOption(t.sort))}function isFacetCount(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.value&&!("number"!=typeof t.count||!Number.isInteger(t.count))}function isFacets(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.brand))return!1;for(const e of t.brand)if(!isFacetCount(e))return!1;if(!Array.isArray(t.categories))return!1;for(const e of t.categories)if(!isFacetCount(e))return!1;if(void 0!==t.availability){if(!Array.isArray(t.availability))return!1;for(const e of t.availability)if(!isFacetCount(e))return!1}return!0}function isProduct(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.id||0===t.id.length)return!1;if("string"!=typeof t.name||0===t.name.length)return!1;if("number"!=typeof t.price||!Number.isFinite(t.price))return!1;if("string"!=typeof t.currency||0===t.currency.length)return!1;if("string"!=typeof t.image)return!1;if("string"!=typeof t.url)return!1;if(void 0!==t.originalPrice&&("number"!=typeof t.originalPrice||!Number.isFinite(t.originalPrice)))return!1;if(void 0!==t.rating&&("number"!=typeof t.rating||!Number.isFinite(t.rating)))return!1;if(void 0!==t.reviewCount&&("number"!=typeof t.reviewCount||!Number.isInteger(t.reviewCount)))return!1;const i=["category","brand","sku","description","variant"];for(const e of i)if(void 0!==t[e]&&"string"!=typeof t[e])return!1;return void 0===t.inStock||"boolean"==typeof t.inStock}function isSpellCorrection(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.original&&0!==t.original.length&&"string"==typeof t.corrected&&0!==t.corrected.length&&!("number"!=typeof t.confidence||!Number.isFinite(t.confidence))}function isSearchMeta(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.cache&&"HIT"!==t.cache&&"MISS"!==t.cache&&"SKIP"!==t.cache||!(void 0===t.latencyMs||"number"==typeof t.latencyMs&&Number.isFinite(t.latencyMs))||void 0!==t.backend&&"string"!=typeof t.backend)}function isSearchResult(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.products))return!1;for(const e of t.products)if(!isProduct(e))return!1;if(!isFacets(t.facets))return!1;if("number"!=typeof t.total||!Number.isFinite(t.total))return!1;if("number"!=typeof t.page||t.page<1)return!1;if("number"!=typeof t.limit||t.limit<1)return!1;if("string"!=typeof t.query)return!1;if(void 0!==t.totalPages&&("number"!=typeof t.totalPages||!Number.isInteger(t.totalPages)))return!1;if(void 0!==t.took&&("number"!=typeof t.took||!Number.isFinite(t.took)))return!1;if(void 0!==t.suggestions){if(!Array.isArray(t.suggestions))return!1;for(const e of t.suggestions)if("string"!=typeof e)return!1}return!(void 0!==t.metadata&&!isSearchMeta(t.metadata)||void 0!==t.spellCorrection&&!isSpellCorrection(t.spellCorrection))}function isAutocompleteSuggestion(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.text&&0!==t.text.length&&(!(void 0!==t.type&&!["query","product","category","brand"].includes(t.type))&&!(void 0!==t.productId&&"string"!=typeof t.productId||void 0!==t.image&&"string"!=typeof t.image||!(void 0===t.count||"number"==typeof t.count&&Number.isFinite(t.count))||void 0!==t.highlight&&"string"!=typeof t.highlight))}function isAutocompleteResult(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.query)return!1;if(!Array.isArray(t.suggestions))return!1;for(const e of t.suggestions)if(!isAutocompleteSuggestion(e))return!1;return!0}function isSimilarProductsOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.limit&&("number"!=typeof t.limit||t.limit<1)||void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock||void 0!==t.categoryFilter&&"string"!=typeof t.categoryFilter||void 0!==t.excludeSameBrand&&"boolean"!=typeof t.excludeSameBrand||void 0!==t.minSimilarity&&("number"!=typeof t.minSimilarity||t.minSimilarity<0||t.minSimilarity>1))}function isProductBadgeType(e){return"sale"===e||"new"===e||"bestseller"===e||"low_stock"===e}function isProductBadge(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!isProductBadgeType(t.type)&&"string"==typeof t.label}function isHighlightField(e){return"string"==typeof e&&["name","name_greeklish","description","categories","sku"].includes(e)}function isHighlightSnippet(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!isHighlightField(t.field))return!1;if("string"!=typeof t.snippet)return!1;if(!Array.isArray(t.matched_tokens))return!1;for(const e of t.matched_tokens)if("string"!=typeof e)return!1;return!0}function isPopularSearch(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.query&&0!==t.query.length&&!("number"!=typeof t.count||!Number.isInteger(t.count))}function isFeaturedCategory(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&0!==t.id.length&&"string"==typeof t.name&&0!==t.name.length&&"string"==typeof t.url&&(void 0===t.image||"string"==typeof t.image)}function isInitialStateResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.trendingProducts))return!1;for(const e of t.trendingProducts)if(!isProduct(e))return!1;if(!Array.isArray(t.popularSearches))return!1;for(const e of t.popularSearches)if(!isPopularSearch(e))return!1;if(void 0!==t.featuredCategories){if(!Array.isArray(t.featuredCategories))return!1;for(const e of t.featuredCategories)if(!isFeaturedCategory(e))return!1}return!0}function isGetQuerySuggestionsOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.limit&&("number"!=typeof t.limit||t.limit<1)||void 0!==t.prefix&&"string"!=typeof t.prefix)}function isQuerySuggestionsResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.suggestions))return!1;for(const e of t.suggestions)if(!isPopularSearch(e))return!1;return!!(void 0===t.total||"number"==typeof t.total&&Number.isInteger(t.total))}function isSimilarProductsMetadata(e){if("object"!=typeof e||null===e)return!1;const t=e;return!("number"!=typeof t.embedding_dimensions||!Number.isInteger(t.embedding_dimensions)||"cosine"!==t.similarity_algorithm||void 0!==t.same_brand_fallback&&"boolean"!=typeof t.same_brand_fallback||void 0!==t.low_confidence&&"boolean"!=typeof t.low_confidence||!(void 0===t.ef_search||"number"==typeof t.ef_search&&Number.isInteger(t.ef_search))||!(void 0===t.results_before_filters||"number"==typeof t.results_before_filters&&Number.isInteger(t.results_before_filters)))}function isSimilarProductsResult(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.products))return!1;for(const e of t.products)if(!isProduct(e))return!1;return"string"==typeof t.sourceProductId&&0!==t.sourceProductId.length&&!(void 0!==t.metadata&&!isSimilarProductsMetadata(t.metadata))}e.DEFAULT_SEARCH_LIMIT=void 0,e.DEFAULT_AUTOCOMPLETE_LIMIT=void 0;var te=__esm({"src/search/types.ts"(){Q=["relevance","price_asc","price_desc","newest"],e.DEFAULT_SEARCH_LIMIT=20,G=100,e.DEFAULT_AUTOCOMPLETE_LIMIT=10,Y=20,X=2,J=10,Z=50}});function combineSignals(e,t){if(!t)return e;if(e.aborted)return e;if(t.aborted)return t;const i=new AbortController,abortHandler=()=>i.abort();return e.addEventListener("abort",abortHandler,{once:!0}),t.addEventListener("abort",abortHandler,{once:!0}),i.signal}function createTimeoutController(e){const t=new AbortController,i=setTimeout(()=>{t.abort("timeout")},e);return{controller:t,cleanup:()=>{clearTimeout(i)}}}function isAbortError(e){return e instanceof Error&&("AbortError"===e.name||e instanceof DOMException&&"AbortError"===e.name)}function getAbortReason(e){if(!e.aborted)return;const t=e.reason;return null!=t?"string"==typeof t?t:t instanceof Error?t.message:String(t):void 0}var ie,re,ne,se=__esm({"src/search/utils/abort.ts"(){}}),oe=__commonJS({"../../node_modules/.pnpm/dompurify@3.3.1/node_modules/dompurify/dist/purify.cjs.js"(e,t){var{entries:i,setPrototypeOf:r,isFrozen:n,getPrototypeOf:s,getOwnPropertyDescriptor:o}=Object,{freeze:a,seal:c,create:l}=Object,{apply:u,construct:d}="undefined"!=typeof Reflect&&Reflect;a||(a=function(e){return e}),c||(c=function(e){return e}),u||(u=function(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return e.apply(t,r)}),d||(d=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return new e(...i)});var h,g=unapply(Array.prototype.forEach),p=unapply(Array.prototype.lastIndexOf),m=unapply(Array.prototype.pop),f=unapply(Array.prototype.push),y=unapply(Array.prototype.splice),v=unapply(String.prototype.toLowerCase),b=unapply(String.prototype.toString),S=unapply(String.prototype.match),w=unapply(String.prototype.replace),C=unapply(String.prototype.indexOf),E=unapply(String.prototype.trim),_=unapply(Object.prototype.hasOwnProperty),I=unapply(RegExp.prototype.test),k=(h=TypeError,function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return d(h,t)});function unapply(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return u(e,t,r)}}function addToSet(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:v;r&&r(e,null);let s=t.length;for(;s--;){let r=t[s];if("string"==typeof r){const e=i(r);e!==r&&(n(t)||(t[s]=e),r=e)}e[r]=!0}return e}function cleanArray(e){for(let t=0;t<e.length;t++)_(e,t)||(e[t]=null);return e}function clone(e){const t=l(null);for(const[r,n]of i(e))_(e,r)&&(Array.isArray(n)?t[r]=cleanArray(n):n&&"object"==typeof n&&n.constructor===Object?t[r]=clone(n):t[r]=n);return t}function lookupGetter(e,t){for(;null!==e;){const i=o(e,t);if(i){if(i.get)return unapply(i.get);if("function"==typeof i.value)return unapply(i.value)}e=s(e)}return function(){return null}}var x=a(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),T=a(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),A=a(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),R=a(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),P=a(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),D=a(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),L=a(["#text"]),M=a(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),O=a(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),$=a(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),N=a(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),F=c(/\{\{[\w\W]*|[\w\W]*\}\}/gm),q=c(/<%[\w\W]*|[\w\W]*%>/gm),U=c(/\$\{[\w\W]*/gm),z=c(/^data-[\-\w.\u00B7-\uFFFF]+$/),H=c(/^aria-[\-\w]+$/),V=c(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),B=c(/^(?:\w+script|data):/i),j=c(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),K=c(/^html$/i),W=c(/^[a-z][.\w]*(-[.\w]+)+$/i),Q=Object.freeze({__proto__:null,ARIA_ATTR:H,ATTR_WHITESPACE:j,CUSTOM_ELEMENT:W,DATA_ATTR:z,DOCTYPE_NAME:K,ERB_EXPR:q,IS_ALLOWED_URI:V,IS_SCRIPT_OR_DATA:B,MUSTACHE_EXPR:F,TMPLIT_EXPR:U}),G=function createDOMPurify(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const DOMPurify3=e=>createDOMPurify(e);if(DOMPurify3.version="3.3.1",DOMPurify3.removed=[],!e||!e.document||9!==e.document.nodeType||!e.Element)return DOMPurify3.isSupported=!1,DOMPurify3;let{document:t}=e;const r=t,n=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:c,Element:u,NodeFilter:d,NamedNodeMap:h=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:F,DOMParser:q,trustedTypes:U}=e,z=u.prototype,H=lookupGetter(z,"cloneNode"),B=lookupGetter(z,"remove"),j=lookupGetter(z,"nextSibling"),W=lookupGetter(z,"childNodes"),G=lookupGetter(z,"parentNode");if("function"==typeof o){const e=t.createElement("template");e.content&&e.content.ownerDocument&&(t=e.content.ownerDocument)}let Y,X="";const{implementation:J,createNodeIterator:Z,createDocumentFragment:ee,getElementsByTagName:te}=t,{importNode:ie}=r;let re={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};DOMPurify3.isSupported="function"==typeof i&&"function"==typeof G&&J&&void 0!==J.createHTMLDocument;const{MUSTACHE_EXPR:ne,ERB_EXPR:se,TMPLIT_EXPR:oe,DATA_ATTR:ae,ARIA_ATTR:ce,IS_SCRIPT_OR_DATA:le,ATTR_WHITESPACE:ue,CUSTOM_ELEMENT:de}=Q;let{IS_ALLOWED_URI:he}=Q,ge=null;const pe=addToSet({},[...x,...T,...A,...P,...L]);let me=null;const fe=addToSet({},[...M,...O,...$,...N]);let ye=Object.seal(l(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ve=null,be=null;const Se=Object.seal(l(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let we=!0,Ce=!0,Ee=!1,_e=!0,Ie=!1,ke=!0,xe=!1,Te=!1,Ae=!1,Re=!1,Pe=!1,De=!1,Le=!0,Me=!1,Oe=!0,$e=!1,Ne={},Fe=null;const qe=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ue=null;const ze=addToSet({},["audio","video","img","source","image","track"]);let He=null;const Ve=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Be="http://www.w3.org/1998/Math/MathML",je="http://www.w3.org/2000/svg",Ke="http://www.w3.org/1999/xhtml";let We=Ke,Qe=!1,Ge=null;const Ye=addToSet({},[Be,je,Ke],b);let Xe=addToSet({},["mi","mo","mn","ms","mtext"]),Je=addToSet({},["annotation-xml"]);const Ze=addToSet({},["title","style","font","a","script"]);let et=null;const tt=["application/xhtml+xml","text/html"];let it=null,rt=null;const nt=t.createElement("form"),isRegexOrFunction=function(e){return e instanceof RegExp||e instanceof Function},_parseConfig=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!rt||rt!==e){if(e&&"object"==typeof e||(e={}),e=clone(e),et=-1===tt.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,it="application/xhtml+xml"===et?b:v,ge=_(e,"ALLOWED_TAGS")?addToSet({},e.ALLOWED_TAGS,it):pe,me=_(e,"ALLOWED_ATTR")?addToSet({},e.ALLOWED_ATTR,it):fe,Ge=_(e,"ALLOWED_NAMESPACES")?addToSet({},e.ALLOWED_NAMESPACES,b):Ye,He=_(e,"ADD_URI_SAFE_ATTR")?addToSet(clone(Ve),e.ADD_URI_SAFE_ATTR,it):Ve,Ue=_(e,"ADD_DATA_URI_TAGS")?addToSet(clone(ze),e.ADD_DATA_URI_TAGS,it):ze,Fe=_(e,"FORBID_CONTENTS")?addToSet({},e.FORBID_CONTENTS,it):qe,ve=_(e,"FORBID_TAGS")?addToSet({},e.FORBID_TAGS,it):clone({}),be=_(e,"FORBID_ATTR")?addToSet({},e.FORBID_ATTR,it):clone({}),Ne=!!_(e,"USE_PROFILES")&&e.USE_PROFILES,we=!1!==e.ALLOW_ARIA_ATTR,Ce=!1!==e.ALLOW_DATA_ATTR,Ee=e.ALLOW_UNKNOWN_PROTOCOLS||!1,_e=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Ie=e.SAFE_FOR_TEMPLATES||!1,ke=!1!==e.SAFE_FOR_XML,xe=e.WHOLE_DOCUMENT||!1,Re=e.RETURN_DOM||!1,Pe=e.RETURN_DOM_FRAGMENT||!1,De=e.RETURN_TRUSTED_TYPE||!1,Ae=e.FORCE_BODY||!1,Le=!1!==e.SANITIZE_DOM,Me=e.SANITIZE_NAMED_PROPS||!1,Oe=!1!==e.KEEP_CONTENT,$e=e.IN_PLACE||!1,he=e.ALLOWED_URI_REGEXP||V,We=e.NAMESPACE||Ke,Xe=e.MATHML_TEXT_INTEGRATION_POINTS||Xe,Je=e.HTML_INTEGRATION_POINTS||Je,ye=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&isRegexOrFunction(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(ye.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&isRegexOrFunction(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(ye.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(ye.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ie&&(Ce=!1),Pe&&(Re=!0),Ne&&(ge=addToSet({},L),me=[],!0===Ne.html&&(addToSet(ge,x),addToSet(me,M)),!0===Ne.svg&&(addToSet(ge,T),addToSet(me,O),addToSet(me,N)),!0===Ne.svgFilters&&(addToSet(ge,A),addToSet(me,O),addToSet(me,N)),!0===Ne.mathMl&&(addToSet(ge,P),addToSet(me,$),addToSet(me,N))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?Se.tagCheck=e.ADD_TAGS:(ge===pe&&(ge=clone(ge)),addToSet(ge,e.ADD_TAGS,it))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?Se.attributeCheck=e.ADD_ATTR:(me===fe&&(me=clone(me)),addToSet(me,e.ADD_ATTR,it))),e.ADD_URI_SAFE_ATTR&&addToSet(He,e.ADD_URI_SAFE_ATTR,it),e.FORBID_CONTENTS&&(Fe===qe&&(Fe=clone(Fe)),addToSet(Fe,e.FORBID_CONTENTS,it)),e.ADD_FORBID_CONTENTS&&(Fe===qe&&(Fe=clone(Fe)),addToSet(Fe,e.ADD_FORBID_CONTENTS,it)),Oe&&(ge["#text"]=!0),xe&&addToSet(ge,["html","head","body"]),ge.table&&(addToSet(ge,["tbody"]),delete ve.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw k('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw k('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Y=e.TRUSTED_TYPES_POLICY,X=Y.createHTML("")}else void 0===Y&&(Y=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let i=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(i=t.getAttribute(r));const n="dompurify"+(i?"#"+i:"");try{return e.createPolicy(n,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+n+" could not be created."),null}}(U,n)),null!==Y&&"string"==typeof X&&(X=Y.createHTML(""));a&&a(e),rt=e}},st=addToSet({},[...T,...A,...R]),ot=addToSet({},[...P,...D]),_forceRemove=function(e){f(DOMPurify3.removed,{element:e});try{G(e).removeChild(e)}catch(t){B(e)}},_removeAttribute=function(e,t){try{f(DOMPurify3.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){f(DOMPurify3.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(Re||Pe)try{_forceRemove(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},_initDocument=function(e){let i=null,r=null;if(Ae)e="<remove></remove>"+e;else{const t=S(e,/^[\r\n\t ]+/);r=t&&t[0]}"application/xhtml+xml"===et&&We===Ke&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const n=Y?Y.createHTML(e):e;if(We===Ke)try{i=(new q).parseFromString(n,et)}catch(e){}if(!i||!i.documentElement){i=J.createDocument(We,"template",null);try{i.documentElement.innerHTML=Qe?X:n}catch(e){}}const s=i.body||i.documentElement;return e&&r&&s.insertBefore(t.createTextNode(r),s.childNodes[0]||null),We===Ke?te.call(i,xe?"html":"body")[0]:xe?i.documentElement:s},_createNodeIterator=function(e){return Z.call(e.ownerDocument||e,e,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},_isClobbered=function(e){return e instanceof F&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof h)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},_isNode=function(e){return"function"==typeof c&&e instanceof c};function _executeHooks(e,t,i){g(e,e=>{e.call(DOMPurify3,t,i,rt)})}const _sanitizeElements=function(e){let t=null;if(_executeHooks(re.beforeSanitizeElements,e,null),_isClobbered(e))return _forceRemove(e),!0;const i=it(e.nodeName);if(_executeHooks(re.uponSanitizeElement,e,{tagName:i,allowedTags:ge}),ke&&e.hasChildNodes()&&!_isNode(e.firstElementChild)&&I(/<[/\w!]/g,e.innerHTML)&&I(/<[/\w!]/g,e.textContent))return _forceRemove(e),!0;if(7===e.nodeType)return _forceRemove(e),!0;if(ke&&8===e.nodeType&&I(/<[/\w]/g,e.data))return _forceRemove(e),!0;if(!(Se.tagCheck instanceof Function&&Se.tagCheck(i))&&(!ge[i]||ve[i])){if(!ve[i]&&_isBasicCustomElement(i)){if(ye.tagNameCheck instanceof RegExp&&I(ye.tagNameCheck,i))return!1;if(ye.tagNameCheck instanceof Function&&ye.tagNameCheck(i))return!1}if(Oe&&!Fe[i]){const t=G(e)||e.parentNode,i=W(e)||e.childNodes;if(i&&t)for(let r=i.length-1;r>=0;--r){const n=H(i[r],!0);n.__removalCount=(e.__removalCount||0)+1,t.insertBefore(n,j(e))}}return _forceRemove(e),!0}return e instanceof u&&!function(e){let t=G(e);t&&t.tagName||(t={namespaceURI:We,tagName:"template"});const i=v(e.tagName),r=v(t.tagName);return!!Ge[e.namespaceURI]&&(e.namespaceURI===je?t.namespaceURI===Ke?"svg"===i:t.namespaceURI===Be?"svg"===i&&("annotation-xml"===r||Xe[r]):Boolean(st[i]):e.namespaceURI===Be?t.namespaceURI===Ke?"math"===i:t.namespaceURI===je?"math"===i&&Je[r]:Boolean(ot[i]):e.namespaceURI===Ke?!(t.namespaceURI===je&&!Je[r])&&!(t.namespaceURI===Be&&!Xe[r])&&!ot[i]&&(Ze[i]||!st[i]):!("application/xhtml+xml"!==et||!Ge[e.namespaceURI]))}(e)?(_forceRemove(e),!0):"noscript"!==i&&"noembed"!==i&&"noframes"!==i||!I(/<\/no(script|embed|frames)/i,e.innerHTML)?(Ie&&3===e.nodeType&&(t=e.textContent,g([ne,se,oe],e=>{t=w(t,e," ")}),e.textContent!==t&&(f(DOMPurify3.removed,{element:e.cloneNode()}),e.textContent=t)),_executeHooks(re.afterSanitizeElements,e,null),!1):(_forceRemove(e),!0)},_isValidAttribute=function(e,i,r){if(Le&&("id"===i||"name"===i)&&(r in t||r in nt))return!1;if(Ce&&!be[i]&&I(ae,i));else if(we&&I(ce,i));else if(Se.attributeCheck instanceof Function&&Se.attributeCheck(i,e));else if(!me[i]||be[i]){if(!(_isBasicCustomElement(e)&&(ye.tagNameCheck instanceof RegExp&&I(ye.tagNameCheck,e)||ye.tagNameCheck instanceof Function&&ye.tagNameCheck(e))&&(ye.attributeNameCheck instanceof RegExp&&I(ye.attributeNameCheck,i)||ye.attributeNameCheck instanceof Function&&ye.attributeNameCheck(i,e))||"is"===i&&ye.allowCustomizedBuiltInElements&&(ye.tagNameCheck instanceof RegExp&&I(ye.tagNameCheck,r)||ye.tagNameCheck instanceof Function&&ye.tagNameCheck(r))))return!1}else if(He[i]);else if(I(he,w(r,ue,"")));else if("src"!==i&&"xlink:href"!==i&&"href"!==i||"script"===e||0!==C(r,"data:")||!Ue[e])if(Ee&&!I(le,w(r,ue,"")));else if(r)return!1;return!0},_isBasicCustomElement=function(e){return"annotation-xml"!==e&&S(e,de)},_sanitizeAttributes=function(e){_executeHooks(re.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||_isClobbered(e))return;const i={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:me,forceKeepAttr:void 0};let r=t.length;for(;r--;){const n=t[r],{name:s,namespaceURI:o,value:a}=n,c=it(s),l=a;let u="value"===s?l:E(l);if(i.attrName=c,i.attrValue=u,i.keepAttr=!0,i.forceKeepAttr=void 0,_executeHooks(re.uponSanitizeAttribute,e,i),u=i.attrValue,!Me||"id"!==c&&"name"!==c||(_removeAttribute(s,e),u="user-content-"+u),ke&&I(/((--!?|])>)|<\/(style|title|textarea)/i,u)){_removeAttribute(s,e);continue}if("attributename"===c&&S(u,"href")){_removeAttribute(s,e);continue}if(i.forceKeepAttr)continue;if(!i.keepAttr){_removeAttribute(s,e);continue}if(!_e&&I(/\/>/i,u)){_removeAttribute(s,e);continue}Ie&&g([ne,se,oe],e=>{u=w(u,e," ")});const d=it(e.nodeName);if(_isValidAttribute(d,c,u)){if(Y&&"object"==typeof U&&"function"==typeof U.getAttributeType)if(o);else switch(U.getAttributeType(d,c)){case"TrustedHTML":u=Y.createHTML(u);break;case"TrustedScriptURL":u=Y.createScriptURL(u)}if(u!==l)try{o?e.setAttributeNS(o,s,u):e.setAttribute(s,u),_isClobbered(e)?_forceRemove(e):m(DOMPurify3.removed)}catch(t){_removeAttribute(s,e)}}else _removeAttribute(s,e)}_executeHooks(re.afterSanitizeAttributes,e,null)},at=function _sanitizeShadowDOM2(e){let t=null;const i=_createNodeIterator(e);for(_executeHooks(re.beforeSanitizeShadowDOM,e,null);t=i.nextNode();)_executeHooks(re.uponSanitizeShadowNode,t,null),_sanitizeElements(t),_sanitizeAttributes(t),t.content instanceof s&&_sanitizeShadowDOM2(t.content);_executeHooks(re.afterSanitizeShadowDOM,e,null)};return DOMPurify3.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=null,n=null,o=null,a=null;if(Qe=!e,Qe&&(e="\x3c!--\x3e"),"string"!=typeof e&&!_isNode(e)){if("function"!=typeof e.toString)throw k("toString is not a function");if("string"!=typeof(e=e.toString()))throw k("dirty is not a string, aborting")}if(!DOMPurify3.isSupported)return e;if(Te||_parseConfig(t),DOMPurify3.removed=[],"string"==typeof e&&($e=!1),$e){if(e.nodeName){const t=it(e.nodeName);if(!ge[t]||ve[t])throw k("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)i=_initDocument("\x3c!----\x3e"),n=i.ownerDocument.importNode(e,!0),1===n.nodeType&&"BODY"===n.nodeName||"HTML"===n.nodeName?i=n:i.appendChild(n);else{if(!Re&&!Ie&&!xe&&-1===e.indexOf("<"))return Y&&De?Y.createHTML(e):e;if(i=_initDocument(e),!i)return Re?null:De?X:""}i&&Ae&&_forceRemove(i.firstChild);const l=_createNodeIterator($e?e:i);for(;o=l.nextNode();)_sanitizeElements(o),_sanitizeAttributes(o),o.content instanceof s&&at(o.content);if($e)return e;if(Re){if(Pe)for(a=ee.call(i.ownerDocument);i.firstChild;)a.appendChild(i.firstChild);else a=i;return(me.shadowroot||me.shadowrootmode)&&(a=ie.call(r,a,!0)),a}let u=xe?i.outerHTML:i.innerHTML;return xe&&ge["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&I(K,i.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+i.ownerDocument.doctype.name+">\n"+u),Ie&&g([ne,se,oe],e=>{u=w(u,e," ")}),Y&&De?Y.createHTML(u):u},DOMPurify3.setConfig=function(){_parseConfig(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Te=!0},DOMPurify3.clearConfig=function(){rt=null,Te=!1},DOMPurify3.isValidAttribute=function(e,t,i){rt||_parseConfig({});const r=it(e),n=it(t);return _isValidAttribute(r,n,i)},DOMPurify3.addHook=function(e,t){"function"==typeof t&&f(re[e],t)},DOMPurify3.removeHook=function(e,t){if(void 0!==t){const i=p(re[e],t);return-1===i?void 0:y(re[e],i,1)[0]}return m(re[e])},DOMPurify3.removeHooks=function(e){re[e]=[]},DOMPurify3.removeAllHooks=function(){re={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},DOMPurify3}();t.exports=G}}),ae=__commonJS({"../../node_modules/.pnpm/isomorphic-dompurify@2.35.0/node_modules/isomorphic-dompurify/browser.js"(e,t){t.exports=self.DOMPurify||(self.DOMPurify=oe().default||oe())}});function setGlobalTrustedTypesConfig(e){var t;return(null==e?void 0:e.enabled)?function(e="overvio-sdk"){if(null!==re)return re;const t=function(){return"undefined"!=typeof window&&"trustedTypes"in window&&"function"==typeof(null==(e=window.trustedTypes)?void 0:e.createPolicy)?window.trustedTypes:null;var e}();if(!t)return null;try{const i=t.createPolicy(e,{createHTML:e=>ie.default.sanitize(e,{ALLOWED_TAGS:ne,ALLOW_DATA_ATTR:!1,SAFE_FOR_TEMPLATES:!0,RETURN_TRUSTED_TYPE:!1})});return re=i}catch(e){return null}}(null!=(t=e.policyName)?t:"overvio-sdk"):null}var ce,le,ue,de,he,ge,pe=__esm({"src/security/trusted-types.ts"(){ie=__toESM(ae()),re=null,ne=["b","i","em","strong","u","s","strike","sub","sup","p","br","hr","div","span","h1","h2","h3","h4","h5","h6","ul","ol","li","a","img","table","thead","tbody","tfoot","tr","th","td","blockquote","code","pre","article","section","aside","header","footer","nav","main","figure","figcaption","mark","svg","path","circle","rect","line","polyline","polygon","g","button","input","label"]}});function escapeHtml(e){return"string"!=typeof e?"":e.replace(ue,e=>{var t;return null!=(t=le[e])?t:e})}function sanitizeHref(e,t={}){const{fallback:i="#"}=t;if("string"!=typeof e||""===e.trim())return i;const r=function(e){if("string"!=typeof e)return"";const t=e.trim(),i=t.toLowerCase();if(t.startsWith("//"))return"";for(const e of de)if(i.startsWith(e))return"";return t}(e);return""===r&&""!==e.trim()?i:escapeHtml(r)||i}function sanitizeImageSrc(e,t={}){var i;const{fallbackPlaceholder:r=""}=t;if("string"!=typeof e||""===e.trim())return r;const n=e.trim(),s=n.toLowerCase();if(s.startsWith("javascript:")||s.startsWith("vbscript:"))return r;if(s.startsWith("data:")&&!s.startsWith("data:image/"))return r;if(s.startsWith("data:image/svg")){const e=s.includes(",")?decodeURIComponent(null!=(i=s.split(",")[1])?i:""):"";if(/<script/i.test(e)||/\bon\w+\s*=/i.test(e)||/javascript:/i.test(e)||/<foreignobject/i.test(e))return r}return n.startsWith("//")?r:escapeHtml(n)}function sanitizeHTML(e,t={}){if("string"!=typeof e)return"";const{allowedTags:i=he,allowedAttributes:r=ge,allowDataAttributes:n=!1,safeForTemplates:s=!t.allowDataAttributes,addRelNoopener:o=!0,allowFormElements:a=!1}=t,c=a?["script","style","iframe","frame","frameset","object","embed"]:["script","style","iframe","frame","frameset","object","embed","form"],l={ALLOWED_TAGS:a?[...i,"form"]:i,ALLOWED_ATTR:r,ALLOW_DATA_ATTR:n,ALLOW_UNKNOWN_PROTOCOLS:!1,FORBID_TAGS:c,FORBID_ATTR:["onerror","onload","onclick","onmouseover","onfocus","onblur","onmouseout","onmouseenter","onmouseleave","onkeydown","onkeyup","onkeypress","onchange","onsubmit","onreset","onselect","oninput","oncontextmenu"],SAFE_FOR_TEMPLATES:s,RETURN_TRUSTED_TYPE:!1},u=ce.default.sanitize(e,l);return o?function(e){return e.includes("<a ")?e.replace(/<a\s+([^>]*)>/gi,(e,t)=>{const i=t.toLowerCase();if(i.includes("rel="))return i.includes("noopener")&&i.includes("noreferrer")?e:e.replace(/rel=["']([^"']*)["']/i,'rel="$1 noopener noreferrer"');const r=/target\s*=\s*["']_blank["']/i.test(t),n=/href\s*=\s*["']https?:\/\//i.test(t)||/href\s*=\s*["']\/\//i.test(t);return r||n?`<a ${t} rel="noopener noreferrer">`:e}):e}(u):u}function sanitizeCssClass(e){if("string"!=typeof e)return"";const t=e.trim();return/^[a-zA-Z_-][a-zA-Z0-9_:-]*$/.test(t)?t:""}function sanitizeCssClasses(e){return Array.isArray(e)?e.map(sanitizeCssClass).filter(Boolean).join(" "):""}var me,fe=__esm({"src/utils/sanitize.ts"(){ce=__toESM(ae()),le={"&":"&","<":"<",">":">",'"':""","'":"'"},ue=/[&<>"']/g,de=["javascript:","data:","vbscript:","file:"],he=["b","i","em","strong","u","s","strike","sub","sup","p","br","hr","div","span","h1","h2","h3","h4","h5","h6","ul","ol","li","a","img","table","thead","tbody","tfoot","tr","th","td","blockquote","code","pre","article","section","aside","header","footer","nav","main","figure","figcaption","mark","svg","path","circle","rect","line","polyline","polygon","g","button","input","label"],ge=["href","src","alt","title","class","id","width","height","target","rel","type","disabled","for","placeholder","value","name","required","maxlength","minlength","pattern","role","tabindex","aria-label","aria-describedby","aria-hidden","aria-expanded","aria-controls","aria-autocomplete","aria-selected","aria-live","aria-modal","aria-labelledby","autocomplete","autocapitalize","autocorrect","spellcheck","loading","viewBox","fill","stroke","stroke-width","stroke-linecap","stroke-opacity","cx","cy","r","d","x","y","x1","y1","x2","y2","points"]}});function sanitizeProductUrl(e,t="#"){if("string"!=typeof e)return t;const i=e.trim();if(""===i)return t;const r=i.toLowerCase();for(const e of me)if(r.startsWith(e))return t;return i}function isDangerousUrl(e){if("string"!=typeof e)return!0;const t=e.trim().toLowerCase();for(const e of me)if(t.startsWith(e))return!0;return!1}function sanitizeHighlight(e){if("string"!=typeof e)return"";const t=[];let i=e;const r=/<\/?mark>/gi;let n,s=0;for(;null!==(n=r.exec(e));){const r=i.slice(0,n.index-s);r&&t.push(escapeHtml(r));const o=n[0].toLowerCase();"<mark>"===o?t.push("<mark>"):"</mark>"===o&&t.push("</mark>"),s=n.index+n[0].length,i=e.slice(s)}return i&&t.push(escapeHtml(i)),t.join("")}function stripHighlightTags(e){return"string"!=typeof e?"":e.replace(/<[^>]*>/g,"")}function sanitizeImageUrl(e,t=""){if("string"!=typeof e)return t;const i=e.trim();if(""===i)return t;const r=i.toLowerCase();return r.startsWith("javascript:")||r.startsWith("vbscript:")?t:r.startsWith("data:")?r.startsWith("data:image/")?i:t:r.startsWith("file:")?t:i}function sanitizeProductUrls(e,t="#"){return Array.isArray(e)?e.map(e=>sanitizeProductUrl(e,t)):[]}var ye,ve,be,Se,we=__esm({"src/search/utils/sanitize.ts"(){fe(),me=["javascript:","data:","vbscript:","file:"]}}),Ce={};function createSearchClient(e){return new Se(e)}function isSearchClient(e){return e instanceof Se}__export(Ce,{SearchClient:()=>Se,createSearchClient:()=>createSearchClient,isSearchClient:()=>isSearchClient});var Ee=__esm({"src/search/client.ts"(){P(),M(),W(),A(),ee(),te(),se(),we(),ye="/search/autocomplete",ve="/search/similar",be=500,Se=class{constructor(e){var t,i,r,n,s,o,a,c,l;__publicField(this,"httpClient"),__publicField(this,"apiKey"),__publicField(this,"eventTracker"),__publicField(this,"endpoint"),__publicField(this,"timeout"),__publicField(this,"debug"),__publicField(this,"defaultLocale"),__publicField(this,"autocompleteCache"),__publicField(this,"similarCache"),__publicField(this,"searchCache"),__publicField(this,"l1BaseUrl"),__publicField(this,"userContext",null),__publicField(this,"cachedInitialState",null),__publicField(this,"backgroundControllers",new Set),__publicField(this,"destroyed",!1),__publicField(this,"stats"),this.httpClient=e.httpClient,this.apiKey=e.apiKey,this.eventTracker=null!=(t=e.eventTracker)?t:null,this.endpoint=null!=(i=e.endpoint)?i:"/user/search",this.timeout=null!=(r=e.timeout)?r:1e4,this.debug=null!=(n=e.debug)&&n,this.defaultLocale=null!=(s=e.defaultLocale)?s:"gr",this.autocompleteCache=null!=(o=e.autocompleteCache)?o:null,this.similarCache=null!=(a=e.similarCache)?a:null,this.searchCache=null!=(c=e.searchCache)?c:null,this.l1BaseUrl=null!=(l=e.l1BaseUrl)?l:null,this.stats={queriesExecuted:0,successfulQueries:0,failedQueries:0,totalProductsReturned:0,totalResponseTime:0,autocompleteRequests:0,successfulAutocompleteRequests:0,failedAutocompleteRequests:0,similarProductsRequests:0,successfulSimilarProductsRequests:0,failedSimilarProductsRequests:0,clicksTracked:0,federatedAutocompleteRequests:0,successfulFederatedAutocompleteRequests:0,failedFederatedAutocompleteRequests:0,initialStateRequests:0,successfulInitialStateRequests:0,failedInitialStateRequests:0,autocompleteCacheHits:0,autocompleteCacheMisses:0},this.log("SearchClient initialized",{endpoint:this.endpoint,timeout:this.timeout,hasEventTracker:null!==this.eventTracker,hasAutocompleteCache:null!==this.autocompleteCache,hasSimilarCache:null!==this.similarCache,hasSearchCache:null!==this.searchCache,hasL1BaseUrl:null!==this.l1BaseUrl})}async query(t,i){const r=Date.now();this.stats.queriesExecuted++;try{this.validateQuery(t),this.validateOptions(i);const e=this.buildRequestPayload(t,i);this.log("Executing search query",{query:t,page:e.page,limit:e.limit,hasFilters:!!e.filters,hasSort:!!e.sort});const n=await this.httpClient.post(this.endpoint,e,{timeout:this.timeout}),s=this.transformResponse(n,t,i),o=Date.now()-r;return this.stats.successfulQueries++,this.stats.totalProductsReturned+=s.products.length,this.stats.totalResponseTime+=o,this.log("Search query completed",{query:t,total:s.total,returned:s.products.length,responseTime:o}),this.trackSearchPerformed(t,s,i),s}catch(i){if(this.stats.failedQueries++,i instanceof e.ValidationError)throw i;if(i instanceof e.NetworkError)throw this.log("Search query failed with network error",{query:t,error:i.message}),i;const r=i instanceof Error?i.message:"Unknown error";throw this.log("Search query failed",{query:t,error:r}),e.NetworkError.connectionError(`Search query failed: ${r}`,this.endpoint,"POST",i instanceof Error?i:void 0)}}async autocomplete(t,i){this.stats.autocompleteRequests++;try{this.validateAutocompleteQuery(t);const e=this.validateAutocompleteLimit(i),r=sanitizeSearchQuery(t,{maxSearchQueryLength:be});this.log("Executing autocomplete query",{query:r,limit:e});const n=new URLSearchParams({query:r,limit:String(e)}),s=await this.httpClient.get(`${ye}?${n.toString()}`,{timeout:this.timeout,headers:{"x-api-key":this.apiKey}}),o=this.transformAutocompleteResponse(s);return this.stats.successfulAutocompleteRequests++,this.log("Autocomplete query completed",{query:t,suggestionsCount:o.suggestions.length}),o}catch(i){if(this.stats.failedAutocompleteRequests++,i instanceof e.ValidationError)throw i;if(i instanceof e.NetworkError)throw this.log("Autocomplete query failed with network error",{query:t,error:i.message}),i;const r=i instanceof Error?i.message:"Unknown error";throw this.log("Autocomplete query failed",{query:t,error:r}),e.NetworkError.connectionError(`Autocomplete query failed: ${r}`,ye,"GET",i instanceof Error?i:void 0)}}async similar(t,i){var r;this.stats.similarProductsRequests++;try{this.validateProductId(t),this.validateSimilarProductsOptions(i);const e=null!=(r=null==i?void 0:i.limit)?r:J;this.log("Fetching similar products",{productId:t,limit:e,excludeOutOfStock:null==i?void 0:i.excludeOutOfStock,categoryFilter:null==i?void 0:i.categoryFilter,excludeSameBrand:null==i?void 0:i.excludeSameBrand,minSimilarity:null==i?void 0:i.minSimilarity});const n=new URLSearchParams({limit:String(e)});(null==i?void 0:i.excludeOutOfStock)&&n.set("exclude_out_of_stock","true"),(null==i?void 0:i.categoryFilter)&&n.set("category",i.categoryFilter),(null==i?void 0:i.excludeSameBrand)&&n.set("exclude_same_brand","true"),void 0!==(null==i?void 0:i.minSimilarity)&&n.set("min_similarity",String(i.minSimilarity));const s=await this.httpClient.get(`${ve}/${encodeURIComponent(t)}?${n.toString()}`,{timeout:this.timeout,headers:{"x-api-key":this.apiKey}}),o=this.transformSimilarProductsResponse(s);return this.stats.successfulSimilarProductsRequests++,this.log("Similar products fetched",{productId:t,count:o.products.length}),o}catch(i){if(this.stats.failedSimilarProductsRequests++,i instanceof e.ValidationError)throw i;if(i instanceof e.NetworkError)throw this.log("Similar products request failed with network error",{productId:t,error:i.message}),i;const r=i instanceof Error?i.message:"Unknown error";throw this.log("Similar products request failed",{productId:t,error:r}),e.NetworkError.connectionError(`Similar products request failed: ${r}`,ve,"GET",i instanceof Error?i:void 0)}}trackClick(e,t,i){if("string"!=typeof e||0===e.trim().length)return void this.log("trackClick ignored: invalid query",{query:e});if(!t||"string"!=typeof t)return void this.log("trackClick ignored: invalid productId",{productId:t});if(!Number.isInteger(i)||i<1)return void this.log("trackClick ignored: invalid position",{position:i});this.stats.clicksTracked++;const r=e.trim();this.log("Click tracked",{query:r,productId:t,position:i}),this.trackSearchClick(r,t,i)}trackSpellCorrectionShown(t){t.original&&t.corrected?this.trackWidgetEvent(e.EventType.SPELL_CORRECTION_SHOWN,{originalQuery:t.original,suggestedQuery:t.corrected}):this.log("trackSpellCorrectionShown ignored: missing required fields")}trackSpellCorrectionAccepted(t){t.original&&t.corrected?this.trackWidgetEvent(e.EventType.SPELL_CORRECTION_ACCEPTED,{originalQuery:t.original,acceptedQuery:t.corrected}):this.log("trackSpellCorrectionAccepted ignored: missing required fields")}trackSpellCorrectionRejected(t){t.original&&t.corrected?this.trackWidgetEvent(e.EventType.SPELL_CORRECTION_REJECTED,{originalQuery:t.original,rejectedSuggestion:t.corrected}):this.log("trackSpellCorrectionRejected ignored: missing required fields")}trackQueryRelaxationShown(t){t.originalQuery&&t.relaxedQuery?this.trackWidgetEvent(e.EventType.QUERY_RELAXATION_SHOWN,{originalQuery:t.originalQuery,relaxedQuery:t.relaxedQuery,originalResultsCount:t.originalResultCount,relaxedResultsCount:t.relaxedResultCount}):this.log("trackQueryRelaxationShown ignored: missing required fields")}trackQueryRelaxationAccepted(t){t.originalQuery&&t.relaxedQuery?this.trackWidgetEvent(e.EventType.QUERY_RELAXATION_ACCEPTED,{originalQuery:t.originalQuery,acceptedQuery:t.relaxedQuery}):this.log("trackQueryRelaxationAccepted ignored: missing required fields")}trackQueryRelaxationRejected(t){t.originalQuery&&t.relaxedQuery?this.trackWidgetEvent(e.EventType.QUERY_RELAXATION_REJECTED,{originalQuery:t.originalQuery,rejectedSuggestion:t.relaxedQuery}):this.log("trackQueryRelaxationRejected ignored: missing required fields")}trackZeroResults(t){t.query?this.trackWidgetEvent(e.EventType.ZERO_RESULTS,{query:t.query,filters:t.filters}):this.log("trackZeroResults ignored: missing query")}trackZeroResultsRecovery(t){t.originalQuery&&t.recoveryMethod?this.trackWidgetEvent(e.EventType.ZERO_RESULTS_RECOVERY,{originalQuery:t.originalQuery,recoveryAction:this.mapRecoveryMethod(t.recoveryMethod),newQuery:t.recoveryQuery,resultsCount:t.resultCount}):this.log("trackZeroResultsRecovery ignored: missing required fields")}trackSimilarProductsShown(t){var i;if(!t.similarProductIds||0===t.similarProductIds.length)return void this.log("trackSimilarProductsShown ignored: no products");const r=t.similarProductIds.map((e,t)=>({productId:e,position:t}));this.trackWidgetEvent(e.EventType.SIMILAR_PRODUCTS_SHOWN,{sourceProductId:null!=(i=t.sourceProductId)?i:"",products:r})}trackSimilarProductClicked(t){var i;t.productId?this.trackWidgetEvent(e.EventType.SIMILAR_PRODUCT_CLICKED,{sourceProductId:null!=(i=t.sourceProductId)?i:"",clickedProductId:t.productId,position:t.position}):this.log("trackSimilarProductClicked ignored: missing productId")}trackFilterApplied(t){var i;const r=null!=(i=t.filterName)?i:t.filterType;this.trackWidgetEvent(e.EventType.FILTER_APPLIED,{filterName:r,filterType:t.filterType,filterValue:this.normalizeFilterValue(t.filterValue),query:t.query})}trackFilterRemoved(t){var i;const r=null!=(i=t.filterName)?i:t.filterType;this.trackWidgetEvent(e.EventType.FILTER_REMOVED,{filterName:r,filterValue:this.normalizeFilterValue(t.filterValue)})}trackFiltersCleared(t){this.trackWidgetEvent(e.EventType.FILTERS_CLEARED,{})}trackViewModeChanged(t){t.newMode?this.trackWidgetEvent(e.EventType.VIEW_MODE_CHANGED,{previousMode:t.previousMode,newMode:t.newMode}):this.log("trackViewModeChanged ignored: missing newMode")}trackSortChanged(t){if(!t.newSort)return void this.log("trackSortChanged ignored: missing newSort");const{sortField:i,sortOrder:r}=this.parseSortOrder(t.newSort);let n,s;if(t.previousSort){const e=this.parseSortOrder(t.previousSort);n=e.sortField,s=e.sortOrder}this.trackWidgetEvent(e.EventType.SORT_CHANGED,{sortField:i,sortOrder:r,previousSortField:n,previousSortOrder:s,previousSort:t.previousSort})}async federatedAutocomplete(t,i){var r,n,s,o,a,c;const l=Date.now();if(this.stats.federatedAutocompleteRequests++,!t||t.length<X)return this.createEmptyFederatedResponse(t||"");const u=sanitizeSearchQuery(t,{maxSearchQueryLength:be});if(this.autocompleteCache){const e=this.autocompleteCache.getWithStaleness(u);if(e)return this.stats.autocompleteCacheHits++,this.log("Federated autocomplete cache hit",{query:u,isStale:e.isStale}),e.isStale&&this.revalidateFederatedAutocomplete(u,i),e.data.response;this.stats.autocompleteCacheMisses++}try{const{controller:e,cleanup:t}=createTimeoutController(this.timeout),d=(null==i?void 0:i.signal)?combineSignals(e.signal,i.signal):e.signal,h=new URLSearchParams({q:u,query_limit:String(null!=(r=null==i?void 0:i.queryLimit)?r:4),product_limit:String(null!=(n=null==i?void 0:i.productLimit)?n:3),category_limit:String(null!=(s=null==i?void 0:i.categoryLimit)?s:3),brand_limit:String(null!=(o=null==i?void 0:i.brandLimit)?o:2),include_categories:String(null==(a=null==i?void 0:i.includeCategories)||a),include_brands:String(null==(c=null==i?void 0:i.includeBrands)||c)});this.log("Executing federated autocomplete",{query:u,params:Object.fromEntries(h)});const g=await this.httpClient.get(`${ye}?${h.toString()}`,{timeout:this.timeout,signal:d,headers:{"x-api-key":this.apiKey}});t();const p=Date.now()-l,m=this.transformFederatedResponse(g,u,p);return this.autocompleteCache&&this.autocompleteCache.set(u,m,p),this.stats.successfulFederatedAutocompleteRequests++,this.log("Federated autocomplete completed",{query:u,querySuggestions:m.results.queries.length,productSuggestions:m.results.products.length,categorySuggestions:m.results.categories.length,brandSuggestions:m.results.brands.length,latencyMs:p}),m}catch(t){if(this.stats.failedFederatedAutocompleteRequests++,isAbortError(t))return this.log("Federated autocomplete aborted",{query:u}),this.createEmptyFederatedResponse(u);if(t instanceof e.NetworkError)throw this.log("Federated autocomplete failed with network error",{query:u,error:t.message}),t;const i=t instanceof Error?t.message:"Unknown error";throw this.log("Federated autocomplete failed",{query:u,error:i}),e.NetworkError.connectionError(`Federated autocomplete failed: ${i}`,ye,"GET",t instanceof Error?t:void 0)}}async getInitialState(e){var t,i,r,n;if(this.stats.initialStateRequests++,this.cachedInitialState){const e=Date.now()-this.cachedInitialState.timestamp;if(e<3e5)return this.log("Initial state served from cache",{age:e}),this.cachedInitialState.response}try{const{controller:s,cleanup:o}=createTimeoutController(this.timeout),a=(null==e?void 0:e.signal)?combineSignals(s.signal,e.signal):s.signal,c=new URLSearchParams({limit:String(null!=(t=null==e?void 0:e.limit)?t:8),locale:null!=(i=null==e?void 0:e.locale)?i:this.defaultLocale});this.log("Fetching initial state",{params:Object.fromEntries(c)});const l=await this.httpClient.get(`/search/initial?${c.toString()}`,{timeout:this.timeout,signal:a,headers:{"x-api-key":this.apiKey}});o();const u=this.transformInitialStateResponse(l);return this.cachedInitialState={response:u,timestamp:Date.now()},this.stats.successfulInitialStateRequests++,this.log("Initial state fetched",{trendingProducts:u.trendingProducts.length,popularSearches:u.popularSearches.length,featuredCategories:null!=(n=null==(r=u.featuredCategories)?void 0:r.length)?n:0}),u}catch(e){if(this.stats.failedInitialStateRequests++,isAbortError(e))return this.log("Initial state request aborted"),this.createEmptyInitialState();const t=e instanceof Error?e.message:"Unknown error";return this.log("Initial state request failed (graceful degradation)",{error:t}),this.createEmptyInitialState()}}async getQuerySuggestions(e){var t;try{const{controller:i,cleanup:r}=createTimeoutController(this.timeout),n=(null==e?void 0:e.signal)?combineSignals(i.signal,e.signal):i.signal,s=Math.min(Math.max(null!=(t=null==e?void 0:e.limit)?t:10,1),50),o=new URLSearchParams({limit:String(s)});(null==e?void 0:e.prefix)&&e.prefix.trim().length>0&&o.set("prefix",e.prefix.trim()),this.log("Fetching query suggestions",{params:Object.fromEntries(o)});const a=await this.httpClient.get(`/search/suggestions?${o.toString()}`,{timeout:this.timeout,signal:n,headers:{"x-api-key":this.apiKey}});r();const c=this.transformQuerySuggestionsResponse(a);return this.log("Query suggestions fetched",{count:c.suggestions.length,total:c.total}),c}catch(e){if(isAbortError(e))return this.log("Query suggestions request aborted"),{suggestions:[],total:0};const t=e instanceof Error?e.message:"Unknown error";return this.log("Query suggestions request failed (graceful degradation)",{error:t}),{suggestions:[],total:0}}}async getUserContext(t){if(!t||"string"!=typeof t)return null;if(!this.l1BaseUrl)return this.log("User context fetch skipped: l1BaseUrl not configured",{}),null;try{const{controller:i,cleanup:r}=createTimeoutController(5e3),n=`${this.l1BaseUrl}/api/user/context/${encodeURIComponent(t)}`,s=await fetch(n,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":this.apiKey},signal:i.signal});if(r(),!s.ok)throw new e.NetworkError(`User context request failed with status ${s.status}`,{statusCode:s.status});const o=await s.json(),a={cookieName:o.cookie_name,segment:o.segment,locale:o.locale,recentProducts:o.recent_products,sessionCount:o.session_count};return this.userContext=a,this.log("User context fetched",{segment:a.segment,sessionCount:a.sessionCount}),a}catch(e){const t=e instanceof Error?e.message:"Unknown error";return this.log("User context fetch failed (non-critical)",{error:t}),null}}setUserContext(e){this.userContext=e,this.log("User context set",{hasContext:null!==e})}getCurrentUserContext(){return this.userContext}clearInitialStateCache(){this.cachedInitialState=null,this.log("Initial state cache cleared")}getApiKey(){return this.apiKey}getEndpoint(){return this.endpoint}getStats(){const e=this.stats.successfulQueries>0?this.stats.totalResponseTime/this.stats.successfulQueries:0;return{queriesExecuted:this.stats.queriesExecuted,successfulQueries:this.stats.successfulQueries,failedQueries:this.stats.failedQueries,totalProductsReturned:this.stats.totalProductsReturned,averageResponseTime:Math.round(e),autocompleteRequests:this.stats.autocompleteRequests,successfulAutocompleteRequests:this.stats.successfulAutocompleteRequests,failedAutocompleteRequests:this.stats.failedAutocompleteRequests,similarProductsRequests:this.stats.similarProductsRequests,successfulSimilarProductsRequests:this.stats.successfulSimilarProductsRequests,failedSimilarProductsRequests:this.stats.failedSimilarProductsRequests,clicksTracked:this.stats.clicksTracked,federatedAutocompleteRequests:this.stats.federatedAutocompleteRequests,successfulFederatedAutocompleteRequests:this.stats.successfulFederatedAutocompleteRequests,failedFederatedAutocompleteRequests:this.stats.failedFederatedAutocompleteRequests,initialStateRequests:this.stats.initialStateRequests,successfulInitialStateRequests:this.stats.successfulInitialStateRequests,failedInitialStateRequests:this.stats.failedInitialStateRequests,autocompleteCacheHits:this.stats.autocompleteCacheHits,autocompleteCacheMisses:this.stats.autocompleteCacheMisses}}resetStats(){this.stats={queriesExecuted:0,successfulQueries:0,failedQueries:0,totalProductsReturned:0,totalResponseTime:0,autocompleteRequests:0,successfulAutocompleteRequests:0,failedAutocompleteRequests:0,similarProductsRequests:0,successfulSimilarProductsRequests:0,failedSimilarProductsRequests:0,clicksTracked:0,federatedAutocompleteRequests:0,successfulFederatedAutocompleteRequests:0,failedFederatedAutocompleteRequests:0,initialStateRequests:0,successfulInitialStateRequests:0,failedInitialStateRequests:0,autocompleteCacheHits:0,autocompleteCacheMisses:0},this.log("Stats reset")}destroy(){if(!this.destroyed){this.destroyed=!0;for(const e of this.backgroundControllers)e.abort();this.backgroundControllers.clear(),this.cachedInitialState=null,this.userContext=null,this.log("SearchClient destroyed")}}isDestroyed(){return this.destroyed}validateQuery(t){if("string"!=typeof t)throw e.ValidationError.typeMismatch("query","string",typeof t,t);if(t.length<1)throw new e.ValidationError("query must be at least 1 character(s)",{field:"query",value:t,constraint:"Must be at least 1 character(s)"});if(t.length>be)throw new e.ValidationError("query must be at most 500 characters",{field:"query",value:t,constraint:"Must be at most 500 characters"})}validateOptions(t){if(t){if(void 0!==t.page&&(!Number.isInteger(t.page)||t.page<1))throw new e.ValidationError("page must be a positive integer",{field:"page",value:t.page,constraint:"Must be a positive integer"});if(void 0!==t.limit){if(!Number.isInteger(t.limit)||t.limit<1)throw new e.ValidationError("limit must be a positive integer",{field:"limit",value:t.limit,constraint:"Must be a positive integer"});if(t.limit>G)throw e.ValidationError.outOfRange("limit",1,G,t.limit)}void 0!==t.sort&&this.validateSortOption(t.sort),void 0!==t.filters&&this.validateFilters(t.filters)}}validateSortOption(t){if("object"!=typeof t||null===t)throw e.ValidationError.typeMismatch("sort","object",typeof t,t);if("string"!=typeof t.field||0===t.field.length)throw new e.ValidationError("sort.field must be a non-empty string",{field:"sort.field",value:t.field,constraint:"Must be a non-empty string"});if("asc"!==t.direction&&"desc"!==t.direction)throw new e.ValidationError("sort.direction must be 'asc' or 'desc'",{field:"sort.direction",value:t.direction,constraint:"Must be 'asc' or 'desc'"})}validateFilters(t){if("object"!=typeof t||null===t)throw e.ValidationError.typeMismatch("filters","object",typeof t,t);for(const[i,r]of Object.entries(t)){if("string"!=typeof i||0===i.length)throw new e.ValidationError("filter keys must be non-empty strings",{field:"filters",value:i,constraint:"Filter keys must be non-empty strings"});if("string"!=typeof r)if(Array.isArray(r)){for(const t of r)if("string"!=typeof t)throw new e.ValidationError(`filters.${i} array values must be strings`,{field:`filters.${i}`,value:r,constraint:"Array values must be strings"})}else{if(!isFilterRange(r))throw new e.ValidationError(`filters.${i} must be a string, array of strings, or FilterRange`,{field:`filters.${i}`,value:r,constraint:"Must be a string, array of strings, or FilterRange"});if(void 0!==r.min&&void 0!==r.max&&r.min>r.max)throw new e.ValidationError(`filters.${i}: min cannot be greater than max`,{field:`filters.${i}`,value:r,constraint:"min cannot be greater than max"})}}}validateAutocompleteQuery(t){if("string"!=typeof t)throw e.ValidationError.typeMismatch("query","string",typeof t,t);if(t.length<X)throw new e.ValidationError(`query must be at least ${X} characters for autocomplete`,{field:"query",value:t,constraint:`Must be at least ${X} characters`});if(t.length>be)throw new e.ValidationError("query must be at most 500 characters",{field:"query",value:t,constraint:"Must be at most 500 characters"})}validateAutocompleteLimit(t){if(void 0===t)return e.DEFAULT_AUTOCOMPLETE_LIMIT;if(!Number.isInteger(t)||t<1)throw new e.ValidationError("limit must be a positive integer",{field:"limit",value:t,constraint:"Must be a positive integer"});if(t>Y)throw e.ValidationError.outOfRange("limit",1,Y,t);return t}validateProductId(t){if(!t||"string"!=typeof t)throw e.ValidationError.typeMismatch("productId","string (ProductId)",typeof t,t);if(0===t.length)throw e.ValidationError.requiredField("productId")}validateSimilarProductsOptions(t){if(t){if(void 0!==t.limit){if(!Number.isInteger(t.limit)||t.limit<1)throw new e.ValidationError("limit must be a positive integer",{field:"limit",value:t.limit,constraint:"Must be a positive integer"});if(t.limit>Z)throw e.ValidationError.outOfRange("limit",1,Z,t.limit)}if(void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock)throw e.ValidationError.typeMismatch("excludeOutOfStock","boolean",typeof t.excludeOutOfStock,t.excludeOutOfStock);if(void 0!==t.categoryFilter&&"string"!=typeof t.categoryFilter)throw e.ValidationError.typeMismatch("categoryFilter","string",typeof t.categoryFilter,t.categoryFilter);if(void 0!==t.excludeSameBrand&&"boolean"!=typeof t.excludeSameBrand)throw e.ValidationError.typeMismatch("excludeSameBrand","boolean",typeof t.excludeSameBrand,t.excludeSameBrand);if(void 0!==t.minSimilarity){if("number"!=typeof t.minSimilarity)throw e.ValidationError.typeMismatch("minSimilarity","number",typeof t.minSimilarity,t.minSimilarity);if(t.minSimilarity<0||t.minSimilarity>1)throw e.ValidationError.outOfRange("minSimilarity",0,1,t.minSimilarity)}}}buildRequestPayload(t,i){var r,n;const s={query:sanitizeSearchQuery(t,{maxSearchQueryLength:be})};return s.page=null!=(r=null==i?void 0:i.page)?r:1,s.limit=null!=(n=null==i?void 0:i.limit)?n:e.DEFAULT_SEARCH_LIMIT,(null==i?void 0:i.filters)&&Object.keys(i.filters).length>0&&(s.filters=this.serializeFilters(i.filters)),(null==i?void 0:i.sort)&&(s.sort={field:i.sort.field,direction:i.sort.direction}),s}serializeFilters(e){const t={};for(const[i,r]of Object.entries(e))if("string"==typeof r)t[i]=r;else if(Array.isArray(r))t[i]=r;else if(isFilterRange(r)){const e={};void 0!==r.min&&(e.min=r.min),void 0!==r.max&&(e.max=r.max),t[i]=e}return t}transformResponse(e,t,i){const r={products:this.transformProducts(e.products),facets:this.transformFacets(e.facets),total:e.total,query:e.query||t,page:e.page,limit:e.limit};return void 0!==e.total_pages?r.totalPages=e.total_pages:r.totalPages=Math.ceil(e.total/e.limit),void 0!==e.took&&(r.took=e.took),e.suggestions&&e.suggestions.length>0&&(r.suggestions=e.suggestions),(null==i?void 0:i.filters)&&(r.filters=i.filters),(null==i?void 0:i.sort)&&(r.sort=i.sort),e.metadata&&(r.metadata=this.transformMetadata(e.metadata)),e.spell_correction&&(r.spellCorrection={original:e.spell_correction.original,corrected:e.spell_correction.corrected,confidence:e.spell_correction.confidence}),r}transformMetadata(e){const t={};return void 0!==e.cache&&(t.cache=e.cache),void 0!==e.latency_ms&&(t.latencyMs=e.latency_ms),void 0!==e.backend&&(t.backend=e.backend),e.semantic_contribution&&(t.semanticContribution={count:e.semantic_contribution.count,percentage:e.semantic_contribution.percentage}),e.query_expansion&&(t.queryExpansion={original:e.query_expansion.original,expandedTerms:e.query_expansion.expanded_terms,expansionType:e.query_expansion.expansion_type}),e.query_relaxation&&(t.queryRelaxation={originalQuery:e.query_relaxation.original_query,relaxedQuery:e.query_relaxation.relaxed_query,relaxationType:e.query_relaxation.relaxation_type,originalResultCount:e.query_relaxation.original_result_count,relaxedResultCount:e.query_relaxation.relaxed_result_count}),t}transformProducts(e){return e.map(e=>this.transformProduct(e))}transformProduct(e){const t={id:createProductId(e.id),name:e.name,price:e.price,currency:e.currency,image:e.image,url:e.url};return void 0!==e.regular_price&&(t.originalPrice=e.regular_price),void 0!==e.category&&(t.category=e.category),void 0!==e.rating&&(t.rating=e.rating),void 0!==e.review_count&&(t.reviewCount=e.review_count),void 0!==e.in_stock&&(t.inStock=e.in_stock),void 0!==e.brand&&(t.brand=e.brand),void 0!==e.sku&&(t.sku=e.sku),void 0!==e.description&&(t.description=e.description),void 0!==e.variant&&(t.variant=e.variant),void 0!==e.attributes&&(t.attributes=e.attributes),t}transformFacets(e){const t={brand:[],categories:[]};for(const i of e){const e=this.transformFacetValues(i.values);"brand"===i.name?t.brand=e:"categories"===i.name||"category"===i.name?t.categories=e:"availability"===i.name&&(t.availability=e)}return t}transformFacetValues(e){return e.map(e=>({value:e.value,count:e.count}))}transformAutocompleteResponse(e){return{suggestions:e.suggestions.map(e=>this.transformAutocompleteSuggestion(e)),query:e.query}}transformAutocompleteSuggestion(e){const t={text:e.text};return void 0!==e.type&&(t.type=e.type),void 0!==e.product_id&&(t.productId=createProductId(e.product_id)),void 0!==e.image&&(t.image=e.image),void 0!==e.count&&(t.count=e.count),void 0!==e.highlight&&(t.highlight=e.highlight),t}transformSimilarProductsResponse(e){var t,i,r,n,s;const o=null!=(i=null!=(t=e.products)?t:e.similar_products)?i:[],a=null!=(s=null!=(n=e.source_product_id)?n:null==(r=e.source_product)?void 0:r.id)?s:"",c={products:this.transformProducts(o),sourceProductId:createProductId(a)};return e.metadata&&(c.metadata=e.metadata),c}log(e,t){this.debug}trackSearchPerformed(t,i,r){if(!this.eventTracker)return;const n={query:t.trim(),resultsCount:i.total};if((null==r?void 0:r.filters)&&Object.keys(r.filters).length>0){const e={};for(const[t,i]of Object.entries(r.filters))("string"==typeof i||Array.isArray(i))&&(e[t]=i);Object.keys(e).length>0&&(n.filters=e)}void 0!==(null==r?void 0:r.page)&&1!==r.page&&(n.page=r.page),this.eventTracker.track(e.EventType.SEARCH_PERFORMED,n).then(e=>{e.queued?this.log("SEARCH_PERFORMED event tracked",{query:n.query,resultsCount:n.resultsCount,idempotencyKey:e.idempotencyKey}):e.pendingConsent?this.log("SEARCH_PERFORMED event pending consent",{query:n.query}):e.blockedByPlugin?this.log("SEARCH_PERFORMED event blocked by plugin",{query:n.query,reason:e.blockReason}):this.log("SEARCH_PERFORMED event not queued",{query:n.query,reason:e.reason})}).catch(e=>{this.log("Failed to track SEARCH_PERFORMED event",{query:n.query,error:e instanceof Error?e.message:String(e)})})}trackSearchClick(t,i,r){if(!this.eventTracker)return;const n={query:t,productId:i,position:r};this.eventTracker.track(e.EventType.SEARCH_CLICK,n).then(e=>{e.queued?this.log("SEARCH_CLICK event tracked",{query:n.query,productId:n.productId,position:n.position,idempotencyKey:e.idempotencyKey}):e.pendingConsent?this.log("SEARCH_CLICK event pending consent",{query:n.query,productId:n.productId}):e.blockedByPlugin?this.log("SEARCH_CLICK event blocked by plugin",{query:n.query,productId:n.productId,reason:e.blockReason}):this.log("SEARCH_CLICK event not queued",{query:n.query,productId:n.productId,reason:e.reason})}).catch(e=>{this.log("Failed to track SEARCH_CLICK event",{query:n.query,productId:n.productId,error:e instanceof Error?e.message:String(e)})})}trackWidgetEvent(e,t){this.eventTracker&&this.eventTracker.track(e,t).then(i=>{i.queued?this.log(`${e} event tracked`,{...t,idempotencyKey:i.idempotencyKey}):i.pendingConsent?this.log(`${e} event pending consent`,t):i.blockedByPlugin?this.log(`${e} event blocked by plugin`,{...t,reason:i.blockReason}):this.log(`${e} event not queued`,{...t,reason:i.reason})}).catch(i=>{this.log(`Failed to track ${e} event`,{...t,error:i instanceof Error?i.message:String(i)})})}mapRecoveryMethod(e){return{spell_correction:"used_suggestion",query_relaxation:"modified_query",filter_removal:"removed_filters",new_search:"modified_query",similar_products:"browsed_category",category_browse:"browsed_category",alternative_search:"modified_query",category_click:"browsed_category",popular_product:"browsed_category"}[e]}parseSortOrder(e){return e.endsWith("_asc")?{sortField:e.replace("_asc",""),sortOrder:"asc"}:e.endsWith("_desc")?{sortField:e.replace("_desc",""),sortOrder:"desc"}:{sortField:e,sortOrder:"desc"}}normalizeFilterValue(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]?`${e[0]}-${e[1]}`:e}transformFederatedResponse(e,t,i){var r,n,s,o,a,c,l;const u=(null!=(r=e.query_suggestions)?r:[]).map(e=>this.transformQuerySuggestion(e)).filter(e=>null!==e),d=(null!=(n=e.product_suggestions)?n:[]).map(e=>this.transformProductSuggestion(e)).filter(e=>null!==e),h=(null!=(s=e.category_suggestions)?s:[]).map(e=>this.transformCategorySuggestion(e)).filter(e=>null!==e),g=(null!=(o=e.brand_suggestions)?o:[]).map(e=>this.transformBrandSuggestion(e)).filter(e=>null!==e),p={cache:null!=(c=null==(a=e.metadata)?void 0:a.cache)?c:"MISS"};return(null==(l=e.metadata)?void 0:l.source_latencies)&&(p.sourceLatencies=e.metadata.source_latencies),{query:t,latencyMs:i,results:{queries:u,products:d,categories:h,brands:g,recent:[]},metadata:p}}transformQuerySuggestion(e){if(!e.query||"string"!=typeof e.query)return null;const t={query:e.query};return void 0!==e.result_count&&(t.resultCount=e.result_count),e.category&&(t.category=e.category),e.highlighted&&(t.highlighted=sanitizeHighlight(e.highlighted)),t}transformProductSuggestion(e){if(!e.id||!e.name||"number"!=typeof e.price||!e.image)return this.log("Invalid product suggestion - missing required fields",{raw:e}),null;const t={id:createProductId(e.id),name:e.name,price:e.price,image:sanitizeImageUrl(e.image),url:sanitizeProductUrl(e.url||`/products/${e.id}`)};return e.category&&(t.category=e.category),void 0!==e.sale_price&&(t.salePrice=e.sale_price),void 0!==e.rating&&(t.rating=e.rating),void 0!==e.review_count&&(t.reviewCount=e.review_count),void 0!==e.in_stock&&(t.inStock=e.in_stock),e.brand&&(t.brand=e.brand),e.highlighted&&(t.highlighted=sanitizeHighlight(e.highlighted)),t}transformCategorySuggestion(e){if(!e.id||!e.name)return null;const t={id:e.id,name:e.name,url:sanitizeProductUrl(e.url||`/categories/${e.id}`)};return void 0!==e.product_count&&(t.productCount=e.product_count),e.breadcrumb&&(t.breadcrumb=e.breadcrumb),e.image&&(t.image=sanitizeImageUrl(e.image)),e.highlighted&&(t.highlighted=sanitizeHighlight(e.highlighted)),t}transformBrandSuggestion(e){if(!e.id||!e.name)return null;const t={id:e.id,name:e.name,url:sanitizeProductUrl(e.url||`/brands/${e.id}`)};return void 0!==e.product_count&&(t.productCount=e.product_count),e.logo&&(t.logo=sanitizeImageUrl(e.logo)),e.highlighted&&(t.highlighted=sanitizeHighlight(e.highlighted)),t}createEmptyFederatedResponse(e){return{query:e,latencyMs:0,results:{queries:[],products:[],categories:[],brands:[],recent:[]},metadata:{cache:"SKIP"}}}revalidateFederatedAutocomplete(e,t){if(this.destroyed)return;const i=sanitizeSearchQuery(e,{maxSearchQueryLength:be}),r=new AbortController;this.backgroundControllers.add(r),(async()=>{var e,n,s,o,a,c;try{const l=new URLSearchParams({q:i,query_limit:String(null!=(e=null==t?void 0:t.queryLimit)?e:4),product_limit:String(null!=(n=null==t?void 0:t.productLimit)?n:3),category_limit:String(null!=(s=null==t?void 0:t.categoryLimit)?s:3),brand_limit:String(null!=(o=null==t?void 0:t.brandLimit)?o:2),include_categories:String(null==(a=null==t?void 0:t.includeCategories)||a),include_brands:String(null==(c=null==t?void 0:t.includeBrands)||c)}),u=Date.now(),d=await this.httpClient.get(`${ye}?${l.toString()}`,{timeout:this.timeout,signal:r.signal,headers:{"x-api-key":this.apiKey}});if(this.destroyed)return;const h=Date.now()-u,g=this.transformFederatedResponse(d,i,h);this.autocompleteCache&&(this.autocompleteCache.set(i,g,h),this.log("Cache revalidated in background",{query:i}))}catch(e){if(isAbortError(e))return;this.log("Background revalidation failed",{query:i,error:e instanceof Error?e.message:"Unknown error"})}finally{this.backgroundControllers.delete(r)}})()}transformInitialStateResponse(e){var t,i,r;return{trendingProducts:(null!=(t=e.trending_products)?t:[]).map(e=>this.transformProduct(e)).filter(e=>this.isValidProduct(e)),popularSearches:(null!=(i=e.popular_searches)?i:[]).filter(e=>e.query&&"string"==typeof e.query).map(e=>{var t;return{query:e.query,count:null!=(t=e.count)?t:0}}),featuredCategories:(null!=(r=e.featured_categories)?r:[]).map(e=>{const t={id:e.id,name:e.name,url:sanitizeProductUrl(e.url||`/categories/${e.id}`)};return e.image&&(t.image=sanitizeImageUrl(e.image)),t})}}transformQuerySuggestionsResponse(e){var t;const i={suggestions:(null!=(t=e.suggestions)?t:[]).filter(e=>e.query&&"string"==typeof e.query).map(e=>{var t;return{query:e.query,count:null!=(t=e.count)?t:0}})};return void 0!==e.total&&(i.total=e.total),i}createEmptyInitialState(){return{trendingProducts:[],popularSearches:[],featuredCategories:[]}}isValidProduct(e){return"string"==typeof e.id&&e.id.length>0&&"string"==typeof e.name&&e.name.length>0&&"number"==typeof e.price&&Number.isFinite(e.price)}}}});function isCacheStatus(e){return"HIT"===e||"MISS"===e||"SKIP"===e}function isSearchBackend(e){return"typesense"===e||"vector"===e||"hybrid"===e}function isSearchLanguage(e){return"el"===e||"en"===e||"mixed"===e||"greeklish"===e}function isRelaxationType(e){return"string"==typeof e&&["spelling","synonym","hyponym","boolean","hypernym","semantic","popular"].includes(e)}function isSemanticContribution(e){if("object"!=typeof e||null===e)return!1;const t=e;return"boolean"==typeof t.enabled&&(!("number"!=typeof t.contributed_results||!Number.isFinite(t.contributed_results))&&(!("number"!=typeof t.overlap_results||!Number.isFinite(t.overlap_results))&&(!("number"!=typeof t.keyword_only_results||!Number.isFinite(t.keyword_only_results))&&!("string"!=typeof t.top_result_source||!["keyword","semantic","both","none"].includes(t.top_result_source)||"boolean"!=typeof t.relaxation_applied||"number"!=typeof t.contribution_ratio||!Number.isFinite(t.contribution_ratio)))))}function isQueryExpansion(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.original_query)return!1;if("string"!=typeof t.preprocessed_query)return!1;if(!Array.isArray(t.stopwords_removed))return!1;for(const e of t.stopwords_removed)if("string"!=typeof e)return!1;return!!isSearchLanguage(t.detected_language)}function isQueryRelaxationMeta(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.original_query&&"string"==typeof t.relaxed_query&&!!isRelaxationType(t.type)&&!("number"!=typeof t.original_result_count||!Number.isInteger(t.original_result_count))}function isRawSearchMeta(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!isCacheStatus(t.cache)||"number"!=typeof t.latency_ms||!Number.isFinite(t.latency_ms)||!isSearchBackend(t.backend)||"number"!=typeof t.total||!Number.isFinite(t.total)||void 0!==t.semantic_contribution&&!isSemanticContribution(t.semantic_contribution)||void 0!==t.query_expansion&&!isQueryExpansion(t.query_expansion)||void 0!==t.query_relaxation&&!isQueryRelaxationMeta(t.query_relaxation))}var _e=__esm({"src/search/metadata-types.ts"(){}});function isHighlightPosition(e){if("object"!=typeof e||null===e)return!1;const t=e;return"number"==typeof t.start&&Number.isInteger(t.start)&&t.start>=0&&"number"==typeof t.end&&Number.isInteger(t.end)&&t.end>=0}function isQuerySuggestion(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.query||0===t.query.length)return!1;if(void 0!==t.resultCount&&("number"!=typeof t.resultCount||!Number.isFinite(t.resultCount)))return!1;if(void 0!==t.category&&"string"!=typeof t.category)return!1;if(void 0!==t.highlights){if(!Array.isArray(t.highlights))return!1;for(const e of t.highlights)if(!isHighlightPosition(e))return!1}return void 0===t.highlighted||"string"==typeof t.highlighted}function isProductSuggestionData(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.id||0===t.id.length)return!1;if("string"!=typeof t.name||0===t.name.length)return!1;if("number"!=typeof t.price||!Number.isFinite(t.price))return!1;if("string"!=typeof t.image)return!1;if("string"!=typeof t.url)return!1;const i=["category","brand","highlighted"];for(const e of i)if(void 0!==t[e]&&"string"!=typeof t[e])return!1;return!(!(void 0===t.salePrice||"number"==typeof t.salePrice&&Number.isFinite(t.salePrice))||!(void 0===t.rating||"number"==typeof t.rating&&Number.isFinite(t.rating))||!(void 0===t.reviewCount||"number"==typeof t.reviewCount&&Number.isInteger(t.reviewCount))||void 0!==t.inStock&&"boolean"!=typeof t.inStock)}function isCategorySuggestionData(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.id||0===t.id.length)return!1;if("string"!=typeof t.name||0===t.name.length)return!1;if("string"!=typeof t.url)return!1;if(void 0!==t.productCount&&("number"!=typeof t.productCount||!Number.isInteger(t.productCount)))return!1;const i=["breadcrumb","image","highlighted"];for(const e of i)if(void 0!==t[e]&&"string"!=typeof t[e])return!1;return!0}function isBrandSuggestionData(e){if("object"!=typeof e||null===e)return!1;const t=e;return!("string"!=typeof t.id||0===t.id.length||"string"!=typeof t.name||0===t.name.length||"string"!=typeof t.url||!(void 0===t.productCount||"number"==typeof t.productCount&&Number.isInteger(t.productCount))||void 0!==t.logo&&"string"!=typeof t.logo||void 0!==t.highlighted&&"string"!=typeof t.highlighted)}function isFederatedResult(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.queries))return!1;for(const e of t.queries)if(!isQuerySuggestion(e))return!1;if(!Array.isArray(t.products))return!1;for(const e of t.products)if(!isProductSuggestionData(e))return!1;if(!Array.isArray(t.categories))return!1;for(const e of t.categories)if(!isCategorySuggestionData(e))return!1;if(!Array.isArray(t.brands))return!1;for(const e of t.brands)if(!isBrandSuggestionData(e))return!1;if(!Array.isArray(t.recent))return!1;for(const e of t.recent)if("string"!=typeof e)return!1;return!0}function isFederatedSelectItem(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.type)return!1;switch(t.type){case"query":return isQuerySuggestion(t.value);case"product":return isProductSuggestionData(t.value);case"category":return isCategorySuggestionData(t.value);case"brand":return isBrandSuggestionData(t.value);case"recent":return"string"==typeof t.value;default:return!1}}function isFederatedAutocompleteMetadata(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.cache||!["HIT","MISS","SKIP"].includes(t.cache))return!1;if(void 0!==t.sourceLatencies){if("object"!=typeof t.sourceLatencies||null===t.sourceLatencies)return!1;const e=t.sourceLatencies;for(const t of Object.keys(e))if("number"!=typeof e[t]||!Number.isFinite(e[t]))return!1}return void 0===t.error||"string"==typeof t.error}function isFederatedAutocompleteResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;return!("string"!=typeof t.query||"number"!=typeof t.latencyMs||!Number.isFinite(t.latencyMs)||!isFederatedResult(t.results)||!isFederatedAutocompleteMetadata(t.metadata))}var Ie=__esm({"src/search/federated-types.ts"(){}});function activeFiltersToSearchFilters(e){const t={};return void 0!==e.categories&&e.categories.length>0&&(t.category=e.categories),void 0!==e.brands&&e.brands.length>0&&(t.brand=e.brands),void 0!==e.priceMin&&(t.price_min=String(e.priceMin)),void 0!==e.priceMax&&(t.price_max=String(e.priceMax)),void 0!==e.availability&&"all"!==e.availability&&(t.availability=e.availability),!0===e.onSale&&(t.on_sale="true"),!0===e.newArrivals&&(t.new_arrivals="true"),!0===e.freeShipping&&(t.free_shipping="true"),t}function searchFiltersToActiveFilters(e){const t={},i=e.category;void 0!==i&&(Array.isArray(i)?t.categories=i:"string"==typeof i&&(t.categories=[i]));const r=e.brand;void 0!==r&&(Array.isArray(r)?t.brands=r:"string"==typeof r&&(t.brands=[r]));const n=e.price_min;if(void 0!==n)if("string"==typeof n){const e=parseFloat(n);isNaN(e)||(t.priceMin=e)}else"number"==typeof n&&(t.priceMin=n);const s=e.price_max;if(void 0!==s)if("string"==typeof s){const e=parseFloat(s);isNaN(e)||(t.priceMax=e)}else"number"==typeof s&&(t.priceMax=s);const o=e.availability;return void 0!==o&&"string"==typeof o&&("in_stock"!==o&&"out_of_stock"!==o&&"all"!==o||(t.availability=o)),"true"===e.on_sale&&(t.onSale=!0),"true"===e.new_arrivals&&(t.newArrivals=!0),"true"===e.free_shipping&&(t.freeShipping=!0),t}function countActiveFilters(e){let t=0;return void 0!==e.categories&&(t+=e.categories.length),void 0!==e.brands&&(t+=e.brands.length),void 0===e.priceMin&&void 0===e.priceMax||(t+=1),void 0!==e.availability&&"all"!==e.availability&&(t+=1),!0===e.onSale&&(t+=1),!0===e.newArrivals&&(t+=1),!0===e.freeShipping&&(t+=1),t}function hasActiveFilters(e){return countActiveFilters(e)>0}function createEmptyActiveFilters(){return{}}function isAvailabilityFilter(e){return"all"===e||"in_stock"===e||"out_of_stock"===e}function isActiveFilters(e){if("object"!=typeof e||null===e)return!1;const t=e;if(void 0!==t.categories){if(!Array.isArray(t.categories))return!1;for(const e of t.categories)if("string"!=typeof e)return!1}if(void 0!==t.brands){if(!Array.isArray(t.brands))return!1;for(const e of t.brands)if("string"!=typeof e)return!1}if(void 0!==t.priceMin&&("number"!=typeof t.priceMin||!Number.isFinite(t.priceMin)))return!1;if(void 0!==t.priceMax&&("number"!=typeof t.priceMax||!Number.isFinite(t.priceMax)))return!1;if(void 0!==t.availability&&!isAvailabilityFilter(t.availability))return!1;const i=["onSale","newArrivals","freeShipping"];for(const e of i)if(void 0!==t[e]&&"boolean"!=typeof t[e])return!1;return!0}function isPriceRange(e){if("object"!=typeof e||null===e)return!1;const t=e;return!("number"!=typeof t.min||!Number.isFinite(t.min)||"number"!=typeof t.max||!Number.isFinite(t.max))}var ke,xe,Te,Ae,Re,Pe,De,Le=__esm({"src/search/filter-types.ts"(){}});function isWidgetTheme(e){return"light"===e||"dark"===e||"auto"===e}function isWidgetLayout(e){return"grid"===e||"list"===e}function isWidgetMode(e){return"inline"===e||"modal"===e}function isWidgetFeatures(e){if("object"!=typeof e||null===e)return!1;const t=e,i=["autocomplete","filters","voiceSearch","instantSearch","recentSearches","spellCorrection","quickView"];for(const e of i)if(void 0!==t[e]&&"boolean"!=typeof t[e])return!1;return!0}function isWidgetVariables(e){if("object"!=typeof e||null===e)return!1;const t=e,i=["colorPrimary","colorPrimaryHover","colorBackground","colorSurface","colorText","colorTextSecondary","colorBorder","colorError","colorSuccess","borderRadius","fontFamily","fontSize","spacing","shadow","inputHeight","buttonHeight","transitionDuration","zIndex"];for(const e of i)if(void 0!==t[e]&&"string"!=typeof t[e])return!1;return!0}function isWidgetStrings(e){if("object"!=typeof e||null===e)return!1;const t=e,i=["placeholder","noResults","loading","error","resultsCount","clearFilters","showMore","showLess","searchButton","closeButton","ariaLoading","ariaResultsLoaded"];for(const e of i)if(void 0!==t[e]&&"string"!=typeof t[e])return!1;return!0}function isWidgetConfig(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.clientId||0===t.clientId.length)return!1;if(void 0!==t.theme&&!isWidgetTheme(t.theme))return!1;if(void 0!==t.locale&&"string"!=typeof t.locale)return!1;if(void 0!==t.features&&!isWidgetFeatures(t.features))return!1;if(void 0!==t.variables&&!isWidgetVariables(t.variables))return!1;if(void 0!==t.strings&&!isWidgetStrings(t.strings))return!1;if(void 0!==t.layout&&!isWidgetLayout(t.layout))return!1;if(void 0!==t.mode&&!isWidgetMode(t.mode))return!1;const i=["resultsPerPage","searchDebounceMs","autocompleteDebounceMs","minQueryLength","maxAutocompleteSuggestions","maxRecentSearches","version","fetchedAt"];for(const e of i)if(void 0!==t[e]&&("number"!=typeof t[e]||!Number.isFinite(t[e])))return!1;if(void 0!==t.analyticsEnabled&&"boolean"!=typeof t.analyticsEnabled)return!1;const r=["customCSS","apiEndpoint"];for(const e of r)if(void 0!==t[e]&&"string"!=typeof t[e])return!1;return!0}var Me,Oe=__esm({"src/search/config-types.ts"(){ke={theme:"light",locale:"gr",resultsPerPage:20,layout:"grid",mode:"inline",searchDebounceMs:200,autocompleteDebounceMs:100,minQueryLength:2,maxAutocompleteSuggestions:8,maxRecentSearches:5,analyticsEnabled:!0},xe={autocomplete:!0,filters:!0,voiceSearch:!1,instantSearch:!0,recentSearches:!1,spellCorrection:!0,quickView:!1},Te={colorPrimary:"#3b82f6",colorPrimaryHover:"#2563eb",colorBackground:"#ffffff",colorSurface:"#f8fafc",colorText:"#1f2937",colorTextSecondary:"#6b7280",colorBorder:"#e5e7eb",colorError:"#ef4444",colorSuccess:"#22c55e",borderRadius:"8px",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",spacing:"16px",shadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",inputHeight:"40px",buttonHeight:"40px",transitionDuration:"150ms",zIndex:"1000"},Ae={colorPrimary:"#60a5fa",colorPrimaryHover:"#3b82f6",colorBackground:"#111827",colorSurface:"#1f2937",colorText:"#f9fafb",colorTextSecondary:"#9ca3af",colorBorder:"#374151",colorError:"#f87171",colorSuccess:"#4ade80",borderRadius:"8px",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:"14px",spacing:"16px",shadow:"0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2)",inputHeight:"40px",buttonHeight:"40px",transitionDuration:"150ms",zIndex:"1000"},Re={placeholder:"Search...",noResults:"No results found",loading:"Loading...",error:"An error occurred. Please try again.",resultsCount:"{count} results",clearFilters:"Clear filters",showMore:"Show more",showLess:"Show less",searchButton:"Search",closeButton:"Close",ariaLoading:"Loading results",ariaResultsLoaded:"{count} results available",autocompleteLoading:"Loading suggestions...",autocompleteNoResults:"No suggestions found"},Pe=3e5,De="overvio_widget_config"}}),$e={};function createWidgetConfigManager(e){return new Me(e)}function isWidgetConfigManager(e){return e instanceof Me}function isGetConfigResult(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!isWidgetConfig(t.config)&&"boolean"==typeof t.cached&&"boolean"==typeof t.usingDefaults}__export($e,{WidgetConfigManager:()=>Me,createWidgetConfigManager:()=>createWidgetConfigManager,isGetConfigResult:()=>isGetConfigResult,isWidgetConfigManager:()=>isWidgetConfigManager});var Ne,Fe,qe,Ue,ze,He,Ve,Be=__esm({"src/search/config.ts"(){P(),Oe(),Me=class{constructor(e){var t,i,r,n,s,o,a;__publicField(this,"httpClient"),__publicField(this,"storage"),__publicField(this,"apiKey"),__publicField(this,"clientId"),__publicField(this,"endpoint"),__publicField(this,"timeout"),__publicField(this,"cacheTTL"),__publicField(this,"storageKey"),__publicField(this,"emitter"),__publicField(this,"debug"),__publicField(this,"cachedConfig",null),__publicField(this,"cachedAt",null),__publicField(this,"fetchPromise",null),__publicField(this,"stats",{totalRequests:0,cacheHits:0,cacheMisses:0,failedFetches:0,lastFetchedAt:null}),this.httpClient=e.httpClient,this.storage=e.storage,this.apiKey=e.apiKey,this.clientId=null!=(t=e.clientId)?t:"default",this.endpoint=null!=(i=e.endpoint)?i:"/api/widget/config",this.timeout=null!=(r=e.timeout)?r:1e4,this.cacheTTL=null!=(n=e.cacheTTL)?n:Pe,this.storageKey=null!=(s=e.storageKey)?s:De,this.emitter=null!=(o=e.emitter)?o:null,this.debug=null!=(a=e.debug)&&a,this.loadCachedConfig(),this.log("WidgetConfigManager initialized",{clientId:this.clientId,endpoint:this.endpoint,cacheTTL:this.cacheTTL})}async getConfig(e){var t;if(this.stats.totalRequests++,(null==(t=null==e?void 0:e.forceRefresh)||!t)&&this.isCacheValid()){this.stats.cacheHits++;const e=this.cachedConfig;return this.log("Returning cached config",{cachedAt:this.cachedAt,expiresIn:this.getCacheExpiresIn()}),this.emit("config:loaded",{config:e,cached:!0}),{config:e,cached:!0,usingDefaults:!1}}if(this.stats.cacheMisses++,this.fetchPromise)return this.log("Reusing in-flight fetch request"),this.fetchPromise;this.fetchPromise=this.fetchConfig(e);try{return await this.fetchPromise}finally{this.fetchPromise=null}}getCachedConfig(){return this.cachedConfig}isCacheValid(){return!(!this.cachedConfig||!this.cachedAt)&&Date.now()<this.cachedAt+this.cacheTTL}invalidateCache(){this.cachedConfig=null,this.cachedAt=null,this.clearStoredConfig(),this.log("Cache invalidated"),this.emit("config:cache-invalidated",{})}getStats(){return{totalRequests:this.stats.totalRequests,cacheHits:this.stats.cacheHits,cacheMisses:this.stats.cacheMisses,failedFetches:this.stats.failedFetches,lastFetchedAt:this.stats.lastFetchedAt,isCached:null!==this.cachedConfig,cacheExpiresIn:this.getCacheExpiresIn()}}resetStats(){this.stats={totalRequests:0,cacheHits:0,cacheMisses:0,failedFetches:0,lastFetchedAt:null},this.log("Stats reset")}getApiKey(){return this.apiKey}getClientId(){return this.clientId}async fetchConfig(t){var i;const r=null!=(i=null==t?void 0:t.timeout)?i:this.timeout,n=this.endpoint;this.log("Fetching config from server",{url:n,timeout:r});try{const e={timeout:r,headers:{"x-api-key":this.apiKey}};(null==t?void 0:t.signal)&&(e.signal=t.signal);const i=await this.httpClient.get(n,e),s=this.transformResponse(i),o=this.cachedConfig;return this.cacheConfig(s),this.emit("config:loaded",{config:s,cached:!1}),o&&!this.configsEqual(o,s)?this.emit("config:changed",{oldConfig:o,newConfig:s}):o||this.emit("config:changed",{oldConfig:null,newConfig:s}),this.stats.lastFetchedAt=Date.now(),this.log("Config fetched successfully",{version:s.version,theme:s.theme}),{config:s,cached:!1,usingDefaults:!1}}catch(t){this.stats.failedFetches++;const i=t instanceof e.NetworkError&&404===t.statusCode;this.log("Config fetch failed",{error:t instanceof Error?t.message:"Unknown error",is404:i});const r=this.createDefaultConfig();return this.emit("config:error",{error:t instanceof Error?t:new Error("Unknown error"),usingDefaults:!0}),this.cachedConfig?(this.log("Returning stale cached config on fetch failure"),{config:this.cachedConfig,cached:!0,usingDefaults:!1,error:t instanceof Error?t:new Error("Unknown error")}):{config:r,cached:!1,usingDefaults:!0,error:t instanceof Error?t:new Error("Unknown error")}}}transformResponse(e){var t;const i={clientId:null!=(t=e.client_id)?t:this.clientId};return"light"!==e.theme&&"dark"!==e.theme&&"auto"!==e.theme||(i.theme=e.theme),e.locale&&(i.locale=e.locale),e.features&&(i.features=this.transformFeatures(e.features)),e.variables&&(i.variables=this.transformVariables(e.variables)),e.strings&&(i.strings=this.transformStrings(e.strings)),"grid"!==e.layout&&"list"!==e.layout||(i.layout=e.layout),"inline"!==e.mode&&"modal"!==e.mode||(i.mode=e.mode),"number"==typeof e.results_per_page&&(i.resultsPerPage=e.results_per_page),"number"==typeof e.search_debounce_ms&&(i.searchDebounceMs=e.search_debounce_ms),"number"==typeof e.autocomplete_debounce_ms&&(i.autocompleteDebounceMs=e.autocomplete_debounce_ms),"number"==typeof e.min_query_length&&(i.minQueryLength=e.min_query_length),"number"==typeof e.max_autocomplete_suggestions&&(i.maxAutocompleteSuggestions=e.max_autocomplete_suggestions),"number"==typeof e.max_recent_searches&&(i.maxRecentSearches=e.max_recent_searches),"boolean"==typeof e.analytics_enabled&&(i.analyticsEnabled=e.analytics_enabled),"string"==typeof e.custom_css&&(i.customCSS=e.custom_css),"string"==typeof e.api_endpoint&&(i.apiEndpoint=e.api_endpoint),"number"==typeof e.version&&(i.version=e.version),i.fetchedAt=Date.now(),i}transformFeatures(e){const t={};return"boolean"==typeof e.autocomplete&&(t.autocomplete=e.autocomplete),"boolean"==typeof e.filters&&(t.filters=e.filters),"boolean"==typeof e.voice_search&&(t.voiceSearch=e.voice_search),"boolean"==typeof e.instant_search&&(t.instantSearch=e.instant_search),"boolean"==typeof e.recent_searches&&(t.recentSearches=e.recent_searches),"boolean"==typeof e.spell_correction&&(t.spellCorrection=e.spell_correction),"boolean"==typeof e.quick_view&&(t.quickView=e.quick_view),t}transformVariables(e){const t={};return"string"==typeof e.color_primary&&(t.colorPrimary=e.color_primary),"string"==typeof e.color_primary_hover&&(t.colorPrimaryHover=e.color_primary_hover),"string"==typeof e.color_background&&(t.colorBackground=e.color_background),"string"==typeof e.color_surface&&(t.colorSurface=e.color_surface),"string"==typeof e.color_text&&(t.colorText=e.color_text),"string"==typeof e.color_text_secondary&&(t.colorTextSecondary=e.color_text_secondary),"string"==typeof e.color_border&&(t.colorBorder=e.color_border),"string"==typeof e.color_error&&(t.colorError=e.color_error),"string"==typeof e.color_success&&(t.colorSuccess=e.color_success),"string"==typeof e.border_radius&&(t.borderRadius=e.border_radius),"string"==typeof e.font_family&&(t.fontFamily=e.font_family),"string"==typeof e.font_size&&(t.fontSize=e.font_size),"string"==typeof e.spacing&&(t.spacing=e.spacing),"string"==typeof e.shadow&&(t.shadow=e.shadow),"string"==typeof e.input_height&&(t.inputHeight=e.input_height),"string"==typeof e.button_height&&(t.buttonHeight=e.button_height),"string"==typeof e.transition_duration&&(t.transitionDuration=e.transition_duration),"string"==typeof e.z_index&&(t.zIndex=e.z_index),t}transformStrings(e){const t={};return"string"==typeof e.placeholder&&(t.placeholder=e.placeholder),"string"==typeof e.no_results&&(t.noResults=e.no_results),"string"==typeof e.loading&&(t.loading=e.loading),"string"==typeof e.error&&(t.error=e.error),"string"==typeof e.results_count&&(t.resultsCount=e.results_count),"string"==typeof e.clear_filters&&(t.clearFilters=e.clear_filters),"string"==typeof e.show_more&&(t.showMore=e.show_more),"string"==typeof e.show_less&&(t.showLess=e.show_less),"string"==typeof e.search_button&&(t.searchButton=e.search_button),"string"==typeof e.close_button&&(t.closeButton=e.close_button),"string"==typeof e.aria_loading&&(t.ariaLoading=e.aria_loading),"string"==typeof e.aria_results_loaded&&(t.ariaResultsLoaded=e.aria_results_loaded),t}loadCachedConfig(){try{if(!this.storage.isAvailable())return void this.log("Storage not available, skipping cache load");const e=this.storage.get(this.storageKey);if(!e)return void this.log("No cached config found");if(1!==e._v)return this.log("Cached config version mismatch, clearing cache",{stored:e._v,expected:1}),void this.clearStoredConfig();if(!isWidgetConfig(e.config))return this.log("Cached config invalid, clearing cache"),void this.clearStoredConfig();const t=Date.now(),i=e.cachedAt+this.cacheTTL;if(t>=i)return this.log("Cached config expired",{cachedAt:e.cachedAt,expiresAt:i,now:t}),this.cachedConfig=e.config,void(this.cachedAt=e.cachedAt);this.cachedConfig=e.config,this.cachedAt=e.cachedAt,this.log("Loaded cached config",{cachedAt:this.cachedAt,expiresIn:i-t})}catch(e){this.log("Error loading cached config",{error:e instanceof Error?e.message:"Unknown error"})}}cacheConfig(e){const t=Date.now();this.cachedConfig=e,this.cachedAt=t;try{if(!this.storage.isAvailable())return void this.log("Storage not available, skipping cache persist");const i={config:e,cachedAt:t,_v:1};this.storage.set(this.storageKey,i,{ttl:this.cacheTTL}),this.log("Config cached to storage",{cachedAt:t,ttl:this.cacheTTL})}catch(e){this.log("Error caching config to storage",{error:e instanceof Error?e.message:"Unknown error"})}}clearStoredConfig(){try{this.storage.isAvailable()&&this.storage.remove(this.storageKey)}catch(e){this.log("Error clearing stored config",{error:e instanceof Error?e.message:"Unknown error"})}}getCacheExpiresIn(){if(!this.cachedAt)return null;const e=this.cachedAt+this.cacheTTL-Date.now();return Math.max(0,e)}createDefaultConfig(){return{clientId:this.clientId,theme:ke.theme,locale:ke.locale,features:{...xe},variables:{...Te},strings:{...Re},resultsPerPage:ke.resultsPerPage,layout:ke.layout,mode:ke.mode,searchDebounceMs:ke.searchDebounceMs,autocompleteDebounceMs:ke.autocompleteDebounceMs,minQueryLength:ke.minQueryLength,maxAutocompleteSuggestions:ke.maxAutocompleteSuggestions,maxRecentSearches:ke.maxRecentSearches,analyticsEnabled:ke.analyticsEnabled,fetchedAt:Date.now()}}configsEqual(e,t){const i={...e},r={...t};return delete i.fetchedAt,delete r.fetchedAt,JSON.stringify(i)===JSON.stringify(r)}emit(e,t){this.emitter&&this.emitter.emit(e,t)}log(e,t){this.debug}}}}),je=__esm({"src/search/widget/types.ts"(){Ne="overvio",Fe=200,qe=100,Ue=2,ze=(e=>(e.IDLE="idle",e.LOADING="loading",e.RESULTS="results",e.NO_RESULTS="no_results",e.ERROR="error",e))(ze||{})}});function applyNonce(e,t){return void 0!==t&&!!function(e){return"string"==typeof e&&0!==e.length&&!!He.test(e)}(t)&&(e.setAttribute("nonce",t),!0)}function getConfiguredNonce(){return null==Ve?void 0:Ve.nonce}var Ke,We=__esm({"src/security/csp.ts"(){He=/^[A-Za-z0-9+/=]+$/}}),Qe=__esm({"src/search/utils/request-manager.ts"(){se(),Ke=class{constructor(e={}){var t,i;__publicField(this,"timeout"),__publicField(this,"debug"),__publicField(this,"currentRequest",null),__publicField(this,"requestIdCounter",0),this.timeout=null!=(t=e.timeout)?t:1e4,this.debug=null!=(i=e.debug)&&i}startRequest(e){this.currentRequest&&(this.log("Cancelling previous request",this.currentRequest.requestId),this.currentRequest.controller.abort());const t=++this.requestIdCounter,{controller:i,cleanup:r}=createTimeoutController(this.timeout),n=combineSignals(i.signal,e),s=Date.now();return this.currentRequest={controller:i,requestId:t,startTime:s},this.log("Started request",t),{signal:n,requestId:t,cleanup:()=>{var e;r(),(null==(e=this.currentRequest)?void 0:e.requestId)===t&&(this.log("Cleanup request",t),this.currentRequest=null)}}}isCurrentRequest(e){var t;return(null==(t=this.currentRequest)?void 0:t.requestId)===e}cancel(){this.currentRequest&&(this.log("Cancel called for request",this.currentRequest.requestId),this.currentRequest.controller.abort(),this.currentRequest=null)}getStats(){return this.currentRequest?{hasPendingRequest:!0,requestId:this.currentRequest.requestId,elapsedMs:Date.now()-this.currentRequest.startTime}:{hasPendingRequest:!1,requestId:null,elapsedMs:null}}log(e,t){this.debug}}}});function debounce(e,t){let i=null;return function(...r){i&&clearTimeout(i),i=setTimeout(()=>{e(...r),i=null},t)}}function createDebouncedFn(e,t){let i=null;const debounced=(...r)=>{i&&clearTimeout(i),i=setTimeout(()=>{e(...r),i=null},t)};return debounced.cancel=()=>{i&&(clearTimeout(i),i=null)},debounced.pending=()=>null!==i,debounced}function createDebouncedAsync(e,t){let i=null,r=null,n=null,s=null;const execute=async()=>{if(!r)return;const t=r,o=n,a=s;r=null,n=null,s=null,i=null;try{const i=await e(...t);return null==o||o(i),i}catch(e){const t=e instanceof Error?e:new Error(String(e));throw null==a||a(t),t}},debounced=(...e)=>{i&&clearTimeout(i),r=e,i=setTimeout(()=>{execute()},t)};return debounced.cancel=()=>{i&&(clearTimeout(i),i=null),s&&s(new Error("Debounced call was cancelled")),r=null,n=null,s=null},debounced.pending=()=>null!==i,debounced.flush=async()=>(i&&clearTimeout(i),execute()),debounced}var Ge,Ye=__esm({"src/search/utils/debounce.ts"(){}});function defaultShouldRetry(e,t){return!t||t.status>=500}function sleep(e,t){return new Promise((i,r)=>{if(null==t?void 0:t.aborted)return void r(new DOMException("Aborted","AbortError"));const n=setTimeout(()=>{t&&s&&t.removeEventListener("abort",s),i()},e);let s=null;t&&(s=()=>{clearTimeout(n),r(new DOMException("Aborted","AbortError"))},t.addEventListener("abort",s,{once:!0}))})}async function fetchWithRetry(e,t={},i={}){const{maxAttempts:r=3,baseDelayMs:n=1e3,shouldRetry:s=defaultShouldRetry}=i;let o,a=null;for(let i=0;i<r;i++)try{const a=await fetch(e,t);if(a.ok||!s(null,a))return a;if(o=a,i<r-1){const e=n*Math.pow(2,i);await sleep(e,t.signal);continue}return a}catch(e){if(a=e instanceof Error?e:new Error(String(e)),"AbortError"===a.name)throw a;if(i<r-1){const e=n*Math.pow(2,i);await sleep(e,t.signal);continue}throw a}if(o)return o;throw null!=a?a:new Error("Retry failed")}var Xe=__esm({"src/search/utils/retry.ts"(){Ge={search:{maxAttempts:3,baseDelayMs:1e3},autocomplete:{maxAttempts:2,baseDelayMs:500},config:{maxAttempts:3,baseDelayMs:1e3}}}}),Je=__esm({"src/search/utils/index.ts"(){se(),Qe(),Ye(),Xe(),we()}});function escapeHTML(e){return escapeHtml(e)}function formatPrice(e,t,i="en-US"){try{return new Intl.NumberFormat(i,{style:"currency",currency:t}).format(e)}catch(i){return`${t} ${e.toFixed(2)}`}}function highlightMatchingText(e,t){if(!t||0===t.length)return escapeHTML(e);const i=e.toLowerCase(),r=t.toLowerCase(),n=i.indexOf(r);if(-1===n)return escapeHTML(e);const s=e.substring(0,n),o=e.substring(n,n+t.length),a=e.substring(n+t.length);return`${escapeHTML(s)}<mark class="${Ne}-autocomplete-highlight">${escapeHTML(o)}</mark>${escapeHTML(a)}`}function buildAutocompleteDropdownHTML(e,t){var i,r;const{isOpen:n,isLoading:s,suggestions:o,highlightedIndex:a}=e,c=n?"":`${Ne}-autocomplete-hidden`;let l="";if(s)l=`\n <div class="${Ne}-autocomplete-loading">\n <div class="${Ne}-autocomplete-spinner"></div>\n <span>${escapeHTML(null!=(i=t.autocompleteLoading)?i:"Loading suggestions...")}</span>\n </div>\n `;else if(0===o.length)l=`\n <div class="${Ne}-autocomplete-empty">\n ${escapeHTML(null!=(r=t.autocompleteNoResults)?r:"No suggestions found")}\n </div>\n `;else{const t=o.map((t,i)=>{const r=i===a;return`\n <li\n class="${Ne}-autocomplete-item ${r?`${Ne}-autocomplete-item-highlighted`:""}"\n role="option"\n id="${Ne}-autocomplete-option-${i}"\n aria-selected="${r}"\n data-index="${i}"\n data-suggestion="${escapeHTML(t.text)}"\n >\n ${function(e,t){const i=`\n <svg class="${Ne}-autocomplete-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <circle cx="11" cy="11" r="8"></circle>\n <path d="M21 21l-4.35-4.35"></path>\n </svg>\n `,r=highlightMatchingText(e.text,t);return`\n ${i}\n <span class="${Ne}-autocomplete-text">${r}</span>\n ${void 0!==e.count?`<span class="${Ne}-autocomplete-count">(${e.count})</span>`:""}\n `}(t,e.query)}\n </li>\n `}).join("");l=`\n <ul\n class="${Ne}-autocomplete-list"\n role="listbox"\n id="${Ne}-autocomplete-listbox"\n >\n ${t}\n </ul>\n `}return`\n <div\n class="${Ne}-autocomplete-dropdown ${c}"\n role="presentation"\n >\n ${l}\n </div>\n `}var Ze=__esm({"src/search/widget/rendering.ts"(){fe(),je()}});function setHighlightedIndex(e,t){return{...e,highlightedIndex:t}}function updateAriaExpanded(e,t,i){const r=e.querySelector(`.${Ne}-search-input`);r&&(r.setAttribute("aria-expanded",String(t)),i>=0?r.setAttribute("aria-activedescendant",`${Ne}-autocomplete-option-${i}`):r.removeAttribute("aria-activedescendant"))}var et=__esm({"src/search/widget/autocomplete.ts"(){fe(),Ze(),je()}});function getSearchInput(e){return e.querySelector(`.${Ne}-search-input`)}function setSearchInputValue(e,t){const i=getSearchInput(e);i&&(i.value=t)}var tt,it=__esm({"src/search/widget/events.ts"(){je()}});function detectSystemTheme(){return"undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function getActiveTheme(e){return"auto"===e?detectSystemTheme():e}function applyThemeVariables(e,t){for(const[i,r]of Object.entries(tt)){const n=t[r];void 0!==n&&e.style.setProperty(i,n)}}function generateWidgetCSS(){return`\n /* Overvio Search Widget Styles */\n\n .${Ne}-widget {\n --overvio-color-primary: #3b82f6;\n --overvio-color-primary-hover: #2563eb;\n --overvio-color-background: #ffffff;\n --overvio-color-surface: #f8fafc;\n --overvio-color-text: #1f2937;\n --overvio-color-text-secondary: #6b7280;\n --overvio-color-border: #e5e7eb;\n --overvio-color-error: #ef4444;\n --overvio-color-success: #22c55e;\n --overvio-border-radius: 8px;\n --overvio-font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n --overvio-font-size: 14px;\n --overvio-spacing: 16px;\n --overvio-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);\n --overvio-input-height: 40px;\n --overvio-button-height: 40px;\n --overvio-transition-duration: 150ms;\n --overvio-z-index: 1000;\n\n font-family: var(--overvio-font-family);\n font-size: var(--overvio-font-size);\n color: var(--overvio-color-text);\n box-sizing: border-box;\n }\n\n .${Ne}-widget *,\n .${Ne}-widget *::before,\n .${Ne}-widget *::after {\n box-sizing: inherit;\n }\n\n /* Dark theme */\n .${Ne}-widget[data-theme="dark"] {\n --overvio-color-primary: #60a5fa;\n --overvio-color-primary-hover: #3b82f6;\n --overvio-color-background: #111827;\n --overvio-color-surface: #1f2937;\n --overvio-color-text: #f9fafb;\n --overvio-color-text-secondary: #9ca3af;\n --overvio-color-border: #374151;\n --overvio-color-error: #f87171;\n --overvio-color-success: #4ade80;\n --overvio-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2);\n }\n\n /* Search Container */\n .${Ne}-search-container {\n width: 100%;\n background: var(--overvio-color-background);\n }\n\n /* Search Form */\n .${Ne}-search-form {\n display: flex;\n margin: 0;\n padding: 0;\n }\n\n .${Ne}-search-input-wrapper {\n display: flex;\n width: 100%;\n position: relative;\n }\n\n .${Ne}-search-input {\n flex: 1;\n height: var(--overvio-input-height);\n padding: 0 calc(var(--overvio-spacing) * 0.75);\n padding-right: var(--overvio-button-height);\n border: 1px solid var(--overvio-color-border);\n border-radius: var(--overvio-border-radius);\n background: var(--overvio-color-background);\n color: var(--overvio-color-text);\n font-family: inherit;\n font-size: inherit;\n outline: none;\n transition: border-color var(--overvio-transition-duration), box-shadow var(--overvio-transition-duration);\n }\n\n .${Ne}-search-input::placeholder {\n color: var(--overvio-color-text-secondary);\n }\n\n .${Ne}-search-input:focus {\n border-color: var(--overvio-color-primary);\n box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);\n }\n\n .${Ne}-search-button {\n position: absolute;\n right: 0;\n top: 0;\n height: var(--overvio-button-height);\n width: var(--overvio-button-height);\n padding: 0;\n border: none;\n background: transparent;\n color: var(--overvio-color-text-secondary);\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: color var(--overvio-transition-duration);\n }\n\n .${Ne}-search-button:hover {\n color: var(--overvio-color-primary);\n }\n\n .${Ne}-search-icon {\n width: 20px;\n height: 20px;\n }\n\n /* Content Area */\n .${Ne}-content {\n margin-top: var(--overvio-spacing);\n }\n\n /* Loading State */\n .${Ne}-loading {\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: calc(var(--overvio-spacing) * 2);\n color: var(--overvio-color-text-secondary);\n }\n\n .${Ne}-spinner {\n width: 32px;\n height: 32px;\n animation: ${Ne}-spin 1s linear infinite;\n }\n\n .${Ne}-spinner svg {\n width: 100%;\n height: 100%;\n stroke: var(--overvio-color-primary);\n }\n\n @keyframes ${Ne}-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n\n .${Ne}-loading-text {\n margin: calc(var(--overvio-spacing) * 0.5) 0 0;\n font-size: 0.875em;\n }\n\n /* Results */\n .${Ne}-results-header {\n margin-bottom: var(--overvio-spacing);\n }\n\n .${Ne}-results-count {\n margin: 0;\n color: var(--overvio-color-text-secondary);\n font-size: 0.875em;\n }\n\n /* Grid Layout */\n .${Ne}-results-grid {\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));\n gap: var(--overvio-spacing);\n }\n\n /* List Layout */\n .${Ne}-results-list {\n display: flex;\n flex-direction: column;\n gap: var(--overvio-spacing);\n }\n\n .${Ne}-results-list .${Ne}-product-card {\n display: flex;\n flex-direction: row;\n }\n\n .${Ne}-results-list .${Ne}-product-link {\n display: flex;\n flex-direction: row;\n width: 100%;\n }\n\n .${Ne}-results-list .${Ne}-product-image-wrapper {\n width: 120px;\n flex-shrink: 0;\n }\n\n .${Ne}-results-list .${Ne}-product-info {\n flex: 1;\n padding: var(--overvio-spacing);\n }\n\n /* Product Card */\n .${Ne}-product-card {\n background: var(--overvio-color-surface);\n border: 1px solid var(--overvio-color-border);\n border-radius: var(--overvio-border-radius);\n overflow: hidden;\n transition: box-shadow var(--overvio-transition-duration), transform var(--overvio-transition-duration);\n }\n\n .${Ne}-product-card:hover {\n box-shadow: var(--overvio-shadow);\n transform: translateY(-2px);\n }\n\n .${Ne}-product-card:focus {\n outline: 2px solid var(--overvio-color-primary);\n outline-offset: 2px;\n }\n\n .${Ne}-product-link {\n display: block;\n text-decoration: none;\n color: inherit;\n }\n\n .${Ne}-product-image-wrapper {\n position: relative;\n aspect-ratio: 1;\n background: var(--overvio-color-background);\n overflow: hidden;\n }\n\n .${Ne}-product-image {\n width: 100%;\n height: 100%;\n object-fit: cover;\n transition: transform var(--overvio-transition-duration);\n }\n\n .${Ne}-product-card:hover .${Ne}-product-image {\n transform: scale(1.05);\n }\n\n .${Ne}-out-of-stock-badge {\n position: absolute;\n top: calc(var(--overvio-spacing) * 0.5);\n left: calc(var(--overvio-spacing) * 0.5);\n padding: 2px 8px;\n background: var(--overvio-color-error);\n color: white;\n font-size: 0.75em;\n font-weight: 500;\n border-radius: calc(var(--overvio-border-radius) / 2);\n }\n\n .${Ne}-product-info {\n padding: calc(var(--overvio-spacing) * 0.75);\n }\n\n .${Ne}-product-name {\n margin: 0 0 calc(var(--overvio-spacing) * 0.25);\n font-size: 1em;\n font-weight: 500;\n line-height: 1.4;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n }\n\n .${Ne}-product-brand {\n margin: 0 0 calc(var(--overvio-spacing) * 0.25);\n color: var(--overvio-color-text-secondary);\n font-size: 0.875em;\n }\n\n .${Ne}-product-price-wrapper {\n display: flex;\n align-items: center;\n gap: calc(var(--overvio-spacing) * 0.5);\n margin-bottom: calc(var(--overvio-spacing) * 0.25);\n }\n\n .${Ne}-product-price {\n font-weight: 600;\n color: var(--overvio-color-text);\n }\n\n .${Ne}-product-original-price {\n color: var(--overvio-color-text-secondary);\n text-decoration: line-through;\n font-size: 0.875em;\n }\n\n .${Ne}-product-rating {\n display: flex;\n align-items: center;\n gap: calc(var(--overvio-spacing) * 0.25);\n font-size: 0.875em;\n }\n\n .${Ne}-stars {\n color: #fbbf24;\n }\n\n .${Ne}-star-empty {\n color: var(--overvio-color-border);\n }\n\n .${Ne}-review-count {\n color: var(--overvio-color-text-secondary);\n }\n\n /* Pagination */\n .${Ne}-pagination {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: var(--overvio-spacing);\n margin-top: var(--overvio-spacing);\n padding-top: var(--overvio-spacing);\n border-top: 1px solid var(--overvio-color-border);\n }\n\n .${Ne}-pagination-btn {\n padding: calc(var(--overvio-spacing) * 0.5) var(--overvio-spacing);\n border: 1px solid var(--overvio-color-border);\n border-radius: var(--overvio-border-radius);\n background: var(--overvio-color-background);\n color: var(--overvio-color-text);\n cursor: pointer;\n transition: all var(--overvio-transition-duration);\n }\n\n .${Ne}-pagination-btn:hover:not(:disabled) {\n background: var(--overvio-color-primary);\n border-color: var(--overvio-color-primary);\n color: white;\n }\n\n .${Ne}-pagination-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .${Ne}-pagination-info {\n color: var(--overvio-color-text-secondary);\n font-size: 0.875em;\n }\n\n /* No Results */\n .${Ne}-no-results {\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: calc(var(--overvio-spacing) * 2);\n text-align: center;\n color: var(--overvio-color-text-secondary);\n }\n\n .${Ne}-no-results-icon {\n width: 48px;\n height: 48px;\n margin-bottom: var(--overvio-spacing);\n opacity: 0.5;\n }\n\n .${Ne}-no-results-text {\n margin: 0;\n }\n\n /* Error State */\n .${Ne}-error {\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: calc(var(--overvio-spacing) * 2);\n text-align: center;\n color: var(--overvio-color-error);\n }\n\n .${Ne}-error-icon {\n width: 48px;\n height: 48px;\n margin-bottom: var(--overvio-spacing);\n }\n\n .${Ne}-error-text {\n margin: 0 0 var(--overvio-spacing);\n color: var(--overvio-color-text);\n }\n\n .${Ne}-error-retry {\n padding: calc(var(--overvio-spacing) * 0.5) var(--overvio-spacing);\n border: 1px solid var(--overvio-color-primary);\n border-radius: var(--overvio-border-radius);\n background: transparent;\n color: var(--overvio-color-primary);\n cursor: pointer;\n transition: all var(--overvio-transition-duration);\n }\n\n .${Ne}-error-retry:hover {\n background: var(--overvio-color-primary);\n color: white;\n }\n\n /* Autocomplete Dropdown */\n .${Ne}-autocomplete-dropdown {\n position: absolute;\n top: 100%;\n left: 0;\n right: 0;\n margin-top: 4px;\n background: var(--overvio-color-background);\n border: 1px solid var(--overvio-color-border);\n border-radius: var(--overvio-border-radius);\n box-shadow: var(--overvio-shadow);\n z-index: calc(var(--overvio-z-index) + 1);\n max-height: 300px;\n overflow-y: auto;\n transition: opacity var(--overvio-transition-duration), transform var(--overvio-transition-duration);\n }\n\n .${Ne}-autocomplete-hidden {\n display: none;\n }\n\n .${Ne}-autocomplete-list {\n list-style: none;\n margin: 0;\n padding: 4px 0;\n }\n\n .${Ne}-autocomplete-item {\n display: flex;\n align-items: center;\n gap: calc(var(--overvio-spacing) * 0.5);\n padding: calc(var(--overvio-spacing) * 0.5) calc(var(--overvio-spacing) * 0.75);\n cursor: pointer;\n transition: background-color var(--overvio-transition-duration);\n }\n\n .${Ne}-autocomplete-item:hover,\n .${Ne}-autocomplete-item-highlighted {\n background: var(--overvio-color-surface);\n }\n\n .${Ne}-autocomplete-icon {\n width: 16px;\n height: 16px;\n flex-shrink: 0;\n color: var(--overvio-color-text-secondary);\n }\n\n .${Ne}-autocomplete-text {\n flex: 1;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--overvio-color-text);\n }\n\n .${Ne}-autocomplete-highlight {\n background: transparent;\n font-weight: 600;\n color: var(--overvio-color-primary);\n }\n\n .${Ne}-autocomplete-count {\n font-size: 0.8em;\n color: var(--overvio-color-text-secondary);\n flex-shrink: 0;\n }\n\n .${Ne}-autocomplete-loading,\n .${Ne}-autocomplete-empty {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: calc(var(--overvio-spacing) * 0.5);\n padding: var(--overvio-spacing);\n color: var(--overvio-color-text-secondary);\n font-size: 0.875em;\n }\n\n .${Ne}-autocomplete-spinner {\n width: 16px;\n height: 16px;\n border: 2px solid var(--overvio-color-border);\n border-top-color: var(--overvio-color-primary);\n border-radius: 50%;\n animation: ${Ne}-spin 0.8s linear infinite;\n }\n\n /* Responsive */\n @media (max-width: 640px) {\n .${Ne}-results-grid {\n grid-template-columns: repeat(2, 1fr);\n gap: calc(var(--overvio-spacing) * 0.75);\n }\n\n .${Ne}-product-name {\n font-size: 0.875em;\n }\n\n .${Ne}-product-info {\n padding: calc(var(--overvio-spacing) * 0.5);\n }\n\n .${Ne}-results-list .${Ne}-product-image-wrapper {\n width: 80px;\n }\n\n .${Ne}-pagination {\n flex-wrap: wrap;\n }\n }\n\n @media (max-width: 480px) {\n .${Ne}-results-grid {\n grid-template-columns: 1fr;\n }\n }\n `}var rt,nt=__esm({"src/search/widget/styles.ts"(){je(),tt={"--overvio-color-primary":"colorPrimary","--overvio-color-primary-hover":"colorPrimaryHover","--overvio-color-background":"colorBackground","--overvio-color-surface":"colorSurface","--overvio-color-text":"colorText","--overvio-color-text-secondary":"colorTextSecondary","--overvio-color-border":"colorBorder","--overvio-color-error":"colorError","--overvio-color-success":"colorSuccess","--overvio-border-radius":"borderRadius","--overvio-font-family":"fontFamily","--overvio-font-size":"fontSize","--overvio-spacing":"spacing","--overvio-shadow":"shadow","--overvio-input-height":"inputHeight","--overvio-button-height":"buttonHeight","--overvio-transition-duration":"transitionDuration","--overvio-z-index":"zIndex"}}});function createSearchWidget(e){return new rt(e)}function isSearchWidget(e){return e instanceof rt}var st=__esm({"src/search/widget/widget.ts"(){We(),fe(),Oe(),Je(),et(),it(),Ze(),nt(),je(),rt=class{constructor(e){var t,i,r,n;__publicField(this,"searchClient"),__publicField(this,"configManager"),__publicField(this,"onResultClick"),__publicField(this,"onSearch"),__publicField(this,"onError"),__publicField(this,"debug"),__publicField(this,"container",null),__publicField(this,"widgetRoot",null),__publicField(this,"styleElement",null),__publicField(this,"config",null),__publicField(this,"internalState"),__publicField(this,"autocompleteState"),__publicField(this,"darkModeDetection",null),__publicField(this,"searchRequestManager",null),__publicField(this,"autocompleteRequestManager",null),__publicField(this,"debouncedSearch",null),__publicField(this,"debouncedAutocomplete",null),__publicField(this,"boundHandlers"),__publicField(this,"stats"),this.searchClient=e.searchClient,this.configManager=e.configManager,this.onResultClick=null!=(t=e.onResultClick)?t:null,this.onSearch=null!=(i=e.onSearch)?i:null,this.onError=null!=(r=e.onError)?r:null,this.debug=null!=(n=e.debug)&&n,this.internalState={state:"idle",query:"",results:null,error:null,page:1},this.autocompleteState={isOpen:!1,isLoading:!1,suggestions:[],query:"",highlightedIndex:-1,error:null},this.boundHandlers={handleInput:null,handleSubmit:null,handleKeydown:null,handleDarkModeChange:null,handleInputFocus:null,handleInputBlur:null,handleDocumentClick:null},this.stats={searchesPerformed:0,resultClicks:0,lastQuery:null,lastResultCount:null},this.log("SearchWidget initialized")}async mount(e){var t;if("undefined"==typeof document)return void this.log("SSR detected, skipping mount");if(this.container)throw new Error("SearchWidget is already mounted. Call unmount() first.");const i=this.resolveContainer(e);if(!i)throw new Error("string"==typeof e?`Element not found for selector: ${e}`:"Invalid target element");this.container=i,this.log("Mounting widget",{target:"string"==typeof e?e:"HTMLElement"});const r=await this.configManager.getConfig();this.config=r.config,this.log("Config loaded",{cached:r.cached,usingDefaults:r.usingDefaults,theme:this.config.theme}),this.searchRequestManager=new Ke({timeout:1e4,debug:this.debug}),this.autocompleteRequestManager=new Ke({timeout:1e4,debug:this.debug});const n=null!=(t=this.config.searchDebounceMs)?t:Fe,s=function(e){var t;return null!=(t=e.autocompleteDebounceMs)?t:qe}(this.config);this.debouncedSearch=createDebouncedFn(e=>{this.executeSearch(e)},n),this.debouncedAutocomplete=createDebouncedFn(e=>{this.executeAutocompleteQuery(e)},s),this.applyStyles(),this.render(),this.attachEventListeners(),"auto"===this.config.theme&&this.setupDarkModeDetection(),this.log("Widget mounted successfully")}unmount(){var e,t,i,r,n;this.container?(this.log("Unmounting widget"),null==(e=this.searchRequestManager)||e.cancel(),null==(t=this.autocompleteRequestManager)||t.cancel(),null==(i=this.debouncedSearch)||i.cancel(),null==(r=this.debouncedAutocomplete)||r.cancel(),this.widgetRoot&&function(e,t){const i=e.querySelector(`.${Ne}-search-input`);i&&t.handleInput&&i.removeEventListener("input",t.handleInput),i&&t.handleKeydown&&i.removeEventListener("keydown",t.handleKeydown),i&&t.handleInputFocus&&i.removeEventListener("focus",t.handleInputFocus),i&&t.handleInputBlur&&i.removeEventListener("blur",t.handleInputBlur);const r=e.querySelector(`.${Ne}-search-form`);r&&t.handleSubmit&&r.removeEventListener("submit",t.handleSubmit),t.handleDocumentClick&&document.removeEventListener("click",t.handleDocumentClick),t.handleInput=null,t.handleSubmit=null,t.handleKeydown=null,t.handleInputFocus=null,t.handleInputBlur=null,t.handleDocumentClick=null}(this.widgetRoot,this.boundHandlers),this.darkModeDetection&&((n=this.darkModeDetection).mediaQuery&&n.handler&&n.mediaQuery.removeEventListener("change",n.handler),this.darkModeDetection=null),this.widgetRoot&&this.container.contains(this.widgetRoot)&&this.container.removeChild(this.widgetRoot),this.styleElement&&this.styleElement.parentNode&&this.styleElement.parentNode.removeChild(this.styleElement),this.container=null,this.widgetRoot=null,this.styleElement=null,this.config=null,this.internalState={state:"idle",query:"",results:null,error:null,page:1},this.autocompleteState={isOpen:!1,isLoading:!1,suggestions:[],query:"",highlightedIndex:-1,error:null},this.searchRequestManager=null,this.autocompleteRequestManager=null,this.debouncedSearch=null,this.debouncedAutocomplete=null,this.log("Widget unmounted")):this.log("Widget not mounted, nothing to unmount")}isMounted(){return null!==this.container}getStats(){return{isMounted:null!==this.container,state:this.internalState.state,searchesPerformed:this.stats.searchesPerformed,resultClicks:this.stats.resultClicks,lastQuery:this.stats.lastQuery,lastResultCount:this.stats.lastResultCount}}resetStats(){this.stats={searchesPerformed:0,resultClicks:0,lastQuery:null,lastResultCount:null},this.log("Stats reset")}async search(e){if(!this.isMounted())throw new Error("Widget must be mounted before searching");this.widgetRoot&&setSearchInputValue(this.widgetRoot,e),await this.executeSearch(e)}clear(){var e,t;this.isMounted()&&this.widgetRoot&&(null==(e=this.searchRequestManager)||e.cancel(),null==(t=this.debouncedSearch)||t.cancel(),setSearchInputValue(this.widgetRoot,""),this.internalState={state:"idle",query:"",results:null,error:null,page:1},this.renderContent(),this.log("Search cleared"))}resolveContainer(e){return"string"==typeof e?document.querySelector(e):e instanceof HTMLElement?e:null}render(){if(!this.container)return;const e=this.getResolvedConfig(),t=this.getResolvedFeatures(),i=this.getResolvedStrings();this.widgetRoot=document.createElement("div"),this.widgetRoot.className=`${Ne}-widget`,this.widgetRoot.setAttribute("data-theme",getActiveTheme(e.theme)),this.widgetRoot.setAttribute("data-layout",e.layout),this.widgetRoot.setAttribute("data-mode",e.mode),applyThemeVariables(this.widgetRoot,this.getResolvedVariables()),this.widgetRoot.innerHTML=sanitizeHTML(function(e,t,i){return`\n <div class="${Ne}-search-container">\n <form class="${Ne}-search-form" role="search">\n <div class="${Ne}-search-input-wrapper">\n <input\n type="search"\n class="${Ne}-search-input"\n placeholder="${escapeHTML(e.placeholder)}"\n aria-label="${escapeHTML(e.placeholder)}"\n autocomplete="off"\n autocapitalize="off"\n autocorrect="off"\n spellcheck="false"\n ${t?`aria-autocomplete="list" aria-expanded="false" aria-controls="${Ne}-autocomplete-listbox"`:""}\n />\n <button\n type="submit"\n class="${Ne}-search-button"\n aria-label="${escapeHTML(e.searchButton)}"\n >\n <svg class="${Ne}-search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <circle cx="11" cy="11" r="8"></circle>\n <path d="M21 21l-4.35-4.35"></path>\n </svg>\n </button>\n ${t?buildAutocompleteDropdownHTML(i,e):""}\n </div>\n </form>\n <div class="${Ne}-content" role="region" aria-live="polite">\n </div>\n </div>\n `}(i,t.autocomplete,this.autocompleteState),{allowDataAttributes:!0,allowFormElements:!0}),this.container.appendChild(this.widgetRoot),this.log("Widget rendered")}renderContent(){var e;if(!this.widgetRoot)return;const t=this.widgetRoot.querySelector(`.${Ne}-content`);t&&(t.innerHTML=sanitizeHTML(function(e,t,i,r){switch(e.state){case"loading":return function(e){return`\n <div class="${Ne}-loading">\n <div class="${Ne}-spinner" role="progressbar" aria-label="${escapeHTML(e.ariaLoading)}">\n <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <circle cx="12" cy="12" r="10" stroke-opacity="0.25"></circle>\n <path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round"></path>\n </svg>\n </div>\n <p class="${Ne}-loading-text">${escapeHTML(e.loading)}</p>\n </div>\n `}(t);case"results":return e.results?function(e,t,i,r){var n;const s=null!=(n=t.layout)?n:"grid",o=i.resultsCount.replace("{count}",String(e.total));return`\n <div class="${Ne}-results">\n <div class="${Ne}-results-header">\n <p class="${Ne}-results-count" aria-live="polite">\n ${escapeHTML(o)}\n </p>\n </div>\n <div class="${Ne}-results-${s}" role="list">\n ${e.products.map((e,t)=>function(e,t,i){const r=t+1,n=formatPrice(e.price,e.currency,i),s=e.originalPrice&&e.originalPrice>e.price?formatPrice(e.originalPrice,e.currency,i):null,o=sanitizeHref(e.url),a=sanitizeImageSrc(e.image);return`\n <article\n class="${Ne}-product-card"\n role="listitem"\n data-product-id="${escapeHTML(e.id)}"\n data-position="${r}"\n tabindex="0"\n >\n <a\n href="${o}"\n class="${Ne}-product-link"\n data-product-id="${escapeHTML(e.id)}"\n data-position="${r}"\n >\n <div class="${Ne}-product-image-wrapper">\n <img\n class="${Ne}-product-image"\n src="${a}"\n alt="${escapeHTML(e.name)}"\n loading="lazy"\n />\n ${!1===e.inStock?`<span class="${Ne}-out-of-stock-badge">Out of Stock</span>`:""}\n </div>\n <div class="${Ne}-product-info">\n <h3 class="${Ne}-product-name">${escapeHTML(e.name)}</h3>\n ${e.brand?`<p class="${Ne}-product-brand">${escapeHTML(e.brand)}</p>`:""}\n <div class="${Ne}-product-price-wrapper">\n <span class="${Ne}-product-price">${n}</span>\n ${s?`<span class="${Ne}-product-original-price">${s}</span>`:""}\n </div>\n ${void 0!==e.rating?function(e,t){const i=Math.floor(e),r=e-i>=.5,n=5-i-(r?1:0),s=[...Array(i).fill(`<span class="${Ne}-star ${Ne}-star-full">★</span>`),...r?[`<span class="${Ne}-star ${Ne}-star-half">★</span>`]:[],...Array(n).fill(`<span class="${Ne}-star ${Ne}-star-empty">☆</span>`)].join("");return`\n <div class="${Ne}-product-rating">\n <span class="${Ne}-stars" aria-label="Rating: ${e.toFixed(1)} out of 5">${s}</span>\n ${void 0!==t?`<span class="${Ne}-review-count">(${t})</span>`:""}\n </div>\n `}(e.rating,e.reviewCount):""}\n </div>\n </a>\n </article>\n `}(e,t,r)).join("")}\n </div>\n ${function(e){if(!e.totalPages||e.totalPages<=1)return"";const t=e.page,i=e.totalPages;return`\n <nav class="${Ne}-pagination" aria-label="Pagination">\n <button\n class="${Ne}-pagination-btn ${Ne}-pagination-prev"\n ${t<=1?"disabled":""}\n data-page="${t-1}"\n aria-label="Previous page"\n >\n ←\n </button>\n <span class="${Ne}-pagination-info">\n Page ${t} of ${i}\n </span>\n <button\n class="${Ne}-pagination-btn ${Ne}-pagination-next"\n ${t>=i?"disabled":""}\n data-page="${t+1}"\n aria-label="Next page"\n >\n →\n </button>\n </nav>\n `}(e)}\n </div>\n `}(e.results,i,t,r):"";case"no_results":return function(e,t){const i=t.noResults.replace("{query}",e);return`\n <div class="${Ne}-no-results">\n <svg class="${Ne}-no-results-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <circle cx="11" cy="11" r="8"></circle>\n <path d="M21 21l-4.35-4.35"></path>\n <path d="M8 8l6 6"></path>\n <path d="M14 8l-6 6"></path>\n </svg>\n <p class="${Ne}-no-results-text">${escapeHTML(i)}</p>\n </div>\n `}(e.query,t);case"error":return function(e){return`\n <div class="${Ne}-error">\n <svg class="${Ne}-error-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <circle cx="12" cy="12" r="10"></circle>\n <path d="M12 8v4"></path>\n <path d="M12 16h.01"></path>\n </svg>\n <p class="${Ne}-error-text">${escapeHTML(e.error)}</p>\n <button class="${Ne}-error-retry" type="button">Try again</button>\n </div>\n `}(t);default:return""}}(this.internalState,this.getResolvedStrings(),this.getResolvedConfig(),null==(e=this.config)?void 0:e.locale),{allowDataAttributes:!0}),this.attachContentEventListeners())}applyStyles(){if(document.getElementById(`${Ne}-widget-styles`))return;this.styleElement=document.createElement("style"),this.styleElement.id=`${Ne}-widget-styles`,this.styleElement.textContent=generateWidgetCSS();const e=getConfiguredNonce();e&&applyNonce(this.styleElement,e),document.head.appendChild(this.styleElement),this.log("Styles injected")}setupDarkModeDetection(){this.darkModeDetection=function(e){if("undefined"==typeof window||!window.matchMedia)return{mediaQuery:null,handler:null};const t=window.matchMedia("(prefers-color-scheme: dark)"),handler=t=>{e(t.matches)};return t.addEventListener("change",handler),{mediaQuery:t,handler:handler}}(e=>{this.handleDarkModeChange(e)})}handleDarkModeChange(e){if(!this.widgetRoot)return;const t=e?"dark":"light";this.widgetRoot.setAttribute("data-theme",t),applyThemeVariables(this.widgetRoot,this.getResolvedVariables()),this.log("Theme changed to",t)}attachEventListeners(){if(!this.widgetRoot)return;const e=this.getResolvedFeatures();!function(e,t,i,r){const n=t.autocomplete,s=e.querySelector(`.${Ne}-search-input`);s&&(i.handleInput=e=>{const t=e.target;r.onInputChange(t.value)},s.addEventListener("input",i.handleInput),i.handleKeydown=e=>{n&&r.onAutocompleteKeydown&&r.onAutocompleteKeydown(e)||"Escape"===e.key&&r.onEscape()},s.addEventListener("keydown",i.handleKeydown),n&&(r.onInputFocus&&(i.handleInputFocus=()=>{r.onInputFocus()},s.addEventListener("focus",i.handleInputFocus)),r.onInputBlur&&(i.handleInputBlur=e=>{r.onInputBlur(e)},s.addEventListener("blur",i.handleInputBlur))));const o=e.querySelector(`.${Ne}-search-form`);o&&(i.handleSubmit=t=>{t.preventDefault();const i=e.querySelector(`.${Ne}-search-input`);i&&i.value.trim()&&r.onSubmit(i.value.trim())},o.addEventListener("submit",i.handleSubmit)),n&&r.onDocumentClick&&(i.handleDocumentClick=e=>{r.onDocumentClick(e)},document.addEventListener("click",i.handleDocumentClick))}(this.widgetRoot,e,this.boundHandlers,{onInputChange:e=>this.handleInputChange(e),onSubmit:t=>{e.autocomplete&&this.closeAutocomplete(),this.executeSearch(t)},onEscape:()=>{e.autocomplete&&this.autocompleteState.isOpen?this.closeAutocomplete():(this.clear(),this.widgetRoot&&function(e){const t=getSearchInput(e);t&&(t.value="",t.blur())}(this.widgetRoot))},onAutocompleteKeydown:e.autocomplete?e=>this.handleAutocompleteKeydown(e):void 0,onInputFocus:e.autocomplete?()=>this.handleInputFocus():void 0,onInputBlur:e.autocomplete?e=>this.handleInputBlur(e):void 0,onDocumentClick:e.autocomplete?e=>this.handleDocumentClick(e):void 0}),this.attachContentEventListeners(),e.autocomplete&&this.attachAutocompleteEventListeners()}attachContentEventListeners(){this.widgetRoot&&function(e,t,i,r,n){e.querySelectorAll(`.${Ne}-product-link`).forEach(e=>{e.addEventListener("click",s=>{var o;const a=e.dataset.productId,c=parseInt(null!=(o=e.dataset.position)?o:"0",10);if(a&&t.results){const e=t.results.products.find(e=>e.id===a);e&&(i.trackClick(t.query,e.id,c),n.onResultClick(a,c),r)&&!1===r(e,c)&&s.preventDefault()}})}),e.querySelectorAll(`.${Ne}-pagination-btn`).forEach(e=>{e.addEventListener("click",()=>{var t;const i=parseInt(null!=(t=e.dataset.page)?t:"1",10);n.onPageChange(i)})});const s=e.querySelector(`.${Ne}-error-retry`);s&&s.addEventListener("click",()=>{n.onRetry()})}(this.widgetRoot,this.internalState,this.searchClient,this.onResultClick,{onPageChange:e=>this.handlePageChange(e),onRetry:()=>{this.internalState.query&&this.executeSearch(this.internalState.query)},onResultClick:()=>{this.stats.resultClicks++}})}handleInputChange(e){var t,i;const r=this.getResolvedConfig(),n=this.getResolvedFeatures();null==(t=this.debouncedSearch)||t.cancel();const s=function(e,t,i,r){var n;const s=null!=(n=t.minQueryLength)?n:1,o=e.trim();return o.length<s?{shouldSearch:!1,shouldFetchAutocomplete:!1,shouldReset:"idle"!==r.state,query:o}:{shouldSearch:i.instantSearch,shouldFetchAutocomplete:i.autocomplete,shouldReset:!1,query:o}}(e,r,n,this.internalState);if(n.autocomplete&&(s.shouldFetchAutocomplete?this.fetchAutocompleteSuggestions(s.query):this.closeAutocomplete()),s.shouldReset)return null==(i=this.searchRequestManager)||i.cancel(),this.internalState={state:"idle",query:"",results:null,error:null,page:1},void this.renderContent();s.shouldSearch&&this.debouncedSearch&&this.debouncedSearch(s.query)}handlePageChange(e){this.internalState.page=e,this.executeSearch(this.internalState.query,e)}async executeSearch(e,t=1){if(!this.searchRequestManager)return;const{requestId:i,cleanup:r}=this.searchRequestManager.startRequest();this.internalState={...this.internalState,state:"loading",query:e,page:t},this.renderContent();const n=this.getResolvedConfig().resultsPerPage;try{this.log("Executing search",{query:e,page:t,limit:n});const r=await this.searchClient.query(e,{page:t,limit:n});if(!this.searchRequestManager.isCurrentRequest(i))return;this.stats.searchesPerformed++,this.stats.lastQuery=e,this.stats.lastResultCount=r.total,this.internalState={state:r.products.length>0?"results":"no_results",query:e,results:r,error:null,page:t},this.log("Search completed",{total:r.total,returned:r.products.length}),this.renderContent(),this.onSearch&&this.onSearch(e,r)}catch(r){if(!this.searchRequestManager.isCurrentRequest(i))return;const n=r instanceof Error?r:new Error("Unknown error");this.log("Search failed",{error:n.message}),this.internalState={state:"error",query:e,results:null,error:n,page:t},this.renderContent(),this.onError&&this.onError(n)}finally{r()}}attachAutocompleteEventListeners(){this.widgetRoot&&function(e,t){const i=e.querySelector(`.${Ne}-autocomplete-dropdown`);i&&(i.addEventListener("mousedown",e=>{e.preventDefault()}),i.addEventListener("click",e=>{const i=e.target.closest(`.${Ne}-autocomplete-item`);if(i){const e=i.dataset.suggestion;e&&t(e)}}))}(this.widgetRoot,e=>{this.selectAutocompleteSuggestion(e)})}handleInputFocus(){if(!this.widgetRoot)return;const e=this.widgetRoot.querySelector(`.${Ne}-search-input`);if(e)switch(function(e,t,i){var r;const n=e.trim(),s=null!=(r=t.minQueryLength)?r:Ue;return n.length>=s?i.suggestions.length>0&&i.query===n?"open":"fetch":"none"}(e.value,this.getResolvedConfig(),this.autocompleteState)){case"fetch":this.fetchAutocompleteSuggestions(e.value.trim());break;case"open":this.openAutocomplete()}}handleInputBlur(e){if(!this.widgetRoot)return;const t=function(e,t){const i=e.relatedTarget;return!i||!t.contains(i)}(e,this.widgetRoot);t&&setTimeout(()=>{this.closeAutocomplete()},150)}handleDocumentClick(e){if(!this.widgetRoot)return;const t=function(e,t,i){if(!i)return!1;const r=e.target;return!t.contains(r)}(e,this.widgetRoot,this.autocompleteState.isOpen);t&&this.closeAutocomplete()}handleAutocompleteKeydown(e){if(!this.autocompleteState.isOpen)return!1;const t=function(e,t){const{suggestions:i,highlightedIndex:r}=t;switch(e.key){case"ArrowDown":return e.preventDefault(),i.length>0?{handled:!0,newState:setHighlightedIndex(t,r<i.length-1?r+1:0)}:{handled:!0};case"ArrowUp":return e.preventDefault(),i.length>0?{handled:!0,newState:setHighlightedIndex(t,r>0?r-1:i.length-1)}:{handled:!0};case"Enter":if(r>=0&&r<i.length){e.preventDefault();const t=i[r];if(t)return{handled:!0,selectedSuggestion:t.text,shouldClose:!0}}return{handled:!1,shouldClose:!0};case"Tab":return{handled:!1,shouldClose:!0};default:return{handled:!1}}}(e,this.autocompleteState);return t.newState&&(this.autocompleteState=t.newState,this.renderAutocompleteDropdown(),this.widgetRoot&&updateAriaExpanded(this.widgetRoot,this.autocompleteState.isOpen,this.autocompleteState.highlightedIndex)),t.selectedSuggestion?(this.selectAutocompleteSuggestion(t.selectedSuggestion),!0):(t.shouldClose&&this.closeAutocomplete(),t.handled)}fetchAutocompleteSuggestions(e){var t;!function(e,t){var i;const r=null!=(i=t.minQueryLength)?i:Ue;return e.length>=r}(e,this.getResolvedConfig())?this.closeAutocomplete():(null==(t=this.debouncedAutocomplete)||t.cancel(),0!==this.autocompleteState.suggestions.length&&this.autocompleteState.query===e||(this.autocompleteState=function(e,t){return{...e,isOpen:!0,isLoading:!0,query:t,highlightedIndex:-1}}(this.autocompleteState,e),this.renderAutocompleteDropdown()),this.debouncedAutocomplete&&this.debouncedAutocomplete(e))}async executeAutocompleteQuery(e){if(!this.autocompleteRequestManager)return;const{signal:t,requestId:i,cleanup:r}=this.autocompleteRequestManager.startRequest();try{const r=await async function(e,t,i){var r;const{searchClient:n,config:s,log:o}=t,a=null!=(r=s.maxAutocompleteSuggestions)?r:5;o("Fetching autocomplete suggestions",{query:e,limit:a});const c=await n.autocomplete(e,a);if(i.aborted)throw new Error("Autocomplete request aborted");return o("Autocomplete suggestions received",{count:c.suggestions.length}),function(e,t){return{isOpen:!0,isLoading:!1,suggestions:t,query:e,highlightedIndex:-1,error:null}}(e,c.suggestions)}(e,{searchClient:this.searchClient,config:this.getResolvedConfig(),log:(e,t)=>this.log(e,t)},t);if(!this.autocompleteRequestManager.isCurrentRequest(i))return;this.autocompleteState=r,this.renderAutocompleteDropdown(),this.widgetRoot&&updateAriaExpanded(this.widgetRoot,!0,-1)}catch(e){if(!this.autocompleteRequestManager.isCurrentRequest(i))return;this.log("Autocomplete fetch failed",{error:e instanceof Error?e.message:"Unknown error"}),this.closeAutocomplete()}finally{r()}}openAutocomplete(){var e;this.autocompleteState=(e=this.autocompleteState).isOpen?e:{...e,isOpen:!0,highlightedIndex:-1},this.renderAutocompleteDropdown(),this.widgetRoot&&updateAriaExpanded(this.widgetRoot,!0,-1),this.log("Autocomplete dropdown opened")}closeAutocomplete(){var e,t,i;null==(e=this.autocompleteRequestManager)||e.cancel(),null==(t=this.debouncedAutocomplete)||t.cancel(),this.autocompleteState=(i=this.autocompleteState).isOpen?{...i,isOpen:!1,highlightedIndex:-1}:i,this.renderAutocompleteDropdown(),this.widgetRoot&&updateAriaExpanded(this.widgetRoot,!1,-1),this.log("Autocomplete dropdown closed")}selectAutocompleteSuggestion(e){this.log("Autocomplete suggestion selected",{suggestion:e}),this.widgetRoot&&setSearchInputValue(this.widgetRoot,e),this.closeAutocomplete(),this.executeSearch(e)}renderAutocompleteDropdown(){this.widgetRoot&&function(e,t,i,r){const n=e.querySelector(`.${Ne}-autocomplete-dropdown`);if(!n)return;const s=document.createElement("div");s.innerHTML=sanitizeHTML(buildAutocompleteDropdownHTML(t,i),{allowDataAttributes:!0});const o=s.firstElementChild;o&&(n.replaceWith(o),r())}(this.widgetRoot,this.autocompleteState,this.getResolvedStrings(),()=>this.attachAutocompleteEventListeners())}getResolvedConfig(){var e,t,i,r,n,s,o,a,c,l;if(!this.config)throw new Error("Widget config not initialized. Call mount() first.");const u=this.config;return{...u,clientId:null!=(e=u.clientId)?e:"",theme:null!=(t=u.theme)?t:ke.theme,layout:null!=(i=u.layout)?i:ke.layout,mode:null!=(r=u.mode)?r:ke.mode,resultsPerPage:null!=(n=u.resultsPerPage)?n:ke.resultsPerPage,searchDebounceMs:null!=(s=u.searchDebounceMs)?s:ke.searchDebounceMs,autocompleteDebounceMs:null!=(o=u.autocompleteDebounceMs)?o:ke.autocompleteDebounceMs,minQueryLength:null!=(a=u.minQueryLength)?a:ke.minQueryLength,maxAutocompleteSuggestions:null!=(c=u.maxAutocompleteSuggestions)?c:ke.maxAutocompleteSuggestions,analyticsEnabled:null!=(l=u.analyticsEnabled)?l:ke.analyticsEnabled}}getResolvedFeatures(){var e;return{...xe,...null==(e=this.config)?void 0:e.features}}getResolvedVariables(){var e;return{..."dark"===getActiveTheme(this.getResolvedConfig().theme)?Ae:Te,...null==(e=this.config)?void 0:e.variables}}getResolvedStrings(){var e;return{...Re,...null==(e=this.config)?void 0:e.strings}}log(e,t){this.debug}}}}),ot={};__export(ot,{CSS_PREFIX:()=>Ne,DEFAULT_AUTOCOMPLETE_DEBOUNCE_MS:()=>qe,DEFAULT_DEBOUNCE_MS:()=>Fe,MIN_AUTOCOMPLETE_QUERY_LENGTH:()=>Ue,SearchWidget:()=>rt,WidgetState:()=>ze,createSearchWidget:()=>createSearchWidget,detectSystemTheme:()=>detectSystemTheme,escapeHTML:()=>escapeHTML,formatPrice:()=>formatPrice,generateWidgetCSS:()=>generateWidgetCSS,getActiveTheme:()=>getActiveTheme,highlightMatchingText:()=>highlightMatchingText,isSearchWidget:()=>isSearchWidget});var at,ct,lt,ut,dt=__esm({"src/search/widget/index.ts"(){je(),st(),Ze(),nt()}});function isCacheEntry(e){return"object"==typeof e&&null!==e&&("data"in e&&"number"==typeof e.timestamp)}function isStalenessResult(e){return"object"==typeof e&&null!==e&&("data"in e&&"boolean"==typeof e.isStale)}function isBaseCacheOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.maxSize&&("number"!=typeof t.maxSize||t.maxSize<=0)||void 0!==t.ttl&&("number"!=typeof t.ttl||t.ttl<=0))}function isCacheStats(e){if("object"!=typeof e||null===e)return!1;const t=e;return"number"==typeof t.size&&Number.isInteger(t.size)&&t.size>=0&&"number"==typeof t.hits&&Number.isInteger(t.hits)&&t.hits>=0&&"number"==typeof t.misses&&Number.isInteger(t.misses)&&t.misses>=0&&"number"==typeof t.hitRate&&Number.isFinite(t.hitRate)&&t.hitRate>=0&&t.hitRate<=100}var ht,gt=__esm({"src/search/cache/types.ts"(){at=3e5,ct=50,lt=12e4,ut=100}});function isLRUCacheOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.maxSize&&("number"!=typeof t.maxSize||t.maxSize<=0)||void 0!==t.ttl&&("number"!=typeof t.ttl||t.ttl<=0)||void 0!==t.keySerializer&&"function"!=typeof t.keySerializer)}var pt,mt=__esm({"src/search/cache/lru-cache.ts"(){gt(),ht=class{constructor(e){var t,i,r;__publicField(this,"cache",new Map),__publicField(this,"maxSize"),__publicField(this,"ttl"),__publicField(this,"keySerializer"),__publicField(this,"hits",0),__publicField(this,"misses",0),this.maxSize=null!=(t=null==e?void 0:e.maxSize)?t:ct,this.ttl=null!=(i=null==e?void 0:e.ttl)?i:at,this.keySerializer=null!=(r=null==e?void 0:e.keySerializer)?r:e=>{try{return JSON.stringify(e)}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw new Error(`LRUCache: Failed to serialize key using JSON.stringify (${t}). Provide a custom keySerializer in options for complex key types. Example: { keySerializer: (key) => \`\${key.type}:\${key.id}\` }`)}}}get(e){const t=this.keySerializer(e),i=this.cache.get(t);return i?Date.now()-i.timestamp>this.ttl?(this.cache.delete(t),this.misses++,null):(this.cache.delete(t),this.cache.set(t,i),this.hits++,i.data):(this.misses++,null)}getWithStaleness(e){const t=this.keySerializer(e),i=this.cache.get(t);if(!i)return this.misses++,null;const r=Date.now()-i.timestamp>this.ttl;return this.cache.delete(t),this.cache.set(t,i),this.hits++,{data:i.data,isStale:r}}set(e,t){const i=this.keySerializer(e);for(this.cache.delete(i);this.cache.size>=this.maxSize;){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(i,{data:t,timestamp:Date.now()})}has(e){const t=this.keySerializer(e),i=this.cache.get(t);return!(!i||Date.now()-i.timestamp>this.ttl&&(this.cache.delete(t),1))}delete(e){return this.cache.delete(this.keySerializer(e))}clear(){this.cache.clear()}prune(){const e=Date.now();let t=0;for(const[i,r]of this.cache)e-r.timestamp>this.ttl&&(this.cache.delete(i),t++);return t}get size(){return this.cache.size}getStats(){const e=this.hits+this.misses,t=e>0?this.hits/e*100:0;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:t}}resetStats(){this.hits=0,this.misses=0}}}});function isAutocompleteCacheOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.ttl&&("number"!=typeof t.ttl||t.ttl<=0)||void 0!==t.maxSize&&("number"!=typeof t.maxSize||t.maxSize<=0))}function isCachedAutocompleteResult(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.response&&null!==t.response&&!("number"!=typeof t.latencyMs||!Number.isFinite(t.latencyMs))}var ft,yt=__esm({"src/search/cache/autocomplete-cache.ts"(){mt(),gt(),pt=class{constructor(e){var t,i;__publicField(this,"cache"),this.cache=new ht({ttl:null!=(t=null==e?void 0:e.ttl)?t:lt,maxSize:null!=(i=null==e?void 0:e.maxSize)?i:ut,keySerializer:e=>e})}get(e){return this.cache.get(e)}getWithStaleness(e){return this.cache.getWithStaleness(e)}set(e,t,i){this.cache.set(e,{response:t,latencyMs:i})}has(e){return this.cache.has(e)}clear(){this.cache.clear()}get size(){return this.cache.size}getStats(){return this.cache.getStats()}prune(){return this.cache.prune()}resetStats(){this.cache.resetStats()}}}});function serializeSimilarKey(e){var t,i,r;return[e.productId,e.clientId,String(null!=(t=e.limit)?t:10),String(null!=(i=e.excludeOutOfStock)&&i),null!=(r=e.categoryFilter)?r:""].join("|")}function isSimilarProductsCacheOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.ttl&&("number"!=typeof t.ttl||t.ttl<=0)||void 0!==t.maxSize&&("number"!=typeof t.maxSize||t.maxSize<=0))}function isSimilarCacheKey(e){if("object"!=typeof e||null===e)return!1;const t=e;return!("string"!=typeof t.productId||0===t.productId.length||"string"!=typeof t.clientId||0===t.clientId.length||void 0!==t.limit&&("number"!=typeof t.limit||!Number.isInteger(t.limit)||t.limit<=0)||void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock||void 0!==t.categoryFilter&&"string"!=typeof t.categoryFilter)}function isSimilarCacheMetadata(e){if("object"!=typeof e||null===e)return!1;const t=e;return"boolean"==typeof t.lowConfidence&&"boolean"==typeof t.sameBrandFallback}function isCachedSimilarProducts(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.result&&null!==t.result&&!!isSimilarCacheMetadata(t.metadata)}var vt,bt=__esm({"src/search/cache/similar-cache.ts"(){mt(),gt(),ft=class{constructor(e){var t,i;__publicField(this,"cache"),this.cache=new ht({ttl:null!=(t=null==e?void 0:e.ttl)?t:at,maxSize:null!=(i=null==e?void 0:e.maxSize)?i:ct,keySerializer:serializeSimilarKey})}get(e){return this.cache.get(e)}set(e,t,i){this.cache.set(e,{result:t,metadata:i})}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}getStats(){return this.cache.getStats()}prune(){return this.cache.prune()}resetStats(){this.cache.resetStats()}}}});function serializeFacetKey(e){var t;const i={};return void 0!==e.filters.categories&&e.filters.categories.length>0&&(i.categories=[...e.filters.categories].sort()),void 0!==e.filters.brands&&e.filters.brands.length>0&&(i.brands=[...e.filters.brands].sort()),void 0!==e.filters.priceMin&&(i.priceMin=e.filters.priceMin),void 0!==e.filters.priceMax&&(i.priceMax=e.filters.priceMax),void 0!==e.filters.availability&&"all"!==e.filters.availability&&(i.availability=e.filters.availability),!0===e.filters.onSale&&(i.onSale=!0),!0===e.filters.newArrivals&&(i.newArrivals=!0),!0===e.filters.freeShipping&&(i.freeShipping=!0),JSON.stringify({q:null!=(t=e.query)?t:"",f:i})}function isFacetCacheOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.ttl&&("number"!=typeof t.ttl||t.ttl<=0)||void 0!==t.maxSize&&("number"!=typeof t.maxSize||t.maxSize<=0))}function isFacetCacheKey(e){if("object"!=typeof e||null===e)return!1;const t=e;return(void 0===t.query||"string"==typeof t.query)&&"object"==typeof t.filters&&null!==t.filters}function isCachedFacetData(e){if("object"!=typeof e||null===e)return!1;const t=e;if("object"!=typeof t.facets||null===t.facets)return!1;if("object"!=typeof t.priceRange||null===t.priceRange)return!1;const i=t.priceRange;return"number"==typeof i.min&&"number"==typeof i.max&&!("number"!=typeof t.resultCount||!Number.isInteger(t.resultCount))}var St,wt=__esm({"src/search/cache/facet-cache.ts"(){mt(),gt(),vt=class{constructor(e,t){let i,r;__publicField(this,"cache"),"number"==typeof e?(i=e,r=t):(i=null==e?void 0:e.ttl,r=null==e?void 0:e.maxSize),this.cache=new ht({ttl:null!=i?i:at,maxSize:null!=r?r:ct,keySerializer:serializeFacetKey})}get(e){return this.cache.get(e)}set(e,t){this.cache.set(e,t)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}getStats(){return this.cache.getStats()}prune(){return this.cache.prune()}resetStats(){this.cache.resetStats()}}}});function isSearchCacheOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!("object"!=typeof t.storage||null===t.storage||void 0!==t.prefix&&"string"!=typeof t.prefix||void 0!==t.maxAge&&("number"!=typeof t.maxAge||t.maxAge<=0)||void 0!==t.maxEntries&&("number"!=typeof t.maxEntries||t.maxEntries<=0))}function isSearchCacheEntry(e){if("object"!=typeof e||null===e)return!1;const t=e;return"object"==typeof t.result&&null!==t.result&&"number"==typeof t.timestamp}var Ct,Et,_t,It,kt,xt=__esm({"src/search/cache/search-cache.ts"(){gt(),St=class{constructor(e){var t,i,r;__publicField(this,"storage"),__publicField(this,"prefix"),__publicField(this,"maxAge"),__publicField(this,"maxEntries"),__publicField(this,"indexKey"),this.storage=e.storage,this.prefix=null!=(t=e.prefix)?t:"overvio_search_",this.maxAge=null!=(i=e.maxAge)?i:at,this.maxEntries=null!=(r=e.maxEntries)?r:ct,this.indexKey=`${this.prefix}index`}get(e,t){const i=this.generateKey(e,t);try{const e=this.storage.get(i);return e?Date.now()-e.timestamp>this.maxAge?(this.removeEntry(i),null):e.result:null}catch(e){return null}}set(e,t,i){const r=this.generateKey(e,i),n={result:t,timestamp:Date.now()};try{return this.storage.set(r,n)?(this.addToIndex(r),this.cleanup(),!0):(this.evictOldest(),!!this.storage.set(r,n)&&(this.addToIndex(r),!0))}catch(e){this.evictOldest();try{if(this.storage.set(r,n))return this.addToIndex(r),!0}catch(e){}return!1}}has(e,t){return null!==this.get(e,t)}invalidate(e,t){const i=this.generateKey(e,t);this.removeEntry(i)}clear(){const e=this.getIndex();for(const t of e)this.storage.remove(t.key);this.storage.remove(this.indexKey)}getStats(){const e=this.getIndex(),t=Date.now(),i=[...e].sort((e,t)=>e.timestamp-t.timestamp),r=i[0],n=i[i.length-1];return{entries:i.length,oldestAge:r?t-r.timestamp:null,newestAge:n?t-n.timestamp:null}}generateKey(e,t){const i=e.toLowerCase().trim().replace(/\s+/g," ");if(!t||0===Object.keys(t).length)return`${this.prefix}${i}`;const r={},n=Object.keys(t).sort();for(const e of n)r[e]=t[e];const s=JSON.stringify(r),o=this.safeBase64Encode(s);return`${this.prefix}${i}_${o}`}safeBase64Encode(e){return"undefined"!=typeof btoa?btoa(unescape(encodeURIComponent(e))):Buffer.from(e,"utf-8").toString("base64")}getIndex(){try{const e=this.storage.get(this.indexKey);return null!=e?e:[]}catch(e){return[]}}saveIndex(e){try{this.storage.set(this.indexKey,e)}catch(e){}}addToIndex(e){const t=this.getIndex().filter(t=>t.key!==e);t.push({key:e,timestamp:Date.now()}),this.saveIndex(t)}removeEntry(e){this.storage.remove(e);const t=this.getIndex().filter(t=>t.key!==e);this.saveIndex(t)}cleanup(){const e=this.getIndex(),t=Date.now(),i=[];for(const r of e)t-r.timestamp>this.maxAge&&i.push(r.key);for(const e of i)this.storage.remove(e);let r=e.filter(e=>!i.includes(e.key));if(r.sort((e,t)=>e.timestamp-t.timestamp),r.length>this.maxEntries){const e=r.slice(0,r.length-this.maxEntries);for(const t of e)this.storage.remove(t.key);r=r.slice(r.length-this.maxEntries)}this.saveIndex(r)}evictOldest(){const e=this.getIndex();if(0===e.length)return;e.sort((e,t)=>e.timestamp-t.timestamp);const t=e[0];if(t){this.storage.remove(t.key);const i=e.slice(1);this.saveIndex(i)}}}}}),Tt=__esm({"src/search/cache/index.ts"(){gt(),mt(),yt(),bt(),wt(),xt()}});function createRateLimiter(e={}){var t,i,r;const n=null!=(t=e.maxTokens)?t:Ct,s=null!=(i=e.refillRate)?i:Et,o=null!=(r=e.name)?r:"search",a=e.onRateLimited,c=e.onSecurityWarning;let l=n,u=Date.now(),d=0,h=0,g=!1;function refillTokens(){const e=Date.now(),t=(e-u)/1e3*s;t>0&&(l=Math.min(n,l+t),u=e)}function getRetryAfterMs(){if(l>=1)return 0;const e=(1-l)/s;return Math.ceil(1e3*e)}function createRateLimitInfo(){return{name:o,currentTokens:Math.floor(l),maxTokens:n,retryAfterMs:getRetryAfterMs(),timestamp:Date.now()}}function notifyRateLimited(e){null==a||a(e),c&&c({type:"rate_limited",message:`Client-side rate limit exceeded for ${o}. Retry after ${e.retryAfterMs}ms.`,severity:"info",timestamp:e.timestamp,context:{action:"blocked",rateLimit:{limit:n,windowMs:Math.ceil(n/s*1e3),current:h+d}}})}return{tryAcquire:()=>!g&&(refillTokens(),l>=1?(l-=1,d++,!0):(h++,notifyRateLimited(createRateLimitInfo()),!1)),acquire(){if(g)throw new Error("Rate limiter has been destroyed");if(refillTokens(),l>=1)return l-=1,void d++;h++;const e=createRateLimitInfo();throw notifyRateLimited(e),new kt(e)},getState:()=>(refillTokens(),{tokens:Math.floor(100*l)/100,maxTokens:n,refillRate:s,lastRefillTime:u,totalAllowed:d,totalDenied:h}),reset(){l=n,u=Date.now(),d=0,h=0},destroy(){g=!0}}}function createSearchRateLimiter(e={}){var t;return createRateLimiter({...e,..._t,name:null!=(t=e.name)?t:"search"})}function createAutocompleteRateLimiter(e={}){var t;return createRateLimiter({...e,...It,name:null!=(t=e.name)?t:"autocomplete"})}var At,Rt=__esm({"src/search/rate-limiter.ts"(){Ct=10,Et=2,_t={maxTokens:15,refillRate:3},It={maxTokens:20,refillRate:5},kt=class _RateLimitExceededError extends Error{constructor(e){super(`Rate limit exceeded for "${e.name}". Retry after ${e.retryAfterMs}ms. Tokens: ${e.currentTokens}/${e.maxTokens}`),__publicField(this,"name","RateLimitExceededError"),__publicField(this,"retryAfterMs"),__publicField(this,"rateLimitInfo"),this.retryAfterMs=e.retryAfterMs,this.rateLimitInfo=e}static isRateLimitExceededError(e){return e instanceof _RateLimitExceededError}}}});function isSearchError(e){return e instanceof At}function isSearchErrorType(e){return"network"===e||"timeout"===e||"rate-limit"===e||"validation"===e||"server"===e||"abort"===e||"unknown"===e}function createSearchError(t,i){if(t instanceof At)return t;const r={};if(i&&(r.operation=i),t instanceof e.RateLimitError)return new At(t.message,{type:"rate-limit",statusCode:429,retryable:!1,retryAfter:t.retryAfter,context:{...r,...t.context},cause:t});if(t instanceof e.TimeoutError)return new At(t.message,{type:"timeout",retryable:!0,context:{...r,...t.context},cause:t});if(t instanceof e.ValidationError)return new At(t.message,{type:"validation",retryable:!1,context:{...r,field:t.field,value:t.value,constraint:t.constraint},cause:t});if(t instanceof e.NetworkError){const e=t.statusCode;let i="network";return void 0!==e&&(429===e?i="rate-limit":e>=500&&(i="server")),new At(t.message,{type:i,statusCode:e,retryable:t.retryable,retryAfter:t.retryAfter,context:{...r,url:t.url,method:t.method},cause:t})}if(t instanceof Error&&("AbortError"===t.name||t.message.includes("aborted")))return new At("Request was cancelled",{type:"abort",retryable:!1,context:r,cause:t});if(t instanceof e.OvervioError){let e="unknown",i=!1;switch(t.code){case"NETWORK_ERROR":e="network",i=!0;break;case"TIMEOUT":e="timeout",i=!0;break;case"RATE_LIMIT_ERROR":e="rate-limit",i=!1;break;case"VALIDATION_ERROR":e="validation",i=!1;break;default:e="unknown",i=!1}return new At(t.message,{type:e,retryable:i,context:{...r,...t.context},cause:t})}return"undefined"!=typeof DOMException&&t instanceof DOMException&&"AbortError"===t.name?new At("Request was cancelled",{type:"abort",retryable:!1,context:r,cause:t}):t instanceof Error?new At(t.message,{type:"unknown",retryable:!1,context:r,cause:t}):"string"==typeof t?new At(t,{type:"unknown",retryable:!1,context:r}):new At("An unknown error occurred",{type:"unknown",retryable:!1,context:{...r,originalValue:String(t)}})}function createNetworkSearchError(e,t){var i;return new At(e,{type:"network",statusCode:null==t?void 0:t.statusCode,retryable:null==(i=null==t?void 0:t.retryable)||i,context:null==t?void 0:t.context,cause:null==t?void 0:t.cause})}function createTimeoutSearchError(e,t,i){const r={};return void 0!==t&&(r.timeoutMs=t),new At(e,{type:"timeout",retryable:!0,context:r,cause:i})}function createRateLimitSearchError(e,t){return new At(null!=t?t:e?`Rate limit exceeded. Try again in ${e} seconds.`:"Rate limit exceeded. Please try again later.",{type:"rate-limit",statusCode:429,retryable:!1,retryAfter:e})}function createValidationSearchError(e,t,i){const r={};return void 0!==t&&(r.field=t),void 0!==i&&(r.value=i),new At(e,{type:"validation",retryable:!1,context:r})}var Pt,Dt=__esm({"src/search/errors.ts"(){x(),P(),D(),L(),M(),At=class extends Error{constructor(e,t){var i,r;super(e),__publicField(this,"name","SearchError"),__publicField(this,"type"),__publicField(this,"statusCode"),__publicField(this,"retryable"),__publicField(this,"retryAfter"),__publicField(this,"context"),__publicField(this,"cause"),__publicField(this,"timestamp"),this.type=t.type,this.statusCode=t.statusCode,this.retryable=null!=(i=t.retryable)?i:this.defaultRetryable(t.type),this.retryAfter=t.retryAfter,this.context=null!=(r=t.context)?r:{},this.cause=t.cause,this.timestamp=new Date,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,new.target)}defaultRetryable(e){switch(e){case"network":case"timeout":case"server":return!0;default:return!1}}toJSON(){const e={name:this.name,message:this.message,type:this.type,retryable:this.retryable,context:this.context,timestamp:this.timestamp.toISOString()};if(void 0!==this.statusCode&&(e.statusCode=this.statusCode),void 0!==this.retryAfter&&(e.retryAfter=this.retryAfter),this.stack&&(e.stack=this.stack),this.cause){const t={name:this.cause.name,message:this.cause.message};void 0!==this.cause.stack&&(t.stack=this.cause.stack),e.cause=t}return e}toString(){return`${this.name} [${this.type}]: ${this.message}`}}}});function createSearchEventEmitter(e){return new Pt(e)}function isSearchEventEmitter(e){return e instanceof Pt}function isSearchEventName(e){return"string"==typeof e&&["search:performed","search:click","search:autocomplete","search:filter","search:sort","search:error","search:zero-results","search:page","search:view"].includes(e)}function isSearchPerformedPayload(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.query&&"number"==typeof t.totalResults&&"number"==typeof t.latencyMs&&"boolean"==typeof t.cached}function isSearchClickPayload(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.query&&"string"==typeof t.productId&&"number"==typeof t.position&&("autocomplete"===t.section||"results"===t.section||"similar"===t.section)}function isSearchAutocompletePayload(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.query||"number"!=typeof t.latencyMs||"boolean"!=typeof t.cached)return!1;const i=t.resultCounts;if("object"!=typeof i||null===i)return!1;const r=i;return"number"==typeof r.queries&&"number"==typeof r.products&&"number"==typeof r.categories&&"number"==typeof r.brands}function isSearchErrorPayload(e){if("object"!=typeof e||null===e)return!1;const t=e;return t.error instanceof Error&&("query"===t.context||"autocomplete"===t.context||"similar"===t.context||"config"===t.context)}function isSearchZeroResultsPayload(e){return"object"==typeof e&&null!==e&&"string"==typeof e.query}var Lt,Mt,Ot,$t,Nt,Ft=__esm({"src/search/events.ts"(){R(),Pt=class extends T{constructor(e={}){const{debug:t,...i}=e;super(i),__publicField(this,"debug"),this.debug=null!=t&&t}emit(e,...t){this.debug&&(String(e),t[0]),super.emit(e,...t)}on(e,t){return this.debug&&String(e),super.on(e,t)}getRegisteredEvents(){return this.eventNames()}hasListeners(e){return this.listenerCount(e)>0}}}});function createRecentSearchesManager(e){return function(){if("undefined"==typeof window)return!1;try{const e="__overvio_test__";return window.localStorage.setItem(e,e),window.localStorage.removeItem(e),!0}catch(e){return!1}}()?new $t(e):new Nt(e)}function isRecentSearchesManager(e){if("object"!=typeof e||null===e)return!1;const t=e;return"function"==typeof t.getAll&&"function"==typeof t.add&&"function"==typeof t.remove&&"function"==typeof t.clear&&"function"==typeof t.has&&"function"==typeof t.count}function isRecentSearchesOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.maxItems&&"number"!=typeof t.maxItems||void 0!==t.storageKey&&"string"!=typeof t.storageKey||void 0!==t.minQueryLength&&"number"!=typeof t.minQueryLength)}var qt=__esm({"src/search/recent-searches.ts"(){Lt=10,Mt="overvio_recent_searches",Ot=2,$t=class{constructor(e={}){var t,i,r;__publicField(this,"maxItems"),__publicField(this,"storageKey"),__publicField(this,"minQueryLength"),this.maxItems=null!=(t=e.maxItems)?t:Lt,this.storageKey=null!=(i=e.storageKey)?i:Mt,this.minQueryLength=null!=(r=e.minQueryLength)?r:Ot}getAll(){try{const e=window.localStorage.getItem(this.storageKey);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}catch(e){return[]}}add(e){const t=this.normalizeQuery(e);if(t&&!(t.length<this.minQueryLength))try{const e=this.getAll().filter(e=>e.toLowerCase()!==t.toLowerCase());e.unshift(t);const i=e.slice(0,this.maxItems);window.localStorage.setItem(this.storageKey,JSON.stringify(i))}catch(e){}}remove(e){const t=this.normalizeQuery(e);if(t)try{const e=this.getAll().filter(e=>e.toLowerCase()!==t.toLowerCase());0===e.length?window.localStorage.removeItem(this.storageKey):window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){}}clear(){try{window.localStorage.removeItem(this.storageKey)}catch(e){}}has(e){const t=this.normalizeQuery(e);return!!t&&this.getAll().some(e=>e.toLowerCase()===t.toLowerCase())}count(){return this.getAll().length}normalizeQuery(e){if("string"!=typeof e)return null;const t=e.trim();return 0===t.length?null:t}},Nt=class{constructor(e={}){var t,i;__publicField(this,"searches",[]),__publicField(this,"maxItems"),__publicField(this,"minQueryLength"),this.maxItems=null!=(t=e.maxItems)?t:Lt,this.minQueryLength=null!=(i=e.minQueryLength)?i:Ot}getAll(){return[...this.searches]}add(e){const t=this.normalizeQuery(e);!t||t.length<this.minQueryLength||(this.searches=this.searches.filter(e=>e.toLowerCase()!==t.toLowerCase()),this.searches.unshift(t),this.searches=this.searches.slice(0,this.maxItems))}remove(e){const t=this.normalizeQuery(e);t&&(this.searches=this.searches.filter(e=>e.toLowerCase()!==t.toLowerCase()))}clear(){this.searches=[]}has(e){const t=this.normalizeQuery(e);return!!t&&this.searches.some(e=>e.toLowerCase()===t.toLowerCase())}count(){return this.searches.length}normalizeQuery(e){if("string"!=typeof e)return null;const t=e.trim();return 0===t.length?null:t}}}}),Ut={};async function mountWidget(e,t){const{httpClient:i,storage:r,apiKey:n,debug:s=!1,onResultClick:o,onError:a}=t,c=createSearchClient({httpClient:i,apiKey:n,debug:s}),l=createWidgetConfigManager({httpClient:i,storage:r,apiKey:n,debug:s}),u=createSearchWidget(Object.assign({searchClient:c,configManager:l,debug:s},o?{onResultClick:o}:{},a?{onError:a}:{}));return await u.mount(e),u}__export(Ut,{AUTOCOMPLETE_CACHE_MAX_SIZE:()=>ut,AUTOCOMPLETE_CACHE_TTL_MS:()=>lt,AUTOCOMPLETE_RATE_LIMIT_CONFIG:()=>It,AutocompleteCache:()=>pt,DEFAULT_AUTOCOMPLETE_LIMIT:()=>e.DEFAULT_AUTOCOMPLETE_LIMIT,DEFAULT_CACHE_MAX_SIZE:()=>ct,DEFAULT_CACHE_TTL_MS:()=>at,DEFAULT_DARK_THEME_VARIABLES:()=>Ae,DEFAULT_LIGHT_THEME_VARIABLES:()=>Te,DEFAULT_MAX_TOKENS:()=>Ct,DEFAULT_REFILL_RATE:()=>Et,DEFAULT_SEARCH_LIMIT:()=>e.DEFAULT_SEARCH_LIMIT,DEFAULT_SIMILAR_PRODUCTS_LIMIT:()=>J,DEFAULT_WIDGET_CONFIG:()=>ke,DEFAULT_WIDGET_FEATURES:()=>xe,DEFAULT_WIDGET_STRINGS:()=>Re,FacetCache:()=>vt,LRUCache:()=>ht,MAX_AUTOCOMPLETE_LIMIT:()=>Y,MAX_SEARCH_LIMIT:()=>G,MAX_SIMILAR_PRODUCTS_LIMIT:()=>Z,MIN_AUTOCOMPLETE_QUERY_LENGTH:()=>X,RECENT_SEARCHES_DEFAULT_MAX_ITEMS:()=>Lt,RECENT_SEARCHES_DEFAULT_MIN_QUERY_LENGTH:()=>Ot,RECENT_SEARCHES_DEFAULT_STORAGE_KEY:()=>Mt,RETRY_CONFIG:()=>Ge,RateLimitExceededError:()=>kt,RequestManager:()=>Ke,SEARCH_RATE_LIMIT_CONFIG:()=>_t,SearchClient:()=>Se,SearchError:()=>At,SearchEventEmitter:()=>Pt,SearchResultsCache:()=>St,SearchWidget:()=>rt,SimilarProductsCache:()=>ft,WIDGET_CONFIG_CACHE_TTL_MS:()=>Pe,WIDGET_CONFIG_STORAGE_KEY:()=>De,WidgetConfigManager:()=>Me,activeFiltersToSearchFilters:()=>activeFiltersToSearchFilters,combineSignals:()=>combineSignals,countActiveFilters:()=>countActiveFilters,createAutocompleteRateLimiter:()=>createAutocompleteRateLimiter,createDebouncedAsync:()=>createDebouncedAsync,createDebouncedFn:()=>createDebouncedFn,createEmptyActiveFilters:()=>createEmptyActiveFilters,createNetworkSearchError:()=>createNetworkSearchError,createRateLimitSearchError:()=>createRateLimitSearchError,createRateLimiter:()=>createRateLimiter,createRecentSearchesManager:()=>createRecentSearchesManager,createSearchClient:()=>createSearchClient,createSearchError:()=>createSearchError,createSearchEventEmitter:()=>createSearchEventEmitter,createSearchRateLimiter:()=>createSearchRateLimiter,createSearchWidget:()=>createSearchWidget,createTimeoutController:()=>createTimeoutController,createTimeoutSearchError:()=>createTimeoutSearchError,createValidationSearchError:()=>createValidationSearchError,createWidgetConfigManager:()=>createWidgetConfigManager,debounce:()=>debounce,fetchWithRetry:()=>fetchWithRetry,getAbortReason:()=>getAbortReason,hasActiveFilters:()=>hasActiveFilters,isAbortError:()=>isAbortError,isActiveFilters:()=>isActiveFilters,isAutocompleteCacheOptions:()=>isAutocompleteCacheOptions,isAutocompleteResult:()=>isAutocompleteResult,isAutocompleteSuggestion:()=>isAutocompleteSuggestion,isAvailabilityFilter:()=>isAvailabilityFilter,isBaseCacheOptions:()=>isBaseCacheOptions,isBrandSuggestionData:()=>isBrandSuggestionData,isCacheEntry:()=>isCacheEntry,isCacheStats:()=>isCacheStats,isCacheStatus:()=>isCacheStatus,isCachedAutocompleteResult:()=>isCachedAutocompleteResult,isCachedFacetData:()=>isCachedFacetData,isCachedSimilarProducts:()=>isCachedSimilarProducts,isCategorySuggestionData:()=>isCategorySuggestionData,isDangerousUrl:()=>isDangerousUrl,isFacetCacheKey:()=>isFacetCacheKey,isFacetCacheOptions:()=>isFacetCacheOptions,isFacetCount:()=>isFacetCount,isFacets:()=>isFacets,isFeaturedCategory:()=>isFeaturedCategory,isFederatedAutocompleteMetadata:()=>isFederatedAutocompleteMetadata,isFederatedAutocompleteResponse:()=>isFederatedAutocompleteResponse,isFederatedResult:()=>isFederatedResult,isFederatedSelectItem:()=>isFederatedSelectItem,isFilterRange:()=>isFilterRange,isGetConfigResult:()=>isGetConfigResult,isGetQuerySuggestionsOptions:()=>isGetQuerySuggestionsOptions,isHighlightField:()=>isHighlightField,isHighlightPosition:()=>isHighlightPosition,isHighlightSnippet:()=>isHighlightSnippet,isInitialStateResponse:()=>isInitialStateResponse,isLRUCacheOptions:()=>isLRUCacheOptions,isPopularSearch:()=>isPopularSearch,isPriceRange:()=>isPriceRange,isProduct:()=>isProduct,isProductBadge:()=>isProductBadge,isProductBadgeType:()=>isProductBadgeType,isProductSuggestionData:()=>isProductSuggestionData,isQueryExpansion:()=>isQueryExpansion,isQueryRelaxationMeta:()=>isQueryRelaxationMeta,isQuerySuggestion:()=>isQuerySuggestion,isQuerySuggestionsResponse:()=>isQuerySuggestionsResponse,isRawSearchMeta:()=>isRawSearchMeta,isRecentSearchesManager:()=>isRecentSearchesManager,isRecentSearchesOptions:()=>isRecentSearchesOptions,isRelaxationType:()=>isRelaxationType,isSearchAutocompletePayload:()=>isSearchAutocompletePayload,isSearchBackend:()=>isSearchBackend,isSearchCacheEntry:()=>isSearchCacheEntry,isSearchCacheOptions:()=>isSearchCacheOptions,isSearchClickPayload:()=>isSearchClickPayload,isSearchClient:()=>isSearchClient,isSearchError:()=>isSearchError,isSearchErrorPayload:()=>isSearchErrorPayload,isSearchErrorType:()=>isSearchErrorType,isSearchEventEmitter:()=>isSearchEventEmitter,isSearchEventName:()=>isSearchEventName,isSearchLanguage:()=>isSearchLanguage,isSearchMeta:()=>isSearchMeta,isSearchOptions:()=>isSearchOptions,isSearchPerformedPayload:()=>isSearchPerformedPayload,isSearchResult:()=>isSearchResult,isSearchWidget:()=>isSearchWidget,isSearchZeroResultsPayload:()=>isSearchZeroResultsPayload,isSemanticContribution:()=>isSemanticContribution,isSimilarCacheKey:()=>isSimilarCacheKey,isSimilarCacheMetadata:()=>isSimilarCacheMetadata,isSimilarProductsCacheOptions:()=>isSimilarProductsCacheOptions,isSimilarProductsMetadata:()=>isSimilarProductsMetadata,isSimilarProductsOptions:()=>isSimilarProductsOptions,isSimilarProductsResult:()=>isSimilarProductsResult,isSortOption:()=>isSortOption,isSortPreset:()=>isSortPreset,isSpellCorrection:()=>isSpellCorrection,isStalenessResult:()=>isStalenessResult,isWidgetConfig:()=>isWidgetConfig,isWidgetConfigManager:()=>isWidgetConfigManager,isWidgetFeatures:()=>isWidgetFeatures,isWidgetLayout:()=>isWidgetLayout,isWidgetMode:()=>isWidgetMode,isWidgetStrings:()=>isWidgetStrings,isWidgetTheme:()=>isWidgetTheme,isWidgetVariables:()=>isWidgetVariables,mountWidget:()=>mountWidget,sanitizeHighlight:()=>sanitizeHighlight,sanitizeImageUrl:()=>sanitizeImageUrl,sanitizeProductUrl:()=>sanitizeProductUrl,sanitizeProductUrls:()=>sanitizeProductUrls,searchFiltersToActiveFilters:()=>searchFiltersToActiveFilters,stripHighlightTags:()=>stripHighlightTags});var zt,Ht,Vt,Bt,jt,Kt,Wt,Qt,Gt,Yt,Xt,Jt,Zt,ei,ti,ii,ri,ni,si,oi=__esm({"src/search/index.ts"(){Ee(),te(),_e(),Ie(),Le(),te(),Oe(),Oe(),Be(),dt(),Je(),Tt(),Rt(),Dt(),Ft(),qt(),Ee(),Be(),dt()}});function isSimilarProductsOptions2(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.limit&&("number"!=typeof t.limit||t.limit<1)||void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock||void 0!==t.categoryFilter&&"string"!=typeof t.categoryFilter||void 0!==t.useCache&&"boolean"!=typeof t.useCache)}function isRawProduct(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&0!==t.id.length&&"string"==typeof t.name&&0!==t.name.length&&!("number"!=typeof t.price||!Number.isFinite(t.price))&&"string"==typeof t.currency&&0!==t.currency.length&&"string"==typeof t.image&&"string"==typeof t.url}function isRawSimilarProductsResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.products))return!1;for(const e of t.products)if(!isRawProduct(e))return!1;return"string"==typeof t.source_product_id}function isSimilarProductsCacheEntry(e){if("object"!=typeof e||null===e)return!1;const t=e;return 1===t.version&&!!Array.isArray(t.products)&&"string"==typeof t.sourceProductId&&"number"==typeof t.cachedAt&&"number"==typeof t.expiresAt}function isPersonalizedOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;if(void 0!==t.limit&&("number"!=typeof t.limit||t.limit<1))return!1;if(void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock)return!1;if(void 0!==t.contextProductId&&"string"!=typeof t.contextProductId)return!1;if(void 0!==t.fallbackToTrending&&"boolean"!=typeof t.fallbackToTrending)return!1;if(void 0!==t.useCache&&"boolean"!=typeof t.useCache)return!1;if(void 0!==t.userSegments){if(!Array.isArray(t.userSegments))return!1;for(const e of t.userSegments)if("string"!=typeof e)return!1}if(void 0!==t.segmentBoosts){if(!Array.isArray(t.segmentBoosts))return!1;for(const e of t.segmentBoosts)if(!isSegmentBoost(e))return!1}return!0}function isSegmentBoost(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.segmentId||0===t.segmentId.length)return!1;if("number"!=typeof t.boostFactor||!Number.isFinite(t.boostFactor))return!1;const i=t.boostFactor;return!(i<ti||i>ii)}function isPersonalizationContext(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.recentViews))return!1;for(const e of t.recentViews)if(!isRecentViewEntry(e))return!1;if(!Array.isArray(t.cartItems))return!1;for(const e of t.cartItems)if(!isCartContextItem(e))return!1;if(!Array.isArray(t.searchTerms))return!1;for(const e of t.searchTerms)if("string"!=typeof e)return!1;return!0}function isRecentViewEntry(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.productId&&0!==t.productId.length&&"number"==typeof t.viewedAt}function isCartContextItem(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.productId&&0!==t.productId.length&&!("number"!=typeof t.quantity||t.quantity<0)}function isRawPersonalizedResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.products))return!1;for(const e of t.products)if(!isRawProduct(e))return!1;return"boolean"==typeof t.is_fallback&&("personalized"===t.source||"trending"===t.source)}function isPersonalizedCacheEntry(e){if("object"!=typeof e||null===e)return!1;const t=e;return 1===t.version&&!!Array.isArray(t.products)&&"boolean"==typeof t.isFallback&&("personalized"===t.source||"trending"===t.source)&&"number"==typeof t.cachedAt&&"number"==typeof t.expiresAt&&"object"==typeof t.keyComponents&&null!==t.keyComponents}function isTrendingTimeWindow(e){return"string"==typeof e&&si.includes(e)}function isTrendingOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.limit&&("number"!=typeof t.limit||t.limit<1)||void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock||void 0!==t.categoryFilter&&"string"!=typeof t.categoryFilter||void 0!==t.timeWindow&&!isTrendingTimeWindow(t.timeWindow)||void 0!==t.useCache&&"boolean"!=typeof t.useCache)}function isRawTrendingResponse(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!Array.isArray(t.products))return!1;for(const e of t.products)if(!isRawProduct(e))return!1;return!0}function isRecentlyViewedOptions(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(void 0!==t.limit&&("number"!=typeof t.limit||t.limit<1)||void 0!==t.excludeCurrentProduct&&"string"!=typeof t.excludeCurrentProduct)}var ai,ci,li,ui=__esm({"src/recommendations/types.ts"(){zt=10,Ht=50,Vt=3e5,Bt="overvio_recommendations",jt=1e4,Kt=10,Wt=50,Qt=8e3,Gt=50,Yt=50,Xt=10,Jt="overvio_recent_views",Zt="overvio_recent_searches",ei=12e4,ti=.1,ii=10,ri=10,ni=50,si=["24h","7d","30d"]}});function createPersonalizedCacheStrategy(e={}){return new li(e)}function isPersonalizedCacheStrategy(e){return e instanceof li}var di,hi,gi,pi,mi=__esm({"src/recommendations/cache-strategy.ts"(){ui(),ai=`${Bt}_personalized`,ci=2,li=class{constructor(e={}){var t,i;__publicField(this,"storage"),__publicField(this,"cacheTTL"),__publicField(this,"onIdentityChangeFn"),__publicField(this,"debug"),__publicField(this,"onDebug"),__publicField(this,"lastIdentity"),__publicField(this,"stats"),this.storage=e.storage,this.cacheTTL=null!=(t=e.cacheTTL)?t:ei,this.onIdentityChangeFn=e.onIdentityChange,this.debug=null!=(i=e.debug)&&i,this.onDebug=e.onDebug,this.lastIdentity=void 0,this.stats={keysGenerated:0,identityInvalidations:0,segmentInvalidations:0},this.log("PersonalizedCacheStrategy initialized",{hasStorage:!!this.storage,cacheTTL:this.cacheTTL})}generateCacheKey(e){var t,i;const{userId:r,anonymousId:n,options:s}=e,o=null!=(t=null!=r?r:n)?t:"unknown";this.lastIdentity=o;const a=[ai,`v${ci}`,o,`limit_${null!=(i=null==s?void 0:s.limit)?i:Kt}`];if((null==s?void 0:s.excludeOutOfStock)&&a.push("oos"),(null==s?void 0:s.contextProductId)&&a.push(`ctx_${s.contextProductId}`),(null==s?void 0:s.userSegments)&&s.userSegments.length>0){const e=[...s.userSegments].sort().join(",");a.push(`seg_${e}`)}this.stats.keysGenerated++;const c=a.join("_");return this.log("Generated cache key",{key:c,identity:o,options:s}),c}getCacheTTL(){return this.cacheTTL}async handleIdentityChange(e,t){this.log("Identity change detected",{oldIdentity:e,newIdentity:t}),this.lastIdentity=t,e&&this.storage&&(await this.invalidateCacheForIdentity(e),this.stats.identityInvalidations++),this.onIdentityChangeFn&&this.onIdentityChangeFn(e,t)}async invalidateCacheForIdentity(e){if(this.storage)try{const t=await this.storage.keys(),i=`${ai}_v${ci}_${e}`;for(const e of t)e.startsWith(i)&&(await this.storage.remove(e),this.log("Invalidated cache entry",{key:e}));this.log("Cache invalidated for identity",{identity:e})}catch(t){this.log("Failed to invalidate cache",{identity:e,error:t instanceof Error?t.message:String(t)})}}async handleSegmentChange(e,t,i){[...t].sort().join(",")!==[...i].sort().join(",")&&(this.log("Segment change detected",{identity:e,oldSegments:t,newSegments:i}),await this.invalidateCacheForIdentity(e),this.stats.segmentInvalidations++)}async clearAllCache(){if(this.storage)try{const e=await this.storage.keys(),t=ai;for(const i of e)i.startsWith(t)&&await this.storage.remove(i);this.log("All personalized cache cleared")}catch(e){this.log("Failed to clear all cache",{error:e instanceof Error?e.message:String(e)})}}getLastIdentity(){return this.lastIdentity}getStats(){return{keysGenerated:this.stats.keysGenerated,identityInvalidations:this.stats.identityInvalidations,segmentInvalidations:this.stats.segmentInvalidations,lastIdentity:this.lastIdentity,hasStorage:!!this.storage}}resetStats(){this.stats={keysGenerated:0,identityInvalidations:0,segmentInvalidations:0}}log(e,t){this.debug&&this.onDebug&&this.onDebug(`[PersonalizedCacheStrategy] ${e}`,t)}}}});function createRecommendationsClient(e){return new pi(e)}function isRecommendationsClient(e){return e instanceof pi}var fi,yi=__esm({"src/recommendations/client.ts"(){P(),M(),A(),mi(),ui(),di="/similar",hi="/personalized",gi="/trending",pi=class{constructor(t){var i,r,n,s;if(__publicField(this,"httpClient"),__publicField(this,"storage"),__publicField(this,"endpoint"),__publicField(this,"timeout"),__publicField(this,"cacheTTL"),__publicField(this,"debug"),__publicField(this,"onDebug"),__publicField(this,"getUserId"),__publicField(this,"getAnonymousId"),__publicField(this,"contextCollector"),__publicField(this,"getUserSegments"),__publicField(this,"onIdentityChange"),__publicField(this,"personalizedCacheStrategy"),__publicField(this,"lastKnownIdentity"),__publicField(this,"inFlightSimilarRequests"),__publicField(this,"inFlightPersonalizedRequests"),__publicField(this,"inFlightTrendingRequests"),__publicField(this,"stats"),!t.httpClient)throw e.ValidationError.requiredField("httpClient");this.httpClient=t.httpClient,this.storage=t.storage,this.endpoint=null!=(i=t.endpoint)?i:"/api/recommendations",this.timeout=null!=(r=t.timeout)?r:jt,this.cacheTTL=null!=(n=t.cacheTTL)?n:Vt,this.debug=null!=(s=t.debug)&&s,this.onDebug=t.onDebug,this.getUserId=t.getUserId,this.getAnonymousId=t.getAnonymousId,this.contextCollector=t.contextCollector,this.getUserSegments=t.getUserSegments,this.onIdentityChange=t.onIdentityChange,this.lastKnownIdentity=void 0,this.personalizedCacheStrategy=createPersonalizedCacheStrategy({storage:this.storage,cacheTTL:ei,onIdentityChange:this.onIdentityChange,debug:this.debug,onDebug:this.onDebug}),this.inFlightSimilarRequests=new Map,this.inFlightPersonalizedRequests=new Map,this.inFlightTrendingRequests=new Map,this.stats=this.createEmptyStats(),this.log("RecommendationsClient initialized",{endpoint:this.endpoint,timeout:this.timeout,cacheTTL:this.cacheTTL,hasStorage:!!this.storage,hasUserIdProvider:!!this.getUserId,hasAnonymousIdProvider:!!this.getAnonymousId,hasContextCollector:!!this.contextCollector,hasSegmentProvider:!!this.getUserSegments})}async similar(t,i){var r;const n=Date.now();this.stats.similarRequests++,this.stats.lastRequestAt=n;try{this.validateProductId(t),this.validateSimilarOptions(i);const e=null!=(r=null==i?void 0:i.limit)?r:zt,s=!1!==(null==i?void 0:i.useCache);if(this.log("Fetching similar products",{productId:t,limit:e,excludeOutOfStock:null==i?void 0:i.excludeOutOfStock,categoryFilter:null==i?void 0:i.categoryFilter,useCache:s}),s&&this.storage){const e=await this.getCachedSimilarProducts(t,i);if(e)return this.stats.similarCacheHits++,this.stats.successfulSimilarRequests++,this.stats.totalProductsReturned+=e.products.length,this.log("Returning cached similar products",{productId:t,count:e.products.length,expiresAt:e.expiresAt}),e;this.stats.similarCacheMisses++}const o=this.buildCacheKey(t,i),a=this.inFlightSimilarRequests.get(o);if(a)return this.log("Reusing in-flight request",{productId:t}),a;const c=this.fetchSimilarProducts(t,i);this.inFlightSimilarRequests.set(o,c);try{const e=await c,r=Date.now()-n;return this.stats.successfulSimilarRequests++,this.stats.totalProductsReturned+=e.products.length,this.stats.totalResponseTime+=r,this.storage&&s&&await this.cacheSimilarProducts(t,e.products,i),this.log("Similar products fetched",{productId:t,count:e.products.length,responseTime:r}),e}finally{this.inFlightSimilarRequests.delete(o)}}catch(i){if(this.stats.failedSimilarRequests++,i instanceof e.ValidationError)throw i;if(i instanceof e.NetworkError)throw this.log("Similar products request failed with network error",{productId:t,error:i.message}),i;const r=i instanceof Error?i.message:"Unknown error";throw this.log("Similar products request failed",{productId:t,error:r}),e.NetworkError.connectionError(`Similar products request failed: ${r}`,`${this.endpoint}${di}/${t}`,"GET",i instanceof Error?i:void 0)}}getEndpoint(){return this.endpoint}getStats(){const e=this.stats.successfulSimilarRequests>0?this.stats.totalResponseTime/this.stats.successfulSimilarRequests:0;return{similarRequests:this.stats.similarRequests,successfulSimilarRequests:this.stats.successfulSimilarRequests,failedSimilarRequests:this.stats.failedSimilarRequests,similarCacheHits:this.stats.similarCacheHits,similarCacheMisses:this.stats.similarCacheMisses,totalProductsReturned:this.stats.totalProductsReturned,averageResponseTime:Math.round(e),lastRequestAt:this.stats.lastRequestAt}}resetStats(){this.stats=this.createEmptyStats(),this.log("Stats reset")}async clearCache(e){if(this.storage)if(e){const t=await this.storage.keys(),i=`${Bt}_similar_${e}`;for(const e of t)e.startsWith(i)&&await this.storage.remove(e);this.log("Cache cleared for product",{productId:e})}else{const e=await this.storage.keys(),t=`${Bt}_similar_`;for(const i of e)i.startsWith(t)&&await this.storage.remove(i);this.log("All similar products cache cleared")}}async handleIdentityChange(e,t){this.log("External identity change notification",{oldIdentity:e,newIdentity:t}),this.lastKnownIdentity=t,await this.personalizedCacheStrategy.handleIdentityChange(e,t)}async clearPersonalizedCache(){await this.personalizedCacheStrategy.clearAllCache(),this.log("All personalized cache cleared")}getCacheStrategy(){return this.personalizedCacheStrategy}async personalized(t){var i,r,n;const s=Date.now();this.stats.personalizedRequests++,this.stats.lastRequestAt=s;try{this.validatePersonalizedOptions(t);const e=null!=(i=null==t?void 0:t.limit)?i:Kt,o=!1!==(null==t?void 0:t.useCache),a=!1!==(null==t?void 0:t.fallbackToTrending),c=null==(r=this.getUserId)?void 0:r.call(this),l=null==(n=this.getAnonymousId)?void 0:n.call(this),u=null!=c?c:l;let d;if(void 0!==this.lastKnownIdentity&&u!==this.lastKnownIdentity&&(this.log("Identity change detected - invalidating cache",{oldIdentity:this.lastKnownIdentity,newIdentity:u}),await this.personalizedCacheStrategy.handleIdentityChange(this.lastKnownIdentity,u)),this.lastKnownIdentity=u,this.log("Fetching personalized recommendations",{limit:e,excludeOutOfStock:null==t?void 0:t.excludeOutOfStock,contextProductId:null==t?void 0:t.contextProductId,hasUserId:!!c,hasAnonymousId:!!l,fallbackToTrending:a}),d=(null==t?void 0:t.context)?t.context:this.contextCollector?await this.contextCollector.collectContext():{recentViews:[],cartItems:[],searchTerms:[]},!(d.recentViews.length>0||d.cartItems.length>0||d.searchTerms.length>0)&&a){this.log("No user history - falling back to trending"),this.stats.personalizedFallbacks++;const i={limit:e,useCache:o};void 0!==(null==t?void 0:t.excludeOutOfStock)&&(i.excludeOutOfStock=t.excludeOutOfStock),void 0!==(null==t?void 0:t.timeout)&&(i.timeout=t.timeout),(null==t?void 0:t.signal)&&(i.signal=t.signal);const r=await this.trending(i),n={products:r.products,cached:r.cached,isFallback:!0,source:"trending"};return void 0!==r.expiresAt&&(n.expiresAt=r.expiresAt),n}const h=this.buildPersonalizedCacheKey(c,l,t);if(o&&this.storage){const e=await this.getCachedPersonalized(h,c,l,t);if(e)return this.stats.personalizedCacheHits++,this.stats.successfulPersonalizedRequests++,this.stats.totalProductsReturned+=e.products.length,this.log("Returning cached personalized recommendations",{count:e.products.length,expiresAt:e.expiresAt}),e;this.stats.personalizedCacheMisses++}const g=this.inFlightPersonalizedRequests.get(h);if(g)return this.log("Reusing in-flight personalized request"),g;const p=this.fetchPersonalized(c,l,d,t);this.inFlightPersonalizedRequests.set(h,p);try{const e=await p,i=Date.now()-s;return this.stats.successfulPersonalizedRequests++,this.stats.totalProductsReturned+=e.products.length,this.stats.totalResponseTime+=i,e.isFallback&&this.stats.personalizedFallbacks++,this.storage&&o&&await this.cachePersonalized(h,e,c,l,t),this.log("Personalized recommendations fetched",{count:e.products.length,responseTime:i,isFallback:e.isFallback,source:e.source}),e}finally{this.inFlightPersonalizedRequests.delete(h)}}catch(t){if(this.stats.failedPersonalizedRequests++,t instanceof e.ValidationError)throw t;if(t instanceof e.NetworkError)throw this.log("Personalized request failed with network error",{error:t.message}),t;const i=t instanceof Error?t.message:"Unknown error";throw this.log("Personalized request failed",{error:i}),e.NetworkError.connectionError(`Personalized recommendations request failed: ${i}`,`${this.endpoint}${hi}`,"POST",t instanceof Error?t:void 0)}}async trending(t){var i;const r=Date.now();this.stats.trendingRequests++,this.stats.lastRequestAt=r;try{this.validateTrendingOptions(t);const e=null!=(i=null==t?void 0:t.limit)?i:zt,n=!1!==(null==t?void 0:t.useCache);this.log("Fetching trending products",{limit:e,excludeOutOfStock:null==t?void 0:t.excludeOutOfStock,categoryFilter:null==t?void 0:t.categoryFilter});const s=this.buildTrendingCacheKey(t);if(n&&this.storage){const e=await this.getCachedTrending(s,t);if(e)return this.stats.successfulTrendingRequests++,this.stats.totalProductsReturned+=e.products.length,this.log("Returning cached trending products",{count:e.products.length,expiresAt:e.expiresAt}),e}const o=this.inFlightTrendingRequests.get(s);if(o)return this.log("Reusing in-flight trending request"),o;const a=this.fetchTrending(t);this.inFlightTrendingRequests.set(s,a);try{const e=await a,i=Date.now()-r;return this.stats.successfulTrendingRequests++,this.stats.totalProductsReturned+=e.products.length,this.stats.totalResponseTime+=i,this.storage&&n&&await this.cacheTrending(s,e,t),this.log("Trending products fetched",{count:e.products.length,responseTime:i}),e}finally{this.inFlightTrendingRequests.delete(s)}}catch(t){if(this.stats.failedTrendingRequests++,t instanceof e.ValidationError)throw t;if(t instanceof e.NetworkError)throw this.log("Trending request failed with network error",{error:t.message}),t;const i=t instanceof Error?t.message:"Unknown error";throw this.log("Trending request failed",{error:i}),e.NetworkError.connectionError(`Trending products request failed: ${i}`,`${this.endpoint}${gi}`,"GET",t instanceof Error?t:void 0)}}async recentlyViewed(e){var t;const i=Math.min(Math.max(1,null!=(t=null==e?void 0:e.limit)?t:ri),ni);this.log("Getting recently viewed products",{limit:i,excludeCurrentProduct:null==e?void 0:e.excludeCurrentProduct});try{let t=[];if(this.contextCollector)t=(await this.contextCollector.collectContext()).recentViews;else if(this.storage){const e=await this.storage.get("overvio_recent_views");e&&Array.isArray(e.views)&&(t=e.views)}if(null==e?void 0:e.excludeCurrentProduct){const i=e.excludeCurrentProduct;t=t.filter(e=>e.productId!==i)}const r=t.length,n=t.slice(0,i),s=n.map(e=>{const t={id:createProductId(e.productId),name:e.productId,price:0,currency:"USD",image:"",url:""};return e.category&&(t.category=e.category),e.brand&&(t.brand=e.brand),t});return this.log("Retrieved recently viewed products",{totalStoredCount:r,returnedCount:s.length}),{products:s,viewEntries:n,totalStoredCount:r}}catch(e){return this.log("Failed to get recently viewed products",{error:e instanceof Error?e.message:String(e)}),{products:[],viewEntries:[],totalStoredCount:0}}}async fetchSimilarProducts(t,i){var r,n;const s=null!=(r=null==i?void 0:i.limit)?r:zt,o=new URLSearchParams({limit:String(s)});(null==i?void 0:i.excludeOutOfStock)&&o.set("exclude_out_of_stock","true"),(null==i?void 0:i.categoryFilter)&&o.set("category",i.categoryFilter);const a=`${this.endpoint}${di}/${encodeURIComponent(t)}?${o.toString()}`,c={timeout:null!=(n=null==i?void 0:i.timeout)?n:this.timeout};(null==i?void 0:i.signal)&&(c.signal=i.signal);const l=await this.httpClient.get(a,c);if(!isRawSimilarProductsResponse(l))throw new e.NetworkError("Invalid response format from recommendations API",{statusCode:200,url:a,method:"GET"});return{products:this.transformProducts(l.products),sourceProductId:createProductId(l.source_product_id),cached:!1}}async fetchPersonalized(t,i,r,n){var s,o,a,c,l;const u={limit:null!=(s=null==n?void 0:n.limit)?s:Kt};t&&(u.user_id=t),i&&(u.anonymous_id=i),(null==n?void 0:n.excludeOutOfStock)&&(u.exclude_out_of_stock=!0),(null==n?void 0:n.contextProductId)&&(u.context_product_id=n.contextProductId);const d=null!=(c=null!=(a=null==n?void 0:n.userSegments)?a:null==(o=this.getUserSegments)?void 0:o.call(this))?c:[];d.length>0&&(u.user_segments=d),(null==n?void 0:n.segmentBoosts)&&n.segmentBoosts.length>0&&(u.segment_boosts=n.segmentBoosts.map(e=>({segment_id:e.segmentId,boost_factor:e.boostFactor}))),(r.recentViews.length>0||r.cartItems.length>0||r.searchTerms.length>0)&&(u.context={},r.recentViews.length>0&&(u.context.recent_views=r.recentViews.map(e=>{const t={product_id:e.productId,viewed_at:e.viewedAt};return e.category&&(t.category=e.category),e.brand&&(t.brand=e.brand),void 0!==e.duration&&(t.duration=e.duration),t})),r.cartItems.length>0&&(u.context.cart_items=r.cartItems.map(e=>{const t={product_id:e.productId,quantity:e.quantity};return e.category&&(t.category=e.category),e.brand&&(t.brand=e.brand),t})),r.searchTerms.length>0&&(u.context.search_terms=r.searchTerms),r.preferredCategories&&r.preferredCategories.length>0&&(u.context.preferred_categories=r.preferredCategories),r.preferredBrands&&r.preferredBrands.length>0&&(u.context.preferred_brands=r.preferredBrands));const h=`${this.endpoint}${hi}`,g={timeout:null!=(l=null==n?void 0:n.timeout)?l:Qt};(null==n?void 0:n.signal)&&(g.signal=n.signal);const p=await this.httpClient.post(h,u,g);if(!isRawPersonalizedResponse(p))throw new e.NetworkError("Invalid response format from personalized recommendations API",{statusCode:200,url:h,method:"POST"});const m={products:this.transformProducts(p.products),cached:!1,isFallback:p.is_fallback,source:p.source};return p.request_id&&(m.requestId=p.request_id),m}async fetchTrending(t){var i,r,n;const s=null!=(i=null==t?void 0:t.limit)?i:zt,o=null!=(r=null==t?void 0:t.timeWindow)?r:"7d",a=new URLSearchParams({limit:String(s),time_window:o});(null==t?void 0:t.excludeOutOfStock)&&a.set("exclude_out_of_stock","true"),(null==t?void 0:t.categoryFilter)&&a.set("category",t.categoryFilter);const c=`${this.endpoint}${gi}?${a.toString()}`,l={timeout:null!=(n=null==t?void 0:t.timeout)?n:this.timeout};(null==t?void 0:t.signal)&&(l.signal=t.signal);const u=await this.httpClient.get(c,l);if(!isRawTrendingResponse(u))throw new e.NetworkError("Invalid response format from trending products API",{statusCode:200,url:c,method:"GET"});const d=u.time_window&&isTrendingTimeWindow(u.time_window)?u.time_window:o,h={products:this.transformProducts(u.products),cached:!1};return h.timeWindow=d,h}buildCacheKey(e,t){var i;const r=[Bt,"similar",e,`limit_${null!=(i=null==t?void 0:t.limit)?i:zt}`];return(null==t?void 0:t.excludeOutOfStock)&&r.push("oos"),(null==t?void 0:t.categoryFilter)&&r.push(`cat_${t.categoryFilter}`),r.join("_")}async getCachedSimilarProducts(e,t){var i,r;if(!this.storage)return null;try{const n=this.buildCacheKey(e,t),s=await this.storage.get(n);if(!s||!isSimilarProductsCacheEntry(s))return null;if(Date.now()>s.expiresAt)return this.log("Cache expired",{productId:e,expiresAt:s.expiresAt}),await this.storage.remove(n),null;const o=null!=(i=null==t?void 0:t.limit)?i:zt;return s.options.limit!==o||s.options.excludeOutOfStock!==(null!=(r=null==t?void 0:t.excludeOutOfStock)&&r)||s.options.categoryFilter!==(null==t?void 0:t.categoryFilter)?null:{products:s.products,sourceProductId:createProductId(s.sourceProductId),cached:!0,expiresAt:s.expiresAt}}catch(t){return this.log("Cache read error",{productId:e,error:t instanceof Error?t.message:String(t)}),null}}async cacheSimilarProducts(e,t,i){var r,n;if(this.storage)try{const s=this.buildCacheKey(e,i),o=Date.now(),a={limit:null!=(r=null==i?void 0:i.limit)?r:zt,excludeOutOfStock:null!=(n=null==i?void 0:i.excludeOutOfStock)&&n};(null==i?void 0:i.categoryFilter)&&(a.categoryFilter=i.categoryFilter);const c={version:1,products:t,sourceProductId:e,cachedAt:o,expiresAt:o+this.cacheTTL,options:a};await this.storage.set(s,c),this.log("Cached similar products",{productId:e,count:t.length,expiresAt:c.expiresAt})}catch(t){this.log("Cache write error",{productId:e,error:t instanceof Error?t.message:String(t)})}}buildPersonalizedCacheKey(e,t,i){var r,n,s;const o=null!=(s=null!=(n=null==i?void 0:i.userSegments)?n:null==(r=this.getUserSegments)?void 0:r.call(this))?s:[],a={...i,userSegments:o};return this.personalizedCacheStrategy.generateCacheKey({userId:e,anonymousId:t,options:a})}buildTrendingCacheKey(e){var t,i;const r=[Bt,"trending",`limit_${null!=(t=null==e?void 0:e.limit)?t:zt}`,`tw_${null!=(i=null==e?void 0:e.timeWindow)?i:"7d"}`];return(null==e?void 0:e.excludeOutOfStock)&&r.push("oos"),(null==e?void 0:e.categoryFilter)&&r.push(`cat_${e.categoryFilter}`),r.join("_")}async getCachedPersonalized(e,t,i,r){var n,s;if(!this.storage)return null;try{const o=await this.storage.get(e);if(!o||!isPersonalizedCacheEntry(o))return null;if(Date.now()>o.expiresAt)return this.log("Personalized cache expired",{expiresAt:o.expiresAt}),await this.storage.remove(e),null;if(o.keyComponents.userId!==t)return null;if(o.keyComponents.anonymousId!==i)return null;const a=null!=(n=null==r?void 0:r.limit)?n:Kt;return o.keyComponents.limit!==a||o.keyComponents.excludeOutOfStock!==(null!=(s=null==r?void 0:r.excludeOutOfStock)&&s)||o.keyComponents.contextProductId!==(null==r?void 0:r.contextProductId)?null:{products:o.products,cached:!0,expiresAt:o.expiresAt,isFallback:o.isFallback,source:o.source}}catch(e){return this.log("Personalized cache read error",{error:e instanceof Error?e.message:String(e)}),null}}async getCachedTrending(e,t){var i,r;if(!this.storage)return null;try{const n=await this.storage.get(e);if(!n||!Array.isArray(n.products)||"number"!=typeof n.expiresAt)return null;if(Date.now()>n.expiresAt)return this.log("Trending cache expired",{expiresAt:n.expiresAt}),await this.storage.remove(e),null;const s={products:n.products,cached:!0,expiresAt:n.expiresAt},o=null!=(r=null!=(i=n.timeWindow)?i:null==t?void 0:t.timeWindow)?r:"7d";return s.timeWindow=o,s}catch(e){return this.log("Trending cache read error",{error:e instanceof Error?e.message:String(e)}),null}}async cachePersonalized(e,t,i,r,n){var s,o,a,c,l;if(this.storage)try{const u=Date.now(),d={limit:null!=(s=null==n?void 0:n.limit)?s:Kt,excludeOutOfStock:null!=(o=null==n?void 0:n.excludeOutOfStock)&&o};i&&(d.userId=i),r&&(d.anonymousId=r),(null==n?void 0:n.contextProductId)&&(d.contextProductId=n.contextProductId);const h=null!=(l=null!=(c=null==n?void 0:n.userSegments)?c:null==(a=this.getUserSegments)?void 0:a.call(this))?l:[];h.length>0&&(d.userSegments=h);const g={version:1,products:t.products,isFallback:t.isFallback,source:t.source,cachedAt:u,expiresAt:u+this.cacheTTL,keyComponents:d};await this.storage.set(e,g),this.log("Cached personalized recommendations",{count:t.products.length,expiresAt:g.expiresAt})}catch(e){this.log("Personalized cache write error",{error:e instanceof Error?e.message:String(e)})}}async cacheTrending(e,t,i){if(this.storage)try{const r=Date.now(),n={products:t.products,cachedAt:r,expiresAt:r+this.cacheTTL};t.timeWindow?n.timeWindow=t.timeWindow:(null==i?void 0:i.timeWindow)&&(n.timeWindow=i.timeWindow),await this.storage.set(e,n),this.log("Cached trending products",{count:t.products.length,expiresAt:n.expiresAt,timeWindow:n.timeWindow})}catch(e){this.log("Trending cache write error",{error:e instanceof Error?e.message:String(e)})}}validateProductId(t){if(!t||"string"!=typeof t)throw e.ValidationError.typeMismatch("productId","string (ProductId)",typeof t,t);if(0===t.length)throw e.ValidationError.requiredField("productId")}validateSimilarOptions(t){if(t){if(void 0!==t.limit){if(!Number.isInteger(t.limit)||t.limit<1)throw new e.ValidationError("limit must be a positive integer",{field:"limit",value:t.limit,constraint:"Must be a positive integer"});if(t.limit>Ht)throw e.ValidationError.outOfRange("limit",1,Ht,t.limit)}if(void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock)throw e.ValidationError.typeMismatch("excludeOutOfStock","boolean",typeof t.excludeOutOfStock,t.excludeOutOfStock);if(void 0!==t.categoryFilter&&"string"!=typeof t.categoryFilter)throw e.ValidationError.typeMismatch("categoryFilter","string",typeof t.categoryFilter,t.categoryFilter)}}validatePersonalizedOptions(t){if(t){if(void 0!==t.limit){if(!Number.isInteger(t.limit)||t.limit<1)throw new e.ValidationError("limit must be a positive integer",{field:"limit",value:t.limit,constraint:"Must be a positive integer"});if(t.limit>Wt)throw e.ValidationError.outOfRange("limit",1,Wt,t.limit)}if(void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock)throw e.ValidationError.typeMismatch("excludeOutOfStock","boolean",typeof t.excludeOutOfStock,t.excludeOutOfStock);if(void 0!==t.contextProductId&&"string"!=typeof t.contextProductId)throw e.ValidationError.typeMismatch("contextProductId","string",typeof t.contextProductId,t.contextProductId);if(void 0!==t.fallbackToTrending&&"boolean"!=typeof t.fallbackToTrending)throw e.ValidationError.typeMismatch("fallbackToTrending","boolean",typeof t.fallbackToTrending,t.fallbackToTrending);if(void 0!==t.userSegments){if(!Array.isArray(t.userSegments))throw e.ValidationError.typeMismatch("userSegments","array",typeof t.userSegments,t.userSegments);for(let i=0;i<t.userSegments.length;i++)if("string"!=typeof t.userSegments[i])throw e.ValidationError.typeMismatch(`userSegments[${i}]`,"string",typeof t.userSegments[i],t.userSegments[i])}if(void 0!==t.segmentBoosts){if(!Array.isArray(t.segmentBoosts))throw e.ValidationError.typeMismatch("segmentBoosts","array",typeof t.segmentBoosts,t.segmentBoosts);for(let i=0;i<t.segmentBoosts.length;i++){const r=t.segmentBoosts[i];if(!isSegmentBoost(r)){if("object"!=typeof r||null===r)throw e.ValidationError.typeMismatch(`segmentBoosts[${i}]`,"SegmentBoost object",typeof r,r);const t=r;if("string"!=typeof t.segmentId||!t.segmentId)throw new e.ValidationError(`segmentBoosts[${i}].segmentId must be a non-empty string`,{field:`segmentBoosts[${i}].segmentId`,value:t.segmentId,constraint:"Must be a non-empty string"});if("number"!=typeof t.boostFactor||!Number.isFinite(t.boostFactor))throw e.ValidationError.typeMismatch(`segmentBoosts[${i}].boostFactor`,"number",typeof t.boostFactor,t.boostFactor);const n=t.boostFactor;if(n<ti||n>ii)throw e.ValidationError.outOfRange(`segmentBoosts[${i}].boostFactor`,ti,ii,n)}}}}}validateTrendingOptions(t){if(t){if(void 0!==t.limit){if(!Number.isInteger(t.limit)||t.limit<1)throw new e.ValidationError("limit must be a positive integer",{field:"limit",value:t.limit,constraint:"Must be a positive integer"});if(t.limit>Ht)throw e.ValidationError.outOfRange("limit",1,Ht,t.limit)}if(void 0!==t.excludeOutOfStock&&"boolean"!=typeof t.excludeOutOfStock)throw e.ValidationError.typeMismatch("excludeOutOfStock","boolean",typeof t.excludeOutOfStock,t.excludeOutOfStock);if(void 0!==t.categoryFilter&&"string"!=typeof t.categoryFilter)throw e.ValidationError.typeMismatch("categoryFilter","string",typeof t.categoryFilter,t.categoryFilter)}}transformProducts(e){return e.map(e=>this.transformProduct(e))}transformProduct(e){const t={id:createProductId(e.id),name:e.name,price:e.price,currency:e.currency,image:e.image,url:e.url};return void 0!==e.original_price&&(t.originalPrice=e.original_price),void 0!==e.category&&(t.category=e.category),void 0!==e.rating&&(t.rating=e.rating),void 0!==e.review_count&&(t.reviewCount=e.review_count),void 0!==e.in_stock&&(t.inStock=e.in_stock),void 0!==e.brand&&(t.brand=e.brand),void 0!==e.sku&&(t.sku=e.sku),void 0!==e.description&&(t.description=e.description),void 0!==e.variant&&(t.variant=e.variant),void 0!==e.attributes&&(t.attributes=e.attributes),t}createEmptyStats(){return{similarRequests:0,successfulSimilarRequests:0,failedSimilarRequests:0,similarCacheHits:0,similarCacheMisses:0,personalizedRequests:0,successfulPersonalizedRequests:0,failedPersonalizedRequests:0,personalizedCacheHits:0,personalizedCacheMisses:0,personalizedFallbacks:0,trendingRequests:0,successfulTrendingRequests:0,failedTrendingRequests:0,totalProductsReturned:0,totalResponseTime:0,lastRequestAt:null}}log(e,t){this.debug&&this.onDebug&&this.onDebug(`[RecommendationsClient] ${e}`,t)}}}});function createContextCollector(e={}){return new fi(e)}function isContextCollector(e){return e instanceof fi}var vi=__esm({"src/recommendations/context-collector.ts"(){ui(),fi=class{constructor(e={}){var t,i,r,n;__publicField(this,"storage"),__publicField(this,"getCartItems"),__publicField(this,"hasConsentFn"),__publicField(this,"maxRecentViews"),__publicField(this,"maxSearchTerms"),__publicField(this,"debug"),__publicField(this,"onDebug"),__publicField(this,"now"),__publicField(this,"inMemoryViews",[]),__publicField(this,"inMemorySearches",[]),__publicField(this,"stats"),this.storage=e.storage,this.getCartItems=e.getCartItems,this.hasConsentFn=e.hasConsent,this.maxRecentViews=null!=(t=e.maxRecentViews)?t:Gt,this.maxSearchTerms=null!=(i=e.maxSearchTerms)?i:Xt,this.debug=null!=(r=e.debug)&&r,this.onDebug=e.onDebug,this.now=null!=(n=e.now)?n:()=>Date.now(),this.stats={viewsRecorded:0,searchesRecorded:0,viewsPruned:0,searchesPruned:0},this.log("ContextCollector initialized",{hasStorage:!!this.storage,hasCartProvider:!!this.getCartItems,hasConsentChecker:!!this.hasConsentFn,maxRecentViews:this.maxRecentViews,maxSearchTerms:this.maxSearchTerms})}async recordProductView(e,t){if(!this.hasConsent())return void this.log("Skipping product view - no consent");if(!e||0===e.length)return void this.log("Skipping product view - invalid productId");const i=this.now(),r={productId:e,viewedAt:i};(null==t?void 0:t.category)&&(r.category=t.category),(null==t?void 0:t.brand)&&(r.brand=t.brand),void 0!==(null==t?void 0:t.duration)&&(r.duration=t.duration);try{const t=(await this.loadViews()).filter(t=>t.productId!==e),i=this.pruneViews(t),n=t.length-i.length;this.stats.viewsPruned+=n;const s=[r,...i].slice(0,this.maxRecentViews);await this.saveViews(s),this.stats.viewsRecorded++,this.log("Recorded product view",{productId:e,viewCount:s.length})}catch(t){this.log("Failed to record product view",{productId:e,error:t instanceof Error?t.message:String(t)})}}async recordSearch(e){if(!this.hasConsent())return void this.log("Skipping search record - no consent");const t=e.trim();if(!t||0===t.length)return void this.log("Skipping search record - empty term");const i=this.now(),r={term:t,searchedAt:i};try{const e=(await this.loadSearches()).filter(e=>e.term.toLowerCase()!==t.toLowerCase()),i=this.pruneSearches(e),n=e.length-i.length;this.stats.searchesPruned+=n;const s=[r,...i].slice(0,this.maxSearchTerms);await this.saveSearches(s),this.stats.searchesRecorded++,this.log("Recorded search",{term:t,searchCount:s.length})}catch(t){this.log("Failed to record search",{term:e,error:t instanceof Error?t.message:String(t)})}}async collectContext(){if(!this.hasConsent())return this.log("Returning empty context - no consent"),this.createEmptyContext();try{const e=await this.loadViews(),t=this.pruneViews(e);let i=[];if(this.getCartItems)try{i=(await Promise.resolve(this.getCartItems())).slice(0,Yt)}catch(e){this.log("Failed to get cart items",{error:e instanceof Error?e.message:String(e)})}const r=await this.loadSearches(),n=this.pruneSearches(r).map(e=>e.term),s=this.extractPreferredCategories(t),o=this.extractPreferredBrands(t),a={recentViews:t,cartItems:i,searchTerms:n};return s.length>0&&(a.preferredCategories=s),o.length>0&&(a.preferredBrands=o),this.log("Collected context",{viewCount:a.recentViews.length,cartItemCount:a.cartItems.length,searchTermCount:a.searchTerms.length,categoryCount:s.length,brandCount:o.length}),a}catch(e){return this.log("Failed to collect context",{error:e instanceof Error?e.message:String(e)}),this.createEmptyContext()}}async hasHistory(){if(!this.hasConsent())return!1;try{return(await this.loadViews()).length>0||(!!(this.getCartItems&&(await Promise.resolve(this.getCartItems())).length>0)||(await this.loadSearches()).length>0)}catch(e){return this.log("Failed to check history",{error:e instanceof Error?e.message:String(e)}),!1}}async clearContext(){try{this.storage&&(await this.storage.remove(Jt),await this.storage.remove(Zt)),this.inMemoryViews=[],this.inMemorySearches=[],this.log("Context cleared")}catch(e){this.log("Failed to clear context",{error:e instanceof Error?e.message:String(e)})}}async getStats(){let e=0,t=0;try{e=(await this.loadViews()).length,t=(await this.loadSearches()).length}catch(e){}return{viewsRecorded:this.stats.viewsRecorded,searchesRecorded:this.stats.searchesRecorded,currentViewCount:e,currentSearchCount:t,viewsPruned:this.stats.viewsPruned,searchesPruned:this.stats.searchesPruned,hasStorage:!!this.storage,hasConsent:this.hasConsent()}}hasConsent(){if(!this.hasConsentFn)return!0;try{return this.hasConsentFn()}catch(e){return!1}}async loadViews(){if(!this.storage)return[...this.inMemoryViews];try{const e=await this.storage.get(Jt);return e&&this.isValidStoredViews(e)?e.views:[]}catch(e){return[]}}async saveViews(e){if(!this.storage)return void(this.inMemoryViews=e);const t={version:1,views:e,updatedAt:this.now()};await this.storage.set(Jt,t)}pruneViews(e){const t=this.now()-6048e5;return e.filter(e=>e.viewedAt>t)}isValidStoredViews(e){if("object"!=typeof e||null===e)return!1;const t=e;return 1===t.version&&!!Array.isArray(t.views)}async loadSearches(){if(!this.storage)return[...this.inMemorySearches];try{const e=await this.storage.get(Zt);return e&&this.isValidStoredSearches(e)?e.searches:[]}catch(e){return[]}}async saveSearches(e){if(!this.storage)return void(this.inMemorySearches=e);const t={version:1,searches:e,updatedAt:this.now()};await this.storage.set(Zt,t)}pruneSearches(e){const t=this.now()-864e5;return e.filter(e=>e.searchedAt>t)}isValidStoredSearches(e){if("object"!=typeof e||null===e)return!1;const t=e;return 1===t.version&&!!Array.isArray(t.searches)}extractPreferredCategories(e){var t;const i=new Map;for(const r of e)if(r.category){const e=null!=(t=i.get(r.category))?t:0;i.set(r.category,e+1)}return[...i.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5).map(([e])=>e)}extractPreferredBrands(e){var t;const i=new Map;for(const r of e)if(r.brand){const e=null!=(t=i.get(r.brand))?t:0;i.set(r.brand,e+1)}return[...i.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5).map(([e])=>e)}createEmptyContext(){return{recentViews:[],cartItems:[],searchTerms:[]}}log(e,t){this.debug&&this.onDebug&&this.onDebug(`[ContextCollector] ${e}`,t)}}}}),bi={};__export(bi,{CACHE_KEY_VERSION:()=>ci,ContextCollector:()=>fi,DEFAULT_CACHE_TTL:()=>Vt,DEFAULT_PERSONALIZED_LIMIT:()=>Kt,DEFAULT_RECENTLY_VIEWED_LIMIT:()=>ri,DEFAULT_SIMILAR_LIMIT:()=>zt,DEFAULT_TIMEOUT:()=>jt,MAX_BOOST_FACTOR:()=>ii,MAX_CART_ITEMS:()=>Yt,MAX_PERSONALIZED_LIMIT:()=>Wt,MAX_RECENTLY_VIEWED_STORED:()=>ni,MAX_RECENT_VIEWS:()=>Gt,MAX_SEARCH_TERMS:()=>Xt,MAX_SIMILAR_LIMIT:()=>Ht,MIN_BOOST_FACTOR:()=>ti,PERSONALIZED_CACHE_PREFIX:()=>ai,PERSONALIZED_CACHE_TTL:()=>ei,PERSONALIZED_TIMEOUT:()=>Qt,PersonalizedCacheStrategy:()=>li,RECENT_SEARCHES_STORAGE_KEY:()=>Zt,RECENT_VIEWS_STORAGE_KEY:()=>Jt,RECOMMENDATIONS_CACHE_KEY:()=>Bt,RecommendationsClient:()=>pi,createContextCollector:()=>createContextCollector,createPersonalizedCacheStrategy:()=>createPersonalizedCacheStrategy,createRecommendationsClient:()=>createRecommendationsClient,isCartContextItem:()=>isCartContextItem,isContextCollector:()=>isContextCollector,isPersonalizationContext:()=>isPersonalizationContext,isPersonalizedCacheEntry:()=>isPersonalizedCacheEntry,isPersonalizedCacheStrategy:()=>isPersonalizedCacheStrategy,isPersonalizedOptions:()=>isPersonalizedOptions,isRawPersonalizedResponse:()=>isRawPersonalizedResponse,isRawProduct:()=>isRawProduct,isRawSimilarProductsResponse:()=>isRawSimilarProductsResponse,isRawTrendingResponse:()=>isRawTrendingResponse,isRecentViewEntry:()=>isRecentViewEntry,isRecentlyViewedOptions:()=>isRecentlyViewedOptions,isRecommendationsClient:()=>isRecommendationsClient,isSegmentBoost:()=>isSegmentBoost,isSimilarProductsCacheEntry:()=>isSimilarProductsCacheEntry,isSimilarProductsOptions:()=>isSimilarProductsOptions2,isTrendingOptions:()=>isTrendingOptions,isTrendingTimeWindow:()=>isTrendingTimeWindow});var Si=__esm({"src/recommendations/index.ts"(){yi(),vi(),mi(),ui(),ui()}});function createBannerId(e){if("string"!=typeof e)throw new Error("BannerId must be a string, received "+typeof e);if(0===e.length)throw new Error("BannerId cannot be an empty string");return e}function isBannerId(e){return"string"==typeof e&&e.length>0}function isRuleGroup(e){return"rules"in e&&Array.isArray(e.rules)}function isSegmentRule(e){return"segment"===e.type}function isCartValueRule(e){return"cartValue"===e.type}function isPageUrlRule(e){return"pageUrl"===e.type}function isDeviceRule(e){return"device"===e.type}function isTimeBasedRule(e){return"timeBased"===e.type}function isRecurringSchedule(e){return"days"in e&&Array.isArray(e.days)}function isBannerRule(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["segment","cartValue","pageUrl","device","timeBased"].includes(t.type)&&"string"==typeof t.operator&&"value"in t}function isBanner(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.name&&"object"==typeof t.content&&null!==t.content&&Array.isArray(t.rules)&&"number"==typeof t.priority&&"boolean"==typeof t.active}function isFrequencyCap(e){if("object"!=typeof e||null===e)return!1;const t=e,i=!("maxImpressions"in t)||"number"==typeof t.maxImpressions,r=!("maxImpressionsPerSession"in t)||"number"==typeof t.maxImpressionsPerSession,n=!("cooldownMs"in t)||"number"==typeof t.cooldownMs;return i&&r&&n}function isBannerContent(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["modal","inline","sticky-bar","slide-in"].includes(t.type)}var wi,Ci,Ei,_i,Ii,ki,xi,Ti,Ai,Ri=__esm({"src/banners/types.ts"(){}});function evaluatePageUrlRule(e,t){const i=t.pageUrl;if(!i)return!1;const r=e.value;switch(e.operator){case"eq":return i===r;case"contains":return i.includes(r);case"startsWith":return i.startsWith(r);case"endsWith":return i.endsWith(r);case"matches":return function(e,t){if(!function(e){if(e.length>ki)return!1;for(const t of Ti)if(t.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}(e))return!1;const i=t.length>xi?t.slice(0,xi):t;try{return new RegExp(e).test(i)}catch(e){return!1}}(r,i);case"glob":try{return function(e){if(e.length>Ii)throw new Error(`Glob pattern exceeds maximum length of ${Ii}`);const t=(e.match(/\*|\?/g)||[]).length;if(t>_i)throw new Error(`Glob pattern has ${t} wildcards, maximum is ${_i}`);const i=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\0").replace(/\*/g,"[^/]*?").replace(/\?/g,".").replace(/\0/g,".*?");return new RegExp(`^${i}$`)}(r).test(i)}catch(e){return!1}default:return!1}}function detectDeviceType(e){return Ci.test(e)?"tablet":wi.test(e)?"mobile":"desktop"}function parseTime(e){const t=/^(\d{1,2}):(\d{2})$/.exec(e);if(!t)return null;const i=parseInt(t[1],10),r=parseInt(t[2],10);return i<0||i>23||r<0||r>59?null:{hours:i,minutes:r}}function getTimeInTimezone(e,t){if(!t)return e;try{const i=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(e),getPart=e=>{const t=i.find(t=>t.type===e);return t?parseInt(t.value,10):0};return new Date(getPart("year"),getPart("month")-1,getPart("day"),getPart("hour"),getPart("minute"),getPart("second"))}catch(e){return null}}function createRulesEngine(e){return new Ai(e)}function isRulesEngine(e){return e instanceof Ai}function and(...e){return{operator:"AND",rules:e}}function or(...e){return{operator:"OR",rules:e}}function not(e){return{...e,negate:!e.negate}}function detectCurrentDeviceType(){return"undefined"!=typeof navigator&&navigator.userAgent?detectDeviceType(navigator.userAgent):"desktop"}var Pi,Di=__esm({"src/banners/rules.ts"(){Ri(),wi=/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i,Ci=/iPad|Android(?!.*Mobile)|Tablet|PlayBook|Silk/i,Ei={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6},_i=10,Ii=500,ki=200,xi=1e4,Ti=[/\([^)]*[+*][^)]*\)[+*]/,/\(\?[^)]*[+*][^)]*\)[+*]/,/\[[^\]]*\][+*]{2,}/,/\([^|)]*\|[^|)]*\)[+*]/],Ai=class{constructor(e={}){var t,i,r;__publicField(this,"debug"),__publicField(this,"onDebug"),__publicField(this,"now"),__publicField(this,"getUrl"),__publicField(this,"getDeviceType"),__publicField(this,"stats",{bannersEvaluated:0,rulesEvaluated:0,totalEvaluationTimeMs:0,averageTimePerBannerMs:0}),this.debug=null!=(t=e.debug)&&t,this.onDebug=e.onDebug,this.now=null!=(i=e.now)?i:()=>new Date,this.getUrl=null!=(r=e.getUrl)?r:()=>"undefined"!=typeof window&&window.location?window.location.href:"",this.getDeviceType=e.getDeviceType}log(e,t){this.debug&&this.onDebug&&this.onDebug(`[RulesEngine] ${e}`,t)}evaluateRule(e,t){if(this.stats.rulesEvaluated++,isRuleGroup(e))return this.evaluateRuleGroup(e,t);let i,r=!1;try{isSegmentRule(e)?r=function(e,t){var i;const r=null!=(i=t.segments)?i:[],n=e.value;switch(e.operator){case"in":case"any":return n.some(e=>r.includes(e));case"notIn":return!n.some(e=>r.includes(e));case"all":return n.every(e=>r.includes(e));default:return!1}}(e,t):isCartValueRule(e)?r=function(e,t){const i=t.cartValue;if(void 0===i)return!1;switch(e.operator){case"eq":return i===e.value;case"gt":return i>e.value;case"lt":return i<e.value;case"gte":return i>=e.value;case"lte":return i<=e.value;case"between":{const t=e.value;return i>=t.min&&i<=t.max}default:return!1}}(e,t):isPageUrlRule(e)?r=evaluatePageUrlRule(e,t):isDeviceRule(e)?r=function(e,t,i){let r=t.device;!r&&i&&(r=i()),r||(r="undefined"!=typeof navigator&&navigator.userAgent?detectDeviceType(navigator.userAgent):"desktop");const n=e.value;switch(e.operator){case"in":return n.includes(r);case"notIn":return!n.includes(r);default:return!1}}(e,t,this.getDeviceType):isTimeBasedRule(e)?r=function(e,t,i){var r,n;const s=null!=(r=t.currentTime)?r:i(),o=e.value,a=null!=(n=t.timezone)?n:o.timezone;if(isRecurringSchedule(o)){const e=getTimeInTimezone(s,a);if(!e)return!1;const t=e.getDay();if(!o.days.some(e=>Ei[e]===t))return!1;const i=parseTime(o.start),r=parseTime(o.end);if(!i||!r)return!1;const n=60*e.getHours()+e.getMinutes(),c=60*i.hours+i.minutes,l=60*r.hours+r.minutes;return c<=l?n>=c&&n<=l:n>=c||n<=l}{const e=o,t=new Date(e.start),i=new Date(e.end);if(isNaN(t.getTime())||isNaN(i.getTime()))return!1;const r=getTimeInTimezone(s,a);return!!r&&r>=t&&r<=i}}(e,t,this.now):(i=`Unknown rule type: ${e.type}`,this.log(i,e)),e.negate&&(r=!r)}catch(r){i=r instanceof Error?r.message:"Unknown error",this.log(`Rule evaluation error: ${i}`,{rule:e,context:t})}const n={matched:r,rule:e};return i&&(n.error=i),this.debug&&(n.debug={contextValue:this.getContextValueForRule(e,t),ruleValue:e.value,operator:e.operator}),n}getContextValueForRule(e,t){var i;switch(e.type){case"segment":return t.segments;case"cartValue":return t.cartValue;case"pageUrl":return t.pageUrl;case"device":return t.device;case"timeBased":return null!=(i=t.currentTime)?i:this.now();default:return}}evaluateRuleGroup(e,t){const i=[];let r;if("AND"===e.operator){r=!0;for(const n of e.rules){const e=this.evaluateRule(n,t);if(i.push(e),!e.matched){r=!1;break}}}else{r=!1;for(const n of e.rules){const e=this.evaluateRule(n,t);if(i.push(e),e.matched){r=!0;break}}}const n={matched:r,rule:e};return this.debug&&(n.debug={contextValue:void 0,ruleValue:i,operator:e.operator}),n}evaluateBanner(e,t){var i,r;const n=performance.now();if(this.stats.bannersEvaluated++,!e.active)return{banner:e,eligible:!1,ruleResults:[],reason:"inactive"};const s=null!=(i=t.currentTime)?i:this.now();if(e.startDate&&s<new Date(e.startDate))return{banner:e,eligible:!1,ruleResults:[],reason:"outside_date_range"};if(e.endDate&&s>new Date(e.endDate))return{banner:e,eligible:!1,ruleResults:[],reason:"outside_date_range"};const o=[],a=null!=(r=e.ruleOperator)?r:"AND";let c;if(0===e.rules.length)c=!0;else if("AND"===a){c=!0;for(const i of e.rules){const e=this.evaluateRule(i,t);if(o.push(e),!e.matched&&(c=!1,!this.debug))break}}else{c=!1;for(const i of e.rules){const e=this.evaluateRule(i,t);if(o.push(e),e.matched&&(c=!0,!this.debug))break}}const l=performance.now()-n;this.stats.totalEvaluationTimeMs+=l,this.stats.averageTimePerBannerMs=this.stats.totalEvaluationTimeMs/this.stats.bannersEvaluated,this.log(`Evaluated banner "${e.name}"`,{eligible:c,evaluationTimeMs:l,rulesEvaluated:o.length});const u={banner:e,eligible:c,ruleResults:o};return c||(u.reason="rules_not_matched"),u}evaluateBanners(e,t){const i=performance.now(),r=this.enrichContext(t),n=e.map(e=>this.evaluateBanner(e,r)),s=performance.now()-i;return this.log(`Evaluated ${e.length} banners`,{totalTimeMs:s,eligibleCount:n.filter(e=>e.eligible).length}),n}getEligibleBanners(e,t){return this.evaluateBanners(e,t).filter(e=>e.eligible).sort((e,t)=>t.banner.priority-e.banner.priority).map(e=>e.banner)}getTopBanner(e,t){const i=this.getEligibleBanners(e,t);return i.length>0?i[0]:null}enrichContext(e){const t={...e};if(t.pageUrl||(t.pageUrl=this.getUrl()),t.currentTime||(t.currentTime=this.now()),!t.timezone&&"undefined"!=typeof Intl)try{t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){}return t}getStats(){return{...this.stats}}resetStats(){this.stats={bannersEvaluated:0,rulesEvaluated:0,totalEvaluationTimeMs:0,averageTimePerBannerMs:0}}}}});function createBannerClient(e){return new Pi(e)}function isBannerClient(e){return e instanceof Pi}var Li,Mi,Oi,$i,Ni,Fi,qi,Ui=__esm({"src/banners/client.ts"(){Pi=class{constructor(e){var t,i,r,n;__publicField(this,"httpClient"),__publicField(this,"storage"),__publicField(this,"apiKey"),__publicField(this,"endpoint"),__publicField(this,"timeout"),__publicField(this,"cacheTTL"),__publicField(this,"storageKey"),__publicField(this,"debug"),__publicField(this,"onDebug"),__publicField(this,"memoryCache",null),__publicField(this,"pendingRequest",null),__publicField(this,"stats",{totalRequests:0,cacheHits:0,cacheMisses:0,failedFetches:0,lastFetchedAt:null,isCached:!1,cacheExpiresIn:null}),this.httpClient=e.httpClient,this.storage=e.storage,this.apiKey=e.apiKey,this.endpoint=null!=(t=e.endpoint)?t:"/api/banners/config",this.timeout=null!=(i=e.timeout)?i:1e4,this.cacheTTL=null!=(r=e.cacheTTL)?r:3e5,this.storageKey=null!=(n=e.storageKey)?n:"banner_config",this.onDebug=e.onDebug,this.debug=!!e.onDebug,this.loadCacheFromStorage()}log(e,t){this.debug&&this.onDebug&&this.onDebug(`[BannerClient] ${e}`,t)}loadCacheFromStorage(){try{const e=this.storage.get(this.storageKey);e&&this.isValidCacheEntry(e)&&(this.memoryCache=e,this.updateCacheStats(),this.log("Loaded cache from storage",{bannerCount:e.banners.length,expiresIn:e.expiresAt-Date.now()}))}catch(e){this.log("Failed to load cache from storage",e)}}isValidCacheEntry(e){if("object"!=typeof e||null===e)return!1;const t=e;return Array.isArray(t.banners)&&"number"==typeof t.fetchedAt&&"number"==typeof t.expiresAt}updateCacheStats(){this.memoryCache?(this.stats.isCached=Date.now()<this.memoryCache.expiresAt,this.stats.cacheExpiresIn=this.stats.isCached?this.memoryCache.expiresAt-Date.now():null):(this.stats.isCached=!1,this.stats.cacheExpiresIn=null)}async getBanners(e={}){this.stats.totalRequests++;const t=this.memoryCache;if(!e.forceRefresh&&t&&this.isCacheValid())return this.stats.cacheHits++,this.log("Returning cached banners",{bannerCount:t.banners.length,cacheAge:Date.now()-t.fetchedAt}),{banners:t.banners,cached:!0,usingDefaults:!1,expiresAt:t.expiresAt};if(this.stats.cacheMisses++,this.pendingRequest)return this.log("Returning pending request"),this.pendingRequest;this.pendingRequest=this.fetchBanners(e);try{return await this.pendingRequest}finally{this.pendingRequest=null}}async fetchBanners(e){var t;const i=performance.now();try{const r=await this.httpClient.get(this.endpoint,{timeout:null!=(t=e.timeout)?t:this.timeout,signal:e.signal}),n=performance.now()-i;this.log("Fetched banners from API",{bannerCount:r.banners.length,fetchTimeMs:n,ttl:r.ttl});const s=Date.now(),o=r.ttl?1e3*r.ttl:this.cacheTTL,a={banners:r.banners,fetchedAt:s,expiresAt:s+o};return void 0!==r.version&&(a.version=r.version),this.memoryCache=a,this.storage.set(this.storageKey,a,{ttl:o}),this.stats.lastFetchedAt=s,this.updateCacheStats(),{banners:r.banners,cached:!1,usingDefaults:!1,expiresAt:a.expiresAt}}catch(e){this.stats.failedFetches++;const t=e instanceof Error?e.message:"Unknown error";return this.log("Failed to fetch banners",{error:t}),this.memoryCache?(this.log("Returning stale cache due to error",{cacheAge:Date.now()-this.memoryCache.fetchedAt}),{banners:this.memoryCache.banners,cached:!0,usingDefaults:!1,error:t}):{banners:[],cached:!1,usingDefaults:!0,error:t}}}getCachedBanners(){var e,t;return null!=(t=null==(e=this.memoryCache)?void 0:e.banners)?t:null}isCacheValid(){return!!this.memoryCache&&Date.now()<this.memoryCache.expiresAt}invalidateCache(){this.memoryCache=null,this.storage.set(this.storageKey,null),this.updateCacheStats(),this.log("Cache invalidated")}getApiKey(){return this.apiKey}getStats(){return this.updateCacheStats(),{...this.stats}}resetStats(){this.stats={totalRequests:0,cacheHits:0,cacheMisses:0,failedFetches:0,lastFetchedAt:this.stats.lastFetchedAt,isCached:this.stats.isCached,cacheExpiresIn:this.stats.cacheExpiresIn}}}}});function escapeHTML2(e){return escapeHtml(e)}function isSSR(e){return null==e}function getFocusableElements(e){const t=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");return Array.from(e.querySelectorAll(t))}function createFocusTrapImpl(e){let t=!1,i=null;return{get isActive(){return t},activate(){var r;if(t)return;t=!0,i=t=>{if("Tab"!==t.key)return;const i=getFocusableElements(e);if(0===i.length)return;const r=i[0],n=i[i.length-1];t.shiftKey?document.activeElement===r&&(t.preventDefault(),null==n||n.focus()):document.activeElement===n&&(t.preventDefault(),null==r||r.focus())},e.addEventListener("keydown",i);const n=getFocusableElements(e);n.length>0&&(null==(r=n[0])||r.focus())},deactivate(){t&&(t=!1,i&&(e.removeEventListener("keydown",i),i=null))}}}function buildBannerContentHTML(e,t,i=!1){if(t.html)return`<div class="${Li}__custom-content">${sanitizeHTML(t.html)}</div>`;const r=[];t.image&&!i&&r.push(`\n <div class="${Li}__image-wrapper">\n <img\n class="${Li}__image"\n src="${sanitizeImageSrc(t.image.src)}"\n alt="${escapeHTML2(t.image.alt)}"\n ${t.image.width?`width="${t.image.width}"`:""}\n ${t.image.height?`height="${t.image.height}"`:""}\n loading="lazy"\n />\n </div>\n `);const n=[];if(t.title&&n.push(`\n <h2\n class="${Li}__title"\n id="${Li}__title-${escapeHTML2(e.id)}"\n >\n ${escapeHTML2(t.title)}\n </h2>\n `),t.body&&!i&&n.push(`\n <p class="${Li}__body">${escapeHTML2(t.body)}</p>\n `),t.cta){const e=t.cta.openInNewTab?'target="_blank" rel="noopener noreferrer"':"";n.push(`\n <a\n class="${Li}__cta"\n href="${sanitizeHref(t.cta.url)}"\n ${e}\n data-cta="true"\n >\n ${escapeHTML2(t.cta.text)}\n </a>\n `)}return n.length>0&&r.push(`<div class="${Li}__text-content">${n.join("")}</div>`),r.join("")}function getTemplateHTML(e,t){const i=e.content,r=null!=t?t:i.position;switch(i.type){case"modal":return function(e,t){var i,r;const n=null!=(i=t.backgroundColor)?i:"#ffffff",s=null!=(r=t.textColor)?r:"#1f2937",o=sanitizeCssClasses(t.cssClasses);return`\n <div\n class="${Li}__modal-overlay"\n data-banner-id="${escapeHTML2(e.id)}"\n role="dialog"\n aria-modal="true"\n aria-labelledby="${Li}__title-${escapeHTML2(e.id)}"\n >\n <div\n class="${Li}__modal ${o}"\n style="background-color: ${escapeHTML2(n)}; color: ${escapeHTML2(s)};"\n >\n <button\n class="${Li}__close-btn"\n aria-label="Close banner"\n type="button"\n >\n <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n ${buildBannerContentHTML(e,t)}\n </div>\n </div>\n `}(e,i);case"inline":default:return function(e,t){var i,r;const n=null!=(i=t.backgroundColor)?i:"#f3f4f6",s=null!=(r=t.textColor)?r:"#1f2937",o=sanitizeCssClasses(t.cssClasses);return`\n <div\n class="${Li}__inline ${o}"\n data-banner-id="${escapeHTML2(e.id)}"\n style="background-color: ${escapeHTML2(n)}; color: ${escapeHTML2(s)};"\n role="region"\n aria-labelledby="${Li}__title-${escapeHTML2(e.id)}"\n >\n <button\n class="${Li}__close-btn"\n aria-label="Close banner"\n type="button"\n >\n <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n ${buildBannerContentHTML(e,t)}\n </div>\n `}(e,i);case"sticky-bar":return function(e,t,i="top"){var r,n;const s=null!=(r=t.backgroundColor)?r:"#3b82f6",o=null!=(n=t.textColor)?n:"#ffffff",a=sanitizeCssClasses(t.cssClasses);return`\n <div\n class="${Li}__sticky-bar ${Li}__sticky-bar--${i} ${a}"\n data-banner-id="${escapeHTML2(e.id)}"\n style="background-color: ${escapeHTML2(s)}; color: ${escapeHTML2(o)};"\n role="region"\n aria-labelledby="${Li}__title-${escapeHTML2(e.id)}"\n >\n <div class="${Li}__sticky-bar-content">\n ${buildBannerContentHTML(e,t,!0)}\n </div>\n <button\n class="${Li}__close-btn"\n aria-label="Close banner"\n type="button"\n >\n <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n </div>\n `}(e,i,null!=r?r:"top");case"slide-in":return function(e,t,i="bottom-right"){var r,n;const s=null!=(r=t.backgroundColor)?r:"#ffffff",o=null!=(n=t.textColor)?n:"#1f2937",a=sanitizeCssClasses(t.cssClasses);return`\n <div\n class="${Li}__slide-in ${Li}__slide-in--${i} ${a}"\n data-banner-id="${escapeHTML2(e.id)}"\n style="background-color: ${escapeHTML2(s)}; color: ${escapeHTML2(o)};"\n role="region"\n aria-labelledby="${Li}__title-${escapeHTML2(e.id)}"\n >\n <button\n class="${Li}__close-btn"\n aria-label="Close banner"\n type="button"\n >\n <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M18 6L6 18M6 6l12 12"></path>\n </svg>\n </button>\n ${buildBannerContentHTML(e,t)}\n </div>\n `}(e,i,null!=r?r:"bottom-right")}}function generateBannerCSS(){return`\n /* Overvio Banner Renderer Styles */\n\n .${Li}__modal-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: ${$i};\n opacity: 0;\n transition: opacity 300ms ease;\n padding: 16px;\n }\n\n .${Li}__modal-overlay--visible {\n opacity: 1;\n }\n\n .${Li}__modal {\n position: relative;\n max-width: 480px;\n width: 100%;\n border-radius: 12px;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);\n padding: 24px;\n transform: scale(0.9);\n transition: transform 300ms ease;\n }\n\n .${Li}__modal-overlay--visible .${Li}__modal {\n transform: scale(1);\n }\n\n .${Li}__inline {\n position: relative;\n border-radius: 8px;\n padding: 16px;\n padding-right: 40px;\n }\n\n .${Li}__sticky-bar {\n position: fixed;\n left: 0;\n right: 0;\n padding: 12px 16px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n z-index: ${Ni};\n transform: translateY(-100%);\n transition: transform 300ms ease;\n }\n\n .${Li}__sticky-bar--top {\n top: 0;\n }\n\n .${Li}__sticky-bar--bottom {\n top: auto;\n bottom: 0;\n transform: translateY(100%);\n }\n\n .${Li}__sticky-bar--visible {\n transform: translateY(0);\n }\n\n .${Li}__sticky-bar-content {\n flex: 1;\n display: flex;\n align-items: center;\n gap: 16px;\n }\n\n .${Li}__slide-in {\n position: fixed;\n max-width: 360px;\n width: calc(100% - 32px);\n border-radius: 12px;\n box-shadow: 0 10px 40px -10px rgba(0, 0, 0, 0.3);\n padding: 20px;\n z-index: ${Fi};\n opacity: 0;\n transition: opacity 300ms ease, transform 300ms ease;\n }\n\n .${Li}__slide-in--top-left {\n top: 16px;\n left: 16px;\n transform: translateX(-100%);\n }\n\n .${Li}__slide-in--top-right {\n top: 16px;\n right: 16px;\n transform: translateX(100%);\n }\n\n .${Li}__slide-in--bottom-left {\n bottom: 16px;\n left: 16px;\n transform: translateX(-100%);\n }\n\n .${Li}__slide-in--bottom-right {\n bottom: 16px;\n right: 16px;\n transform: translateX(100%);\n }\n\n .${Li}__slide-in--visible {\n opacity: 1;\n transform: translateX(0);\n }\n\n .${Li}__close-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n width: 28px;\n height: 28px;\n padding: 4px;\n border: none;\n background: transparent;\n cursor: pointer;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n color: currentColor;\n opacity: 0.6;\n transition: opacity 150ms ease, background-color 150ms ease;\n }\n\n .${Li}__close-btn:hover {\n opacity: 1;\n background: rgba(0, 0, 0, 0.1);\n }\n\n .${Li}__close-btn:focus {\n outline: 2px solid currentColor;\n outline-offset: 2px;\n opacity: 1;\n }\n\n .${Li}__close-btn svg {\n width: 20px;\n height: 20px;\n }\n\n .${Li}__image-wrapper {\n margin-bottom: 16px;\n border-radius: 8px;\n overflow: hidden;\n }\n\n .${Li}__image {\n display: block;\n width: 100%;\n height: auto;\n }\n\n .${Li}__text-content {\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .${Li}__sticky-bar .${Li}__text-content {\n flex-direction: row;\n align-items: center;\n }\n\n .${Li}__title {\n margin: 0;\n font-size: 1.25em;\n font-weight: 600;\n line-height: 1.3;\n }\n\n .${Li}__sticky-bar .${Li}__title {\n font-size: 1em;\n }\n\n .${Li}__body {\n margin: 0;\n font-size: 1em;\n line-height: 1.5;\n opacity: 0.9;\n }\n\n .${Li}__cta {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: 10px 20px;\n background: currentColor;\n color: inherit;\n border-radius: 6px;\n text-decoration: none;\n font-weight: 500;\n font-size: 0.9375em;\n transition: opacity 150ms ease, transform 150ms ease;\n filter: brightness(0.9);\n }\n\n .${Li}__cta:hover {\n filter: brightness(1);\n transform: translateY(-1px);\n }\n\n .${Li}__cta:focus {\n outline: 2px solid currentColor;\n outline-offset: 2px;\n }\n\n .${Li}__sticky-bar .${Li}__cta {\n flex-shrink: 0;\n }\n\n .${Li}__custom-content {\n /* Custom HTML content container */\n }\n\n /* Dark mode adjustments */\n @media (prefers-color-scheme: dark) {\n .${Li}__close-btn:hover {\n background: rgba(255, 255, 255, 0.1);\n }\n }\n\n /* Responsive adjustments */\n @media (max-width: 640px) {\n .${Li}__modal {\n max-width: 100%;\n margin: 16px;\n }\n\n .${Li}__slide-in {\n max-width: calc(100% - 32px);\n }\n\n .${Li}__sticky-bar-content {\n flex-direction: column;\n align-items: flex-start;\n gap: 8px;\n }\n\n .${Li}__sticky-bar .${Li}__text-content {\n flex-direction: column;\n align-items: flex-start;\n }\n }\n `}function createBannerRenderer(e={}){return new qi(e)}function isBannerRenderer(e){return e instanceof qi}var zi,Hi,Vi,Bi,ji=__esm({"src/banners/renderer.ts"(){We(),fe(),Li="overvio-banner",Mi=1e4,Oi=300,$i=1e4,Ni=9999,Fi=9998,qi=class{constructor(e={}){var t,i,r;__publicField(this,"frequencyCapManager"),__publicField(this,"trackEvent"),__publicField(this,"onBannerClick"),__publicField(this,"onBannerDismiss"),__publicField(this,"onBannerDisplay"),__publicField(this,"onError"),__publicField(this,"customRender"),__publicField(this,"animationDuration"),__publicField(this,"debug"),__publicField(this,"onDebug"),__publicField(this,"now"),__publicField(this,"doc"),__publicField(this,"activeBanners",new Map),__publicField(this,"styleElement",null),__publicField(this,"stats",{activeBanners:0,totalDisplayed:0,totalClicks:0,totalCtaClicks:0,totalDismissals:0,dismissalsByReason:{close_button:0,overlay_click:0,escape_key:0,auto_dismiss:0,programmatic:0},errors:0,isSSR:!0}),this.frequencyCapManager=e.frequencyCapManager,this.trackEvent=e.trackEvent,this.onBannerClick=e.onBannerClick,this.onBannerDismiss=e.onBannerDismiss,this.onBannerDisplay=e.onBannerDisplay,this.onError=e.onError,this.customRender=e.customRender,this.animationDuration=null!=(t=e.animationDuration)?t:Oi,this.debug=null!=(i=e.debug)&&i,this.onDebug=e.onDebug,this.now=null!=(r=e.now)?r:()=>Date.now(),void 0!==e.document?this.doc=e.document:"undefined"!=typeof document&&(this.doc=document),this.stats.isSSR=isSSR(this.doc),this.stats.isSSR||this.injectStyles()}log(e,t){this.debug&&this.onDebug&&this.onDebug(`[BannerRenderer] ${e}`,t)}injectStyles(){if(!this.doc||this.styleElement)return;const e=this.doc.getElementById(`${Li}-styles`);if(e)return void(this.styleElement=e);this.styleElement=this.doc.createElement("style"),this.styleElement.id=`${Li}-styles`,this.styleElement.textContent=generateBannerCSS();const t=getConfiguredNonce();t&&applyNonce(this.styleElement,t),this.doc.head.appendChild(this.styleElement),this.log("Injected banner styles")}async display(e,t,i={}){var r;const n=t.id;if(this.stats.isSSR||!this.doc)return this.log("SSR mode - skipping display",{bannerId:n}),{success:!1,bannerId:t.id,error:"Cannot display banner in SSR environment"};let s=null;if(s="string"==typeof e?this.doc.querySelector(e):e,!s){const i=`Container not found: ${e}`;return this.log(i),this.stats.errors++,{success:!1,bannerId:t.id,error:i}}if(!i.skipFrequencyCap&&this.frequencyCapManager){const e=this.frequencyCapManager.canShowBanner(t);if(!e.canShow)return this.log("Banner blocked by frequency cap",{bannerId:n,reason:e.reason}),{success:!1,bannerId:t.id,error:`Banner blocked by frequency cap: ${e.reason}`,frequencyCapResult:e}}if(this.activeBanners.has(n))return this.log("Banner already displayed",{bannerId:n}),{success:!1,bannerId:t.id,error:"Banner is already displayed"};try{const e=this.createBannerElement(t,i),o=this.now(),a={banner:t,element:e,container:s,displayedAt:o,state:"rendering"};if(this.activeBanners.set(n,a),this.customRender){const i=this.createRenderHelpers(t,a);await this.customRender(t,e,i)}else e.innerHTML=sanitizeHTML(getTemplateHTML(t,i.position),{allowDataAttributes:!0});if(i.cssClasses){const t=sanitizeCssClasses(i.cssClasses).split(" ").filter(Boolean);t.length>0&&e.classList.add(...t)}i.styles&&Object.entries(i.styles).forEach(([t,i])=>{if(!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t))return void this.log(`Blocked invalid CSS property name: ${t}`);const r=i.toLowerCase();r.includes("expression(")||r.includes("javascript:")||r.includes("behavior:")||r.includes("url(")&&r.includes("javascript")?this.log(`Blocked potentially dangerous CSS value for ${t}`):e.style.setProperty(t,i)}),s.appendChild(e),this.setupEventListeners(t,a),"modal"===t.content.type&&(a.previouslyFocusedElement=this.doc.activeElement,a.focusTrap=createFocusTrapImpl(e),a.focusTrap.activate()),("undefined"!=typeof requestAnimationFrame?requestAnimationFrame:e=>setTimeout(e,0))(()=>{this.showBanner(a)});const c=null!=(r=i.autoDismissMs)?r:t.autoDismissMs;if(c&&c>0&&(a.autoDismissTimer=setTimeout(()=>{this.dismiss(t.id,"auto_dismiss")},c)),this.frequencyCapManager&&this.frequencyCapManager.recordImpression(t.id),this.stats.totalDisplayed++,this.stats.activeBanners=this.activeBanners.size,this.trackEvent){const e={bannerId:n,bannerName:t.name,bannerType:t.content.type,priority:t.priority};void 0!==t.content.position&&(e.position=t.content.position),Promise.resolve(this.trackEvent("banner_view",e)).catch(e=>{this.log("Failed to track banner_view event",{error:e})})}return this.onBannerDisplay&&this.onBannerDisplay(t,e),this.log("Banner displayed",{bannerId:n,template:t.content.type}),{success:!0,bannerId:t.id,element:e,displayedAt:o}}catch(e){const i=e instanceof Error?e:new Error(String(e));return this.log("Error displaying banner",{bannerId:n,error:i.message}),this.stats.errors++,this.onError&&this.onError(i,t),this.activeBanners.delete(n),{success:!1,bannerId:t.id,error:i.message}}}async displayModal(e,t={}){if(this.stats.isSSR||!this.doc)return{success:!1,bannerId:e.id,error:"Cannot display modal in SSR environment"};const i={...e,content:{...e.content,type:"modal"}};return this.display(this.doc.body,i,t)}async displayStickyBar(e,t={}){if(this.stats.isSSR||!this.doc)return{success:!1,bannerId:e.id,error:"Cannot display sticky bar in SSR environment"};const i={...e,content:{...e.content,type:"sticky-bar"}};return this.display(this.doc.body,i,t)}async displaySlideIn(e,t={}){if(this.stats.isSSR||!this.doc)return{success:!1,bannerId:e.id,error:"Cannot display slide-in in SSR environment"};const i={...e,content:{...e.content,type:"slide-in"}};return this.display(this.doc.body,i,t)}dismiss(e,t="programmatic"){var i;const r=e,n=this.activeBanners.get(r);if(!n)return void this.log("Banner not found for dismiss",{bannerId:r});if("animating-out"===n.state||"dismissed"===n.state)return;n.state="animating-out",n.autoDismissTimer&&clearTimeout(n.autoDismissTimer),(null==(i=n.focusTrap)?void 0:i.isActive)&&n.focusTrap.deactivate();const s=n.previouslyFocusedElement;s&&"function"==typeof s.focus&&s.focus(),this.hideBanner(n),setTimeout(()=>{if(n.state="dismissed",n.cleanup&&n.cleanup(),n.element.remove(),this.activeBanners.delete(r),this.stats.activeBanners=this.activeBanners.size,this.stats.totalDismissals++,this.stats.dismissalsByReason[t]++,this.trackEvent){const e=this.now()-n.displayedAt,i={bannerId:r,bannerName:n.banner.name,bannerType:n.banner.content.type,dismissReason:t,displayDuration:e,priority:n.banner.priority};void 0!==n.banner.content.position&&(i.position=n.banner.content.position),Promise.resolve(this.trackEvent("banner_dismiss",i)).catch(e=>{this.log("Failed to track banner_dismiss event",{error:e})})}this.onBannerDismiss&&this.onBannerDismiss({banner:n.banner,reason:t,timestamp:this.now(),visibleDuration:this.now()-n.displayedAt}),this.log("Banner dismissed",{bannerId:r,reason:t})},this.animationDuration)}dismissAll(e="programmatic"){const t=Array.from(this.activeBanners.keys());for(const i of t)this.dismiss(i,e)}trackClick(e,t=!1,i){const r=e,n=this.activeBanners.get(r);if(n){if(this.stats.totalClicks++,t&&this.stats.totalCtaClicks++,this.trackEvent){const e=this.now()-n.displayedAt,s={bannerId:r,bannerName:n.banner.name,bannerType:n.banner.content.type,isCtaClick:t,displayDuration:e,priority:n.banner.priority};void 0!==i&&(s.ctaUrl=i),void 0!==n.banner.content.position&&(s.position=n.banner.content.position),Promise.resolve(this.trackEvent("banner_click",s)).catch(e=>{this.log("Failed to track banner_click event",{error:e})})}if(this.onBannerClick){const e={banner:n.banner,element:n.element,position:{x:0,y:0},timestamp:this.now(),isCtaClick:t};void 0!==i&&(e.ctaUrl=i),this.onBannerClick(e)}this.log("Banner click tracked",{bannerId:r,isCtaClick:t,ctaUrl:i})}else this.log("Banner not found for click tracking",{bannerId:r})}trackDismiss(e,t="close_button"){this.dismiss(e,t)}isDisplayed(e){const t=e,i=this.activeBanners.get(t);return void 0!==i&&"dismissed"!==i.state}getActiveBannerIds(){return Array.from(this.activeBanners.keys())}getStats(){return{...this.stats}}resetStats(){this.stats={activeBanners:this.activeBanners.size,totalDisplayed:0,totalClicks:0,totalCtaClicks:0,totalDismissals:0,dismissalsByReason:{close_button:0,overlay_click:0,escape_key:0,auto_dismiss:0,programmatic:0},errors:0,isSSR:this.stats.isSSR}}destroy(){var e;for(const t of this.activeBanners.keys()){const i=this.activeBanners.get(t);i&&(i.autoDismissTimer&&clearTimeout(i.autoDismissTimer),(null==(e=i.focusTrap)?void 0:e.isActive)&&i.focusTrap.deactivate(),i.cleanup&&i.cleanup(),i.element.remove())}this.activeBanners.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.log("Renderer destroyed")}createBannerElement(e,t){if(!this.doc)throw new Error("Cannot create banner element: document is not available");const i=this.doc.createElement("div");return i.className=`${Li}`,i.setAttribute("data-banner-id",e.id),i.setAttribute("data-banner-type",e.content.type),i}createRenderHelpers(e,t){return{escapeHTML:escapeHTML2,trackClick:(t=!1,i)=>{this.trackClick(e.id,t,i)},dismiss:(t="programmatic")=>{this.dismiss(e.id,t)},createFocusTrap:e=>{const i=createFocusTrapImpl(e);return t.focusTrap=i,i},getCssPrefix:()=>Li}}setupEventListeners(e,t){var i;const r=t.element,handleCloseClick=t=>{t.preventDefault(),t.stopPropagation(),this.dismiss(e.id,"close_button")},handleCtaClick=t=>{const i=t.target.closest('[data-cta="true"]');i&&this.trackClick(e.id,!0,i.href)},handleBannerClick=t=>{const i=t.target;i.closest(`.${Li}__close-btn`)||i.closest('[data-cta="true"]')||this.trackClick(e.id,!1)},handleOverlayClick=t=>{t.target.classList.contains(`${Li}__modal-overlay`)&&this.dismiss(e.id,"overlay_click")},handleEscapeKey=t=>{"Escape"===t.key&&"modal"===e.content.type&&this.dismiss(e.id,"escape_key")};r.addEventListener("click",handleCloseClick,!0),r.addEventListener("click",handleCtaClick),r.addEventListener("click",handleBannerClick),"modal"===e.content.type&&(r.addEventListener("click",handleOverlayClick),null==(i=this.doc)||i.addEventListener("keydown",handleEscapeKey)),t.cleanup=()=>{var t;r.removeEventListener("click",handleCloseClick,!0),r.removeEventListener("click",handleCtaClick),r.removeEventListener("click",handleBannerClick),"modal"===e.content.type&&(r.removeEventListener("click",handleOverlayClick),null==(t=this.doc)||t.removeEventListener("keydown",handleEscapeKey))}}showBanner(e){const{element:t,banner:i}=e,r=i.content.type;if("modal"===r){const e=t.querySelector(`.${Li}__modal-overlay`);null==e||e.classList.add(`${Li}__modal-overlay--visible`)}else if("sticky-bar"===r){const e=t.querySelector(`.${Li}__sticky-bar`);null==e||e.classList.add(`${Li}__sticky-bar--visible`)}else if("slide-in"===r){const e=t.querySelector(`.${Li}__slide-in`);null==e||e.classList.add(`${Li}__slide-in--visible`)}e.state="visible"}hideBanner(e){const{element:t,banner:i}=e,r=i.content.type;if("modal"===r){const e=t.querySelector(`.${Li}__modal-overlay`);null==e||e.classList.remove(`${Li}__modal-overlay--visible`)}else if("sticky-bar"===r){const e=t.querySelector(`.${Li}__sticky-bar`);null==e||e.classList.remove(`${Li}__sticky-bar--visible`)}else if("slide-in"===r){const e=t.querySelector(`.${Li}__slide-in`);null==e||e.classList.remove(`${Li}__slide-in--visible`)}}}}});function createSegmentProvider(e){return new Bi(e)}function isSegmentProvider(e){return e instanceof Bi}var Ki,Wi,Qi,Gi,Yi,Xi,Ji=__esm({"src/banners/segment-provider.ts"(){zi="user_segments",Hi=3e5,Vi=100,Bi=class{constructor(e={}){var t,i,r,n,s;__publicField(this,"storage"),__publicField(this,"httpClient"),__publicField(this,"apiKey"),__publicField(this,"endpoint"),__publicField(this,"cacheTTL"),__publicField(this,"storageKey"),__publicField(this,"source"),__publicField(this,"fallbackSegments"),__publicField(this,"debug"),__publicField(this,"onDebug"),__publicField(this,"cachedData",null),__publicField(this,"inFlightRequest",null),__publicField(this,"stats",{totalRequests:0,cacheHits:0,cacheMisses:0,failedFetches:0,lastFetchedAt:null,isCached:!1,cacheExpiresIn:null,segmentCount:0,identityInvalidations:0}),__publicField(this,"unsubscribeIdentify"),this.storage=e.storage,this.httpClient=e.httpClient,this.apiKey=e.apiKey,this.endpoint=null!=(t=e.endpoint)?t:"/api/user/segments",this.cacheTTL=null!=(i=e.cacheTTL)?i:Hi,this.storageKey=null!=(r=e.storageKey)?r:zi,this.source=e.source,this.fallbackSegments=null!=(n=e.fallbackSegments)?n:[],this.debug=null!=(s=e.debug)&&s,this.onDebug=e.onDebug,this.loadFromStorage(),e.emitter&&this.subscribeToIdentityEvents(e.emitter)}log(e,t){this.debug&&this.onDebug&&this.onDebug(`[SegmentProvider] ${e}`,t)}subscribeToIdentityEvents(e){this.unsubscribeIdentify=e.on("identify",e=>{var t;this.log("Identity changed, invalidating segment cache",{userId:e.user.userId}),(null==(t=this.cachedData)?void 0:t.userId)!==e.user.userId&&(this.invalidateCache(),this.stats.identityInvalidations++)})}loadFromStorage(){if(this.storage)try{const e=this.storage.get(this.storageKey);e&&this.isCachedDataValid(e)&&(this.cachedData=e,this.updateCacheStats(),this.log("Loaded segments from storage",{segmentCount:e.segments.length}))}catch(e){this.log("Failed to load segments from storage",{error:e})}}isCachedDataValid(e){const t=Date.now();return 1===e._v&&t-e.cachedAt<this.cacheTTL}updateCacheStats(){this.cachedData&&this.isCachedDataValid(this.cachedData)?(this.stats.isCached=!0,this.stats.segmentCount=this.cachedData.segments.length,this.stats.cacheExpiresIn=Math.max(0,this.cacheTTL-(Date.now()-this.cachedData.cachedAt))):(this.stats.isCached=!1,this.stats.segmentCount=0,this.stats.cacheExpiresIn=null)}persistToStorage(e,t){const i={segments:e.slice(0,Vi),cachedAt:Date.now(),userId:t,_v:1};if(this.cachedData=i,this.updateCacheStats(),this.storage)try{this.storage.set(this.storageKey,i,{ttl:this.cacheTTL}),this.log("Persisted segments to storage",{segmentCount:e.length})}catch(e){this.log("Failed to persist segments to storage",{error:e})}}async fetchSegments(e={}){var t;if(this.source){const e=await Promise.resolve(this.source());return Array.isArray(e)?e:[]}if(this.httpClient&&this.apiKey){const i={timeout:null!=(t=e.timeout)?t:5e3};e.signal&&(i.signal=e.signal);const r=await this.httpClient.get(this.endpoint,i);return Array.isArray(null==r?void 0:r.segments)?r.segments:[]}return[]}async getSegments(e={}){if(this.stats.totalRequests++,!e.forceRefresh&&this.cachedData&&this.isCachedDataValid(this.cachedData))return this.stats.cacheHits++,this.updateCacheStats(),{segments:[...this.cachedData.segments],cached:!0,usingFallback:!1,expiresAt:this.cachedData.cachedAt+this.cacheTTL};if(this.stats.cacheMisses++,this.inFlightRequest&&!e.forceRefresh)return this.inFlightRequest;this.inFlightRequest=this.performFetch(e);try{return await this.inFlightRequest}finally{this.inFlightRequest=null}}async performFetch(e){try{const t=(await this.fetchSegments(e)).filter(e=>"string"==typeof e&&e.length>0).slice(0,Vi);return this.persistToStorage(t),this.stats.lastFetchedAt=Date.now(),this.log("Fetched segments successfully",{segmentCount:t.length}),{segments:t,cached:!1,usingFallback:!1,expiresAt:Date.now()+this.cacheTTL}}catch(e){return this.stats.failedFetches++,this.log("Failed to fetch segments",{error:e}),this.cachedData?{segments:[...this.cachedData.segments],cached:!0,usingFallback:!1,error:e instanceof Error?e:new Error(String(e)),expiresAt:this.cachedData.cachedAt+this.cacheTTL}:{segments:[...this.fallbackSegments],cached:!1,usingFallback:!0,error:e instanceof Error?e:new Error(String(e))}}}getCachedSegments(){return this.cachedData&&this.isCachedDataValid(this.cachedData)?[...this.cachedData.segments]:null}isCacheValid(){return null!==this.cachedData&&this.isCachedDataValid(this.cachedData)}invalidateCache(){if(this.cachedData=null,this.storage)try{this.storage.remove(this.storageKey)}catch(e){}this.stats.isCached=!1,this.stats.segmentCount=0,this.stats.cacheExpiresIn=null,this.log("Cache invalidated")}setSegments(e,t){const i=e.filter(e=>"string"==typeof e&&e.length>0).slice(0,Vi);this.persistToStorage(i,t)}getStats(){return this.updateCacheStats(),{...this.stats}}resetStats(){this.stats={totalRequests:0,cacheHits:0,cacheMisses:0,failedFetches:0,lastFetchedAt:this.stats.lastFetchedAt,isCached:this.stats.isCached,cacheExpiresIn:this.stats.cacheExpiresIn,segmentCount:this.stats.segmentCount,identityInvalidations:0}}destroy(){this.unsubscribeIdentify&&(this.unsubscribeIdentify(),this.unsubscribeIdentify=void 0),this.cachedData=null,this.inFlightRequest=null}}}});function isImpressionData(e){if("object"!=typeof e||null===e)return!1;const t=e;if("number"!=typeof t.version||"object"!=typeof t.impressions||null===t.impressions||"number"!=typeof t.updatedAt||!Array.isArray(t.lruOrder))return!1;if(1!==t.version)return!1;if(t.updatedAt<0||t.updatedAt>Date.now()+864e5)return!1;const i=t.lruOrder;if(i.length>2*Yi)return!1;for(const e of i)if("string"!=typeof e)return!1;const r=t.impressions;if(Object.keys(r).length>2*Yi)return!1;for(const[e,t]of Object.entries(r))if("string"!=typeof e||!isBannerImpressionValid(t))return!1;return!0}function isBannerImpressionValid(e){if("object"!=typeof e||null===e)return!1;const t=e;if("number"!=typeof t.count||"number"!=typeof t.firstSeenAt||"number"!=typeof t.lastSeenAt)return!1;if(t.count<0||t.count>1e6)return!1;const i=864e5,r=Date.now();return!(t.firstSeenAt<0||t.firstSeenAt>r+i||t.lastSeenAt<0||t.lastSeenAt>r+i||t.firstSeenAt>t.lastSeenAt)}function isSessionImpressionData(e){if("object"!=typeof e||null===e)return!1;const t=e;if("number"!=typeof t.version||"object"!=typeof t.impressions||null===t.impressions||"string"!=typeof t.sessionId||"number"!=typeof t.updatedAt)return!1;if(1!==t.version)return!1;if(0===t.sessionId.length)return!1;if(t.updatedAt<0||t.updatedAt>Date.now()+864e5)return!1;const i=t.impressions;if(Object.keys(i).length>2*Yi)return!1;for(const[e,r]of Object.entries(i))if("string"!=typeof e||!isSessionImpressionValid(r,t.sessionId))return!1;return!0}function isSessionImpressionValid(e,t){if("object"!=typeof e||null===e)return!1;const i=e;if("number"!=typeof i.count||"number"!=typeof i.firstSeenAt||"number"!=typeof i.lastSeenAt||"string"!=typeof i.sessionId)return!1;if(i.count<0||i.count>1e6)return!1;if(i.sessionId!==t)return!1;const r=864e5,n=Date.now();return!(i.firstSeenAt<0||i.firstSeenAt>n+r||i.lastSeenAt<0||i.lastSeenAt>n+r||i.firstSeenAt>i.lastSeenAt)}function isBannerImpression(e){return isBannerImpressionValid(e)}function createFrequencyCapManager(e){return new Xi(e)}function isFrequencyCapManager(e){return e instanceof Xi}var Zi=__esm({"src/banners/frequency-cap.ts"(){Ki="overvio_banner_impressions",Wi="overvio_banner_session_impressions",Qi=2592e6,Gi="BANNER_IMPRESSION_UPDATED",Yi=100,Xi=class{constructor(e){var t,i,r,n;__publicField(this,"storage"),__publicField(this,"sessionStorage"),__publicField(this,"sessionId"),__publicField(this,"userId"),__publicField(this,"crossTabSync"),__publicField(this,"impressionTTL"),__publicField(this,"debug"),__publicField(this,"onDebug"),__publicField(this,"now"),__publicField(this,"impressionCache",null),__publicField(this,"sessionImpressionCache",null),__publicField(this,"unsubscribeCrossTab",null),__publicField(this,"stats"),this.storage=e.storage,this.sessionStorage=null!=(t=e.sessionStorage)?t:e.storage,this.sessionId=e.sessionId,this.userId=e.userId,this.crossTabSync=e.crossTabSync,this.impressionTTL=null!=(i=e.impressionTTL)?i:Qi,this.debug=null!=(r=e.debug)&&r,this.onDebug=e.onDebug,this.now=null!=(n=e.now)?n:()=>Date.now(),this.stats={totalImpressionsRecorded:0,uniqueBannersTracked:0,cappedDisplays:0,crossTabSyncs:0,lruEvictions:0,hasSessionData:!1,sessionId:this.sessionId},this.loadFromStorage(),this.setupCrossTabSync()}log(e,t){this.debug&&this.onDebug&&this.onDebug(`[FrequencyCapManager] ${e}`,t)}loadFromStorage(){try{const e=this.storage.get(Ki);e&&isImpressionData(e)&&(this.userId&&e.userId!==this.userId?this.log("User ID mismatch, starting fresh",{stored:e.userId,current:this.userId}):(this.impressionCache=e,this.stats.uniqueBannersTracked=Object.keys(e.impressions).length,this.log("Loaded lifetime impressions from storage",{count:this.stats.uniqueBannersTracked})))}catch(e){this.log("Failed to load lifetime impressions",e)}try{const e=this.sessionStorage.get(Wi);e&&isSessionImpressionData(e)&&(e.sessionId===this.sessionId?(this.sessionImpressionCache=e,this.stats.hasSessionData=!0,this.log("Loaded session impressions from storage",{count:Object.keys(e.impressions).length,sessionId:e.sessionId})):this.log("Session ID mismatch, starting fresh session data",{stored:e.sessionId,current:this.sessionId}))}catch(e){this.log("Failed to load session impressions",e)}}saveLifetimeToStorage(){if(this.impressionCache)try{this.storage.set(Ki,this.impressionCache,{ttl:this.impressionTTL}),this.log("Saved lifetime impressions to storage")}catch(e){this.log("Failed to save lifetime impressions",e)}}saveSessionToStorage(){if(this.sessionImpressionCache)try{this.sessionStorage.set(Wi,this.sessionImpressionCache),this.log("Saved session impressions to storage")}catch(e){this.log("Failed to save session impressions",e)}}setupCrossTabSync(){this.crossTabSync&&(this.unsubscribeCrossTab=this.crossTabSync.on(Gi,e=>{this.handleCrossTabSync(e)}),this.log("Cross-tab sync initialized"))}handleCrossTabSync(e){this.stats.crossTabSyncs++;const{bannerId:t,impression:i,sessionImpression:r}=e;if(this.impressionCache){const e=this.impressionCache.impressions[t];(!e||i.lastSeenAt>e.lastSeenAt)&&(this.impressionCache.impressions[t]=i,this.impressionCache.updatedAt=this.now(),this.updateLruOrder(t),this.saveLifetimeToStorage(),this.log("Updated impression from cross-tab sync",{bannerId:t,count:i.count}))}if(r&&this.sessionImpressionCache&&r.sessionId===this.sessionId){const e=this.sessionImpressionCache.impressions[t];(!e||r.lastSeenAt>e.lastSeenAt)&&(this.sessionImpressionCache.impressions[t]=r,this.sessionImpressionCache.updatedAt=this.now(),this.saveSessionToStorage(),this.log("Updated session impression from cross-tab sync",{bannerId:t,count:r.count}))}}updateLruOrder(e){if(!this.impressionCache)return;const t=this.impressionCache.lruOrder.indexOf(e);for(-1!==t&&this.impressionCache.lruOrder.splice(t,1),this.impressionCache.lruOrder.push(e);this.impressionCache.lruOrder.length>Yi;){const e=this.impressionCache.lruOrder.shift();e&&(delete this.impressionCache.impressions[e],this.stats.lruEvictions++,this.log("Evicted oldest banner from tracking",{bannerId:e}))}this.stats.uniqueBannersTracked=this.impressionCache.lruOrder.length}ensureLifetimeCache(){if(!this.impressionCache){const e={version:1,impressions:{},updatedAt:this.now(),lruOrder:[]};void 0!==this.userId&&(e.userId=this.userId),this.impressionCache=e}return this.impressionCache}ensureSessionCache(){return this.sessionImpressionCache||(this.sessionImpressionCache={version:1,impressions:{},sessionId:this.sessionId,updatedAt:this.now()},this.stats.hasSessionData=!0),this.sessionImpressionCache}canShowBanner(e){var t,i,r,n;const s=e.frequencyCap;if(!s)return{canShow:!0,reason:"no_cap"};const o=e.id,a=this.now(),c=null==(t=this.impressionCache)?void 0:t.impressions[o],l=null==(i=this.sessionImpressionCache)?void 0:i.impressions[o];if(void 0!==s.maxImpressions&&c&&c.count>=s.maxImpressions)return this.stats.cappedDisplays++,{canShow:!1,reason:"max_impressions_reached",details:{impressionCount:c.count,maxImpressions:s.maxImpressions}};if(void 0!==s.maxImpressionsPerSession&&l&&l.count>=s.maxImpressionsPerSession)return this.stats.cappedDisplays++,{canShow:!1,reason:"max_session_impressions_reached",details:{sessionImpressionCount:l.count,maxSessionImpressions:s.maxImpressionsPerSession}};if(void 0!==s.cooldownMs&&c){const e=a-c.lastSeenAt;if(e<s.cooldownMs){const t=s.cooldownMs-e;return this.stats.cappedDisplays++,{canShow:!1,reason:"cooldown_active",details:{cooldownRemaining:t,nextAllowedAt:c.lastSeenAt+s.cooldownMs}}}}const u={impressionCount:null!=(r=null==c?void 0:c.count)?r:0,sessionImpressionCount:null!=(n=null==l?void 0:l.count)?n:0};return void 0!==s.maxImpressions&&(u.maxImpressions=s.maxImpressions),void 0!==s.maxImpressionsPerSession&&(u.maxSessionImpressions=s.maxImpressionsPerSession),{canShow:!0,details:u}}canShowBannerById(e,t){const i={id:e,name:"",content:{type:"inline"},rules:[],priority:0,active:!0,frequencyCap:t};return this.canShowBanner(i)}recordImpression(e){var t,i;const r=e,n=this.now(),s=this.ensureLifetimeCache(),o=s.impressions[r];o?(o.count++,o.lastSeenAt=n):s.impressions[r]={count:1,firstSeenAt:n,lastSeenAt:n},s.updatedAt=n,this.updateLruOrder(r),this.saveLifetimeToStorage();const a=this.ensureSessionCache(),c=a.impressions[r];if(c?(c.count++,c.lastSeenAt=n):a.impressions[r]={count:1,firstSeenAt:n,lastSeenAt:n,sessionId:this.sessionId},a.updatedAt=n,this.saveSessionToStorage(),this.crossTabSync){const e=s.impressions[r],t=a.impressions[r];if(e){const i={bannerId:r,impression:e,timestamp:n};t&&(i.sessionImpression=t),this.crossTabSync.broadcast(Gi,i)}}this.stats.totalImpressionsRecorded++,this.log("Recorded impression",{bannerId:r,lifetimeCount:null==(t=s.impressions[r])?void 0:t.count,sessionCount:null==(i=a.impressions[r])?void 0:i.count})}getImpression(e){var t,i;const r=e;return null!=(i=null==(t=this.impressionCache)?void 0:t.impressions[r])?i:null}getSessionImpression(e){var t,i;const r=e;return null!=(i=null==(t=this.sessionImpressionCache)?void 0:t.impressions[r])?i:null}getAllImpressions(){var e,t;return{...null!=(t=null==(e=this.impressionCache)?void 0:e.impressions)?t:{}}}resetImpressions(e){var t,i;if(e){const r=e;if(null==(t=this.impressionCache)?void 0:t.impressions[r]){delete this.impressionCache.impressions[r];const e=this.impressionCache.lruOrder.indexOf(r);-1!==e&&this.impressionCache.lruOrder.splice(e,1),this.impressionCache.updatedAt=this.now(),this.saveLifetimeToStorage(),this.stats.uniqueBannersTracked=this.impressionCache.lruOrder.length}(null==(i=this.sessionImpressionCache)?void 0:i.impressions[r])&&(delete this.sessionImpressionCache.impressions[r],this.sessionImpressionCache.updatedAt=this.now(),this.saveSessionToStorage()),this.log("Reset impressions for banner",{bannerId:r})}else{this.impressionCache=null,this.sessionImpressionCache=null;try{this.storage.set(Ki,null)}catch(e){}try{this.sessionStorage.set(Wi,null)}catch(e){}this.stats.uniqueBannersTracked=0,this.stats.hasSessionData=!1,this.log("Reset all impressions")}}filterEligibleBanners(e){return e.filter(e=>this.canShowBanner(e).canShow)}setSessionId(e){if(e!==this.sessionId)throw this.sessionImpressionCache=null,this.stats.hasSessionData=!1,new Error("Changing session ID after initialization is not supported. Create a new FrequencyCapManager instance with the new session ID.")}getStats(){return{...this.stats}}resetStats(){var e,t;this.stats={totalImpressionsRecorded:0,uniqueBannersTracked:null!=(t=null==(e=this.impressionCache)?void 0:e.lruOrder.length)?t:0,cappedDisplays:0,crossTabSyncs:0,lruEvictions:0,hasSessionData:null!==this.sessionImpressionCache,sessionId:this.sessionId}}destroy(){this.unsubscribeCrossTab&&(this.unsubscribeCrossTab(),this.unsubscribeCrossTab=null),this.impressionCache=null,this.sessionImpressionCache=null,this.log("Manager destroyed")}}}}),er={};function evaluate(e,t,i){return new Ai(i).getEligibleBanners(e,t)}function evaluateTopBanner(e,t,i){return new Ai(i).getTopBanner(e,t)}__export(er,{BANNER_CSS_PREFIX:()=>Li,BannerClient:()=>Pi,BannerRenderer:()=>qi,DEFAULT_ANIMATION_DURATION_MS:()=>Oi,DEFAULT_AUTO_DISMISS_MS:()=>Mi,DEFAULT_IMPRESSION_TTL_MS:()=>Qi,DEFAULT_SEGMENT_CACHE_TTL_MS:()=>Hi,FrequencyCapManager:()=>Xi,IMPRESSION_STORAGE_KEY:()=>Ki,IMPRESSION_SYNC_EVENT:()=>Gi,MAX_SEGMENTS:()=>Vi,MAX_TRACKED_BANNERS:()=>Yi,MODAL_Z_INDEX:()=>$i,RulesEngine:()=>Ai,SEGMENT_STORAGE_KEY:()=>zi,SESSION_IMPRESSION_STORAGE_KEY:()=>Wi,SLIDE_IN_Z_INDEX:()=>Fi,STICKY_BAR_Z_INDEX:()=>Ni,SegmentProvider:()=>Bi,and:()=>and,createBannerClient:()=>createBannerClient,createBannerId:()=>createBannerId,createBannerRenderer:()=>createBannerRenderer,createFrequencyCapManager:()=>createFrequencyCapManager,createRulesEngine:()=>createRulesEngine,createSegmentProvider:()=>createSegmentProvider,detectCurrentDeviceType:()=>detectCurrentDeviceType,escapeHTML:()=>escapeHTML2,evaluate:()=>evaluate,evaluateTopBanner:()=>evaluateTopBanner,generateBannerCSS:()=>generateBannerCSS,isBanner:()=>isBanner,isBannerClient:()=>isBannerClient,isBannerContent:()=>isBannerContent,isBannerId:()=>isBannerId,isBannerImpression:()=>isBannerImpression,isBannerRenderer:()=>isBannerRenderer,isBannerRule:()=>isBannerRule,isCartValueRule:()=>isCartValueRule,isDeviceRule:()=>isDeviceRule,isFrequencyCap:()=>isFrequencyCap,isFrequencyCapManager:()=>isFrequencyCapManager,isImpressionData:()=>isImpressionData,isPageUrlRule:()=>isPageUrlRule,isRecurringSchedule:()=>isRecurringSchedule,isRuleGroup:()=>isRuleGroup,isRulesEngine:()=>isRulesEngine,isSSR:()=>isSSR,isSegmentProvider:()=>isSegmentProvider,isSegmentRule:()=>isSegmentRule,isSessionImpressionData:()=>isSessionImpressionData,isTimeBasedRule:()=>isTimeBasedRule,not:()=>not,or:()=>or,sanitizeHTML:()=>sanitizeHTML});var tr=__esm({"src/banners/index.ts"(){Ri(),Di(),Ui(),ji(),Ji(),Zi(),Di()}}),ir="https://l1.overvio.ai",rr="https://ml-flask.overvio.ai",nr={modules:["events"],consent:{necessary:!0,analytics:!1,marketing:!1,functional:!1,waitForConsent:!1},endpoints:{events:ir,search:rr,recommendations:"https://ml-flask.overvio.ai",ml:"https://ml-flask.overvio.ai"},queue:{maxSize:100,flushInterval:5e3,maxRetries:3,persist:!0},storage:{type:"cookie",prefix:"overvio_",disablePersistence:!1,cookie:{secure:!1,sameSite:"Lax",domain:void 0,path:"/"},enableWarnings:!0},crossDomain:{enabled:!1,allowedDomains:void 0,acceptIncoming:!1,signatureSecret:void 0,expiryMs:12e4,autoCleanUrl:!0,decorateLinks:!0,linkSelector:"a[data-overvio-link]"},securityLogging:{enabled:!1,endpoint:void 0,callback:void 0,flushIntervalMs:3e4,maxQueueSize:100,redactPII:!0,eventFilter:void 0,headers:{},maxRetries:3},csp:{nonce:void 0,enableTrustedTypes:!1,trustedTypesPolicyName:"overvio-sdk"},debug:!1,logLevel:"error",plugins:[],pluginTimeout:5e3,trackingMode:"direct",respectGPC:!0,privacy:{piiProtection:{mode:"off",allowedFields:[],detectTypes:{ssn:!0,creditCard:!0,email:!0}},excludeUserAgent:!1,excludeScreenResolution:!1,excludeReferrer:!1,hashUrls:!1,sanitizeUrlParams:!0,additionalSensitiveParams:[],preserveParams:[],validatePropertyKeys:!0,additionalSuspiciousKeys:[]}};x();var sr=class _ConfigurationError extends e.OvervioError{constructor(e,t={}){const{configKey:i,expectedType:r,providedValue:n,defaultValue:s,cause:o,context:a={}}=t,c={...a};void 0!==i&&(c.configKey=i),void 0!==r&&(c.expectedType=r),super(e,"CONFIGURATION_ERROR",c,o),__publicField(this,"name","ConfigurationError"),__publicField(this,"configKey"),__publicField(this,"expectedType"),__publicField(this,"providedValue"),__publicField(this,"defaultValue"),this.configKey=i,this.expectedType=r,this.providedValue=n,this.defaultValue=s,Object.setPrototypeOf(this,new.target.prototype)}static missingRequired(e,t){const i=t?`Configuration "${e}" is required (expected: ${t})`:`Configuration "${e}" is required`,r={configKey:e};return void 0!==t&&(r.expectedType=t),new _ConfigurationError(i,r)}static invalidValue(e,t,i){return new _ConfigurationError(`Invalid value for "${e}": expected ${t}`,{configKey:e,expectedType:t,providedValue:i})}static incompatible(e,t){return new _ConfigurationError(`Incompatible configuration: ${t}`,{context:{configKeys:e}})}static isConfigurationError(e){return e instanceof _ConfigurationError}toJSON(){const e=super.toJSON();return isProductionEnvironment()?e:{...e,...void 0!==this.configKey&&{configKey:this.configKey},...void 0!==this.expectedType&&{expectedType:this.expectedType}}}},ar="cart";function isCartItem(e){if("object"!=typeof e||null===e)return!1;const t=e;return!("string"!=typeof t.productId||0===t.productId.length||"number"!=typeof t.quantity||!Number.isFinite(t.quantity)||void 0!==t.price&&"number"!=typeof t.price||void 0!==t.name&&"string"!=typeof t.name||void 0!==t.variant&&"string"!=typeof t.variant||void 0!==t.sku&&"string"!=typeof t.sku||void 0!==t.currency&&"string"!=typeof t.currency||void 0!==t.attributes&&!function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;for(const t of Object.keys(e))if("string"!=typeof e[t])return!1;return!0}(t.attributes))}function isCartState(e){if("object"!=typeof e||null===e)return!1;const t=e;return!(!Array.isArray(t.items)||!t.items.every(isCartItem)||"number"!=typeof t.updatedAt||!Number.isFinite(t.updatedAt)||void 0!==t.total&&"number"!=typeof t.total||void 0!==t.currency&&"string"!=typeof t.currency)}function createEmptyCartState(e=Date.now){return{items:[],updatedAt:e()}}function cloneCartState(e){const t={items:e.items.map(e=>{const t={productId:e.productId,quantity:e.quantity};return void 0!==e.price&&(t.price=e.price),void 0!==e.name&&(t.name=e.name),void 0!==e.variant&&(t.variant=e.variant),void 0!==e.sku&&(t.sku=e.sku),void 0!==e.currency&&(t.currency=e.currency),void 0!==e.attributes&&(t.attributes={...e.attributes}),t}),updatedAt:e.updatedAt};return void 0!==e.total&&(t.total=e.total),void 0!==e.currency&&(t.currency=e.currency),t}var cr=createEmptyCartState(()=>0),lr=class{constructor(){__publicField(this,"listeners",new Set)}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getStateSync(){return cr}async getState(){return cloneCartState(cr)}add(e){return{success:!1,state:cloneCartState(cr),error:"Cart not initialized"}}remove(e){return{success:!1,state:cloneCartState(cr),error:"Cart not initialized"}}update(e,t){return{success:!1,state:cloneCartState(cr),error:"Cart not initialized"}}clear(){return{success:!1,state:cloneCartState(cr),error:"Cart not initialized"}}getManager(){return null}},ur={page_view:"analytics",scroll_depth:"analytics",search_performed:"analytics",search_click:"analytics",search_autocomplete:"analytics",time_on_page:"analytics",session_start:"analytics",session_end:"analytics",product_view:"marketing",view_item:"marketing",view_item_list:"marketing",select_item:"marketing",add_to_cart:"marketing",remove_from_cart:"marketing",view_cart:"marketing",begin_checkout:"marketing",add_payment_info:"marketing",add_shipping_info:"marketing",purchase:"marketing",order_completed:"marketing",refund:"marketing",view_promotion:"marketing",select_promotion:"marketing",add_to_wishlist:"marketing",banner_view:"marketing",banner_click:"marketing",recommendation_view:"marketing",recommendation_click:"marketing",preference_update:"functional",user_segment:"functional",language_change:"functional",currency_change:"functional",theme_change:"functional",filter_apply:"functional",sort_change:"functional",identify:"necessary",logout:"necessary",error:"necessary",sdk_error:"necessary",consent_update:"necessary"};h();var dr=["necessary","analytics","marketing","functional"],hr={low:1,normal:2,high:3,critical:4};function isConsentCategory(e){return"string"==typeof e&&dr.includes(e)}function createDefaultConsentState(){return{necessary:!0,analytics:!1,marketing:!1,functional:!1,updatedAt:Date.now()}}function mergeConsentState(e,t){var i,r,n;const s=null!=e?e:createDefaultConsentState();return{necessary:!0,analytics:null!=(i=t.analytics)?i:s.analytics,marketing:null!=(r=t.marketing)?r:s.marketing,functional:null!=(n=t.functional)?n:s.functional,updatedAt:Date.now()}}function consentStatesEqual(e,t){return null===e&&null===t||null!==e&&null!==t&&e.necessary===t.necessary&&e.analytics===t.analytics&&e.marketing===t.marketing&&e.functional===t.functional}function getChangedCategories(e,t){const i={};return null===e?(i.analytics=t.analytics,i.marketing=t.marketing,i.functional=t.functional,i):(e.analytics!==t.analytics&&(i.analytics=t.analytics),e.marketing!==t.marketing&&(i.marketing=t.marketing),e.functional!==t.functional&&(i.functional=t.functional),i)}var gr=["granted","denied","withdrawn","updated","reset","loaded","expired"],pr=["user","cmp","api","cross-tab","init"],mr=class{constructor(e,t,i){var r,n,s;__publicField(this,"entries",[]),__publicField(this,"storage"),__publicField(this,"debug"),__publicField(this,"enabled"),__publicField(this,"maxEntries"),__publicField(this,"storageKey"),__publicField(this,"onAuditEntry"),__publicField(this,"onAuditError"),this.storage=null!=e?e:null,this.debug=null!=t?t:()=>{},this.enabled=null==(r=null==i?void 0:i.enabled)||r,this.maxEntries=null!=(n=null==i?void 0:i.maxEntries)?n:100,this.storageKey=null!=(s=null==i?void 0:i.storageKey)?s:"overvio_consent_audit",this.onAuditEntry=null==i?void 0:i.onAuditEntry,this.onAuditError=null==i?void 0:i.onAuditError}async init(){if(this.enabled&&this.storage)try{const e=this.storage.get(this.storageKey);Array.isArray(e)&&(this.entries=e.filter(this.isValidAuditEntry),this.debug("Loaded audit log from storage",{entryCount:this.entries.length}))}catch(e){this.debug("Error loading audit log from storage",{error:e}),this.entries=[]}}log(e,t,i,r,n,s){if(!this.enabled)return this.createEntry(e,t,i,r,n,s);const o=this.createEntry(e,t,i,r,n,s);for(this.entries.push(o);this.entries.length>this.maxEntries;)this.entries.shift();if(this.persistToStorage(),this.onAuditEntry)try{this.onAuditEntry(o)}catch(e){if(this.debug("Audit entry callback error",{error:e}),this.onAuditError)try{this.onAuditError(e,o)}catch(e){this.debug("Audit error callback also failed",{error:e})}}return this.debug("Consent audit entry logged",{id:o.id,action:e,categories:t,source:i}),o}logGranted(e,t,i,r,n){return this.log("granted",e,t,i,r,n)}logDenied(e,t,i,r,n){return this.log("denied",e,t,i,r,n)}logWithdrawn(e,t,i,r,n){return this.log("withdrawn",e,t,i,r,n)}logUpdated(e,t,i,r,n){return this.log("updated",e,t,i,r,n)}logReset(e,t,i,r){return this.log("reset",["analytics","marketing","functional"],e,t,i,r)}logLoaded(e,t){const i=[];return e.analytics&&i.push("analytics"),e.marketing&&i.push("marketing"),e.functional&&i.push("functional"),this.log("loaded",i,"init",null,e,t)}getAll(){return[...this.entries].reverse()}getByTimeRange(e,t){return this.entries.filter(i=>i.timestamp>=e&&i.timestamp<=t)}getByAction(e){return this.entries.filter(t=>t.action===e)}getLatest(){if(0===this.entries.length)return null;const e=this.entries.at(-1);return null!=e?e:null}get count(){return this.entries.length}export(){return{exportedAt:Date.now(),entryCount:this.entries.length,entries:[...this.entries]}}clear(){this.entries=[],this.storage&&this.storage.remove(this.storageKey),this.debug("Audit log cleared")}createEntry(e,t,i,r,n,s){const o={id:`audit_${Date.now()}_${secureRandomHex(8)}`,timestamp:Date.now(),action:e,categories:t,source:i,previousState:r?{necessary:r.necessary,analytics:r.analytics,marketing:r.marketing,functional:r.functional}:null,newState:{necessary:n.necessary,analytics:n.analytics,marketing:n.marketing,functional:n.functional}};return void 0!==s&&(o.metadata=s),o}persistToStorage(){if(this.storage)try{const e=this.entries.map(e=>({...e,_version:1}));this.storage.set(this.storageKey,e),this.debug("Audit log persisted to storage",{entryCount:this.entries.length})}catch(e){this.debug("Error persisting audit log",{error:e})}}isValidAuditEntry(e){if("object"!=typeof e||null===e)return!1;const t=e;if("string"!=typeof t.id||"number"!=typeof t.timestamp||"string"!=typeof t.action||!Array.isArray(t.categories)||"string"!=typeof t.source||"object"!=typeof t.newState)return!1;if(!gr.includes(t.action))return!1;if(!pr.includes(t.source))return!1;for(const e of t.categories)if(!isConsentCategory(e))return!1;return!0}},fr=class{constructor(e){__publicField(this,"adapter",null),__publicField(this,"unsubscribe",null),__publicField(this,"debug"),this.debug=null!=e?e:()=>{}}getAdapter(){return this.adapter}getName(){var e,t;return null!=(t=null==(e=this.adapter)?void 0:e.name)?t:null}isConnected(){return null!==this.adapter}connect(e,t){const{adapter:i,autoSync:r=!0,cmpTakesPrecedence:n=!0}=e;this.disconnect(),this.adapter=i,this.debug("CMP connected",{name:i.name});let s=null;if(r){const e=i.getConsent();e&&n&&(s=e)}if(i.onConsentChange){const e=i.onConsentChange(e=>{this.debug("CMP consent change received",{consent:e}),n&&t(e)});"function"==typeof e&&(this.unsubscribe=e)}return s}disconnect(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.adapter&&(this.debug("CMP disconnected",{name:this.adapter.name}),this.adapter=null)}showModal(){var e;(null==(e=this.adapter)?void 0:e.showConsentModal)?this.adapter.showConsentModal():this.debug("No CMP or showConsentModal not supported")}},yr=class{constructor(e,t){var i,r;__publicField(this,"events",new Map),__publicField(this,"releaseListeners",new Set),__publicField(this,"debug"),__publicField(this,"maxQueueSize"),__publicField(this,"maxEventAge"),__publicField(this,"onQueueOverflow"),__publicField(this,"onEventsExpired"),__publicField(this,"stats",{evictedCount:0,expiredCount:0}),this.debug=null!=e?e:()=>{},this.maxQueueSize=null!=(i=null==t?void 0:t.maxQueueSize)?i:1e3,this.maxEventAge=null!=(r=null==t?void 0:t.maxEventAge)?r:18e5,this.onQueueOverflow=null==t?void 0:t.onQueueOverflow,this.onEventsExpired=null==t?void 0:t.onEventsExpired}get size(){return this.events.size}queue(e,t,i="analytics",r="normal"){if(this.pruneExpiredEvents(),this.events.size>=this.maxQueueSize){const e=this.evictLowestPriorityEvents(1,r);if(this.stats.evictedCount+=e,e>0){if(this.debug("Queue overflow - evicted lowest priority event",{evictedCount:e,category:i,newEventPriority:r,queueSize:this.events.size}),this.onQueueOverflow)try{this.onQueueOverflow(e,i)}catch(e){this.debug("Queue overflow callback error",{error:e})}}else this.debug("Queue at capacity with no lower-priority events to evict",{category:i,newEventPriority:r,queueSize:this.events.size})}const n=secureRandomUUID(),s={id:n,event:e,requiredCategory:i,queuedAt:Date.now(),method:t,priority:r};return this.events.set(n,s),this.debug("Event queued pending consent",{id:n,method:t,requiredCategory:i,priority:r}),n}remove(e){return this.events.delete(e)}getAll(){return Array.from(this.events.values())}clear(){this.events.clear()}clearCategories(e){const t=new Set(e);let i=0;for(const[e,r]of this.events)t.has(r.requiredCategory)&&(this.events.delete(e),i++);return i>0&&this.debug("Cleared events for categories",{categories:e,clearedCount:i}),i}onRelease(e){return this.releaseListeners.add(e),()=>{this.releaseListeners.delete(e)}}clearListeners(){this.releaseListeners.clear()}resetStats(){this.stats.evictedCount=0,this.stats.expiredCount=0,this.debug("Queue statistics reset")}getStats(){const e={};for(const t of dr)e[t]=0;let t=null;for(const i of this.events.values())e[i.requiredCategory]++,(null===t||i.queuedAt<t)&&(t=i.queuedAt);return{totalEvents:this.events.size,eventsByCategory:e,evictedCount:this.stats.evictedCount,expiredCount:this.stats.expiredCount,oldestEventTimestamp:t}}processAfterConsentChange(e,t){if(this.pruneExpiredEvents(),0===this.events.size)return{released:0,discarded:0,releasedEvents:[],discardedEvents:[]};const i=getChangedCategories(t,e),r={released:0,discarded:0,releasedEvents:[],discardedEvents:[]};for(const[t,n]of this.events){const s=n.requiredCategory;s in i&&(e[s]?(r.released++,r.releasedEvents.push(n),this.events.delete(t),this.debug("Pending event released",{id:t,category:s})):(r.discarded++,r.discardedEvents.push(n),this.events.delete(t),this.debug("Pending event discarded",{id:t,category:s})))}if(r.releasedEvents.length>0)for(const e of this.releaseListeners)try{e(r.releasedEvents)}catch(e){this.debug("Release listener error",{error:e})}return this.debug("Pending events processed",{released:r.released,discarded:r.discarded,remaining:this.events.size}),r}pruneExpiredEvents(){const e=Date.now(),t=e-this.maxEventAge;let i=0;for(const[r,n]of this.events)n.queuedAt<t&&(this.events.delete(r),i++,this.debug("Event expired and pruned",{id:r,age:e-n.queuedAt,category:n.requiredCategory}));if(i>0&&(this.stats.expiredCount+=i,this.debug("Pruned expired events",{prunedCount:i,remaining:this.events.size}),this.onEventsExpired))try{this.onEventsExpired(i)}catch(e){this.debug("Events expired callback error",{error:e})}return i}evictLowestPriorityEvents(e,t){var i,r;if(e<=0||0===this.events.size)return 0;const n=hr[t];let s=0;const o=[],a=[];for(const[e,t]of this.events){const r=null!=(i=t.priority)?i:"normal",s=hr[r];"critical"!==r&&(s<n?o.push({id:e,event:t,priorityValue:s}):s===n&&a.push({id:e,event:t,priorityValue:s}))}let c=o,l=!1;0===o.length&&a.length>0&&(c=a,l=!0),c.sort((e,t)=>e.priorityValue!==t.priorityValue?e.priorityValue-t.priorityValue:e.event.queuedAt-t.event.queuedAt);for(const t of c){if(s>=e)break;this.events.delete(t.id),s++,this.debug(l?"Event evicted (FIFO fallback)":"Event evicted (priority-based)",{id:t.id,category:t.event.requiredCategory,priority:null!=(r=t.event.priority)?r:"normal",age:Date.now()-t.event.queuedAt})}return s}},vr=class{constructor(e,t={}){var i,r,n,s,o,a,c,l,u,d,h,g,p,m,f;__publicField(this,"state",null),__publicField(this,"storage"),__publicField(this,"emitter"),__publicField(this,"crossTabSync"),__publicField(this,"pendingQueue"),__publicField(this,"cmpManager"),__publicField(this,"auditLog"),__publicField(this,"pendingTimeoutTimer",null),__publicField(this,"categoryStorageKeys"),__publicField(this,"options"),__publicField(this,"changeListeners",new Set),__publicField(this,"crossTabUnsubscribe",null),__publicField(this,"initialized",!1),__publicField(this,"destroyed",!1),__publicField(this,"isUpdating",!1),__publicField(this,"pendingUpdateQueue",[]),this.storage=e,this.emitter=null!=(i=t.emitter)?i:null,this.crossTabSync=null!=(r=t.crossTabSync)?r:null;const y="undefined"!=typeof window&&"https:"===(null==(n=window.location)?void 0:n.protocol);this.options={defaultConsent:null!=(s=t.defaultConsent)?s:{analytics:!1,marketing:!1,functional:!1},waitForConsent:null!=(o=t.waitForConsent)&&o,requiredCategories:null!=(a=t.requiredCategories)?a:["analytics"],cookieName:null!=(c=t.cookieName)?c:"consent",cookieMaxAge:null!=(l=t.cookieMaxAge)?l:31536e3,cookieDomain:t.cookieDomain,cookieSecure:null!=(u=t.cookieSecure)?u:y,enableCrossTabSync:null==(d=t.enableCrossTabSync)||d,debug:null!=(h=t.debug)&&h,currentPolicyVersion:t.currentPolicyVersion,onPolicyVersionMismatch:t.onPolicyVersionMismatch,auditConfig:null!=(g=t.auditConfig)?g:{},queueConfig:null!=(p=t.queueConfig)?p:{},pendingTimeout:null!=(m=t.pendingTimeout)?m:{}},this.categoryStorageKeys=null!=(f=t.categoryStorageKeys)?f:{};const v=this.debug.bind(this);this.pendingQueue=new yr(v,this.options.queueConfig),this.cmpManager=new fr(v),this.auditLog=new mr(e,v,this.options.auditConfig),t.onConsentChange&&this.changeListeners.add(t.onConsentChange)}async init(){if(this.initialized)this.debug("Already initialized");else{if(this.destroyed)throw new Error("Cannot initialize a destroyed ConsentManager");if(this.debug("Initializing ConsentManager"),await this.auditLog.init(),await this.loadFromStorage(),this.state){const e=void 0!==this.options.currentPolicyVersion?{policyVersion:this.options.currentPolicyVersion}:void 0;this.auditLog.logLoaded(this.state,e)}this.checkPolicyVersionMismatch(),this.options.enableCrossTabSync&&this.crossTabSync&&this.setupCrossTabSync(),this.options.waitForConsent&&!this.state&&this.startPendingTimeout(),this.initialized=!0,this.debug("ConsentManager initialized",{state:this.state})}}checkPolicyVersionMismatch(){const e=this.options.currentPolicyVersion;if(!e)return;if(!this.state)return;const t=this.state.policyVersion;if(t!==e&&(this.debug("Policy version mismatch detected",{storedVersion:t,currentVersion:e}),this.options.onPolicyVersionMismatch))try{this.options.onPolicyVersionMismatch(t,e)}catch(e){this.debug("Error in onPolicyVersionMismatch callback",{error:e})}}async loadFromStorage(){try{const t=this.storage.get(this.options.cookieName);if(t&&function(e){if("object"!=typeof e||null===e)return!1;const t=e;return!0===t.necessary&&"boolean"==typeof t.analytics&&"boolean"==typeof t.marketing&&"boolean"==typeof t.functional&&"number"==typeof t.updatedAt}(e=t)&&"number"==typeof e._version){const e=t.policyVersion;this.state={necessary:!0,analytics:t.analytics,marketing:t.marketing,functional:t.functional,updatedAt:t.updatedAt,...void 0!==e&&{policyVersion:e}},this.debug("Loaded consent from storage",{state:this.state})}else this.options.waitForConsent?this.debug("No consent stored, waiting for user consent"):(this.state=mergeConsentState(null,this.options.defaultConsent),this.debug("Using default consent",{state:this.state}))}catch(e){this.debug("Error loading consent from storage",{error:e})}var e}setupCrossTabSync(){this.crossTabSync&&(this.crossTabUnsubscribe=this.crossTabSync.on("CONSENT_CHANGED",e=>{try{this.debug("Received cross-tab consent change",{payload:e}),this.handleCrossTabConsentChange(e)}catch(e){this.debug("Error handling cross-tab consent change",{error:e})}}),this.debug("Cross-tab sync enabled"))}handleCrossTabConsentChange(e){const t={necessary:!0,analytics:e.analytics,marketing:e.marketing,functional:e.functional,updatedAt:e.updatedAt};if(!consentStatesEqual(this.state,t)){const e=this.state;this.state=t,this.persistToStorage(),this.notifyChangeListeners(t,e),this.emitConsentChangeEvent(t),this.pendingQueue.processAfterConsentChange(t,e)}}getConsent(){return this.state?{...this.state}:null}hasConsent(e){return this.state?this.state[e]:"necessary"===e}setConsent(e,t){if(this.destroyed)return void this.debug("Cannot setConsent on destroyed manager");if("necessary"===e)return void this.debug("Cannot change necessary consent - always true");const i={[e]:t};this.updateConsent(i)}updateConsent(e,t="user"){if(this.destroyed)this.debug("Cannot updateConsent on destroyed manager");else{if(this.isUpdating)return this.pendingUpdateQueue.push({updates:e,source:t}),void this.debug("Reentrant updateConsent detected, queuing update with source:",t);this.isUpdating=!0;try{this.executeConsentUpdate(e,t)}finally{for(this.isUpdating=!1;this.pendingUpdateQueue.length>0;){const e=this.pendingUpdateQueue.shift();this.debug("Processing queued pending update with source:",e.source),this.isUpdating=!0;try{this.executeConsentUpdate(e.updates,e.source)}finally{this.isUpdating=!1}}}}}executeConsentUpdate(e,t){const i=this.state;let r=mergeConsentState(i,e);if(this.options.currentPolicyVersion&&(this.validatePolicyVersionFormat(this.options.currentPolicyVersion),r={...r,policyVersion:this.options.currentPolicyVersion}),consentStatesEqual(i,r))return void this.debug("No consent change detected");this.clearPendingTimeout(),this.state=r,this.debug("Consent updated",{previous:i,new:r});const n=getChangedCategories(i,r),s=Object.keys(n),o=s.filter(e=>!0===n[e]),a=s.filter(e=>!1===n[e]&&!0===(null==i?void 0:i[e])),c=a.length>0?o.length>0?"updated":"withdrawn":o.length>0?"granted":"updated",l=void 0!==this.options.currentPolicyVersion?{policyVersion:this.options.currentPolicyVersion}:void 0;this.auditLog.log(c,s,t,i,r,l),this.persistToStorage(),this.broadcastConsentChange(r),this.notifyChangeListeners(r,i),this.emitConsentChangeEvent(r),this.pendingQueue.processAfterConsentChange(r,i),a.length>0&&this.handleConsentWithdrawal(a,!1)}setAllConsent(e){this.updateConsent({analytics:e,marketing:e,functional:e})}resetConsent(){if(this.destroyed)return void this.debug("Cannot resetConsent on destroyed manager");const e=this.state,t=createDefaultConsentState();if(this.state=null,this.storage.remove(this.options.cookieName),e){const i=void 0!==this.options.currentPolicyVersion?{policyVersion:this.options.currentPolicyVersion}:void 0;this.auditLog.logReset("user",e,t,i)}if(this.options.enableCrossTabSync&&this.crossTabSync&&e&&this.crossTabSync.broadcast("CONSENT_CHANGED",{necessary:!0,analytics:t.analytics,marketing:t.marketing,functional:t.functional,updatedAt:t.updatedAt}),this.debug("Consent reset"),e){for(const i of this.changeListeners)try{i(t,e)}catch(e){this.debug("Change listener error",{error:e})}const i=[];e.analytics&&i.push("analytics"),e.marketing&&i.push("marketing"),e.functional&&i.push("functional"),i.length>0&&this.handleConsentWithdrawal(i,!0)}this.options.waitForConsent&&this.startPendingTimeout()}persistToStorage(){if(!this.state)return;const e={...this.state,_version:1};try{this.storage.setCookie(this.options.cookieName,e,{maxAge:this.options.cookieMaxAge,...void 0!==this.options.cookieDomain&&{domain:this.options.cookieDomain},secure:this.options.cookieSecure,sameSite:this.options.cookieSecure?"None":"Lax",path:"/"}),this.debug("Consent persisted to storage")}catch(e){this.debug("Error persisting consent",{error:e})}}broadcastConsentChange(e){if(!this.options.enableCrossTabSync||!this.crossTabSync)return;const t={necessary:!0,analytics:e.analytics,marketing:e.marketing,functional:e.functional,updatedAt:e.updatedAt};this.crossTabSync.broadcast("CONSENT_CHANGED",t),this.debug("Consent change broadcast to other tabs")}emitConsentChangeEvent(e){this.emitter&&this.emitter.emit("consent:change",function(e){return{necessary:e.necessary,analytics:e.analytics,marketing:e.marketing,functional:e.functional,updatedAt:new Date(e.updatedAt)}}(e))}notifyChangeListeners(e,t){for(const i of this.changeListeners)try{i(e,t)}catch(e){this.debug("Change listener error",{error:e})}}onConsentChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}queueEvent(e,t,i="analytics"){return this.pendingQueue.queue(e,t,i)}removePendingEvent(e){return this.pendingQueue.remove(e)}getPendingEvents(){return this.pendingQueue.getAll()}get pendingEventCount(){return this.pendingQueue.size}onEventsReleased(e){return this.pendingQueue.onRelease(e)}shouldQueueEvent(e){return!!this.options.waitForConsent&&!!this.options.requiredCategories.includes(e)&&!this.hasConsent(e)}connectCMP(e){if(this.destroyed)return void this.debug("Cannot connectCMP on destroyed manager");const t=this.cmpManager.connect(e,e=>{this.updateConsent(e)});t&&this.updateConsent(t)}disconnectCMP(){this.cmpManager.disconnect()}getCMP(){return this.cmpManager.getAdapter()}showConsentModal(){this.cmpManager.showModal()}getStats(){return{hasConsent:null!==this.state,currentState:this.getConsent(),pendingEventCount:this.pendingQueue.size,crossTabSyncEnabled:this.options.enableCrossTabSync&&null!==this.crossTabSync,cmpConnected:this.cmpManager.isConnected(),cmpName:this.cmpManager.getName()}}get hasCollectedConsent(){return null!==this.state}get isInitialized(){return this.initialized}getCategories(){return dr}getRequiredCategories(){return[...this.options.requiredCategories]}getAuditLog(){return this.auditLog}handleConsentWithdrawal(e,t){const i={categories:e,timestamp:Date.now(),isFullReset:t};this.emitter&&(this.emitter.emit("consent:purge",i),this.debug("Consent purge event emitted",{categories:e,isFullReset:t})),this.pendingQueue.clearCategories(e);for(const t of e){const e=this.categoryStorageKeys[t];if(e&&e.length>0)for(const i of e)try{this.storage.remove(i),this.debug("Purged storage key",{category:t,key:i})}catch(e){this.debug("Error purging storage key",{category:t,key:i,error:e})}}this.debug("Consent withdrawal handled",{categories:e,isFullReset:t})}startPendingTimeout(){var e;if(!this.options.pendingTimeout.enabled)return;this.clearPendingTimeout();const t=null!=(e=this.options.pendingTimeout.timeoutMs)?e:3e5;this.pendingTimeoutTimer=setTimeout(()=>{if(!this.destroyed){if(this.debug("Pending consent timeout reached"),this.emitter&&this.emitter.emit("consent:timeout"),this.options.pendingTimeout.onTimeout)try{this.options.pendingTimeout.onTimeout()}catch(e){this.debug("Pending timeout callback error",{error:e})}this.options.pendingTimeout.applyDefaultsOnTimeout&&(this.updateConsent(this.options.defaultConsent,"api"),this.debug("Applied default consent on timeout"))}},t),this.debug("Pending consent timeout started",{timeoutMs:t})}clearPendingTimeout(){this.pendingTimeoutTimer&&(clearTimeout(this.pendingTimeoutTimer),this.pendingTimeoutTimer=null,this.debug("Pending consent timeout cleared"))}destroy(){this.destroyed||(this.debug("Destroying ConsentManager"),this.clearPendingTimeout(),this.cmpManager.disconnect(),this.crossTabUnsubscribe&&(this.crossTabUnsubscribe(),this.crossTabUnsubscribe=null),this.changeListeners.clear(),this.pendingQueue.clearListeners(),this.pendingQueue.clear(),this.destroyed=!0,this.debug("ConsentManager destroyed"))}validatePolicyVersionFormat(e){/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?$/.test(e)||/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/.test(e)||/^\d+\.\d+$/.test(e)||this.debug(`Policy version "${e}" does not match expected formats. Recommended formats: semver (e.g., "1.0.0") or date (e.g., "2024-01-15"). The value will still be used.`,{version:e})}debug(e,t){this.options.debug}};R();var br={minAttempts:1,maxAttempts:10,minDelayMs:50,maxDelayMs:3e5,minMultiplier:1,maxMultiplier:10},Sr={minTimeoutMs:100,maxTimeoutMs:6e5},wr={maxAttempts:3,initialDelayMs:1e3,maxDelayMs:3e4,multiplier:2,jitter:"full",retryableStatusCodes:[408,429,500,502,503,504],retryOnNetworkError:!0,skipRetryForNonIdempotent:!1},Cr=["GET","PUT","DELETE"];function calculateRetryDelay(e,t,i){const r=t.initialDelayMs*Math.pow(t.multiplier,e-1);return function(e,t,i,r){switch(t){case"none":default:return{delayMs:e,newLastDelay:e};case"full":{const t=Math.random()*e;return{delayMs:Math.floor(t),newLastDelay:t}}case"equal":{const t=e/2+Math.random()*(e/2);return{delayMs:Math.floor(t),newLastDelay:t}}case"decorrelated":{const e=i.initialDelayMs,t=Math.min(i.maxDelayMs,e+Math.random()*(3*r-e)),n=Math.max(e,t);return{delayMs:Math.floor(n),newLastDelay:t}}}}(Math.min(r,t.maxDelayMs),t.jitter,t,i)}function parseRetryAfterHeader(e){if(!e)return;const t=parseInt(e,10);if(!isNaN(t))return 1e3*t;const i=new Date(e);if(!isNaN(i.getTime())){const e=i.getTime()-Date.now();return Math.max(0,e)}}function shouldRetryRequest(e,t,i,r,n){return!(r>=i.maxAttempts-1||!i.retryableStatusCodes.includes(e)||i.skipRetryForNonIdempotent&&!Cr.includes(t)&&!n)}function isIdempotentOrHasKey(e,t,i){return!!t||!!Cr.includes(e)||!i.skipRetryForNonIdempotent}function delay(e){return new Promise(t=>setTimeout(t,e))}var Er={failureThreshold:5,resetTimeoutMs:3e4,successThreshold:2,windowMs:6e4},_r=class{constructor(e={}){__publicField(this,"state","closed"),__publicField(this,"failures",[]),__publicField(this,"successes",0),__publicField(this,"lastFailureTime",0),__publicField(this,"config"),this.config={...Er,...e}}canRetry(){switch(this.pruneOldFailures(),this.state){case"closed":case"half-open":return!0;case"open":return Date.now()-this.lastFailureTime>=this.config.resetTimeoutMs&&(this.state="half-open",this.successes=0,!0)}}recordSuccess(){"half-open"===this.state&&(this.successes++,this.successes>=this.config.successThreshold&&(this.state="closed",this.failures=[]))}recordFailure(){const e=Date.now();this.failures.push(e),this.lastFailureTime=e,this.pruneOldFailures(),("half-open"===this.state||this.failures.length>=this.config.failureThreshold)&&(this.state="open")}getState(){return this.state}reset(){this.state="closed",this.failures=[],this.successes=0,this.lastFailureTime=0}pruneOldFailures(){const e=Date.now()-this.config.windowMs;this.failures=this.failures.filter(t=>t>e)}};x();var Ir=class _AuthenticationError extends e.OvervioError{constructor(e,t={}){const{url:i,method:r,cause:n,context:s={}}=t,o={...s};void 0!==i&&(o.url=i),void 0!==r&&(o.method=r),super(e,"AUTHENTICATION_ERROR",o,n),__publicField(this,"name","AuthenticationError"),__publicField(this,"url"),__publicField(this,"method"),this.url=i,this.method=r,Object.setPrototypeOf(this,new.target.prototype)}static fromResponse(e,t,i,r){const n=null!=r?r:`HTTP 401: ${e.statusText||"Authentication required"}`,s={url:null!=t?t:e.url};return void 0!==i&&(s.method=i),new _AuthenticationError(n,s)}static isAuthenticationError(e){return e instanceof _AuthenticationError}toJSON(){return{...super.toJSON(),...void 0!==this.url&&{url:this.url},...void 0!==this.method&&{method:this.method}}}};x();var kr=class _AuthorizationError extends e.OvervioError{constructor(e,t={}){const{url:i,method:r,resource:n,cause:s,context:o={}}=t,a={...o};void 0!==i&&(a.url=i),void 0!==r&&(a.method=r),void 0!==n&&(a.resource=n),super(e,"AUTHORIZATION_ERROR",a,s),__publicField(this,"name","AuthorizationError"),__publicField(this,"url"),__publicField(this,"method"),__publicField(this,"resource"),this.url=i,this.method=r,this.resource=n,Object.setPrototypeOf(this,new.target.prototype)}static fromResponse(e,t,i,r){const n=null!=r?r:`HTTP 403: ${e.statusText||"Access denied"}`,s={url:null!=t?t:e.url};return void 0!==i&&(s.method=i),new _AuthorizationError(n,s)}static isAuthorizationError(e){return e instanceof _AuthorizationError}toJSON(){return{...super.toJSON(),...void 0!==this.url&&{url:this.url},...void 0!==this.method&&{method:this.method},...void 0!==this.resource&&{resource:this.resource}}}};P(),x();var xr=class _NotFoundError extends e.OvervioError{constructor(e,t={}){const{url:i,method:r,resource:n,resourceType:s,cause:o,context:a={}}=t,c={...a};void 0!==i&&(c.url=i),void 0!==r&&(c.method=r),void 0!==n&&(c.resource=n),void 0!==s&&(c.resourceType=s),super(e,"NOT_FOUND",c,o),__publicField(this,"name","NotFoundError"),__publicField(this,"url"),__publicField(this,"method"),__publicField(this,"resource"),__publicField(this,"resourceType"),this.url=i,this.method=r,this.resource=n,this.resourceType=s,Object.setPrototypeOf(this,new.target.prototype)}static fromResponse(e,t,i,r){const n=null!=r?r:`HTTP 404: ${e.statusText||"Resource not found"}`,s={url:null!=t?t:e.url};return void 0!==i&&(s.method=i),new _NotFoundError(n,s)}static isNotFoundError(e){return e instanceof _NotFoundError}toJSON(){return{...super.toJSON(),...void 0!==this.url&&{url:this.url},...void 0!==this.method&&{method:this.method},...void 0!==this.resource&&{resource:this.resource},...void 0!==this.resourceType&&{resourceType:this.resourceType}}}};D(),L(),M();var Tr=null,Ar=null;function getRuntime(){return null!==Tr?Tr:Tr="undefined"!=typeof self&&void 0!==globalThis.WorkerGlobalScope?"web-worker":"undefined"!=typeof window&&"undefined"!=typeof document?"browser":void 0!==globalThis.Deno?"deno":void 0!==globalThis.Bun?"bun":"undefined"!=typeof process&&"edge"===(null==(e=process.env)?void 0:e.NEXT_RUNTIME)?"vercel-edge":void 0!==globalThis.caches&&void 0===(null==(t=globalThis.navigator)?void 0:t.userAgent)&&"undefined"==typeof window?"cloudflare-worker":"undefined"!=typeof process&&(null==(i=process.versions)?void 0:i.node)?"node":"unknown";var e,t,i}function isBrowser(){return"browser"===getRuntime()}function isServer(){const e=getRuntime();return"node"===e||"deno"===e||"bun"===e}function isEdge(){const e=getRuntime();return"cloudflare-worker"===e||"vercel-edge"===e}function isWorker(){return"web-worker"===getRuntime()}function hasLocalStorageAccess(){try{if("undefined"==typeof localStorage)return!1;const e="__overvio_storage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}function getCapabilities(){return null!==Ar?Ar:Ar={hasFetch:void 0!==globalThis.fetch,hasLocalStorage:hasLocalStorageAccess(),hasCookies:"undefined"!=typeof document&&"cookie"in document,hasDOM:"undefined"!=typeof document,hasBroadcastChannel:"undefined"!=typeof BroadcastChannel,hasAbortController:"undefined"!=typeof AbortController}}function getFetchUnavailableErrorMessage(e){return`[Overvio] fetch is not available in this environment (${e}).\n\nSolutions:\n1. Upgrade to Node.js 18+ (has native fetch)\n2. Install a polyfill:\n npm install cross-fetch\n # Then: import 'cross-fetch/polyfill';\n3. Inject fetch manually:\n import fetch from 'cross-fetch';\n Overvio.init({ apiKey: 'pk_live_...', fetch });\n\nSee: https://docs.overvio.com/sdk/ssr/fetch-polyfill`}h();var Rr="0.0.1",Pr="@overvio/sdk",Dr=`${Pr}@${Rr}`,Lr=class _HttpClientWithInterceptors{constructor(e){var t,i,r,n;__publicField(this,"baseUrl"),__publicField(this,"defaultTimeout"),__publicField(this,"defaultHeaders"),__publicField(this,"fetchImpl"),__publicField(this,"retryConfig"),__publicField(this,"debug"),__publicField(this,"logger"),__publicField(this,"requestInterceptors",[]),__publicField(this,"responseInterceptors",[]),__publicField(this,"errorInterceptors",[]),__publicField(this,"circuitBreaker");const s=null!=(t=e.fetch)?t:globalThis.fetch;if(!s){const e=getRuntime();throw new sr(getFetchUnavailableErrorMessage(e),{configKey:"fetch",expectedType:"typeof fetch",context:{runtime:e}})}if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.defaultHeaders={"Content-Type":"application/json","X-SDK-Version":`overvio-sdk/${Rr}`,...e.headers},this.fetchImpl=s,this.debug=null!=(i=e.debug)&&i,this.logger=null!=(r=e.logger)?r:{debug:console.debug.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},this.defaultTimeout=null!=(n=function(e,t){if(void 0===e)return;const{minTimeoutMs:i,maxTimeoutMs:r}=Sr,n=Math.max(i,Math.min(r,e));return n!==e&&(null==t||t.warn(`[HTTP] timeout (${e}ms) clamped to bounds [${i}, ${r}]ms`)),n}(e.timeout,this.logger))?n:1e4,!1===e.retry)this.retryConfig=!1;else{const t={...wr,...e.retry};this.retryConfig=function(e,t){if(!e)return{};const i={...e},{minAttempts:r,maxAttempts:n,minDelayMs:s,maxDelayMs:o,minMultiplier:a,maxMultiplier:c}=br;if(void 0!==e.maxAttempts){const s=Math.max(r,Math.min(n,e.maxAttempts));s!==e.maxAttempts&&(null==t||t.warn(`[HTTP] retry.maxAttempts (${e.maxAttempts}) clamped to bounds [${r}, ${n}]`),i.maxAttempts=s)}if(void 0!==e.initialDelayMs){const r=Math.max(s,Math.min(o,e.initialDelayMs));r!==e.initialDelayMs&&(null==t||t.warn(`[HTTP] retry.initialDelayMs (${e.initialDelayMs}) clamped to bounds [${s}, ${o}]`),i.initialDelayMs=r)}if(void 0!==e.maxDelayMs){const r=Math.max(s,Math.min(o,e.maxDelayMs));r!==e.maxDelayMs&&(null==t||t.warn(`[HTTP] retry.maxDelayMs (${e.maxDelayMs}) clamped to bounds [${s}, ${o}]`),i.maxDelayMs=r)}if(void 0!==e.multiplier){const r=Math.max(a,Math.min(c,e.multiplier));r!==e.multiplier&&(null==t||t.warn(`[HTTP] retry.multiplier (${e.multiplier}) clamped to bounds [${a}, ${c}]`),i.multiplier=r)}return i}(t,this.logger)}this.circuitBreaker=new _r({failureThreshold:5,resetTimeoutMs:3e4,windowMs:6e4}),this.baseUrl.startsWith("https://")}addRequestInterceptor(e){return this.requestInterceptors.push(e),()=>{const t=this.requestInterceptors.indexOf(e);t>-1&&this.requestInterceptors.splice(t,1)}}addResponseInterceptor(e){return this.responseInterceptors.push(e),()=>{const t=this.responseInterceptors.indexOf(e);t>-1&&this.responseInterceptors.splice(t,1)}}addErrorInterceptor(e){return this.errorInterceptors.push(e),()=>{const t=this.errorInterceptors.indexOf(e);t>-1&&this.errorInterceptors.splice(t,1)}}get requestInterceptorCount(){return this.requestInterceptors.length}get responseInterceptorCount(){return this.responseInterceptors.length}get errorInterceptorCount(){return this.errorInterceptors.length}clearInterceptors(){this.requestInterceptors.length=0,this.responseInterceptors.length=0,this.errorInterceptors.length=0}async get(e,t){return this.requestWithRetry("GET",e,void 0,t)}async getOptional(e,t){return this.requestWithRetry("GET",e,void 0,t)}async post(e,t,i){return this.requestWithRetry("POST",e,t,i)}async put(e,t,i){return this.requestWithRetry("PUT",e,t,i)}async delete(e,t){return this.requestWithRetry("DELETE",e,void 0,t)}async deleteOptional(e,t){return this.requestWithRetry("DELETE",e,void 0,t)}async patch(e,t,i){return this.requestWithRetry("PATCH",e,t,i)}async requestWithResponse(e,t,i,r){const n=Date.now();let s=this.buildInterceptorConfig(e,t,i,r);(null==r?void 0:r.skipRequestInterceptors)||(s=await this.runRequestInterceptors(s));let o={response:await this.executeWithRetry(s,r),request:s,durationMs:Date.now()-n};return(null==r?void 0:r.skipResponseInterceptors)||(o=await this.runResponseInterceptors(o)),{data:await this.parseResponse(o.response,s.url,e),status:o.response.status,statusText:o.response.statusText,headers:o.response.headers}}async requestWithRetry(e,t,i,r){const n=Date.now();let s=this.buildInterceptorConfig(e,t,i,r);(null==r?void 0:r.skipRequestInterceptors)||(s=await this.runRequestInterceptors(s));try{let t={response:await this.executeWithRetry(s,r),request:s,durationMs:Date.now()-n};return(null==r?void 0:r.skipResponseInterceptors)||(t=await this.runResponseInterceptors(t)),this.parseResponse(t.response,s.url,e)}catch(e){throw await this.runErrorInterceptors(e,s),e}}buildInterceptorConfig(e,t,i,r={}){var n;const s=this.buildUrl(t,r.params),o={...this.defaultHeaders,...r.headers},a=null!=(n=r.timeout)?n:this.defaultTimeout;o["X-Request-ID"]||(o["X-Request-ID"]=this.generateRequestId());const c={method:e,url:s,headers:o,timeout:a,retryAttempt:0};return r.signal&&(c.signal=r.signal),r.idempotencyKey&&(c.idempotencyKey=r.idempotencyKey,c.headers["Idempotency-Key"]=r.idempotencyKey),void 0!==i&&(c.body=JSON.stringify(i)),c}generateRequestId(){return secureRandomUUID()}buildUrl(e,t){const i=e.startsWith("/")?e:`/${e}`;let r=`${this.baseUrl}${i}`;if(t){const e=new URLSearchParams;for(const[i,r]of Object.entries(t))null!=r&&e.append(i,String(r));const i=e.toString();i&&(r+=`?${i}`)}return r}async runRequestInterceptors(e){let t=e;for(const e of this.requestInterceptors)t=await e(t);return t}async runResponseInterceptors(e){let t=e;for(const e of this.responseInterceptors)t=await e(t);return t}async runErrorInterceptors(e,t){for(const i of this.errorInterceptors)await i(e,t)}async executeWithRetry(t,i){const r=(n=this.retryConfig,s=null==i?void 0:i.retry,!1!==n&&!1!==s&&(s?{...n,...s}:n));var n,s;if(!r)return this.executeRequest(t);if(!this.circuitBreaker.canRetry())throw this.debug&&this.logger.warn(`[HttpClient] Circuit breaker open, failing fast for ${t.method} ${t.url}`),new e.NetworkError("Circuit breaker open - too many recent failures",{url:t.url,method:t.method,retryable:!1});let o,a,c=r.initialDelayMs;for(let i=0;i<r.maxAttempts;i++){if(t.retryAttempt=i,i>0){if(!this.circuitBreaker.canRetry())throw this.debug&&this.logger.warn(`[HttpClient] Circuit breaker opened during retries for ${t.method} ${t.url}`),new e.NetworkError("Circuit breaker open - too many recent failures",{url:t.url,method:t.method,retryable:!1});const n=void 0!==a?{delayMs:a,newLastDelay:c}:calculateRetryDelay(i,r,c);c=n.newLastDelay,a=void 0,this.debug&&this.logger.debug(`[HttpClient] Retry attempt ${i} for ${t.method} ${t.url}, waiting ${n.delayMs}ms`),await delay(n.delayMs)}try{const n=await this.executeRequest(t);if(!n.ok&&shouldRetryRequest(n.status,t.method,r,i,t.idempotencyKey)){o=e.NetworkError.fromResponse(n,t.url,t.method),this.circuitBreaker.recordFailure(),429===n.status&&(a=parseRetryAfterHeader(n.headers.get("Retry-After"))),this.debug&&this.logger.warn(`[HttpClient] Request failed with status ${n.status}, will retry`);continue}return this.circuitBreaker.recordSuccess(),n}catch(e){if(o=e,this.circuitBreaker.recordFailure(),r.retryOnNetworkError&&this.isNetworkError(e)&&isIdempotentOrHasKey(t.method,t.idempotencyKey,r)){this.debug&&this.logger.warn(`[HttpClient] Network error on ${t.method} ${t.url}, will retry: ${e.message}`);continue}throw e}}throw this.debug&&this.logger.error(`[HttpClient] All ${r.maxAttempts} attempts exhausted for ${t.method} ${t.url}`),null!=o?o:new e.NetworkError("Request failed after all retry attempts",{url:t.url,method:t.method,retryable:!1})}isNetworkError(t){return"AbortError"!==t.name&&(t instanceof e.TimeoutError||(t instanceof e.NetworkError?void 0===t.statusCode&&t.retryable:t instanceof TypeError))}async executeRequest(t){const i=new AbortController,r=setTimeout(()=>i.abort(),t.timeout),n=t.signal?this.combineSignals(t.signal,i.signal):i.signal,s=Date.now();try{const e={method:t.method,headers:t.headers,signal:n};void 0!==t.body&&(e.body=t.body),this.debug&&this.logger.debug(`[HttpClient] ${t.method} ${t.url}`,t.retryAttempt>0?`(retry ${t.retryAttempt})`:"");const i=await this.fetchImpl(t.url,e);if(clearTimeout(r),this.debug){const e=Date.now()-s;this.logger.debug(`[HttpClient] ${t.method} ${t.url} -> ${i.status} (${e}ms)`)}return i}catch(n){if(clearTimeout(r),n instanceof Error&&"AbortError"===n.name){if(i.signal.aborted)throw e.TimeoutError.httpRequest(t.url,t.timeout,t.method);throw new e.NetworkError("Request was aborted",{url:t.url,method:t.method,retryable:!1,cause:n})}throw e.NetworkError.connectionError(n instanceof Error?n.message:"Network request failed",t.url,t.method,n instanceof Error?n:void 0)}}combineSignals(...e){const t=new AbortController;for(const i of e){if(i.aborted){t.abort();break}i.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}async parseResponse(t,i,r){var n;if(429===t.status){const r={"retry-after":t.headers.get("Retry-After"),"x-ratelimit-limit":t.headers.get("X-RateLimit-Limit"),"x-ratelimit-remaining":t.headers.get("X-RateLimit-Remaining"),"x-ratelimit-reset":t.headers.get("X-RateLimit-Reset")};if(!r["retry-after"])try{const e=await t.clone().json();"object"==typeof e&&null!==e&&"retryAfter"in e&&"number"==typeof e.retryAfter&&(r["retry-after"]=String(e.retryAfter))}catch(e){}throw e.RateLimitError.fromHeaders(r,i)}if(!t.ok){let s;try{const n=await t.clone().json();if(s=function(e){if(!isBackendErrorResponse(e))return;const t={code:e.error.code,message:e.error.message};return void 0!==e.retryAfter&&(t.retryAfter=e.retryAfter),t}(n),400===t.status&&function(e){if("object"!=typeof e||null===e)return!1;if(!("success"in e)||!1!==e.success)return!1;if(!("error"in e)||"object"!=typeof e.error||null===e.error)return!1;const t=e.error;return"VALIDATION_ERROR"===t.code&&"string"==typeof t.message}(n))throw e.ValidationError.fromResponse(n,i,r)}catch(t){if(t instanceof e.ValidationError)throw t}if(401===t.status)throw Ir.fromResponse(t,i,r,null==s?void 0:s.message);if(403===t.status)throw kr.fromResponse(t,i,r,null==s?void 0:s.message);if(404===t.status)throw xr.fromResponse(t,i,r,null==s?void 0:s.message);const o=null!=(n=null==s?void 0:s.message)?n:`HTTP ${t.status}: ${t.statusText||"Request failed"}`,a=t.status>=500,c={statusCode:t.status,retryable:a,url:i,method:r};throw(null==s?void 0:s.code)&&(c.context={backendErrorCode:s.code}),new e.NetworkError(o,c)}const s=t.headers.get("Content-Length"),o=t.headers.get("Content-Type");if(204===t.status||"0"===s)return;if(null==o?void 0:o.includes("application/json"))try{return await t.json()}catch(n){const s={statusCode:t.status,retryable:!1,url:i,method:r,context:{parseError:!0}};throw n instanceof Error&&(s.cause=n),new e.NetworkError("Failed to parse JSON response",s)}const a=await t.text();throw new e.NetworkError(`Unexpected content type: ${null!=o?o:"unknown"}`,{statusCode:t.status,retryable:!1,url:i,method:r,context:{contentType:o,responsePreview:a.slice(0,200)}})}getBaseUrl(){return this.baseUrl}getDefaultTimeout(){return this.defaultTimeout}getRetryConfig(){return this.retryConfig}isDebugEnabled(){return this.debug}static isHttpClientWithInterceptors(e){return e instanceof _HttpClientWithInterceptors}};P(),D(),L();var Mr=class _HttpClient{constructor(e){var t,i,r,n;__publicField(this,"baseUrl"),__publicField(this,"defaultTimeout"),__publicField(this,"defaultHeaders"),__publicField(this,"fetchImpl"),__publicField(this,"onSecurityWarning");const s=null!=(t=e.fetch)?t:globalThis.fetch;if(!s){const e=getRuntime();throw new sr(getFetchUnavailableErrorMessage(e),{configKey:"fetch",expectedType:"typeof fetch",context:{runtime:e}})}this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.defaultTimeout=null!=(i=e.timeout)?i:1e4,this.defaultHeaders={"Content-Type":"application/json","X-SDK-Version":`overvio-sdk/${Rr}`,...e.headers},this.fetchImpl=s,this.onSecurityWarning=e.onSecurityWarning;const o=null!=(r=e.enforceHttps)&&r,a=null!=(n=e.allowedHttpHosts)?n:["localhost","127.0.0.1","[::1]"];if(!this.baseUrl.startsWith("https://")){let e=!1;try{const t=new URL(this.baseUrl);e=a.some(e=>t.hostname===e||t.hostname.endsWith(`.${e}`))}catch(e){}if(o&&!e)throw new sr(`API endpoint "${this.baseUrl}" must use HTTPS. HTTP is not allowed when enforceHttps is enabled. Set enforceHttps: false only for development with localhost.`,{configKey:"baseUrl",expectedType:"HTTPS URL",context:{url:this.baseUrl,allowedHttpHosts:a}});const t=`API endpoint "${this.baseUrl}" does not use HTTPS. Using HTTP exposes data to interception. `+(o?"This is allowed because the host is in allowedHttpHosts.":"Enable enforceHttps: true in production.");this.onSecurityWarning&&this.onSecurityWarning({type:"insecure_endpoint",url:this.baseUrl,message:t,severity:"high",timestamp:Date.now()})}}async get(e,t){return this.request("GET",e,void 0,t)}async getOptional(e,t){return this.request("GET",e,void 0,t)}async post(e,t,i){return this.request("POST",e,t,i)}async put(e,t,i){return this.request("PUT",e,t,i)}async delete(e,t){return this.request("DELETE",e,null==t?void 0:t.body,t)}async deleteOptional(e,t){return this.request("DELETE",e,void 0,t)}async patch(e,t,i){return this.request("PATCH",e,t,i)}async head(e,t){return this.requestWithResponse("HEAD",e,void 0,t)}async options(e,t){return this.requestWithResponse("OPTIONS",e,void 0,t)}async requestWithResponse(e,t,i,r){const n=this.buildRequestConfig(e,t,i,r),s=await this.executeRequest(n);return{data:await this.parseResponse(s,n.url,e),status:s.status,statusText:s.statusText,headers:s.headers}}async request(e,t,i,r){const n=this.buildRequestConfig(e,t,i,r),s=await this.executeRequest(n);return this.parseResponse(s,n.url,e)}buildRequestConfig(e,t,i,r={}){var n;const s={method:e,url:this.buildUrl(t,r.params),headers:{...this.defaultHeaders,...r.headers},timeout:null!=(n=r.timeout)?n:this.defaultTimeout};return r.signal&&(s.signal=r.signal),void 0!==i&&(s.body=JSON.stringify(i)),s}buildUrl(e,t){const i=e.startsWith("/")?e:`/${e}`;let r=`${this.baseUrl}${i}`;if(t){const e=new URLSearchParams;for(const[i,r]of Object.entries(t))null!=r&&e.append(i,String(r));const i=e.toString();i&&(r+=`?${i}`)}return r}async executeRequest(t){const i=new AbortController,r=setTimeout(()=>i.abort(),t.timeout),n=t.signal?this.combineSignals(t.signal,i.signal):i.signal;try{const e={method:t.method,headers:t.headers,signal:n};void 0!==t.body&&(e.body=t.body);const i=await this.fetchImpl(t.url,e);return clearTimeout(r),i}catch(n){if(clearTimeout(r),n instanceof Error&&"AbortError"===n.name){if(i.signal.aborted)throw e.TimeoutError.httpRequest(t.url,t.timeout,t.method);throw e.NetworkError.connectionError("Request was aborted",t.url,t.method,n)}throw e.NetworkError.connectionError(n instanceof Error?n.message:"Network request failed",t.url,t.method,n instanceof Error?n:void 0)}}combineSignals(...e){const t=new AbortController;for(const i of e){if(i.aborted){t.abort();break}i.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}async parseResponse(t,i,r){if(429===t.status){const r={"retry-after":t.headers.get("Retry-After"),"x-ratelimit-limit":t.headers.get("X-RateLimit-Limit"),"x-ratelimit-remaining":t.headers.get("X-RateLimit-Remaining"),"x-ratelimit-reset":t.headers.get("X-RateLimit-Reset")};throw e.RateLimitError.fromHeaders(r,i)}if(!t.ok)throw e.NetworkError.fromResponse(t,i,r);const n=t.headers.get("Content-Length"),s=t.headers.get("Content-Type");if(204===t.status||"0"===n)return;if(null==s?void 0:s.includes("application/json"))try{return await t.json()}catch(n){const s={statusCode:t.status,retryable:!1,url:i,method:r,code:"PARSE_ERROR",context:{parseError:!0}};throw n instanceof Error&&(s.cause=n),new e.NetworkError("Failed to parse JSON response",s)}const o=await t.text();throw new e.NetworkError(`Unexpected content type: ${null!=s?s:"unknown"}`,{statusCode:t.status,retryable:!1,url:i,method:r,context:{contentType:s,responsePreview:o.slice(0,200)}})}getBaseUrl(){return this.baseUrl}getDefaultTimeout(){return this.defaultTimeout}static isHttpClient(e){return e instanceof _HttpClient}};f(),x(),P(),M(),D(),x();var Or=class _ConsentError extends e.OvervioError{constructor(e,t={}){const{requiredCategory:i,grantedCategories:r,operation:n,cause:s,context:o={}}=t,a={...o};void 0!==i&&(a.requiredCategory=i),void 0!==r&&(a.grantedCategories=r),void 0!==n&&(a.operation=n),super(e,"CONSENT_REQUIRED",a,s),__publicField(this,"name","ConsentError"),__publicField(this,"requiredCategory"),__publicField(this,"grantedCategories"),__publicField(this,"operation"),this.requiredCategory=i,this.grantedCategories=r,this.operation=n,Object.setPrototypeOf(this,new.target.prototype)}static missingConsent(e,t,i){const r=t?`User consent for "${e}" is required to ${t}`:`User consent for "${e}" is required`,n={requiredCategory:e};return void 0!==i&&(n.grantedCategories=i),void 0!==t&&(n.operation=t),new _ConsentError(r,n)}static notInitialized(e){const t=e?`Consent has not been collected yet. Cannot ${e}`:"Consent has not been collected yet",i={grantedCategories:[]};return void 0!==e&&(i.operation=e),new _ConsentError(t,i)}hasRequiredConsent(){return!(!this.requiredCategory||!this.grantedCategories)&&this.grantedCategories.includes(this.requiredCategory)}static isConsentError(e){return e instanceof _ConsentError}toJSON(){const e=super.toJSON();return isProductionEnvironment()?{...e,...void 0!==this.requiredCategory&&{requiredCategory:this.requiredCategory}}:{...e,...void 0!==this.requiredCategory&&{requiredCategory:this.requiredCategory},...void 0!==this.grantedCategories&&{grantedCategories:this.grantedCategories},...void 0!==this.operation&&{operation:this.operation}}}};x();var $r=class _PluginError extends e.OvervioError{constructor(e,t={}){const{pluginName:i,pluginVersion:r,lifecycleMethod:n,recoverable:s=!1,cause:o,context:a={}}=t,c={...a};void 0!==i&&(c.pluginName=i),void 0!==r&&(c.pluginVersion=r),void 0!==n&&(c.lifecycleMethod=n),c.recoverable=s,super(e,"PLUGIN_ERROR",c,o),__publicField(this,"name","PluginError"),__publicField(this,"pluginName"),__publicField(this,"pluginVersion"),__publicField(this,"lifecycleMethod"),__publicField(this,"recoverable"),this.pluginName=i,this.pluginVersion=r,this.lifecycleMethod=n,this.recoverable=s,Object.setPrototypeOf(this,new.target.prototype)}static initFailed(e,t,i){const r={pluginName:e,lifecycleMethod:"init",recoverable:!1};return void 0!==i&&(r.pluginVersion=i),void 0!==t&&(r.cause=t),new _PluginError(`Plugin "${e}" failed to initialize`,r)}static executionFailed(e,t,i,r){const n={pluginName:e,lifecycleMethod:t,recoverable:!0};return void 0!==r&&(n.pluginVersion=r),void 0!==i&&(n.cause=i),new _PluginError(`Plugin "${e}" failed during ${t}`,n)}static timeout(e,t,i,r){const n={pluginName:e,lifecycleMethod:t,recoverable:!0,context:{timeoutMs:i}};return void 0!==r&&(n.pluginVersion=r),new _PluginError(`Plugin "${e}" timed out during ${t} after ${i}ms`,n)}static duplicate(e){return new _PluginError(`Plugin "${e}" is already registered`,{pluginName:e,recoverable:!0})}static notFound(e){return new _PluginError(`Plugin "${e}" is not registered`,{pluginName:e,recoverable:!0})}static isPluginError(e){return e instanceof _PluginError}toJSON(){const e=super.toJSON();return isProductionEnvironment()?{...e,recoverable:this.recoverable}:{...e,recoverable:this.recoverable,...void 0!==this.pluginName&&{pluginName:this.pluginName},...void 0!==this.pluginVersion&&{pluginVersion:this.pluginVersion},...void 0!==this.lifecycleMethod&&{lifecycleMethod:this.lifecycleMethod}}}};x();var Nr=class _QueueError extends e.OvervioError{constructor(e,t={}){const{queueSize:i,maxSize:r,droppedEvent:n,droppedCount:s,cause:o,context:a={}}=t,c={...a};void 0!==i&&(c.queueSize=i),void 0!==r&&(c.maxSize=r),void 0!==s&&(c.droppedCount=s),super(e,"QUEUE_FULL",c,o),__publicField(this,"name","QueueError"),__publicField(this,"queueSize"),__publicField(this,"maxSize"),__publicField(this,"droppedEvent"),__publicField(this,"droppedCount"),this.queueSize=i,this.maxSize=r,this.droppedEvent=n,this.droppedCount=s,Object.setPrototypeOf(this,new.target.prototype)}static overflow(e,t,i){return new _QueueError(`Event queue is full (${e}/${t}). Event dropped.`,{queueSize:e,maxSize:t,droppedEvent:i,droppedCount:1})}static persistenceFailed(e){const t={};return void 0!==e&&(t.cause=e),new _QueueError("Failed to persist event queue",t)}static deserializationFailed(e){const t={};return void 0!==e&&(t.cause=e),new _QueueError("Failed to deserialize event queue",t)}static flushFailed(e,t){const i={droppedCount:e};return void 0!==t&&(i.cause=t),new _QueueError(`Failed to flush ${e} events from queue`,i)}static isQueueError(e){return e instanceof _QueueError}toJSON(){const e=super.toJSON();return isProductionEnvironment()?e:{...e,...void 0!==this.queueSize&&{queueSize:this.queueSize},...void 0!==this.maxSize&&{maxSize:this.maxSize},...void 0!==this.droppedCount&&{droppedCount:this.droppedCount}}}};L();var Fr=["search","recommendations","banners"],qr="not_loaded",Ur="loading",zr="loaded",Hr="error",Vr=class{constructor(e={}){var t,i,r,n;__publicField(this,"registry",new Map),__publicField(this,"debug"),__publicField(this,"emitter"),__publicField(this,"moduleImporters"),__publicField(this,"timeout"),this.debug=null!=(t=e.debug)&&t,this.emitter=null!=(i=e.emitter)?i:null,this.moduleImporters=null!=(r=e.moduleImporters)?r:{},this.timeout=null!=(n=e.timeout)?n:3e4;for(const e of Fr)this.registry.set(e,this.createDefaultEntry());this.log("ModuleLoader initialized")}async loadModule(e,t){var i;if(null==(i=null==t?void 0:t.signal)?void 0:i.aborted){const t=new Error(`Module load cancelled: '${e}'`);return t.name="AbortError",{success:!1,module:null,error:t,cached:!1,loadTimeMs:0}}if(!this.isValidModuleName(e))return{success:!1,module:null,error:new Error(`Unknown module: '${e}'. Available modules: ${Fr.join(", ")}`),cached:!1,loadTimeMs:0};const r=this.getRegistryEntry(e);if(r.state===zr&&null!==r.module)return this.log(`Module '${e}' already loaded (cached)`),{success:!0,module:r.module,error:null,cached:!0,loadTimeMs:0};if(r.state===Ur&&null!==r.loadingPromise){if(this.log(`Module '${e}' already loading, returning existing promise`),null==t?void 0:t.signal){let i;const n=new Promise((r,n)=>{const onAbort=()=>{const t=new Error(`Module load cancelled: '${e}'`);t.name="AbortError",n(t)};t.signal.aborted?onAbort():(t.signal.addEventListener("abort",onAbort,{once:!0}),i=()=>t.signal.removeEventListener("abort",onAbort))});n.catch(()=>{});try{return{success:!0,module:await Promise.race([r.loadingPromise,n]),error:null,cached:!1,loadTimeMs:r.loadCompletedAt&&r.loadStartedAt?r.loadCompletedAt-r.loadStartedAt:0}}catch(e){return{success:!1,module:null,error:e instanceof Error?e:new Error(String(e)),cached:!1,loadTimeMs:0}}finally{i&&i()}}try{return{success:!0,module:await r.loadingPromise,error:null,cached:!1,loadTimeMs:r.loadCompletedAt&&r.loadStartedAt?r.loadCompletedAt-r.loadStartedAt:0}}catch(e){return{success:!1,module:null,error:e instanceof Error?e:new Error(String(e)),cached:!1,loadTimeMs:0}}}return this.initiateLoad(e,null==t?void 0:t.signal)}getModule(e){const t=this.registry.get(e);return t&&t.state===zr?t.module:null}getModuleOrThrow(e){var t;const i=this.registry.get(e);if(!i||i.state!==zr||null===i.module){const r=null!=(t=null==i?void 0:i.state)?t:"not_registered";throw new Error(`Module '${e}' is not loaded (state: ${r}). Call 'await sdk.loadModule("${e}")' before accessing sdk.${e}.`)}return i.module}isModuleLoaded(e){const t=this.registry.get(e);return(null==t?void 0:t.state)===zr}isModuleLoading(e){const t=this.registry.get(e);return(null==t?void 0:t.state)===Ur}getModuleState(e){var t;const i=this.registry.get(e);return null!=(t=null==i?void 0:i.state)?t:qr}getModuleError(e){var t;const i=this.registry.get(e);return null!=(t=null==i?void 0:i.error)?t:null}getStats(){const e=[],t=[],i=[];for(const[r,n]of this.registry)switch(n.state){case zr:e.push(r);break;case Ur:t.push(r);break;case Hr:i.push(r)}return{loadedCount:e.length,loadingCount:t.length,errorCount:i.length,loadedModules:e,loadingModules:t,failedModules:i}}async preloadModules(e){this.log("Preloading modules",{names:e});const t=new Map,i=e.map(async e=>{const i=await this.loadModule(e);t.set(e,i)});return await Promise.all(i),t}resetModule(e){this.registry.has(e)&&(this.registry.set(e,this.createDefaultEntry()),this.log(`Module '${e}' reset`))}resetAllModules(){for(const e of Fr)this.registry.set(e,this.createDefaultEntry());this.log("All modules reset")}async initiateLoad(e,t){const i=Date.now();this.log(`Loading module '${e}'`);const r=this.getRegistryEntry(e);r.state=Ur,r.loadStartedAt=i,r.error=null,this.emit("module:loading",{name:e});const n=this.importModule(e,t);r.loadingPromise=n;try{const t=await n,s=Date.now()-i;return r.state=zr,r.module=t,r.loadCompletedAt=Date.now(),r.loadingPromise=null,this.log(`Module '${e}' loaded successfully`,{loadTimeMs:s}),this.emit("module:loaded",{name:e,loadTimeMs:s}),{success:!0,module:t,error:null,cached:!1,loadTimeMs:s}}catch(t){const n=t instanceof Error?t:new Error(String(t)),s=Date.now()-i;return"AbortError"===n.name?(r.state=qr,r.error=null,this.log(`Module '${e}' load cancelled`,{loadTimeMs:s})):(r.state=Hr,r.error=n,this.log(`Failed to load module '${e}'`,{error:n.message}),this.emit("module:error",{name:e,error:n})),r.loadCompletedAt=Date.now(),r.loadingPromise=null,{success:!1,module:null,error:n,cached:!1,loadTimeMs:s}}}async importModule(t,i){const r=this.moduleImporters[t],n=r?r():this.getImportPromise(t),s=function(t,i){let r;const n=new Promise((n,s)=>{r=setTimeout(()=>{s(e.TimeoutError.operation(i,t))},t)});return n.catch(()=>{}),{promise:n,clear:()=>{void 0!==r&&clearTimeout(r)}}}(this.timeout,`Load module '${t}'`);let o,a;i&&(o=new Promise((e,r)=>{const onAbort=()=>{const e=new Error(`Module load cancelled: '${t}'`);e.name="AbortError",r(e)};i.aborted?onAbort():(i.addEventListener("abort",onAbort,{once:!0}),a=()=>i.removeEventListener("abort",onAbort))}),o.catch(()=>{}));try{const e=[n,s.promise];return o&&e.push(o),await Promise.race(e)}finally{s.clear(),a&&a()}}getImportPromise(e){switch(e){case"search":return Promise.resolve().then(()=>(oi(),Ut));case"recommendations":return Promise.resolve().then(()=>(Si(),bi));case"banners":return Promise.resolve().then(()=>(tr(),er));default:return Promise.reject(new Error(`No importer found for module: ${e}`))}}createDefaultEntry(){return{state:qr,module:null,error:null,loadingPromise:null,loadStartedAt:null,loadCompletedAt:null}}isValidModuleName(e){return Fr.includes(e)}getRegistryEntry(e){const t=this.registry.get(e);if(!t)throw new Error(`Registry entry not found for module: ${e}`);return t}emit(e,t){this.emitter&&this.emitter.emit(e,t)}log(e,t){this.debug}};function isSecureContext(){return"undefined"!=typeof window&&"isSecureContext"in window?window.isSecureContext:"undefined"!=typeof window&&"undefined"!=typeof location&&"https:"===location.protocol}function resolveCookieConfig(e){var t,i,r,n;const s={name:"overvio-user",maxAge:31536e3,path:"/",domain:void 0,secure:isSecureContext(),sameSite:"Lax"};if(!e)return s;let o;o=void 0===e.secure||"auto"===e.secure?isSecureContext():e.secure;let a=null!=(t=e.sameSite)?t:s.sameSite;return"None"!==a||o||(a="Lax"),{name:null!=(i=e.name)?i:s.name,maxAge:null!=(r=e.maxAge)?r:s.maxAge,path:null!=(n=e.path)?n:s.path,domain:e.domain,secure:o,sameSite:a}}function validateCookieConfig(e){if(void 0!==e.name){if("string"!=typeof e.name)return{valid:!1,error:"Cookie name must be a string, received "+typeof e.name};if(0===e.name.length)return{valid:!1,error:"Cookie name cannot be an empty string"};if(/[=;,\s]/.test(e.name))return{valid:!1,error:"Cookie name cannot contain semicolons, commas, equals signs, or whitespace"}}if(void 0!==e.maxAge){if("number"!=typeof e.maxAge)return{valid:!1,error:"Cookie maxAge must be a number, received "+typeof e.maxAge};if(e.maxAge<=0)return{valid:!1,error:"Cookie maxAge must be a positive number"};if(!Number.isFinite(e.maxAge))return{valid:!1,error:"Cookie maxAge must be a finite number"}}if(void 0!==e.path){if("string"!=typeof e.path)return{valid:!1,error:"Cookie path must be a string, received "+typeof e.path};if(!e.path.startsWith("/"))return{valid:!1,error:"Cookie path must start with /"}}if(void 0!==e.domain){if("string"!=typeof e.domain)return{valid:!1,error:"Cookie domain must be a string, received "+typeof e.domain};if(0===e.domain.length)return{valid:!1,error:"Cookie domain cannot be an empty string"}}return void 0!==e.secure&&!0!==e.secure&&!1!==e.secure&&"auto"!==e.secure?{valid:!1,error:"Cookie secure must be a boolean or 'auto', received "+typeof e.secure}:void 0!==e.sameSite&&"Strict"!==e.sameSite&&"Lax"!==e.sameSite&&"None"!==e.sameSite?{valid:!1,error:`Cookie sameSite must be 'Strict', 'Lax', or 'None', received '${e.sameSite}'`}:{valid:!0}}function validateAnonymousId(e){return"string"!=typeof e?{valid:!1,error:"Anonymous ID must be a string, received "+typeof e}:e.length<1?{valid:!1,error:"Anonymous ID cannot be an empty string"}:e.length>255?{valid:!1,error:`Anonymous ID cannot exceed 255 characters (received ${e.length})`}:{valid:!0}}function generateUuid(){return secureRandomUUID()}function generateAnonymousId(e){return`anon_${e?e():generateUuid()}`}A(),h();var Br=class{constructor(e){var t,i,r;if(__publicField(this,"storage"),__publicField(this,"storageKey"),__publicField(this,"ttl"),__publicField(this,"uuidGenerator"),__publicField(this,"cookieConfig"),__publicField(this,"cachedId",null),e.cookieConfig){const t=validateCookieConfig(e.cookieConfig);if(!t.valid)throw new Error(`Invalid cookie configuration: ${t.error}`)}this.storage=e.storage,this.storageKey=null!=(t=e.storageKey)?t:"anonymous_id",this.ttl=null!=(i=e.ttl)?i:63072e6,this.uuidGenerator=null!=(r=e.uuidGenerator)?r:generateUuid,this.cookieConfig=resolveCookieConfig(e.cookieConfig),this.loadFromStorage()}getOrCreate(){if(null!==this.cachedId)return this.cachedId;if(this.loadFromStorage(),null!==this.cachedId)return this.cachedId;const e=createUserId(generateAnonymousId(this.uuidGenerator));return this.persistToStorage(e),this.cachedId=e,e}get(){return null!==this.cachedId||this.loadFromStorage(),this.cachedId}set(e){const t=validateAnonymousId(e);if(!t.valid)throw new Error(t.error);const i=createUserId(e);this.persistToStorage(i),this.cachedId=i}reset(){const e=createUserId(generateAnonymousId(this.uuidGenerator));return this.persistToStorage(e),this.cachedId=e,e}exists(){return null!==this.get()}clear(){this.storage.remove(this.storageKey),this.cachedId=null}getCookieConfig(){return{...this.cookieConfig}}setCookieConfig(e){const t=validateCookieConfig(e);if(!t.valid)throw new Error(`Invalid cookie configuration: ${t.error}`);const i={};void 0!==e.name?i.name=e.name:void 0!==this.cookieConfig.name&&(i.name=this.cookieConfig.name),void 0!==e.maxAge?i.maxAge=e.maxAge:void 0!==this.cookieConfig.maxAge&&(i.maxAge=this.cookieConfig.maxAge),void 0!==e.path?i.path=e.path:void 0!==this.cookieConfig.path&&(i.path=this.cookieConfig.path),"domain"in e&&void 0!==e.domain?i.domain=e.domain:void 0!==this.cookieConfig.domain&&(i.domain=this.cookieConfig.domain),void 0!==e.secure?i.secure=e.secure:void 0!==this.cookieConfig.secure&&(i.secure=this.cookieConfig.secure),void 0!==e.sameSite?i.sameSite=e.sameSite:void 0!==this.cookieConfig.sameSite&&(i.sameSite=this.cookieConfig.sameSite),this.cookieConfig=resolveCookieConfig(i)}loadFromStorage(){const e=this.storage.get(this.storageKey);null!==e&&validateAnonymousId(e).valid&&(this.cachedId=createUserId(e))}persistToStorage(e){if(this.isCookieStorage(this.storage)){const t={ttl:this.ttl,path:this.cookieConfig.path,secure:this.cookieConfig.secure,sameSite:this.cookieConfig.sameSite,maxAge:this.cookieConfig.maxAge};void 0!==this.cookieConfig.domain&&(t.domain=this.cookieConfig.domain),this.storage.setCookie(this.storageKey,e,t)}else this.storage.set(this.storageKey,e,{ttl:this.ttl})}isCookieStorage(e){return"setCookie"in e&&"function"==typeof e.setCookie}};P(),Rt();var jr=class extends Error{constructor(e){super(`No session found for anonymous ID: ${e}. User may not have started a session yet.`),this.name="IdentifySessionNotFoundError"}},Kr=class extends Error{constructor(e){super(e),this.name="IdentifyValidationError"}},Wr=class extends Error{constructor(e){super(`Identify rate limit exceeded. Retry after ${e}ms. This prevents abuse of the identity API.`),__publicField(this,"retryAfterMs"),this.name="IdentifyRateLimitError",this.retryAfterMs=e}},Qr=class{constructor(e){var t,i,r,n,s;__publicField(this,"httpClient"),__publicField(this,"endpoint"),__publicField(this,"onDebug"),__publicField(this,"consentManager"),__publicField(this,"requireMarketingConsent"),__publicField(this,"pendingQueue",new Map),__publicField(this,"queueIdCounter",0),__publicField(this,"consentUnsubscribe"),__publicField(this,"rateLimiter"),this.httpClient=e.httpClient,this.endpoint=null!=(t=e.endpoint)?t:"/identify",void 0!==e.onDebug&&(this.onDebug=e.onDebug),void 0!==e.consentManager&&(this.consentManager=e.consentManager),this.requireMarketingConsent=null!=(i=e.requireMarketingConsent)?i:void 0!==e.consentManager;const o=null==(r=e.rateLimit)||r;if(!1===o)this.rateLimiter=null;else{const e=!0===o?{maxTokens:5,refillRate:.5,name:"identify"}:{...o,maxTokens:null!=(n=o.maxTokens)?n:5,refillRate:null!=(s=o.refillRate)?s:.5,name:"identify"};this.rateLimiter=createRateLimiter(e),this.debug("Rate limiting enabled",{maxTokens:e.maxTokens,refillRate:e.refillRate})}this.consentManager&&this.requireMarketingConsent&&(this.consentUnsubscribe=this.consentManager.onConsentChange((e,t)=>{e.marketing&&this.processQueue()}))}async identify(e){if(this.debug("Calling identify API",{anonymousId:this.redactId(e.anonymousId),userId:this.redactId(e.userId),hasTraits:!!e.traits}),this.rateLimiter)try{this.rateLimiter.acquire()}catch(e){if(e instanceof kt)throw this.debug("Identify rate limited",{retryAfterMs:e.retryAfterMs}),new Wr(e.retryAfterMs);throw e}return this.requireMarketingConsent&&this.consentManager&&!this.consentManager.hasConsent("marketing")?(this.debug("Marketing consent not granted, queuing identify for later",{anonymousId:e.anonymousId,userId:e.userId}),this.queueIdentify(e)):this.executeIdentify(e)}queueIdentify(e){return new Promise((t,i)=>{const r=`identify_${++this.queueIdCounter}_${Date.now()}`,n={id:r,params:e,queuedAt:Date.now(),resolve:t,reject:i};this.pendingQueue.set(r,n),this.debug("Identify queued pending marketing consent",{queueId:r,anonymousId:e.anonymousId,userId:e.userId,queueSize:this.pendingQueue.size})})}processQueue(){if(0===this.pendingQueue.size)return;this.debug("Processing queued identify requests",{count:this.pendingQueue.size});const e=Array.from(this.pendingQueue.values());this.pendingQueue.clear();for(const t of e)this.debug("Processing queued identify",{queueId:t.id,anonymousId:t.params.anonymousId,userId:t.params.userId,queuedAt:t.queuedAt,waitTime:Date.now()-t.queuedAt}),this.executeIdentify(t.params).then(t.resolve).catch(t.reject)}async executeIdentify(t){const i={anonymousId:t.anonymousId,userId:t.userId};void 0!==t.traits&&(i.traits=t.traits);try{const t=await this.httpClient.post(this.endpoint,i);if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;if("boolean"!=typeof t.success)return!1;if("object"!=typeof t.data||null===t.data)return!1;const i=t.data;return"boolean"==typeof i.linked&&(null===i.previousUserId||"string"==typeof i.previousUserId)&&"string"==typeof i.cookieName}(t))throw new e.NetworkError("Invalid identify response from server",{statusCode:0,retryable:!1,url:this.endpoint,method:"POST",context:{response:t}});const r=this.parseResponse(t);return this.debug("Identify API success",{linked:r.linked,wasReidentified:r.wasReidentified,previousUserId:r.previousUserId}),r}catch(i){if(i instanceof e.NetworkError&&404===i.statusCode)throw this.debug("Identify failed - session not found",{anonymousId:t.anonymousId}),new jr(t.anonymousId);if(i instanceof e.NetworkError&&400===i.statusCode)throw this.debug("Identify failed - validation error",{anonymousId:t.anonymousId,userId:t.userId}),new Kr(`Invalid identify request: ${i.message||"Bad request"}`);throw i}}parseResponse(e){return{linked:e.data.linked,previousUserId:e.data.previousUserId,cookieName:e.data.cookieName,wasReidentified:null!==e.data.previousUserId}}get pendingCount(){return this.pendingQueue.size}getPendingRequests(){return Array.from(this.pendingQueue.values()).map(e=>({id:e.id,params:e.params,queuedAt:e.queuedAt}))}removePendingRequest(e){const t=this.pendingQueue.delete(e);return t&&this.debug("Pending identify request removed",{queueId:e}),t}clearPendingQueue(){const e=this.pendingQueue.size;return e>0&&(this.pendingQueue.clear(),this.debug("Pending identify queue cleared",{count:e})),e}destroy(){this.consentUnsubscribe&&(this.consentUnsubscribe(),delete this.consentUnsubscribe),this.clearPendingQueue(),this.rateLimiter&&this.rateLimiter.destroy(),this.debug("IdentifyApiClient destroyed")}debug(e,t){this.onDebug&&this.onDebug(`[IdentifyApi] ${e}`,t)}redactId(e){return e.length<=12?e.slice(0,3)+"***":e.slice(0,4)+"***"+e.slice(-4)}};A();var Gr=class extends Error{constructor(e="Web Crypto API is not available in this environment"){super(e),this.name="WebCryptoUnavailableError"}};function isWebCryptoAvailable(){var e;try{if("object"!=typeof(null==(e=globalThis.crypto)?void 0:e.subtle))return!1;const t=globalThis.crypto.subtle;return"function"==typeof t.generateKey&&"function"==typeof t.encrypt&&"function"==typeof t.decrypt&&"function"==typeof t.deriveBits&&"function"==typeof t.importKey}catch(e){return!1}}var Yr=!1;function bufferToHex(e){const t=new Uint8Array(e);let i="";for(let e=0;e<t.length;e++)i+=t[e].toString(16).padStart(2,"0");return i}function isHmacAvailable(){if(!isWebCryptoAvailable())return!1;try{return"function"==typeof globalThis.crypto.subtle.importKey&&"function"==typeof globalThis.crypto.subtle.sign}catch(e){return!1}}function isSha256Available(){if(!isWebCryptoAvailable())return!1;try{return"function"==typeof globalThis.crypto.subtle.digest}catch(e){return!1}}var Xr="_overvio_id",Jr="_overvio_session",Zr="_overvio_ts",en="_overvio_sig",tn=12e4,rn=[Xr,Jr,Zr,en],nn=!1;function isValidUrl(e){try{return new URL(e),!0}catch(e){return!1}}function matchesDomainPattern(e,t){const i=t.toLowerCase();if(e===i)return!0;if(i.startsWith("*.")){const t=i.slice(1);if(e.endsWith(t)&&e.length>t.length){const i=e.slice(0,e.length-t.length);return i.length>0&&!i.includes(".")}if(e===i.slice(2))return!0}return!1}function isAllowedDomain(e,t){const i=function(e){try{return new URL(e).hostname.toLowerCase()}catch(e){return null}}(e);return!!i&&t.some(e=>matchesDomainPattern(i,e))}function isBrowser2(){return"undefined"!=typeof window&&void 0!==window.location}function isHistoryAvailable(){return isBrowser2()&&void 0!==window.history&&"function"==typeof window.history.replaceState}var sn=class{constructor(e){var t,i,r,n,s,o,a,c,l,u,d;__publicField(this,"anonymousIdManager"),__publicField(this,"sessionManager"),__publicField(this,"config"),__publicField(this,"hasWarnedHttp",!1),this.anonymousIdManager=e.anonymousIdManager,this.sessionManager=null!=(t=e.sessionManager)?t:null;let h=null!=(i=e.expiryMs)?i:3e4;h<3e4?h=3e4:h>tn&&(h=tn);const g="undefined"!=typeof process&&!0;this.config={allowedDomains:e.allowedDomains,acceptIncoming:null!=(r=e.acceptIncoming)&&r,expiryMs:h,autoCleanUrl:null==(n=e.autoCleanUrl)||n,signatureSecret:e.signatureSecret,strictSignature:null!=(s=e.strictSignature)?s:g,validateReferrer:null==(o=e.validateReferrer)||o,warnOnHttp:null==(a=e.warnOnHttp)||a,now:null!=(c=e.now)?c:()=>Date.now(),getUrl:null!=(l=e.getUrl)?l:()=>isBrowser2()?window.location.href:"",setUrl:null!=(u=e.setUrl)?u:e=>{isHistoryAvailable()&&window.history.replaceState({},"",e)},getReferrer:null!=(d=e.getReferrer)?d:()=>isBrowser2()&&"undefined"!=typeof document?document.referrer:"",onDebug:e.onDebug},!e.allowedDomains||e.allowedDomains.length,this.debug("CrossDomainLinker created",{expiryMs:this.config.expiryMs,hasSignatureSecret:!!this.config.signatureSecret,strictSignature:this.config.strictSignature,hasAllowedDomains:!!this.config.allowedDomains,acceptIncoming:this.config.acceptIncoming,warnOnHttp:this.config.warnOnHttp})}async getLinkerParams(){var e;const t=this.anonymousIdManager.get();if(!t)return this.debug("No anonymous ID available for linker params"),null;const i=null==(e=this.sessionManager)?void 0:e.getSessionId(),r=this.config.now(),n={[Xr]:t,[Jr]:null!=i?i:"",[Zr]:String(r)};if(this.config.signatureSecret){const e=await this.generateSignature(t,null!=i?i:"",String(r));e&&(n[en]=e)}return this.debug("Generated linker params",{params:{...n,[en]:n[en]?"[REDACTED]":void 0}}),n}async getLinkerUrl(e){if(!isValidUrl(e))throw new Error(`Invalid URL: ${e}`);if(this.config.allowedDomains&&this.config.allowedDomains.length>0&&!isAllowedDomain(e,this.config.allowedDomains))return this.debug("Destination domain not in allowedDomains, skipping decoration",{baseUrl:e,allowedDomains:this.config.allowedDomains}),e;const t=await this.getLinkerParams();if(!t)return e;const i=new URL(e);!this.config.warnOnHttp||this.hasWarnedHttp||"http:"!==i.protocol||this.isLocalhost(i.hostname)||(console.warn("[Overvio Security] Cross-domain linking over HTTP exposes identity parameters to network observers. Consider using HTTPS for production environments. Set warnOnHttp: false to suppress this warning."),this.hasWarnedHttp=!0),i.searchParams.set(Xr,t[Xr]),i.searchParams.set(Jr,t[Jr]),i.searchParams.set(Zr,t[Zr]);const r=t[en];void 0!==r&&i.searchParams.set(en,r);const n=i.toString();return n.length>2e3?(this.debug("Decorated URL exceeds safe length limit, skipping decoration",{baseUrl:e,decoratedLength:n.length,maxLength:2e3}),console.warn(`[Overvio Security] Cross-domain linker URL exceeds safe length (${n.length} > 2000 chars). Decoration skipped to prevent URL truncation. Consider using shorter URLs or server-side identity passing.`),e):(this.debug("Generated linker URL",{baseUrl:e,result:n}),n)}async parseLinkerParams(e){var t;const i=null!=e?e:this.config.getUrl();if(!i||!isValidUrl(i))return this.debug("No valid URL to parse"),null;const r=new URL(i).searchParams,n=r.get(Xr),s=r.get(Jr),o=r.get(Zr);if(!n||!o)return this.debug("Missing required linker params",{hasId:!!n,hasTimestamp:!!o}),null;if(!isUserId(n))return this.debug("Invalid anonymous ID in linker params",{idParam:this.redactId(n)}),null;const a=parseInt(o,10);if(isNaN(a))return this.debug("Invalid timestamp in linker params",{timestampParam:o}),null;if(this.config.signatureSecret){const e=r.get(en);if(!e)return this.debug("Missing required signature in linker params (signatureSecret is configured)"),null;const t=await this.generateSignature(n,null!=s?s:"",o);if(null===t){if(this.config.strictSignature)return this.debug("Rejecting linker params: strictSignature is enabled but signature verification is unavailable (HTTP context)"),null;this.debug("Signature verification skipped: Web Crypto unavailable (HTTP context). Set strictSignature: true to reject params in this scenario.")}else if(!function(e,t){const i=Math.max(e.length,t.length);let r=e.length^t.length;for(let n=0;n<i;n++)r|=(n<e.length?e.charCodeAt(n):0)^(n<t.length?t.charCodeAt(n):0);return 0===r}(e,t))return this.debug("Invalid signature in linker params"),null}const c=this.config.now(),l=c-a;if(l<-5e3)return this.debug("Rejected future timestamp in linker params (clock manipulation)",{timestamp:a,now:c,age:l}),null;const u=l>this.config.expiryMs,d=!u,h=s&&s.length>0&&isSessionId(s)?createSessionId(s):null,g={anonymousId:createUserId(n),sessionId:h,timestamp:a,isValid:d,isExpired:u};return this.debug("Parsed linker params",{anonymousId:this.redactId(g.anonymousId),sessionId:this.redactId(null!=(t=g.sessionId)?t:void 0),timestamp:g.timestamp,isValid:g.isValid,isExpired:g.isExpired,age:l,maxAge:this.config.expiryMs}),g}async applyLinkerParams(){var e;if(!isBrowser2())return this.debug("Cannot apply linker params in SSR environment"),{applied:!1,urlCleaned:!1,reason:"ssr"};if(!this.config.acceptIncoming)return this.debug("acceptIncoming is disabled, not applying linker params"),{applied:!1,urlCleaned:!(!this.config.autoCleanUrl||!this.hasLinkerParams())&&this.cleanLinkerParamsFromUrl(),reason:"accept_incoming_disabled"};if(this.config.validateReferrer&&this.config.allowedDomains){const e=this.config.getReferrer();if(e)try{const t=new URL(e).hostname;if(!this.isDomainAllowed(t))return this.debug("Referrer not in allowedDomains, rejecting linker params",{referrer:t,allowedDomains:this.config.allowedDomains}),{applied:!1,urlCleaned:!(!this.config.autoCleanUrl||!this.hasLinkerParams())&&this.cleanLinkerParamsFromUrl(),reason:"invalid_referrer"};this.debug("Referrer validated",{referrer:t})}catch(t){this.debug("Could not parse referrer URL",{referrer:e})}}const t=await this.parseLinkerParams();if(!t)return this.debug("No linker params found in URL"),{applied:!1,urlCleaned:!1,reason:"no_params"};if(t.isExpired)return this.debug("Linker params expired",{timestamp:t.timestamp}),{applied:!1,params:t,urlCleaned:!!this.config.autoCleanUrl&&this.cleanLinkerParamsFromUrl(),reason:"expired"};try{this.anonymousIdManager.set(t.anonymousId),this.debug("Applied anonymous ID from linker params",{anonymousId:this.redactId(t.anonymousId),sessionId:this.redactId(null!=(e=t.sessionId)?e:void 0)})}catch(e){return this.debug("Failed to apply anonymous ID",{error:e}),{applied:!1,params:t,urlCleaned:!1,reason:"invalid"}}return{applied:!0,params:t,urlCleaned:!!this.config.autoCleanUrl&&this.cleanLinkerParamsFromUrl()}}cleanLinkerParamsFromUrl(){if(!isHistoryAvailable())return this.debug("History API not available for URL cleanup"),!1;const e=this.config.getUrl();if(!e||!isValidUrl(e))return!1;const t=new URL(e);let i=!1;for(const e of rn)t.searchParams.has(e)&&(t.searchParams.delete(e),i=!0);return!!i&&(this.config.setUrl(t.toString()),this.debug("Cleaned linker params from URL",{newUrl:t.toString()}),!0)}hasLinkerParams(e){const t=null!=e?e:this.config.getUrl();if(!t||!isValidUrl(t))return!1;const i=new URL(t);return i.searchParams.has(Xr)&&i.searchParams.has(Zr)}getExpiryMs(){return this.config.expiryMs}getAllowedDomains(){return this.config.allowedDomains}isAcceptingIncoming(){return this.config.acceptIncoming}isWarnOnHttpEnabled(){return this.config.warnOnHttp}isUrlAllowed(e){return!this.config.allowedDomains||0===this.config.allowedDomains.length||isAllowedDomain(e,this.config.allowedDomains)}isDomainAllowed(e){if(!this.config.allowedDomains||0===this.config.allowedDomains.length)return!1;const t=e.toLowerCase();return this.config.allowedDomains.some(e=>matchesDomainPattern(t,e))}async generateSignature(e,t,i){const r=this.config.signatureSecret;return r?async function(e,t,i){if(!isHmacAvailable())return(null==i?void 0:i.onInsecureContext)&&!Yr&&(i.onInsecureContext(),Yr=!0),null;try{return await async function(e,t){if(!isHmacAvailable())throw new Gr("Web Crypto API is required for HMAC-SHA256 signing. Ensure you are using HTTPS in browser environments.");const i=new TextEncoder,r=await globalThis.crypto.subtle.importKey("raw",i.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return bufferToHex(await globalThis.crypto.subtle.sign("HMAC",r,i.encode(e)))}(e,t)}catch(e){return(null==i?void 0:i.onInsecureContext)&&!Yr&&(i.onInsecureContext(),Yr=!0),null}}(`${e}|${t}|${i}`,r,{onInsecureContext:()=>{nn||(console.warn("[Overvio Security] HMAC signing unavailable. Web Crypto API requires HTTPS. Cross-domain signature will be skipped."),nn=!0)}}):null}debug(e,t){this.config.onDebug&&this.config.onDebug(`[CrossDomain] ${e}`,t)}redactId(e){return e?e.length<=12?e.slice(0,3)+"***":e.slice(0,4)+"***"+e.slice(-4):"(none)"}isLocalhost(e){const t=e.toLowerCase();return"localhost"===t||"127.0.0.1"===t||"::1"===t||"[::1]"===t||"0.0.0.0"===t}},on="data-overvio-decorated";function isBrowser3(){return"undefined"!=typeof window&&"undefined"!=typeof document}var an=class{constructor(e){var t,i,r,n;__publicField(this,"crossDomainLinker"),__publicField(this,"config"),__publicField(this,"customIsExternalUrl"),__publicField(this,"isEnabled",!1),__publicField(this,"observedLinks",new Set),__publicField(this,"boundClickHandler"),__publicField(this,"mutationObserver",null),__publicField(this,"clicksHandled",0),this.crossDomainLinker=e.crossDomainLinker,void 0!==e.isExternalUrl&&(this.customIsExternalUrl=e.isExternalUrl),this.config={selector:null!=(t=e.selector)?t:"a[data-overvio-link]",autoDecorateExternalLinks:null!=(i=e.autoDecorateExternalLinks)&&i,observeDynamicLinks:null!=(r=e.observeDynamicLinks)&&r,getCurrentHostname:null!=(n=e.getCurrentHostname)?n:()=>isBrowser3()?window.location.hostname:""},void 0!==e.onDebug&&(this.config.onDebug=e.onDebug),this.boundClickHandler=this.handleClick.bind(this),this.debug("LinkDecorator created",{selector:this.config.selector,autoDecorateExternalLinks:this.config.autoDecorateExternalLinks,observeDynamicLinks:this.config.observeDynamicLinks})}decorateLinks(e){if(!isBrowser3())return this.debug("Cannot decorate links in non-browser environment"),{decoratedCount:0,skippedCount:0,totalCount:0};const t=null!=e?e:this.config.selector,i=document.querySelectorAll(t);let r=0,n=0;return i.forEach(e=>{this.decorateLink(e)?r++:n++}),this.debug("Decorated links",{selector:t,decoratedCount:r,skippedCount:n,totalCount:i.length}),{decoratedCount:r,skippedCount:n,totalCount:i.length}}decorateLink(e){return!(e.hasAttribute(on)||!function(e){var t;const i=e.href;return!(!i||i.startsWith("javascript:")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("#")||(null==(t=e.getAttribute("href"))?void 0:t.startsWith("#"))||i.startsWith("blob:")||i.startsWith("data:"))}(e)||!this.isExternalUrl(e.href)||(e.addEventListener("click",this.boundClickHandler),this.observedLinks.add(e),e.setAttribute(on,"true"),this.debug("Decorated link",{href:e.href}),0))}enable(){this.isEnabled||(isBrowser3()?(this.isEnabled=!0,this.config.autoDecorateExternalLinks?this.decorateAllExternalLinks():this.decorateLinks(),this.config.observeDynamicLinks&&this.startObserving(),this.debug("LinkDecorator enabled")):this.debug("Cannot enable in non-browser environment"))}disable(){this.isEnabled&&(this.isEnabled=!1,this.observedLinks.forEach(e=>{e.removeEventListener("click",this.boundClickHandler),e.removeAttribute(on)}),this.observedLinks.clear(),this.stopObserving(),this.debug("LinkDecorator disabled"))}decorateAllExternalLinks(){if(!isBrowser3())return{decoratedCount:0,skippedCount:0,totalCount:0};const e=document.querySelectorAll("a[href]");let t=0,i=0;return e.forEach(e=>{this.isExternalUrl(e.href)&&this.decorateLink(e)?t++:i++}),this.debug("Decorated all external links",{decoratedCount:t,skippedCount:i,totalCount:e.length}),{decoratedCount:t,skippedCount:i,totalCount:e.length}}getStats(){return{isEnabled:this.isEnabled,observedLinksCount:this.observedLinks.size,clicksHandled:this.clicksHandled,isObserving:null!==this.mutationObserver}}isExternalUrl(e){return this.customIsExternalUrl?this.customIsExternalUrl(e):function(e,t){const i=function(e){try{return new URL(e,isBrowser3()?window.location.origin:void 0).hostname}catch(e){return null}}(e);return!!i&&i.toLowerCase()!==t.toLowerCase()}(e,this.config.getCurrentHostname())}getSelector(){return this.config.selector}destroy(){this.disable(),this.debug("LinkDecorator destroyed")}handleClick(e){const t=e.currentTarget;if(!t||!t.href)return;if(!e.isTrusted)return void this.debug("Skipping untrusted (programmatic) click",{href:t.href});if(e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return void this.debug("Skipping modified click",{href:t.href});if(0!==e.button)return;if(!this.crossDomainLinker.isUrlAllowed(t.href))return void this.debug("Link destination not in allowedDomains, skipping decoration",{href:t.href,allowedDomains:this.crossDomainLinker.getAllowedDomains()});e.preventDefault();const i=t.href,r=t.target;this.crossDomainLinker.getLinkerUrl(i).then(e=>{var t;this.clicksHandled++,this.debug("Handling click with decorated URL",{originalHref:i,decoratedUrl:e}),"_blank"===r?window.open(e,"_blank","noopener,noreferrer"):"_parent"===r?window.parent.location.href=e:"_top"===r&&null!=(null==(t=window.top)?void 0:t.location.assign(e))||(window.location.href=e)})}startObserving(){isBrowser3()&&"undefined"!=typeof MutationObserver?this.mutationObserver||(this.mutationObserver=new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{e instanceof HTMLAnchorElement?this.processNewLink(e):e instanceof HTMLElement&&e.querySelectorAll("a[href]").forEach(e=>this.processNewLink(e))})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.debug("MutationObserver started")):this.debug("MutationObserver not available")}stopObserving(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null,this.debug("MutationObserver stopped"))}processNewLink(e){this.config.autoDecorateExternalLinks?this.isExternalUrl(e.href)&&this.decorateLink(e):e.matches(this.config.selector)&&this.decorateLink(e)}debug(e,t){this.config.onDebug&&this.config.onDebug(`[LinkDecorator] ${e}`,t)}},cn="USER_IDENTIFIED",ln="SESSION_UPDATED",un="LOGOUT";A(),h();var dn=100,hn=4096;function isValidTraitKey(e){return!("string"!=typeof e||0===e.length||e.length>256||e.startsWith("$"))}function isValidTraitValue(e){return null===e||("string"==typeof e?e.length<=hn:"number"==typeof e?Number.isFinite(e):"boolean"==typeof e||!!Array.isArray(e)&&(0===e.length||!(e.length>100)&&(!!e.every(e=>"string"==typeof e&&e.length<=hn)||!!e.every(e=>"number"==typeof e&&Number.isFinite(e)))))}function isUserTraits(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;const t=e,i=Object.keys(t);if(i.length>dn)return!1;for(const e of i){if(!isValidTraitKey(e))return!1;const i=t[e];if(void 0!==i&&!isValidTraitValue(i))return!1}return!0}function validateUserTraits(e){const t=[];if("object"!=typeof e||null===e||Array.isArray(e))return{valid:!1,errors:[{code:"INVALID_TYPE",message:"Traits must be an object, received "+(null===e?"null":Array.isArray(e)?"array":typeof e)}]};const i=e,r=Object.keys(i);r.length>dn&&t.push({code:"TOO_MANY_TRAITS",message:`Too many traits: ${r.length} exceeds maximum of 100`});for(const e of r){if("string"!=typeof e||0===e.length){t.push({key:e,code:"INVALID_KEY",message:"Trait key must be a non-empty string"});continue}e.startsWith("$")&&t.push({key:e,code:"RESERVED_KEY",message:`Trait key '${e}' uses reserved prefix '$'`}),e.length>256&&t.push({key:e,code:"KEY_TOO_LONG",message:`Trait key '${e.substring(0,20)}...' exceeds maximum length of 256`});const r=i[e];void 0!==r&&(isValidTraitValue(r)||("string"==typeof r&&r.length>hn?t.push({key:e,code:"VALUE_TOO_LONG",message:`Trait '${e}' value exceeds maximum length of 4096`}):Array.isArray(r)&&r.length>100?t.push({key:e,code:"INVALID_VALUE",message:`Trait '${e}' array exceeds maximum length of 100 elements`}):t.push({key:e,code:"INVALID_VALUE",message:`Trait '${e}' has invalid value type: ${typeof r}`})))}return{valid:0===t.length,errors:t}}var gn="user_";var pn=class{constructor(e){var t,i,r;__publicField(this,"storage"),__publicField(this,"emitter"),__publicField(this,"anonymousIdManager"),__publicField(this,"storageKey"),__publicField(this,"ttl"),__publicField(this,"onDebug"),__publicField(this,"crossTabSync"),__publicField(this,"crossTabSyncEnabled"),__publicField(this,"securityLogger"),__publicField(this,"identityState",null),__publicField(this,"isSyncingFromOtherTab",!1),__publicField(this,"unsubscribeCallbacks",[]),__publicField(this,"changeListeners",new Set),__publicField(this,"cachedSnapshot",null),this.storage=e.storage,this.emitter=e.emitter,this.anonymousIdManager=e.anonymousIdManager,this.storageKey=null!=(t=e.storageKey)?t:"identity",this.ttl=null!=(i=e.ttl)?i:31536e6,void 0!==e.onDebug&&(this.onDebug=e.onDebug),this.crossTabSyncEnabled=null==(r=e.enableCrossTabSync)||r,void 0!==e.crossTabSync&&(this.crossTabSync=e.crossTabSync),void 0!==e.securityLogger&&(this.securityLogger=e.securityLogger),this.loadFromStorage(),this.crossTabSync&&this.crossTabSyncEnabled&&this.setupCrossTabListeners()}identify(e,t){var i,r,n;let s,o;if("string"==typeof e?(s=e,o=null!=t?t:{}):(o=e,s=o.email&&"string"==typeof o.email?function(e){const t=function(e){let t=5381,i=52711;for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);t=(t<<5)+t^n,i=(i<<5)+i^n}const r=Math.abs(t).toString(16).padStart(8,"0"),n=Math.abs(i).toString(16).padStart(8,"0");let s=0,o=0;for(let t=0;t<e.length;t++){const i=e.charCodeAt(t);s=31*s+i>>>0,o=37*o+i>>>0}return`${r}${n}${s.toString(16).padStart(8,"0")}${o.toString(16).padStart(8,"0")}`.substring(0,32)}(e.toLowerCase().trim());return`${gn}${t}`}(o.email):`${gn}${secureRandomUUID()}`),!isUserTraits(o)){const e=validateUserTraits(o);this.debug("Invalid traits provided",{errors:e.errors}),o={}}const a=this.anonymousIdManager.getOrCreate(),c=Date.now(),l=null===this.identityState||this.identityState.userId!==s,u=this.identityState;let d;if(l||!u)d={...o};else{d={...u.traits,...o};const e=Object.keys(d);if(e.length>dn){this.debug("Merged traits exceed maximum count, truncating to limit",{count:e.length,max:dn});const t=Object.keys(o),i=Object.keys(u.traits).filter(e=>!t.includes(e)),r=new Set;for(const e of t)r.size<dn&&r.add(e);for(const e of i)r.size<dn&&r.add(e);const n={};for(const e of r)n[e]=d[e];d=n}}this.identityState={userId:s,traits:d,identifiedAt:l?c:null!=(i=null==u?void 0:u.identifiedAt)?i:c,updatedAt:c,previousAnonymousId:l?a:null!=(r=null==u?void 0:u.previousAnonymousId)?r:a},this.persistToStorage();const h={type:"identify",userId:createUserId(s),anonymousId:a,traits:this.identityState.traits,timestamp:c},g={userId:h.userId};return void 0!==h.traits&&(g.traits=h.traits),this.emitter.emit("identify",{user:g}),this.isSyncingFromOtherTab||this.broadcastIdentity(h.userId,h.traits,l),this.debug("User identified",{userId:s,isNewUser:l,traitCount:Object.keys(this.identityState.traits).length,syncedFromOtherTab:this.isSyncingFromOtherTab}),null==(n=this.securityLogger)||n.log({type:"AUTHN_LOGIN_SUCCESS",action:"user_identified",outcome:"success",userId:h.userId,metadata:{component:"IdentityManager",isNewUser:l,traitCount:Object.keys(this.identityState.traits).length,hasTraits:Object.keys(this.identityState.traits).length>0,previousAnonymousId:this.identityState.previousAnonymousId}}),this.notifyChangeListeners(),h}getUserId(){return null===this.identityState?null:createUserId(this.identityState.userId)}getTraits(){return null===this.identityState?null:{...this.identityState.traits}}isIdentified(){return null!==this.identityState}getPreviousAnonymousId(){return null===this.identityState?null:createUserId(this.identityState.previousAnonymousId)}getStats(){return null===this.identityState?{isIdentified:!1,userId:null,traitCount:0,identifiedAt:null,updatedAt:null,previousAnonymousId:null,crossTabSyncEnabled:this.crossTabSyncEnabled&&void 0!==this.crossTabSync}:{isIdentified:!0,userId:createUserId(this.identityState.userId),traitCount:Object.keys(this.identityState.traits).length,identifiedAt:this.identityState.identifiedAt,updatedAt:this.identityState.updatedAt,previousAnonymousId:createUserId(this.identityState.previousAnonymousId),crossTabSyncEnabled:this.crossTabSyncEnabled&&void 0!==this.crossTabSync}}getState(){return null!==this.cachedSnapshot||(this.cachedSnapshot=this.buildSnapshot()),this.cachedSnapshot}onChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}buildSnapshot(){const e=this.anonymousIdManager.get(),t=null!==e?String(e):null;if(null===this.identityState)return Object.freeze({userId:null,anonymousId:t,traits:Object.freeze({}),isIdentified:!1});const i={};for(const e of Object.keys(this.identityState.traits))i[e]=this.identityState.traits[e];return Object.freeze({userId:this.identityState.userId,anonymousId:t,traits:Object.freeze(i),isIdentified:!0})}notifyChangeListeners(){if(this.cachedSnapshot=null,0===this.changeListeners.size)return;const e=this.getState();this.debug("Notifying change listeners",{listenerCount:this.changeListeners.size,isIdentified:e.isIdentified});for(const t of this.changeListeners)try{t(e)}catch(e){this.debug("Error in change listener",{error:e})}}reset(){var e;const t=this.getUserId();this.identityState=null,this.storage.remove(this.storageKey);const i=this.anonymousIdManager.reset();return this.isSyncingFromOtherTab||this.broadcastLogout(t),this.debug("Identity reset",{previousUserId:t,newAnonymousId:i,syncedFromOtherTab:this.isSyncingFromOtherTab}),null==(e=this.securityLogger)||e.log({type:"AUTHN_LOGOUT",action:"user_logout",outcome:"success",metadata:{component:"IdentityManager",previousUserId:null!=t?t:void 0,newAnonymousId:i}}),this.notifyChangeListeners(),i}updateTraits(e){if(null===this.identityState)throw new Error("Cannot update traits: no user is identified");if(!isUserTraits(e)){const t=validateUserTraits(e);return void this.debug("Invalid traits provided for update",{errors:t.errors})}let t={...this.identityState.traits,...e};const i=Object.keys(t);if(i.length>dn){this.debug("Merged traits exceed maximum count, truncating to limit",{count:i.length,max:dn});const r=Object.keys(e),n=Object.keys(this.identityState.traits).filter(e=>!r.includes(e)),s=new Set;for(const e of r)s.size<dn&&s.add(e);for(const e of n)s.size<dn&&s.add(e);const o={};for(const e of s)o[e]=t[e];t=o}this.identityState={...this.identityState,traits:t,updatedAt:Date.now()},this.persistToStorage(),this.emitter.emit("identify",{user:{userId:createUserId(this.identityState.userId),traits:this.identityState.traits}}),this.debug("Traits updated",{userId:this.identityState.userId,traitCount:Object.keys(this.identityState.traits).length}),this.notifyChangeListeners()}loadFromStorage(){try{const e=this.storage.get(this.storageKey);if(null!==e&&function(e){if("object"!=typeof e||null===e)return!1;const t=e;return 1===t._v&&"string"==typeof t.userId&&""!==t.userId&&"object"==typeof t.traits&&null!==t.traits&&"number"==typeof t.identifiedAt&&"number"==typeof t.updatedAt&&"string"==typeof t.previousAnonymousId}(e)){const{_v:t,...i}=e;this.identityState=i,this.debug("Identity loaded from storage",{userId:i.userId,traitCount:Object.keys(i.traits).length})}}catch(e){this.debug("Failed to load identity from storage",{error:e}),this.identityState=null}}persistToStorage(){if(null===this.identityState)return;const e={...this.identityState,_v:1};this.storage.set(this.storageKey,e,{ttl:this.ttl})||this.debug("Failed to persist identity to storage")}debug(e,t){this.onDebug&&this.onDebug(e,t)}setupCrossTabListeners(){if(!this.crossTabSync)return;const e=this.crossTabSync.on(cn,(e,t)=>{this.handleCrossTabIdentify(e,t)});this.unsubscribeCallbacks.push(e);const t=this.crossTabSync.on(un,(e,t)=>{this.handleCrossTabLogout(e,t)});this.unsubscribeCallbacks.push(t),this.debug("Cross-tab listeners setup complete",{tabId:this.crossTabSync.tabId})}broadcastIdentity(e,t,i){if(!this.crossTabSync||!this.crossTabSyncEnabled)return;const r={userId:e};void 0!==t&&(r.traits=t),i&&(r.isNewUser=!0),this.crossTabSync.broadcast(cn,r),this.debug("Broadcast USER_IDENTIFIED to other tabs",{userId:e,isNewUser:i})}broadcastLogout(e){if(!this.crossTabSync||!this.crossTabSyncEnabled)return;const t={reason:"manual"};null!==e&&(t.previousUserId=e),this.crossTabSync.broadcastImmediate(un,t),this.debug("Broadcast LOGOUT to other tabs",{previousUserId:e})}handleCrossTabIdentify(e,t){var i;if(this.debug("Received USER_IDENTIFIED from another tab",{userId:e.userId,sourceTabId:t.sourceTabId,timestamp:t.timestamp,isNewUser:e.isNewUser}),null!==this.identityState&&this.identityState.updatedAt>t.timestamp)this.debug("Ignoring stale USER_IDENTIFIED event",{localUpdatedAt:this.identityState.updatedAt,remoteTimestamp:t.timestamp});else{this.isSyncingFromOtherTab=!0;try{const r=e.userId,n=null!=(i=e.traits)?i:{};this.identify(r,n),this.debug("Applied USER_IDENTIFIED from another tab",{userId:e.userId,sourceTabId:t.sourceTabId})}finally{this.isSyncingFromOtherTab=!1}}}handleCrossTabLogout(e,t){this.debug("Received LOGOUT from another tab",{previousUserId:e.previousUserId,sourceTabId:t.sourceTabId,reason:e.reason}),this.isSyncingFromOtherTab=!0;try{this.reset(),this.debug("Applied LOGOUT from another tab",{sourceTabId:t.sourceTabId})}finally{this.isSyncingFromOtherTab=!1}}destroy(){for(const e of this.unsubscribeCallbacks)e();this.unsubscribeCallbacks.length=0,this.changeListeners.clear(),this.cachedSnapshot=null,this.debug("IdentityManager destroyed")}};h();var mn=18e5,fn=6e4,yn=864e5;function generateUUID(){return secureRandomUUID()}function calculateTimeUntilExpiration(e,t,i=Date.now()){const r=e+t-i;return Math.max(0,r)}function isSessionExpired(e,t,i=Date.now()){return 0===calculateTimeUntilExpiration(e,t,i)}var vn={debug:()=>{},warn:()=>{},error:()=>{}},bn=class{constructor(e={}){var t,i,r,n;__publicField(this,"name","composite"),__publicField(this,"adapterEntries"),__publicField(this,"logger"),__publicField(this,"readStrategy"),__publicField(this,"writeStrategy"),__publicField(this,"persistenceDisabled"),this.logger=null!=(t=e.logger)?t:vn,this.readStrategy=null!=(i=e.readStrategy)?i:"first-available",this.writeStrategy=null!=(r=e.writeStrategy)?r:"all",this.persistenceDisabled=null!=(n=e.disablePersistence)&&n,e.adapters&&e.adapters.length>0?this.adapterEntries=this.buildAdapterEntries(e.adapters):this.adapterEntries=[];const s=this.adapterEntries.filter(e=>e.available).map(e=>e.adapter.name);0===s.length?this.logger.warn("CompositeAdapter created with no available adapters - all storage operations will fail silently"):this.logger.debug(`CompositeAdapter initialized with ${s.length} available adapter(s): ${s.join(", ")}`)}buildAdapterEntries(e){const t=[];for(const i of e){if(this.persistenceDisabled&&"memory"!==i.name){this.logger.debug(`Skipping adapter '${i.name}' - persistence is disabled`);continue}let e=!1;try{e=i.isAvailable()}catch(t){this.logger.warn(`Adapter '${i.name}' threw during isAvailable() check`,t),e=!1}t.push({adapter:i,available:e}),e||this.logger.debug(`Adapter '${i.name}' is not available`)}return t}getAvailableAdapters(){return this.adapterEntries.filter(e=>e.available).map(e=>e.adapter)}getPrimaryAdapter(){const e=this.getAvailableAdapters()[0];return void 0!==e?e:null}isAvailable(){return this.adapterEntries.some(e=>e.available)}get(e,t){if("primary-only"===this.readStrategy){const i=this.getPrimaryAdapter();if(!i)return null;try{return i.get(e,t)}catch(t){return this.logger.error(`Primary adapter '${i.name}' failed to get key '${e}'`,t),null}}const i=this.getAvailableAdapters();for(const r of i)try{const i=r.get(e,t);if(null!==i)return this.logger.debug(`Found value for key '${e}' in adapter '${r.name}'`),i}catch(t){this.logger.warn(`Adapter '${r.name}' failed to get key '${e}'`,t)}return null}set(e,t,i){if("primary-only"===this.writeStrategy){const r=this.getPrimaryAdapter();if(!r)return this.logger.warn("No primary adapter available for set operation"),!1;try{const n=r.set(e,t,i);return n||this.logger.warn(`Primary adapter '${r.name}' failed to set key '${e}'`),n}catch(t){return this.logger.error(`Primary adapter '${r.name}' threw during set for key '${e}'`,t),!1}}const r=this.getAvailableAdapters();let n=0;for(const s of r)try{s.set(e,t,i)?(n++,this.logger.debug(`Successfully set key '${e}' in adapter '${s.name}'`)):this.logger.warn(`Adapter '${s.name}' returned false for set key '${e}'`)}catch(t){this.logger.error(`Adapter '${s.name}' threw during set for key '${e}'`,t)}return n>0}remove(e){const t=this.getAvailableAdapters();let i=0;for(const r of t)try{r.remove(e)&&(i++,this.logger.debug(`Removed key '${e}' from adapter '${r.name}'`))}catch(t){this.logger.warn(`Adapter '${r.name}' failed to remove key '${e}'`,t)}return i>0}clear(){const e=this.getAvailableAdapters();let t=0;for(const i of e)try{const e=i.clear();t+=e,this.logger.debug(`Cleared ${e} key(s) from adapter '${i.name}'`)}catch(e){this.logger.warn(`Adapter '${i.name}' failed during clear`,e)}return t}keys(){const e=this.getAvailableAdapters(),t=new Set;for(const i of e)try{const e=i.keys();for(const i of e)t.add(i)}catch(e){this.logger.warn(`Adapter '${i.name}' failed to list keys`,e)}return Array.from(t)}has(e){const t=this.getAvailableAdapters();for(const i of t)try{if(i.has(e))return!0}catch(t){this.logger.warn(`Adapter '${i.name}' failed to check key '${e}'`,t)}return!1}getEntry(e){if("primary-only"===this.readStrategy){const t=this.getPrimaryAdapter();if(!t)return null;try{return t.getEntry(e)}catch(i){return this.logger.error(`Primary adapter '${t.name}' failed to getEntry for key '${e}'`,i),null}}const t=this.getAvailableAdapters();for(const i of t)try{const t=i.getEntry(e);if(null!==t)return this.logger.debug(`Found entry for key '${e}' in adapter '${i.name}'`),t}catch(t){this.logger.warn(`Adapter '${i.name}' failed to getEntry for key '${e}'`,t)}return null}getAdapterInfo(){return this.adapterEntries.map(e=>({name:e.adapter.name,available:e.available}))}get availableAdapterCount(){return this.adapterEntries.filter(e=>e.available).length}getPrimaryAdapterName(){var e;const t=this.getPrimaryAdapter();return null!=(e=null==t?void 0:t.name)?e:null}refreshAvailability(){for(const e of this.adapterEntries)try{e.available=e.adapter.isAvailable()}catch(t){this.logger.warn(`Adapter '${e.adapter.name}' threw during availability refresh`,t),e.available=!1}const e=this.adapterEntries.filter(e=>e.available).map(e=>e.adapter.name);this.logger.debug(`Availability refreshed: ${e.length} adapter(s) available`)}synchronize(e,t){const i=this.getPrimaryAdapter();if(!i)return!1;try{const r=i.get(e,t);if(null===r)return!0;const n=this.getAvailableAdapters();let s=0;for(const o of n)if(o!==i)try{o.set(e,r,t)&&s++}catch(t){this.logger.warn(`Failed to sync key '${e}' to adapter '${o.name}'`,t)}else s++;return s>0}catch(t){return this.logger.error(`Failed to read key '${e}' for synchronization`,t),!1}}destroy(){for(const e of this.adapterEntries)try{const t=e.adapter;"function"==typeof t.destroy&&(t.destroy(),this.logger.debug(`Destroyed adapter '${e.adapter.name}'`))}catch(t){this.logger.warn(`Error destroying adapter '${e.adapter.name}'`,t)}}};function createCompositeAdapter(e){return new bn(e)}var Sn=["identity","session"],wn="[Overvio SDK Cookie Security]";function logSecurityWarnings(e,t={}){var i;if(0===e.length)return;const r="undefined"!=typeof process&&!0,n=t.suppressInProduction&&r;for(const r of e)n||console.warn(r),(null==(i=t.securityLogger)?void 0:i.isEnabled())&&t.securityLogger.log({type:"SEC_COOKIE_WARNING",action:"cookie_security_validation",outcome:"failure",severity:"medium",metadata:{warning:r,source:"cookie-security"}})}var Cn=new Set(["com","org","net","edu","gov","mil","io","co","ai","app","dev","info","biz","me","tv","cc","ws"]),En=new Set(["uk","de","fr","it","es","nl","be","at","ch","pl","ru","cn","jp","kr","au","nz","ca","br","mx","in","za","se","no","dk","fi","ie","pt","gr","cz","hu","ro","bg","sk","ua"]),_n=new Set(["co.uk","org.uk","me.uk","ac.uk","gov.uk","com.au","net.au","org.au","edu.au","gov.au","co.nz","org.nz","net.nz","co.jp","or.jp","ne.jp","com.br","org.br","net.br","com.cn","org.cn","net.cn","com.mx","org.mx","co.in","org.in","net.in","co.za","org.za"]),In=new Set;function isIPv4Address(e){const t=e.split(".");if(4!==t.length)return!1;for(const e of t){const t=parseInt(e,10);if(isNaN(t)||t<0||t>255||String(t)!==e)return!1}return!0}function isIPv6Address(e){const t=e.replace(/^\[/,"").replace(/\]$/,"");return t.includes(":")&&/^[0-9a-fA-F:]+$/.test(t)}var kn="overvio_",xn=6048e5;function isStorageAdapter(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.name&&"function"==typeof t.get&&"function"==typeof t.set&&"function"==typeof t.remove&&"function"==typeof t.clear&&"function"==typeof t.keys&&"function"==typeof t.has&&"function"==typeof t.isAvailable&&"function"==typeof t.getEntry}function buildStorageKey(e){const{key:t,namespace:i,includePrefix:r=!0}=e,n=[];return r&&n.push(kn),i&&n.push(`${i}_`),n.push(t),n.join("")}function parseStorageKey(e){if(!e.startsWith(kn))return null;const t=e.slice(8),i=t.indexOf("_");return i>0?{namespace:t.slice(0,i),key:t.slice(i+1)}:{key:t}}function isStorageWrapper(e){if("object"!=typeof e||null===e)return!1;const t=e;return"v"in t&&"number"==typeof t.s&&1===t._v}var Tn=class extends Error{constructor(e,t){super(`Cookie size exceeded for key "${e}": ${t} bytes (max: 4096 bytes)`),__publicField(this,"code","COOKIE_SIZE_EXCEEDED"),__publicField(this,"key"),__publicField(this,"size"),__publicField(this,"maxSize",4096),this.name="CookieSizeExceededError",this.key=e,this.size=t}};function parseCookies(e){const t=new Map;if(!e||""===e.trim())return t;const i=e.split(";");for(const e of i){const i=e.trim();if(""===i)continue;const r=i.indexOf("=");if(-1===r){t.set(i,"");continue}const n=i.slice(0,r).trim(),s=i.slice(r+1).trim();""!==n&&t.set(n,s)}return t}function serializeCookie(e,t,i){const r=[`${e}=${t}`];return void 0!==i.path&&r.push(`path=${i.path}`),void 0!==i.domain&&r.push(`domain=${i.domain}`),i.secure&&r.push("secure"),void 0!==i.sameSite&&r.push(`samesite=${i.sameSite}`),void 0!==i.maxAge?r.push(`max-age=${i.maxAge}`):void 0!==i.expires&&r.push(`expires=${i.expires.toUTCString()}`),r.join("; ")}var An=class{constructor(e={}){var t,i,r,n,s,o;__publicField(this,"name","cookie"),__publicField(this,"availabilityCache",null),__publicField(this,"_path"),__publicField(this,"_domain"),__publicField(this,"_secure"),__publicField(this,"_sameSite"),__publicField(this,"_maxAge"),__publicField(this,"_getter"),__publicField(this,"_setter"),__publicField(this,"_getCookieString"),__publicField(this,"_hasSSRInjection"),__publicField(this,"_securityContext"),__publicField(this,"_suppressSecurityWarningsInProduction"),this._path=null!=(t=e.path)?t:"/",this._domain=e.domain;const a="undefined"!=typeof window&&"https:"===(null==(i=window.location)?void 0:i.protocol);this._secure=null!=(r=e.secure)?r:a,this._sameSite=null!=(n=e.sameSite)?n:"Lax",this._maxAge=e.maxAge,this._getter=e.getter,this._setter=e.setter,this._getCookieString=e.getCookieString,this._hasSSRInjection=!!(this._getter||this._setter||this._getCookieString),this._securityContext=null!=(s=e.securityContext)?s:"general",this._suppressSecurityWarningsInProduction=null!=(o=e.suppressSecurityWarningsInProduction)&&o}isAvailable(){if(null!==this.availabilityCache)return this.availabilityCache;if(this._hasSSRInjection)return this.availabilityCache=!0,!0;if("undefined"==typeof document)return this.availabilityCache=!1,!1;try{const e=`${kn}__cookie_test__`,t="test";document.cookie=`${e}=${t}; path=/`;const i=parseCookies(document.cookie).get(e)===t;return document.cookie=`${e}=; path=/; max-age=0`,this.availabilityCache=i,i}catch(e){return this.availabilityCache=!1,!1}}_resolveCookieString(){return void 0!==this._getCookieString?this._getCookieString():"undefined"!=typeof document?document.cookie:null}_resolveCookieValue(e){var t;return void 0!==this._getter?this._getter(e):"undefined"!=typeof document&&null!=(t=parseCookies(document.cookie).get(e))?t:null}_writeCookie(e,t,i){if(void 0!==this._setter)return this._setter(e,t,i),!0;if("undefined"!=typeof document){const r=serializeCookie(e,t,i);return document.cookie=r,!0}return!1}_cookieExists(e){return void 0!==this._getter?null!==this._getter(e):void 0!==this._getCookieString?parseCookies(this._getCookieString()).has(e):"undefined"!=typeof document&&parseCookies(document.cookie).has(e)}get(e,t){var i;const r=this.getEntry(e,t);return null!=(i=null==r?void 0:r.value)?i:null}set(e,t,i){const r={...i};return void 0!==(null==i?void 0:i.ttl)&&i.ttl>0&&(r.maxAge=Math.ceil(i.ttl/1e3)),this.setCookie(e,t,r)}setCookie(e,t,i){if(void 0===this._setter&&"undefined"==typeof document)return!1;try{const r=buildStorageKey((null==i?void 0:i.namespace)?{key:e,namespace:i.namespace,includePrefix:!0}:{key:e,includePrefix:!0}),n=Date.now(),s={v:t,s:n,_v:1};void 0!==(null==i?void 0:i.ttl)&&i.ttl>0?s.e=n+i.ttl:void 0!==(null==i?void 0:i.maxAge)&&i.maxAge>0&&(s.e=n+1e3*i.maxAge);const o=JSON.stringify(s),a=encodeURIComponent(o),c=function(e,t){return 2*(e.length+1+t.length)}(r,a);if(c>4096)throw new Tn(e,c);const l=this.buildMergedOptions(i);return this._writeCookie(r,a,l)}catch(e){if(e instanceof Tn)throw e;return!1}}remove(e,t){const i=void 0!==this._getter||void 0!==this._getCookieString||"undefined"!=typeof document,r=void 0!==this._setter||"undefined"!=typeof document;if(!i||!r)return!1;try{const i=buildStorageKey((null==t?void 0:t.namespace)?{key:e,namespace:t.namespace,includePrefix:!0}:{key:e,includePrefix:!0});if(!this._cookieExists(i))return!1;const r=this.buildDeleteOptions();return this._writeCookie(i,"",r)}catch(e){return!1}}clear(){try{const e=this._resolveCookieString();if(null===e)return 0;const t=parseCookies(e);let i=0;for(const e of t.keys())if(e.startsWith(kn)){const t=this.buildDeleteOptions(),r=serializeCookie(e,"",t);void 0!==this._setter?this._setter(e,"",t):"undefined"!=typeof document&&(document.cookie=r),i++}return i}catch(e){return 0}}keys(){try{const e=this._resolveCookieString();if(null===e)return[];const t=parseCookies(e),i=[];for(const e of t.keys())e.startsWith(kn)&&i.push(e.slice(8));return i}catch(e){return[]}}has(e,t){try{const i=buildStorageKey((null==t?void 0:t.namespace)?{key:e,namespace:t.namespace,includePrefix:!0}:{key:e,includePrefix:!0}),r=this._resolveCookieValue(i);if(!r)return!1;const n=decodeURIComponent(r),s=JSON.parse(n);return!(!isStorageWrapper(s)||void 0!==s.e&&Date.now()>s.e&&(this.remove(e,t),1))}catch(e){return!1}}getEntry(e,t){try{const i=buildStorageKey((null==t?void 0:t.namespace)?{key:e,namespace:t.namespace,includePrefix:!0}:{key:e,includePrefix:!0}),r=this._resolveCookieValue(i);if(!r)return null;const n=decodeURIComponent(r),s=JSON.parse(n);if(!isStorageWrapper(s))return null;if(void 0!==s.e&&Date.now()>s.e)return this.remove(e),null;const o={value:s.v,storedAt:s.s};return void 0!==s.e&&(o.expiresAt=s.e),o}catch(e){return null}}getDefaultOptions(){const e={path:this._path,secure:this._secure,sameSite:this._sameSite};return void 0!==this._domain&&(e.domain=this._domain),void 0!==this._maxAge&&(e.maxAge=this._maxAge),e}resetAvailabilityCache(){this.availabilityCache=null}getAllEntries(){const e=new Map;try{const t=this._resolveCookieString();if(null===t)return e;const i=parseCookies(t);for(const[t,r]of i.entries())if(t.startsWith(kn)){const i=t.slice(8);try{const t=decodeURIComponent(r),n=JSON.parse(t);isStorageWrapper(n)&&e.set(i,n.v)}catch(e){}}return e}catch(t){return e}}buildMergedOptions(e,t){var i,r,n,s,o;const a={path:null!=(i=null==e?void 0:e.path)?i:this._path,secure:null!=(r=null==e?void 0:e.secure)?r:this._secure,sameSite:null!=(n=null==e?void 0:e.sameSite)?n:this._sameSite},c=null!=(s=null==e?void 0:e.domain)?s:this._domain;if(void 0!==c){const e=function(e){const t=[];if(void 0===e||""===e.trim())return{isValid:!0,domain:void 0,warnings:t};if(/[\r\n\x00]/.test(e))return t.push(`${wn} Cookie domain contains invalid control characters. Domain rejected to prevent header injection attacks.`),{isValid:!1,domain:void 0,warnings:t,rejectionReason:"invalid_format"};const i="undefined"==typeof window?null:void 0!==window.location&&window.location.hostname?window.location.hostname:null;if(null===i)return{isValid:!0,domain:e.trim(),warnings:t};if(function(e){const t=e.toLowerCase();return"localhost"===t||!!t.endsWith(".localhost")||"127.0.0.1"===t||"::1"===t||"[::1]"===t||!!(t.endsWith(".local")||t.endsWith(".test")||t.endsWith(".example"))}(i))return{isValid:!0,domain:e.trim(),warnings:t};if(isIPv4Address(i)||isIPv6Address(i))return e.trim()!==i?(t.push(`${wn} Cookie domain cannot be set for IP address hosts. Domain attribute will be ignored.`),{isValid:!1,domain:void 0,warnings:t,rejectionReason:"invalid_format"}):{isValid:!0,domain:void 0,warnings:t};const r=function(e){const t=e.trim().toLowerCase();return t.startsWith(".")||isIPv4Address(t)||isIPv6Address(t)?t:"."+t}(e);return function(e){const t=e.startsWith(".")?e.slice(1):e,i=t.split(".");if(In.has(t))return!0;if(1===i.length)return Cn.has(t)||En.has(t);if(2===i.length){if(_n.has(t))return!0;const e=i[i.length-1];if(void 0!==e&&En.has(e)){const e=i[i.length-2];if(void 0!==e&&["com","org","net","gov","edu","co","ac"].includes(e))return!0}}if(i.length>=3){const e=i.slice(-2).join(".");if(In.has(e))return!1}return!1}(r)?(t.push(`${wn} Cookie domain '${e}' is a public suffix and too broad. Setting cookies on public suffixes enables cookie tossing attacks. Domain removed to prevent security vulnerability.`),{isValid:!1,domain:void 0,warnings:t,rejectionReason:"tld_too_broad"}):function(e,t){const i=e.toLowerCase(),r=t.toLowerCase(),n=r.startsWith(".")?r.slice(1):r;return i===n||!!i.endsWith(r)||!!i.endsWith("."+n)}(i,r)?{isValid:!0,domain:r,warnings:t}:(t.push(`${wn} Cookie domain '${e}' does not match current hostname '${i}'. Cookies can only be set for the current domain or parent domains. Domain removed to prevent browser rejection.`),{isValid:!1,domain:void 0,warnings:t,rejectionReason:"not_suffix"})}(c);logSecurityWarnings(e.warnings,{suppressInProduction:this._suppressSecurityWarningsInProduction}),e.isValid&&void 0!==e.domain&&(a.domain=e.domain)}const l=null!=(o=null==e?void 0:e.maxAge)?o:this._maxAge;void 0!==l&&(a.maxAge=l),void 0!==(null==e?void 0:e.expires)&&(a.expires=e.expires),"None"!==a.sameSite||a.secure||(a.secure=!0);const u=function(e={},t="general"){const i=[],r={...e};let n=!1;const s="undefined"!=typeof window&&("boolean"==typeof window.isSecureContext?window.isSecureContext:void 0!==window.location&&"https:"===window.location.protocol),o="undefined"!=typeof window&&("boolean"!=typeof window.isSecureContext||window.isSecureContext||void 0===window.location?void 0!==window.location&&"http:"===window.location.protocol:"http:"===window.location.protocol);return"undefined"==typeof window||(s&&("secure"in e?!1===e.secure&&(r.secure=!0,n=!0,i.push(`${wn} 'secure: false' was overridden to 'secure: true' on HTTPS. Setting cookies without the Secure flag on HTTPS exposes them to man-in-the-middle attacks.`)):(r.secure=!0,n=!0,i.push(`${wn} Secure flag auto-enabled on HTTPS. Consider explicitly setting 'secure: true' in your configuration.`))),"None"===r.sameSite&&(s?r.secure||(r.secure=!0,n=!0,i.push(`${wn} SameSite=None requires Secure flag. Secure flag auto-enabled because sameSite='None' was set. Modern browsers reject SameSite=None cookies without the Secure flag.`)):o&&(r.sameSite="Lax",n=!0,i.push(`${wn} SameSite=None cannot be used on HTTP. SameSite=None requires the Secure flag, which is only valid on HTTPS. Falling back to sameSite='Lax' to prevent browser rejection.`))),o&&function(e){return Sn.includes(e)}(t)&&i.push(`${wn} Setting ${t} cookie over HTTP is insecure. This cookie may be intercepted. Use HTTPS in production.`)),{options:r,warnings:i,wasModified:n}}(a,null!=t?t:this._securityContext);return logSecurityWarnings(u.warnings,{suppressInProduction:this._suppressSecurityWarningsInProduction}),u.options}buildDeleteOptions(){const e={path:this._path,maxAge:0};return void 0!==this._domain&&(e.domain=this._domain),e}};function createCookieAdapter(e){return new An(e)}var Rn=class extends Error{constructor(e,t,i){super(`Storage quota exceeded when setting key "${e}" (estimated size: ${t} bytes)`),__publicField(this,"code","QUOTA_EXCEEDED"),__publicField(this,"key"),__publicField(this,"estimatedSize"),this.name="StorageQuotaExceededError",this.key=e,this.estimatedSize=t,i&&(this.cause=i)}},Pn=class{constructor(e={}){__publicField(this,"name","localStorage"),__publicField(this,"availabilityCache",null),__publicField(this,"customStorage"),this.customStorage=e.storage}getStorage(){if(this.customStorage)return this.customStorage;if("undefined"!=typeof window)try{return window.localStorage}catch(e){return}}isAvailable(){if(null!==this.availabilityCache)return this.availabilityCache;const e=this.getStorage();if(!e)return this.availabilityCache=!1,!1;try{const t=`${kn}__availability_test__`;e.setItem(t,"test");const i=e.getItem(t);return e.removeItem(t),this.availabilityCache="test"===i,this.availabilityCache}catch(e){return this.availabilityCache=!1,!1}}get(e,t){var i;const r=this.getEntry(e,t);return null!=(i=null==r?void 0:r.value)?i:null}set(e,t,i){const r=this.getStorage();if(!r)return!1;try{const n=buildStorageKey((null==i?void 0:i.namespace)?{key:e,namespace:i.namespace,includePrefix:!0}:{key:e,includePrefix:!0}),s=Date.now(),o={v:t,s:s,_v:1};void 0!==(null==i?void 0:i.ttl)&&i.ttl>0&&(o.e=s+i.ttl);const a=JSON.stringify(o);try{return r.setItem(n,a),!0}catch(t){if(this.isQuotaExceededError(t)){this.cleanupExpired();try{return r.setItem(n,a),!0}catch(t){if(this.isQuotaExceededError(t))throw new Rn(e,a.length,t instanceof Error?t:void 0);throw t}}throw t}}catch(e){if(e instanceof Rn)throw e;return!1}}remove(e){const t=this.getStorage();if(!t)return!1;try{const i=buildStorageKey({key:e,includePrefix:!0});return null!==t.getItem(i)&&(t.removeItem(i),!0)}catch(e){return!1}}clear(){const e=this.getStorage();if(!e)return 0;try{const t=[];for(let i=0;i<e.length;i++){const r=e.key(i);null!==r&&r.startsWith(kn)&&t.push(r)}for(const i of t)e.removeItem(i);return t.length}catch(e){return 0}}keys(){const e=this.getStorage();if(!e)return[];try{const t=[];for(let i=0;i<e.length;i++){const r=e.key(i);null!==r&&r.startsWith(kn)&&t.push(r.slice(8))}return t}catch(e){return[]}}has(e){const t=this.getStorage();if(!t)return!1;try{const i=buildStorageKey({key:e,includePrefix:!0}),r=t.getItem(i);if(null===r)return!1;const n=JSON.parse(r);return isStorageWrapper(n)&&!(void 0!==n.e&&Date.now()>n.e)||(t.removeItem(i),!1)}catch(e){return!1}}getEntry(e,t){const i=this.getStorage();if(!i)return null;try{const r=buildStorageKey((null==t?void 0:t.namespace)?{key:e,namespace:t.namespace,includePrefix:!0}:{key:e,includePrefix:!0}),n=i.getItem(r);if(null===n)return null;const s=JSON.parse(n);if(!isStorageWrapper(s))return i.removeItem(r),null;if(void 0!==s.e&&Date.now()>s.e)return i.removeItem(r),null;const o={value:s.v,storedAt:s.s};return void 0!==s.e&&(o.expiresAt=s.e),o}catch(e){return null}}cleanupExpired(){const e=this.getStorage();if(!e)return 0;const t=Date.now(),i=[];try{for(let r=0;r<e.length;r++){const n=e.key(r);if(null!==n&&n.startsWith(kn))try{const r=e.getItem(n);if(null===r)continue;const s=JSON.parse(r);isStorageWrapper(s)&&void 0!==s.e&&t>s.e&&i.push(n)}catch(e){i.push(n)}}for(const t of i)e.removeItem(t);return i.length}catch(e){return 0}}getStorageUsage(){const e=this.getStorage();if(!e)return-1;try{let t=0;for(let i=0;i<e.length;i++){const r=e.key(i);if(null!==r&&r.startsWith(kn)){const i=e.getItem(r);null!==i&&(t+=2*(r.length+i.length))}}return t}catch(e){return-1}}isQuotaExceededError(e){if(!(e instanceof Error))return!1;const t=e.name,i=e.message.toLowerCase();return"QuotaExceededError"===t||"NS_ERROR_DOM_QUOTA_REACHED"===t||i.includes("quota exceeded")||i.includes("quota_exceeded")||i.includes("storage quota")}resetAvailabilityCache(){this.availabilityCache=null}};function createLocalStorageAdapter(e){return new Pn(e)}var Dn=class{constructor(e={}){var t,i,r;__publicField(this,"name","memory"),__publicField(this,"store"),__publicField(this,"cleanupTimer",null),__publicField(this,"options"),this.store=new Map,this.options={autoCleanup:null!=(t=e.autoCleanup)&&t,cleanupInterval:null!=(i=e.cleanupInterval)?i:6e4,maxEntries:null!=(r=e.maxEntries)?r:1/0},this.options.autoCleanup&&this.startCleanup()}get(e,t){var i;const r=this.getEntry(e,t);return null!=(i=null==r?void 0:r.value)?i:null}set(e,t,i){try{const r=buildStorageKey((null==i?void 0:i.namespace)?{key:e,namespace:i.namespace,includePrefix:!0}:{key:e,includePrefix:!0}),n=Date.now(),s={v:t,s:n,_v:1};return void 0!==(null==i?void 0:i.ttl)&&i.ttl>0&&(s.e=n+i.ttl),this.store.size>=this.options.maxEntries&&!this.store.has(r)&&this.evictOldest(),this.store.set(r,JSON.stringify(s)),!0}catch(e){return!1}}remove(e){const t=buildStorageKey({key:e,includePrefix:!0});return this.store.delete(t)}clear(){let e=0;const t=[];for(const e of this.store.keys())e.startsWith(kn)&&t.push(e);for(const i of t)this.store.delete(i),e++;return e}keys(){const e=[];for(const t of this.store.keys())t.startsWith(kn)&&e.push(t.slice(8));return e}has(e){const t=buildStorageKey({key:e,includePrefix:!0}),i=this.store.get(t);if(!i)return!1;try{const e=JSON.parse(i);return!(void 0!==e.e&&Date.now()>e.e&&(this.store.delete(t),1))}catch(e){return!1}}isAvailable(){return!0}getEntry(e,t){const i=buildStorageKey((null==t?void 0:t.namespace)?{key:e,namespace:t.namespace,includePrefix:!0}:{key:e,includePrefix:!0}),r=this.store.get(i);if(!r)return null;try{const e=JSON.parse(r);if(void 0!==e.e&&Date.now()>e.e)return this.store.delete(i),null;const t={value:e.v,storedAt:e.s};return void 0!==e.e&&(t.expiresAt=e.e),t}catch(e){return this.store.delete(i),null}}get size(){return this.store.size}clearAll(){this.store.clear()}destroy(){null!==this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}startCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},this.options.cleanupInterval)}cleanupExpired(){const e=Date.now(),t=[];for(const[i,r]of this.store.entries())try{const n=JSON.parse(r);void 0!==n.e&&e>n.e&&t.push(i)}catch(e){t.push(i)}for(const e of t)this.store.delete(e);return t.length}evictOldest(){let e=null,t=1/0;for(const[i,r]of this.store.entries())try{const n=JSON.parse(r);n.s<t&&(t=n.s,e=i)}catch(e){return void this.store.delete(i)}null!==e&&this.store.delete(e)}};function createMemoryAdapter(e){return new Dn(e)}var Ln=new Set(["com","org","net","edu","gov","mil","int","info","biz","name","pro","coop","museum","aero","jobs","travel","mobi","cat","asia","tel","xxx","app","dev","io","co","me","tv","co.uk","org.uk","me.uk","ac.uk","gov.uk","com.au","net.au","org.au","edu.au","gov.au","co.nz","net.nz","org.nz","govt.nz","ac.nz","co.jp","ne.jp","or.jp","ac.jp","go.jp","com.br","net.br","org.br","gov.br","edu.br","com.mx","net.mx","org.mx","gob.mx","edu.mx","com.cn","net.cn","org.cn","gov.cn","edu.cn","co.in","net.in","org.in","gov.in","ac.in","com.de","co.de","com.fr","com.es","com.it","co.it","com.nl","co.nl","com.pl","net.pl","org.pl","com.ru","net.ru","org.ru","com.za","net.za","org.za","co.za","gov.za","co.kr","or.kr","ne.kr","go.kr","ac.kr","com.sg","net.sg","org.sg","gov.sg","edu.sg","com.hk","net.hk","org.hk","gov.hk","edu.hk","com.tw","net.tw","org.tw","gov.tw","edu.tw","github.io","gitlab.io","herokuapp.com","vercel.app","netlify.app","cloudflare.com","azurewebsites.net","amazonaws.com","firebaseapp.com","web.app","appspot.com","pages.dev","workers.dev","deno.dev","fly.dev","railway.app","render.com","onrender.com","surge.sh","now.sh","repl.co","glitch.me","stackblitz.io","codesandbox.io"]);function getRootDomain(e={}){const{includeDot:t=!0}=e;let i=e.hostname;if(!i){if("undefined"==typeof window)return;i=window.location.hostname}if(function(e){return"localhost"===e||!!/^(\d{1,3}\.){3}\d{1,3}$/.test(e)||!(!e.startsWith("[")&&!e.includes(":"))}(i))return;const r=i.toLowerCase().split(".");if(r.length<2)return;const n=function(e){const t=e.toLowerCase().split(".");if(t.length>=2){const e=`${t[t.length-2]}.${t[t.length-1]}`;if(Ln.has(e))return 2}const i=t[t.length-1];return void 0!==i&&Ln.has(i),1}(i);if(r.length<=n)return;const s=r.slice(-(n+1)).join(".");return function(e){const t=e.toLowerCase();if(Ln.has(t))return!0;const i=t.split(".");if(i.length>=2){const e=`${i[i.length-2]}.${i[i.length-1]}`;if(Ln.has(e))return!0}return!1}(s)?void 0:t?`.${s}`:s}function isSecureContext2(){return"undefined"==typeof window||"https:"===window.location.protocol}function resolveCookieDomain(e){return e.cookieDomain?e.cookieDomain:e.crossSubdomain?getRootDomain():void 0}function createStorageAdapter(e,t,i){const r=[];try{const n={};void 0!==e.path&&(n.path=e.path),void 0!==e.domain&&(n.domain=e.domain),void 0!==e.secure&&(n.secure=e.secure),void 0!==e.sameSite&&(n.sameSite=e.sameSite),void 0!==e.maxAge&&(n.maxAge=e.maxAge);const s=createCookieAdapter(n);r.push(s),null==i||i(`[${t}] Cookie adapter created`)}catch(e){null==i||i(`[${t}] Failed to create cookie adapter`,{error:e})}try{const e=createLocalStorageAdapter();r.push(e),null==i||i(`[${t}] localStorage adapter created`)}catch(e){null==i||i(`[${t}] Failed to create localStorage adapter`,{error:e})}const n=createMemoryAdapter();r.push(n),null==i||i(`[${t}] Memory adapter created`);const s={adapters:r,readStrategy:"first-available",writeStrategy:"all"},o=function(e,t){if(t)return{debug:(i,...r)=>t(`[${e}] ${i}`,r),warn:(i,...r)=>t(`[${e}] WARN: ${i}`,r),error:(i,...r)=>t(`[${e}] ERROR: ${i}`,r)}}(t,i);return void 0!==o&&(s.logger=o),createCompositeAdapter(s)}var Mn={AUTHN:"info",AUTHZ:"warning",INPUT:"warning",SESSION:"info",EXCESS:"warning",MALICIOUS:"critical",DATA:"notice",SYS:"info"};function getDefaultSeverity(e){const t=function(e){return e.split("_")[0]}(e);return Mn[t]}var On=["hex_secret","base64_secret"],$n=[{pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,replacement:"[EMAIL]",name:"email"},{pattern:/\b(?:\d{4}[-\s]?){3}\d{4}\b/g,replacement:"[CARD]",name:"credit_card"},{pattern:/\b3[47]\d{2}[-\s]?\d{6}[-\s]?\d{5}\b/g,replacement:"[CARD]",name:"amex"},{pattern:/\b(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)){3}\b/g,replacement:"[IP]",name:"ipv4"},{pattern:/\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b/g,replacement:"[IP]",name:"ipv6_full"},{pattern:/\b(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}\b/g,replacement:"[IP]",name:"ipv6_compressed"},{pattern:/\+[1-9]\d{6,14}\b/g,replacement:"[PHONE]",name:"intl_phone"},{pattern:/(?:\+?1[-.\s]?)?\(?[2-9]\d{2}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g,replacement:"[PHONE]",name:"us_phone"},{pattern:/\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b/g,replacement:"[SSN]",name:"ssn"},{pattern:/\beyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\b/g,replacement:"[JWT]",name:"jwt"},{pattern:/\bBearer\s+[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*\b/gi,replacement:"Bearer [TOKEN]",name:"bearer_token"},{pattern:/\b(?:sk|pk|api)[_-](?:live|test|key)[_-][A-Za-z0-9]{16,}\b/gi,replacement:"[API_KEY]",name:"api_key"},{pattern:/\b(?:AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16}\b/g,replacement:"[AWS_KEY]",name:"aws_key"},{pattern:/\b[A-Fa-f0-9]{32,}\b/g,replacement:"[HEX_SECRET]",name:"hex_secret"},{pattern:/\b[A-Za-z0-9+/]{40,}={0,2}\b/g,replacement:"[BASE64_SECRET]",name:"base64_secret"},{pattern:/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,replacement:"[UUID]",name:"uuid"}],Nn=["password","passwd","pwd","pass","secret","token","accesstoken","access_token","refreshtoken","refresh_token","idtoken","id_token","authtoken","auth_token","bearertoken","bearer_token","sessiontoken","session_token","apikey","api_key","apikeys","api_keys","privatekey","private_key","publickey","public_key","secretkey","secret_key","auth","authorization","authenticate","authentication","credential","credentials","creditcard","credit_card","cardnumber","card_number","ccnumber","cc_number","cvv","cvc","cvv2","cvc2","securitycode","security_code","expiry","expirydate","expiry_date","expirationdate","expiration_date","ssn","socialsecurity","social_security","socialsecuritynumber","social_security_number","taxid","tax_id","nationalid","national_id","driverslicense","drivers_license","passportnumber","passport_number","phonenumber","phone_number","mobilenumber","mobile_number","cellphone","cell_phone","bankaccount","bank_account","accountnumber","account_number","routingnumber","routing_number","iban","swift","bic","encryptionkey","encryption_key","decryptionkey","decryption_key","signingkey","signing_key","hmackey","hmac_key","aeskey","aes_key","awsaccesskey","aws_access_key","awssecretkey","aws_secret_key","awssessiontoken","aws_session_token"],Fn=[/password/i,/passwd/i,/secret/i,/token/i,/apikey/i,/api_key/i,/private/i,/credential/i,/auth/i,/ssn/i,/credit/i,/card/i,/cvv/i,/cvc/i,/pin/i],qn=class{constructor(e={}){var t,i,r,n,s,o,a,c,l;__publicField(this,"config");const u=null!=(t=e.mode)?t:"strict",d=new Set(null!=(i=e.excludePatterns)?i:[]);if("permissive"===u)for(const e of On)d.add(e);const h=[...$n.filter(e=>!e.name||!d.has(e.name)),...null!=(r=e.customPatterns)?r:[]],g=new Set([...Nn.map(e=>e.toLowerCase()),...null!=(s=null==(n=e.customSensitiveFields)?void 0:n.map(e=>e.toLowerCase()))?s:[]]);this.config={patterns:h,sensitiveFields:g,sensitiveFieldPatterns:Fn,enableDeepScan:null==(o=e.enableDeepScan)||o,redactUnknownSensitive:null==(a=e.redactUnknownSensitive)||a,maxDepth:null!=(c=e.maxDepth)?c:10,sensitiveFieldReplacement:null!=(l=e.sensitiveFieldReplacement)?l:"[REDACTED]"}}sanitize(e){return this.sanitizeValue(e,0)}sanitizeString(e){let t=e;for(const{pattern:e,replacement:i}of this.config.patterns)e.lastIndex=0,t=t.replace(e,i);return t}isSensitiveField(e){const t=e.toLowerCase();if(this.config.sensitiveFields.has(t))return!0;if(this.config.redactUnknownSensitive)for(const t of this.config.sensitiveFieldPatterns)if(t.test(e))return!0;return!1}addPatterns(e){this.config.patterns.push(...e)}addSensitiveFields(e){for(const t of e)this.config.sensitiveFields.add(t.toLowerCase())}getStats(){return{patternCount:this.config.patterns.length,sensitiveFieldCount:this.config.sensitiveFields.size}}sanitizeValue(e,t){return t>this.config.maxDepth?this.config.sensitiveFieldReplacement:null==e?e:"string"==typeof e?this.sanitizeString(e):Array.isArray(e)?e.map(e=>this.sanitizeValue(e,t+1)):e instanceof Date?new Date(e.getTime()):"object"==typeof e&&this.config.enableDeepScan?this.sanitizeObject(e,t+1):e}sanitizeObject(e,t){const i={};for(const[r,n]of Object.entries(e))null!=n?this.isSensitiveField(r)&&!this.isContainer(n)?i[r]=this.config.sensitiveFieldReplacement:i[r]=this.sanitizeValue(n,t):i[r]=n;return i}isContainer(e){return!(null==e||!Array.isArray(e)&&("object"!=typeof e||e instanceof Date))}},Un=class extends Error{constructor(e,t){super(e),__publicField(this,"retryable"),this.name="SecurityLoggerError",this.retryable=t}},zn=class{constructor(e){var t,i,r,n,s,o,a,c,l,u;if(__publicField(this,"config"),__publicField(this,"queue",[]),__publicField(this,"flushTimer",null),__publicField(this,"isDestroyed",!1),__publicField(this,"isFlushing",!1),__publicField(this,"piiRedactor"),__publicField(this,"stats",{totalLogged:0,totalTransmitted:0,totalDropped:0,totalFailures:0}),this.config={enabled:e.enabled,...void 0!==e.endpoint&&{endpoint:e.endpoint},...void 0!==e.callback&&{callback:e.callback},flushIntervalMs:null!=(t=e.flushIntervalMs)?t:3e4,maxQueueSize:null!=(i=e.maxQueueSize)?i:100,maxRetries:null!=(r=e.maxRetries)?r:3,headers:null!=(n=e.headers)?n:{},fetch:null!=(o=e.fetch)?o:null==(s=globalThis.fetch)?void 0:s.bind(globalThis),redactPII:null==(a=e.redactPII)||a,hashUserIds:null==(c=e.hashUserIds)||c},this.piiRedactor=null!=(u=e.piiRedactor)?u:new qn({mode:null!=(l=e.piiRedactorMode)?l:"permissive",...void 0!==e.customPatterns&&{customPatterns:e.customPatterns},...void 0!==e.customSensitiveFields&&{customSensitiveFields:e.customSensitiveFields}}),this.config.enabled&&!this.config.endpoint&&!this.config.callback)throw new Error("SecurityLogger: Either endpoint or callback must be provided when enabled");if(this.config.enabled&&this.config.endpoint&&!this.config.fetch)throw new Error("SecurityLogger: fetch is not available. Provide a custom fetch implementation via the `fetch` config option, or use callback mode instead.");this.config.enabled&&this.config.flushIntervalMs>0&&this.startFlushTimer()}log(e){var t;if(!this.config.enabled||this.isDestroyed)return;const i=this.config.redactPII?this.piiRedactor.sanitize(e):e,r={...i,timestamp:(new Date).toISOString(),severity:null!=(t=i.severity)?t:getDefaultSeverity(i.type)};this.queue.length>=this.config.maxQueueSize&&(this.queue.shift(),this.stats.totalDropped++),this.queue.push(r),this.stats.totalLogged++}async flush(){if(this.isFlushing||0===this.queue.length)return;this.isFlushing=!0;const e=this.queue.splice(0,this.queue.length);try{const t=await this.processUserIds(e);await this.transmit(t),this.stats.totalTransmitted+=e.length}catch(t){this.stats.totalFailures++,this.requeue(e)}finally{this.isFlushing=!1}}destroy(){this.isDestroyed||(this.isDestroyed=!0,null!==this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush())}getStats(){return{queueLength:this.queue.length,totalLogged:this.stats.totalLogged,totalTransmitted:this.stats.totalTransmitted,totalDropped:this.stats.totalDropped,totalFailures:this.stats.totalFailures,enabled:this.config.enabled,destroyed:this.isDestroyed}}isEnabled(){return this.config.enabled&&!this.isDestroyed}updateConfig(e){if(void 0!==e.enabled){const t=this.config.enabled;this.config.enabled=e.enabled,!e.enabled||t||this.isDestroyed?!e.enabled&&t&&this.stopFlushTimer():this.startFlushTimer()}void 0!==e.headers&&Object.assign(this.config.headers,e.headers)}startFlushTimer(){null===this.flushTimer&&(this.flushTimer=setInterval(()=>{this.flush()},this.config.flushIntervalMs),"object"==typeof this.flushTimer&&"unref"in this.flushTimer&&this.flushTimer.unref())}stopFlushTimer(){null!==this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}async transmit(e){0!==e.length&&(this.config.callback?await this.transmitViaCallback(e):this.config.endpoint&&await this.transmitViaEndpoint(e))}async transmitViaCallback(e){await this.config.callback(e)}async transmitViaEndpoint(e){const{endpoint:t,headers:i,fetch:r,maxRetries:n}=this.config;let s;for(let o=0;o<n;o++)try{const a=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...i},body:JSON.stringify({events:e,timestamp:(new Date).toISOString()})});if(a.ok)return;if(a.status>=400&&a.status<500)throw new Un(`SecurityLogger: HTTP ${a.status} ${a.statusText}`,!1);s=new Error(`SecurityLogger: HTTP ${a.status} ${a.statusText}`),o<n-1&&await this.delay(100*Math.pow(2,o))}catch(e){if(e instanceof Un&&!e.retryable)throw e;s=e instanceof Error?e:new Error(String(e)),o<n-1&&await this.delay(100*Math.pow(2,o))}throw null!=s?s:new Error("SecurityLogger: Transmission failed")}requeue(e){const t=this.config.maxQueueSize-this.queue.length;if(t<=0)return void(this.stats.totalDropped+=e.length);const i=e.slice(-t),r=e.length-i.length;this.queue.unshift(...i),this.stats.totalDropped+=r}delay(e){return new Promise(t=>setTimeout(t,e))}async processUserIds(e){return this.config.hashUserIds?Promise.all(e.map(async e=>{if(!e.userId)return e;const t=await async function(e){if(!isSha256Available())return null;try{return await async function(e){if(!isSha256Available())throw new Gr("Web Crypto API is required for SHA-256 hashing. Ensure you are using HTTPS in browser environments.");const t=(new TextEncoder).encode(e);return bufferToHex(await globalThis.crypto.subtle.digest("SHA-256",t))}(e)}catch(e){return null}}(e.userId);return{...e,userId:null!=t?t:e.userId}})):e}};function createDisabledLogger(){return new zn({enabled:!1})}var Hn=["before","enrichment","destination","after"],Vn={before:0,enrichment:1,destination:2,after:3},Bn=["necessary","analytics","marketing","functional"];function definePlugin(e){return e}function isOvervioPlugin(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.name&&t.name.length>0&&"string"==typeof t.version&&t.version.length>0&&"string"==typeof t.type&&Hn.includes(t.type)&&"function"==typeof t.isLoaded}function isValidPluginType(e){return"string"==typeof e&&Hn.includes(e)}var jn=class{constructor(e){var t,i;__publicField(this,"plugins",new Map),__publicField(this,"emitter"),__publicField(this,"sdkContext"),__publicField(this,"defaultTimeout"),__publicField(this,"continueOnError"),this.emitter=e.emitter,this.sdkContext=e.sdkContext,this.defaultTimeout=null!=(t=e.defaultTimeout)?t:5e3,this.continueOnError=null==(i=e.continueOnError)||i}async register(e){var t;const{plugin:i,config:r={},initTimeout:n}=e;if(!isOvervioPlugin(i))throw new $r("Invalid plugin: missing required properties",{recoverable:!0});if(this.plugins.has(i.name))throw $r.duplicate(i.name);const s={config:r,sdk:this.sdkContext};if(i.init){const e=null!=n?n:this.defaultTimeout;try{await this.withTimeout(Promise.resolve(i.init(s)),e,i.name,"init")}catch(e){if(e instanceof $r)throw this.emitError(i.name,e,"init"),e;const t=$r.initFailed(i.name,e instanceof Error?e:void 0,i.version);throw this.emitError(i.name,t,"init"),t}}this.plugins.set(i.name,{plugin:i,config:r,registeredAt:new Date}),null==(t=this.emitter)||t.emit("plugin:loaded",{name:i.name,version:i.version,type:i.type})}async unregister(e){var t;const i=this.plugins.get(e);if(!i)throw $r.notFound(e);const{plugin:r}=i;if(r.unload)try{await this.withTimeout(Promise.resolve(r.unload()),this.defaultTimeout,e,"unload")}catch(t){const i=t instanceof $r?t:$r.executionFailed(e,"unload",t instanceof Error?t:void 0,r.version);this.emitError(e,i,"unload")}this.plugins.delete(e),null==(t=this.emitter)||t.emit("plugin:unloaded",{name:e})}async executeChain(e,t){const i=[];let r,n=t,s=!1;const o=this.getPluginsByExecutionOrder();for(const t of o){const{plugin:o}=t,a=o[e];if(!a)continue;if(s)break;if(null===n)break;const c=this.createPluginContext(n,s,r);try{const t=await this.withTimeout(Promise.resolve(a.call(o,c)),this.defaultTimeout,o.name,e);c.aborted&&(s=!0,r=c.abortReason),null===t?n=null:void 0!==t&&(n=t)}catch(t){const r=t instanceof $r?t:$r.executionFailed(o.name,e,t instanceof Error?t:void 0,o.version);if(i.push(r),this.emitError(o.name,r,e),!this.continueOnError)break}}return{event:n,aborted:s,abortReason:r,errors:i}}getPlugin(e){const t=this.plugins.get(e);if(!t)return;const{plugin:i,registeredAt:r}=t;return{name:i.name,version:i.version,type:i.type,isLoaded:i.isLoaded(),registeredAt:r}}getAllPlugins(){return Array.from(this.plugins.values()).map(({plugin:e,registeredAt:t})=>({name:e.name,version:e.version,type:e.type,isLoaded:e.isLoaded(),registeredAt:t}))}getPluginsByType(e){return this.getAllPlugins().filter(t=>t.type===e)}hasPlugin(e){return this.plugins.has(e)}get pluginCount(){return this.plugins.size}getPluginsByExecutionOrder(){return Array.from(this.plugins.values()).sort((e,t)=>Vn[e.plugin.type]-Vn[t.plugin.type])}createPluginContext(e,t,i){let r=t,n=i;return{event:e,sdk:this.sdkContext,abort(e){r=!0,n=e},get aborted(){return r},get abortReason(){return n}}}async withTimeout(e,t,i,r,n){return new Promise((s,o)=>{let a=!1;const c=setTimeout(()=>{a||(a=!0,null==n||n.abort(),o($r.timeout(i,r,t)))},t);e.then(e=>{a||(a=!0,clearTimeout(c),s(e))}).catch(e=>{a||(a=!0,clearTimeout(c),o(e))})})}emitError(e,t,i){var r;null==(r=this.emitter)||r.emit("plugin:error",{name:e,error:t,method:i})}};function createPluginManager(e){return new jn(e)}function transformEventForBackend(e){if(function(e){return"track"===e.type}(e))return function(e){var t;const i={event:e.event};if(e.properties)for(const[t,r]of Object.entries(e.properties))i[t]=r;const r={eventType:"track",data:i,timestamp:null!=(t=e.timestamp)?t:Date.now()};return void 0!==e.userId&&(r.userId=String(e.userId)),void 0!==e.sessionId&&(r.sessionId=String(e.sessionId)),void 0!==e.context&&(r.context=e.context),r}(e);if(function(e){return"identify"===e.type}(e))return function(e){var t;const i={};if(e.traits)for(const[t,r]of Object.entries(e.traits))i[t]=r;const r={eventType:"identify",data:i,timestamp:null!=(t=e.timestamp)?t:Date.now(),userId:String(e.userId)};return void 0!==e.context&&(r.context=e.context),r}(e);if(function(e){return"page"===e.type}(e))return function(e){var t;const i={};if(void 0!==e.name&&(i.name=e.name),void 0!==e.category&&(i.category=e.category),e.properties)for(const[t,r]of Object.entries(e.properties))i[t]=r;const r={eventType:"page",data:i,timestamp:null!=(t=e.timestamp)?t:Date.now()};return void 0!==e.userId&&(r.userId=String(e.userId)),void 0!==e.sessionId&&(r.sessionId=String(e.sessionId)),void 0!==e.context&&(r.context=e.context),r}(e);throw new Error(`Unknown event type: ${e.type}`)}h();var Kn=[408,429,500,502,503,504],Wn=class{constructor(e){var t,i,r,n,s,o,a,c;__publicField(this,"batch",[]),__publicField(this,"flushTimer",null),__publicField(this,"flushing",!1),__publicField(this,"started",!1),__publicField(this,"config"),__publicField(this,"identityProvider",null),__publicField(this,"boundOnlineHandler"),__publicField(this,"lastDelay"),__publicField(this,"abortController",null);const l={apiKey:e.apiKey,proxyEndpoint:e.proxyEndpoint,batchSize:null!=(t=e.batchSize)?t:10,flushInterval:null!=(i=e.flushInterval)?i:2e3,maxRetries:null!=(r=e.maxRetries)?r:3,timeout:null!=(n=e.timeout)?n:1e4,baseDelay:null!=(s=e.baseDelay)?s:1e3,maxDelay:null!=(o=e.maxDelay)?o:3e4,jitter:null!=(a=e.jitter)?a:"full",csrfHeaderName:null!=(c=e.csrfHeaderName)?c:"X-CSRF-Token"};void 0!==e.csrfToken?this.config={...l,csrfToken:e.csrfToken}:this.config=l,this.lastDelay=this.config.baseDelay,this.boundOnlineHandler=()=>this.onOnline()}getCsrfToken(){if(this.config.csrfToken)return"function"==typeof this.config.csrfToken?this.config.csrfToken():this.config.csrfToken}setCsrfToken(e){this.config.csrfToken=e}async send(e,t,i){var r;const n=Date.now(),s={event:e,type:t,idempotencyKey:i,timestamp:null!=(r=e.timestamp)?r:n,batchedAt:n,retryCount:0};return this.batch.push(s),this.batch.length>=this.config.batchSize&&this.flush().catch(()=>{}),{success:!0}}async flush(){if(!this.flushing&&0!==this.batch.length&&this.isReady()){this.flushing=!0;try{const e=[...this.batch];this.batch=[],await this.sendBatchWithRetry(e)}finally{this.flushing=!1}}}isReady(){return"undefined"==typeof navigator||!1!==navigator.onLine}start(){this.started||(this.started=!0,this.setupOnlineListener(),this.startFlushTimer())}stop(){this.stopFlushTimer(),this.removeOnlineListener(),this.started=!1}destroy(){this.stop(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.batch=[]}setIdentityProvider(e){this.identityProvider=e}get pendingCount(){return this.batch.length}get isFlushing(){return this.flushing}async sendBatchWithRetry(e){let t=0,i=e;for(;i.length>0&&t<this.config.maxRetries;){t++;try{const e=await this.sendBatchRequest(i);if(e.success)return;if(!e.failedEvents||0===e.failedEvents.length)return;if(i=e.failedEvents.filter(e=>e.retryCount<this.config.maxRetries),0===i.length)return;for(const e of i)e.retryCount++;if(t<this.config.maxRetries){const e=this.calculateBackoff(t);await this.sleep(e)}}catch(e){if(t<this.config.maxRetries){const r=this.calculateBackoff(t);await this.sleep(r);for(const t of i)t.retryCount++,t.lastError=e instanceof Error?e.message:String(e)}}}}async sendBatchRequest(e){this.abortController=new AbortController;const t=setTimeout(()=>{var e;null==(e=this.abortController)||e.abort()},this.config.timeout);try{const r=this.createBatchPayload(e),n={"Content-Type":"application/json"},s=this.getCsrfToken();s&&(n[this.config.csrfHeaderName]=s);const o=await fetch(this.config.proxyEndpoint,{method:"POST",headers:n,body:JSON.stringify(r),signal:this.abortController.signal});if(clearTimeout(t),!o.ok)return i=o.status,Kn.includes(i)||i>=500&&i<600?{success:!1,failedEvents:e}:{success:!1};try{const t=await o.json();if(t.errors&&t.errors.length>0){const i=new Set(t.errors.map(e=>e.idempotencyKey)),r=e.filter(e=>i.has(e.idempotencyKey));return r.length>0?{success:!1,failedEvents:r}:{success:!0}}return{success:!1!==t.success}}catch(e){return{success:!0}}}catch(i){return clearTimeout(t),i instanceof Error&&i.name,{success:!1,failedEvents:e}}finally{this.abortController=null}var i}createBatchPayload(e){var t;const i={api_key:this.config.apiKey,events:e.map(e=>({...transformEventForBackend(e.event),idempotencyKey:e.idempotencyKey,batchedAt:e.batchedAt})),metadata:{sdkVersion:"__SDK_VERSION__",batchId:this.generateBatchId(),sentAt:Date.now()}},r=null==(t=this.identityProvider)?void 0:t.call(this);return r&&(r.userId||r.anonymousId||r.sessionId)&&(i.identity=r),i}generateBatchId(){return secureRandomUUID()}calculateBackoff(e){const{baseDelay:t,maxDelay:i,jitter:r}=this.config,n=t*Math.pow(2,e-1),s=Math.min(n,i);switch(r){case"none":default:return this.lastDelay=s,s;case"full":{const e=Math.random()*s;return this.lastDelay=e,Math.floor(e)}case"equal":{const e=s/2+Math.random()*(s/2);return this.lastDelay=e,Math.floor(e)}case"decorrelated":{const e=Math.min(i,t+Math.random()*(3*this.lastDelay-t)),r=Math.max(t,e);return this.lastDelay=e,Math.floor(r)}}}sleep(e){return new Promise(t=>setTimeout(t,e))}startFlushTimer(){null===this.flushTimer&&(this.flushTimer=setInterval(()=>{this.isReady()&&!this.flushing&&this.batch.length>0&&this.flush().catch(()=>{})},this.config.flushInterval))}stopFlushTimer(){null!==this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}onOnline(){this.batch.length>0&&!this.flushing&&this.flush().catch(()=>{})}setupOnlineListener(){"undefined"!=typeof window&&window.addEventListener("online",this.boundOnlineHandler)}removeOnlineListener(){"undefined"!=typeof window&&window.removeEventListener("online",this.boundOnlineHandler)}};function redactId(e){return!e||e.length<=8?"[REDACTED]":`${e.slice(0,4)}...${e.slice(-4)}`}We(),pe(),A();var Qn=class{constructor(e,t,i={}){__publicField(this,"storage"),__publicField(this,"emitter"),__publicField(this,"crossTabSync",null),__publicField(this,"config"),__publicField(this,"callbacks"),__publicField(this,"session",null),__publicField(this,"checkIntervalId",null),__publicField(this,"started",!1),__publicField(this,"destroyed",!1),__publicField(this,"crossTabUnsubscribe",null),this.storage=e,this.emitter=t,this.config=this.resolveConfig(i.config),this.callbacks={onSessionStarted:i.onSessionStarted,onSessionExpired:i.onSessionExpired,onSessionActivity:i.onSessionActivity},this.debug("SessionManager created",{config:this.config})}resolveConfig(e){var t,i,r,n,s;const o=null==e?void 0:e.onDebug;let a=null!=(t=null==e?void 0:e.sessionTimeoutMs)?t:mn;return a<fn?(o&&o("[Session] sessionTimeoutMs too low, clamping to minimum",{requested:a,minimum:fn}),a=fn):a>yn&&(o&&o("[Session] sessionTimeoutMs too high, clamping to maximum",{requested:a,maximum:yn}),a=yn),{sessionTimeoutMs:a,activityCheckIntervalMs:null!=(i=null==e?void 0:e.activityCheckIntervalMs)?i:6e4,storageKey:null!=(r=null==e?void 0:e.storageKey)?r:"session",enableCrossTabSync:null==(n=null==e?void 0:e.enableCrossTabSync)||n,onDebug:o,generateSessionId:null!=(s=null==e?void 0:e.generateSessionId)?s:generateUUID}}start(){if(this.destroyed)return void this.debug("Cannot start: manager is destroyed");if(this.started)return void this.debug("Already started");this.debug("Starting session manager"),this.started=!0;const e=this.loadSession();e?isSessionExpired(e.lastActivity,this.config.sessionTimeoutMs)?(this.debug("Existing session has expired",{sessionId:redactId(e.sessionId)}),this.session=e,this.expireSession("timeout"),this.createNewSession()):(this.session=e,this.touch(),this.emitSessionStarted(!1)):this.createNewSession(),this.startActivityCheckInterval(),this.debug("Session manager started",{sessionId:this.session?redactId(this.session.sessionId):null})}stop(){this.started&&(this.debug("Stopping session manager"),this.stopActivityCheckInterval(),this.started=!1)}setCrossTabSync(e){this.destroyed?this.debug("Cannot set cross-tab sync: manager is destroyed"):(this.crossTabUnsubscribe&&(this.crossTabUnsubscribe(),this.crossTabUnsubscribe=null),this.crossTabSync=e,this.config.enableCrossTabSync&&(this.crossTabUnsubscribe=e.on(ln,e=>{this.handleCrossTabSessionUpdate(e)}),this.debug("Cross-tab sync enabled")))}handleCrossTabSessionUpdate(e){if(this.session)return e.isNewSession&&e.sessionId!==this.session.sessionId?(this.debug("New session started in another tab",{newSessionId:redactId(e.sessionId)}),this.session={sessionId:e.sessionId,startedAt:Date.now(),lastActivity:e.lastActivity,pageViews:0,events:0,isEnded:!1},this.saveSession(),void this.emitSessionStarted(!1)):void(e.lastActivity>this.session.lastActivity&&(this.session.lastActivity=e.lastActivity,this.saveSession(),this.debug("Session updated from cross-tab sync",{lastActivity:e.lastActivity})))}createNewSession(){const e=createSessionId(this.config.generateSessionId()),t=Date.now();this.session={sessionId:e,startedAt:t,lastActivity:t,pageViews:0,events:0,isEnded:!1},this.saveSession(),this.emitSessionStarted(!0),this.broadcastSessionUpdate(!0),this.debug("New session created",{sessionId:redactId(e)})}expireSession(e){if(!this.session||this.session.isEnded)return;const t=this.session.sessionId;if(this.session.isEnded=!0,this.saveSession(),this.emitter.emit("session:expired",{sessionId:t,reason:e}),this.callbacks.onSessionExpired)try{this.callbacks.onSessionExpired(t,e)}catch(e){this.debug("Error in onSessionExpired callback",{error:e})}this.debug("Session expired",{sessionId:redactId(t),reason:e})}emitSessionStarted(e){if(this.session&&(this.emitter.emit("session:started",{sessionId:this.session.sessionId,isNew:e}),this.callbacks.onSessionStarted))try{this.callbacks.onSessionStarted(this.session,e)}catch(e){this.debug("Error in onSessionStarted callback",{error:e})}}broadcastSessionUpdate(e){this.crossTabSync&&this.config.enableCrossTabSync&&this.session&&this.crossTabSync.broadcast(ln,{sessionId:this.session.sessionId,lastActivity:this.session.lastActivity,isNewSession:e})}touch(e=!0){if(this.session&&!this.session.isEnded&&!this.destroyed){if(isSessionExpired(this.session.lastActivity,this.config.sessionTimeoutMs))return this.debug("Session expired before touch, creating new session"),this.expireSession("timeout"),void this.createNewSession();if(this.session.lastActivity=Date.now(),this.saveSession(),this.callbacks.onSessionActivity)try{this.callbacks.onSessionActivity(this.session)}catch(e){this.debug("Error in onSessionActivity callback",{error:e})}e&&this.broadcastSessionUpdate(!1)}}recordEvent(){!this.session||this.session.isEnded||this.destroyed||isSessionExpired(this.session.lastActivity,this.config.sessionTimeoutMs)&&(this.debug("Session expired before recordEvent, creating new session"),this.expireSession("timeout"),this.createNewSession(),!this.session)||(this.session.events++,this.touch(),this.debug("Event recorded",{events:this.session.events}))}recordPageView(){!this.session||this.session.isEnded||this.destroyed||isSessionExpired(this.session.lastActivity,this.config.sessionTimeoutMs)&&(this.debug("Session expired before recordPageView, creating new session"),this.expireSession("timeout"),this.createNewSession(),!this.session)||(this.session.pageViews++,this.touch(),this.debug("Page view recorded",{pageViews:this.session.pageViews}))}getSession(){return this.session}getSessionId(){var e,t;return null!=(t=null==(e=this.session)?void 0:e.sessionId)?t:null}getStats(){const e=Date.now();if(!this.session)return{sessionId:null,isActive:!1,isExpired:!1,sessionDurationMs:0,timeSinceLastActivityMs:0,timeUntilExpirationMs:0,pageViews:0,events:0,crossTabSyncEnabled:this.config.enableCrossTabSync};const t=isSessionExpired(this.session.lastActivity,this.config.sessionTimeoutMs,e),i=calculateTimeUntilExpiration(this.session.lastActivity,this.config.sessionTimeoutMs,e);return{sessionId:this.session.sessionId,isActive:this.started&&!this.session.isEnded&&!t,isExpired:t||this.session.isEnded,sessionDurationMs:e-this.session.startedAt,timeSinceLastActivityMs:e-this.session.lastActivity,timeUntilExpirationMs:i,pageViews:this.session.pageViews,events:this.session.events,crossTabSyncEnabled:this.config.enableCrossTabSync}}endSession(){this.session&&!this.session.isEnded&&(this.debug("Manually ending session",{sessionId:redactId(this.session.sessionId)}),this.expireSession("manual"),this.session=null,this.clearStoredSession())}regenerateSession(){if(!this.session||this.session.isEnded||this.destroyed)return this.debug("Cannot regenerate session: no active session"),null;const e=this.session.sessionId,t=createSessionId(this.config.generateSessionId());return this.debug("Regenerating session for security",{oldSessionId:redactId(e),newSessionId:redactId(t)}),this.session={...this.session,sessionId:t,lastActivity:Date.now()},this.clearStoredSession(),this.saveSession(),this.emitter.emit("session:regenerated",{oldSessionId:e,newSessionId:t,reason:"authentication"}),this.broadcastSessionUpdate(!0),t}loadSession(){try{const t=this.storage.get(this.config.storageKey);if(!t||!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.sessionId&&t.sessionId.length>0&&"number"==typeof t.startedAt&&"number"==typeof t.lastActivity&&"number"==typeof t.pageViews&&"number"==typeof t.events&&"boolean"==typeof t.isEnded}(e=t)||1!==e._version)return null;const i={sessionId:createSessionId(t.sessionId),startedAt:t.startedAt,lastActivity:t.lastActivity,pageViews:t.pageViews,events:t.events,isEnded:t.isEnded};return this.debug("Session loaded from storage",{sessionId:redactId(i.sessionId)}),i}catch(e){return this.debug("Error loading session from storage",{error:e}),null}var e}saveSession(){if(this.session)try{const e={sessionId:this.session.sessionId,startedAt:this.session.startedAt,lastActivity:this.session.lastActivity,pageViews:this.session.pageViews,events:this.session.events,isEnded:this.session.isEnded,_version:1};this.storage.set(this.config.storageKey,e)}catch(e){this.debug("Error saving session to storage",{error:e})}}clearStoredSession(){try{this.storage.remove(this.config.storageKey)}catch(e){this.debug("Error clearing stored session",{error:e})}}startActivityCheckInterval(){this.checkIntervalId||(this.checkIntervalId=setInterval(()=>{this.checkSessionExpiration()},this.config.activityCheckIntervalMs),this.debug("Activity check interval started",{intervalMs:this.config.activityCheckIntervalMs}))}stopActivityCheckInterval(){this.checkIntervalId&&(clearInterval(this.checkIntervalId),this.checkIntervalId=null,this.debug("Activity check interval stopped"))}checkSessionExpiration(){this.session&&!this.session.isEnded&&isSessionExpired(this.session.lastActivity,this.config.sessionTimeoutMs)&&(this.debug("Session expired during check",{sessionId:redactId(this.session.sessionId)}),this.expireSession("timeout"),this.session=null)}destroy(){this.destroyed||(this.debug("Destroying session manager"),this.stopActivityCheckInterval(),this.crossTabUnsubscribe&&(this.crossTabUnsubscribe(),this.crossTabUnsubscribe=null),this.crossTabSync=null,this.started=!1,this.destroyed=!0,this.debug("Session manager destroyed"))}debug(e,t){this.config.onDebug&&this.config.onDebug(`[Session] ${e}`,t)}};P(),A();var Gn=class{constructor(e){var t;__publicField(this,"httpClient"),__publicField(this,"endpoint"),__publicField(this,"onDebug"),this.httpClient=e.httpClient,this.endpoint=null!=(t=e.endpoint)?t:"/session",void 0!==e.onDebug&&(this.onDebug=e.onDebug)}async createSession(t){this.debug("Creating session",{cookieName:t.cookieName,url:t.url,hasAnonymousId:!!t.anonymousId});const i={cookie_name:t.cookieName,referrer:t.referrer,userAgent:t.userAgent,url:t.url};void 0!==t.anonymousId&&(i.anonymousId=t.anonymousId);try{const t=await this.httpClient.post(this.endpoint,i);if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.sessionId&&t.sessionId.length>0&&(null===t.userId||"string"==typeof t.userId)&&"string"==typeof t.cookieName&&"boolean"==typeof t.isNew&&"number"==typeof t.timestamp&&(void 0===t.expiresAt||"number"==typeof t.expiresAt)}(t))throw new e.NetworkError("Invalid session response from server",{statusCode:0,retryable:!1,url:this.endpoint,method:"POST",context:{response:t}});const r=this.parseResponse(t);return this.debug("Session created successfully",{sessionId:r.sessionId,isNew:r.isNew,hasUserId:!!r.userId}),r}catch(t){if(t instanceof e.NetworkError&&401===t.statusCode)throw this.debug("Invalid apiKey - 401 Unauthorized"),sr.invalidValue("apiKey","valid API key (pk_live_* or pk_test_*)","[redacted]");throw t}}parseResponse(e){const t={sessionId:createSessionId(e.sessionId),userId:e.userId?createUserId(e.userId):null,cookieName:e.cookieName,isNew:e.isNew,timestamp:e.timestamp};return void 0!==e.expiresAt&&(t.expiresAt=e.expiresAt),t}debug(e,t){this.onDebug&&this.onDebug(`[SessionApi] ${e}`,t)}};function getDefaultUrl(){return"undefined"!=typeof window&&void 0!==window.location?window.location.href:""}function getDefaultReferrer(){return"undefined"!=typeof document?document.referrer:""}function getDefaultUserAgent(){return"undefined"!=typeof navigator?navigator.userAgent:"SSR"}function delay2(e){return new Promise(t=>setTimeout(t,e))}A();var Yn=class{constructor(e){var t,i,r,n,s,o;__publicField(this,"sessionManager"),__publicField(this,"sessionApiClient"),__publicField(this,"anonymousIdManager"),__publicField(this,"apiKey"),__publicField(this,"getCookieName"),__publicField(this,"getUrl"),__publicField(this,"getReferrer"),__publicField(this,"getUserAgent"),__publicField(this,"requireServerSession"),__publicField(this,"maxRetries"),__publicField(this,"retryDelayMs"),__publicField(this,"onDebug"),__publicField(this,"onServerSessionCreated"),__publicField(this,"onServerSessionFailed"),__publicField(this,"initialized",!1),__publicField(this,"initializationPromise",null),__publicField(this,"hasServerSession",!1),__publicField(this,"serverSessionId",null),__publicField(this,"serverUserId",null),__publicField(this,"initAttempts",0),__publicField(this,"lastError",null),this.sessionManager=e.sessionManager,this.sessionApiClient=e.sessionApiClient,this.anonymousIdManager=e.anonymousIdManager,this.apiKey=e.apiKey,this.getCookieName=e.getCookieName,this.getUrl=null!=(t=e.getUrl)?t:getDefaultUrl,this.getReferrer=null!=(i=e.getReferrer)?i:getDefaultReferrer,this.getUserAgent=null!=(r=e.getUserAgent)?r:getDefaultUserAgent,this.requireServerSession=null!=(n=e.requireServerSession)&&n,this.maxRetries=null!=(s=e.maxRetries)?s:3,this.retryDelayMs=null!=(o=e.retryDelayMs)?o:1e3,void 0!==e.onDebug&&(this.onDebug=e.onDebug),void 0!==e.onServerSessionCreated&&(this.onServerSessionCreated=e.onServerSessionCreated),void 0!==e.onServerSessionFailed&&(this.onServerSessionFailed=e.onServerSessionFailed)}async initialize(){if(this.initialized){this.debug("Session service already initialized");const e=this.getSessionId();if(!e)throw new Error("Session ID unavailable after initialization");return{success:!0,sessionId:e,hasServerSession:this.hasServerSession}}return this.initializationPromise?(this.debug("Initialization already in progress, waiting for existing promise"),this.initializationPromise):(this.initializationPromise=this.doInitialize(),this.initializationPromise)}async doInitialize(){var e,t,i;this.debug("Starting session service initialization"),this.sessionManager.start();const r=this.sessionManager.getSessionId();if(!r){const i=createSessionId(null!=(t=null==(e=crypto.randomUUID)?void 0:e.call(crypto))?t:Date.now().toString());return this.debug("No local session after start, using fallback",{fallbackId:i}),{success:!this.requireServerSession,sessionId:i,hasServerSession:!1,error:new Error("Failed to create local session")}}let n=null,s=null;for(let e=0;e<this.maxRetries;e++){this.initAttempts=e+1;try{n=await this.createServerSession(),this.lastError=null;break}catch(t){if(s=t instanceof Error?t:new Error(String(t)),this.lastError=s,t instanceof sr){this.debug("Configuration error, not retrying",{error:s.message});break}e<this.maxRetries-1&&(this.debug(`Server session attempt ${e+1} failed, retrying`,{error:s.message,nextAttemptIn:this.retryDelayMs}),await delay2(this.retryDelayMs))}}if(n){if(this.hasServerSession=!0,this.serverSessionId=n.sessionId,this.serverUserId=n.userId,this.onServerSessionCreated)try{this.onServerSessionCreated(n)}catch(e){this.debug("Error in onServerSessionCreated callback",{callbackError:e})}this.debug("Server session established",{sessionId:n.sessionId,isNew:n.isNew,hasUserId:!!n.userId})}else if(s){if(this.onServerSessionFailed)try{this.onServerSessionFailed(s)}catch(e){this.debug("Error in onServerSessionFailed callback",{callbackError:e})}this.debug("Server session creation failed",{error:s.message,attempts:this.initAttempts})}this.initialized=!0;const o=null!=(i=this.serverSessionId)?i:r,a=!this.requireServerSession||this.hasServerSession,c={success:a,sessionId:o,hasServerSession:this.hasServerSession};return n&&(c.serverResponse=n),!a&&s&&(c.error=s),this.debug("Session service initialization complete",{success:a,sessionId:o,hasServerSession:this.hasServerSession}),c}async createServerSession(){const e=this.anonymousIdManager.get(),t={cookieName:this.getCookieName(),apiKey:this.apiKey,referrer:this.getReferrer(),userAgent:this.getUserAgent(),url:this.getUrl()};return null!==e&&(t.anonymousId=e),this.sessionApiClient.createSession(t)}getSession(){return this.sessionManager.getSession()}getSessionId(){var e;return null!=(e=this.serverSessionId)?e:this.sessionManager.getSessionId()}getServerUserId(){return this.serverUserId}getStats(){return{isInitialized:this.initialized,hasServerSession:this.hasServerSession,sessionId:this.getSessionId(),serverSessionId:this.serverSessionId,serverUserId:this.serverUserId,initAttempts:this.initAttempts,lastError:this.lastError}}isInitialized(){return this.initialized}hasServerSessionEstablished(){return this.hasServerSession}async retryServerSession(){if(this.hasServerSession)return this.debug("Server session already established"),!0;try{const e=await this.createServerSession();if(this.hasServerSession=!0,this.serverSessionId=e.sessionId,this.serverUserId=e.userId,this.lastError=null,this.onServerSessionCreated)try{this.onServerSessionCreated(e)}catch(e){this.debug("Error in onServerSessionCreated callback",{callbackError:e})}return this.debug("Server session established on retry",{sessionId:e.sessionId}),!0}catch(e){if(this.lastError=e instanceof Error?e:new Error(String(e)),this.onServerSessionFailed)try{this.onServerSessionFailed(this.lastError)}catch(e){this.debug("Error in onServerSessionFailed callback",{callbackError:e})}return this.debug("Server session retry failed",{error:this.lastError.message}),!1}}debug(e,t){this.onDebug&&this.onDebug(`[SessionService] ${e}`,t)}};function createSessionStorage(e={}){var t;const i=e.onDebug;if(e.disablePersistence)return null==i||i("[SessionStorage] Creating memory-only storage (persistence disabled)"),createMemoryAdapter();const r=function(e){var t,i,r;const n=null!=(t=e.sessionTimeoutMs)?t:mn,s=function(e){return e.cookieDomain?e.cookieDomain:e.crossSubdomain?getRootDomain():void 0}(e),o={path:null!=(i=e.cookiePath)?i:"/",secure:null!=(r=e.secure)?r:"undefined"==typeof window||"https:"===window.location.protocol,sameSite:"Lax",maxAge:Math.floor(n/1e3)};return void 0!==s&&(o.domain=s),o}(e);null==i||i("[SessionStorage] Creating cookie-first storage",{domain:null!=(t=r.domain)?t:"(current domain)",secure:r.secure,sameSite:r.sameSite,maxAge:r.maxAge});const n=[];try{const e={};void 0!==r.path&&(e.path=r.path),void 0!==r.domain&&(e.domain=r.domain),void 0!==r.secure&&(e.secure=r.secure),void 0!==r.sameSite&&(e.sameSite=r.sameSite),void 0!==r.maxAge&&(e.maxAge=r.maxAge);const t=createCookieAdapter(e);n.push(t),null==i||i("[SessionStorage] Cookie adapter created")}catch(e){null==i||i("[SessionStorage] Failed to create cookie adapter",{error:e})}try{const e=createLocalStorageAdapter();n.push(e),null==i||i("[SessionStorage] localStorage adapter created")}catch(e){null==i||i("[SessionStorage] Failed to create localStorage adapter",{error:e})}const s=createMemoryAdapter();n.push(s),null==i||i("[SessionStorage] Memory adapter created");const o={adapters:n,readStrategy:"first-available",writeStrategy:"all"},a=function(e){if(e)return{debug:(t,...i)=>e(`[SessionStorage] ${t}`,i),warn:(t,...i)=>e(`[SessionStorage] WARN: ${t}`,i),error:(t,...i)=>e(`[SessionStorage] ERROR: ${t}`,i)}}(i);return void 0!==a&&(o.logger=a),createCompositeAdapter(o)}function createConsentWrapper(e,t,i,r){let n=e,s=t,o=t?null:e;return{name:"consent-aware",get:(e,t)=>n.get(e,t),set:(e,t,i)=>n.set(e,t,i),remove:e=>n.remove(e),clear:()=>n.clear(),keys:()=>n.keys(),has:e=>n.has(e),isAvailable:()=>n.isAvailable(),getEntry:e=>n.getEntry(e),async grantConsent(){var e;if(s)return void(null==r||r("[ConsentStorage] Consent already granted"));null==r||r("[ConsentStorage] Granting consent, migrating to persistent storage");const t=null!=(e=null==o?void 0:o.keys())?e:[],a=[];for(const e of t){const t=null==o?void 0:o.get(e);null!==t&&a.push({key:e,value:t})}const c=createSessionStorage(i);n=c,s=!0;for(const{key:e,value:t}of a)c.set(e,t);null==r||r("[ConsentStorage] Migration complete",{migratedKeys:t.length}),o=null},async revokeConsent(){s?(null==r||r("[ConsentStorage] Revoking consent, clearing persistent storage"),n.clear(),o=createMemoryAdapter(),n=o,s=!1,null==r||r("[ConsentStorage] Revocation complete, switched to memory-only")):null==r||r("[ConsentStorage] Consent not granted, nothing to revoke")},hasConsent:()=>s,isMemoryOnly:()=>!s}}function detectGPCWithContext(){return"undefined"==typeof navigator?{enabled:!1,source:"server"}:!0===navigator.globalPrivacyControl?{enabled:!0,source:"navigator"}:{enabled:!1,source:"none"}}A(),A();var Xn={allowedFields:[],maxDepth:10,detectSSN:!0,detectCreditCard:!0,detectEmail:!0},Jn=null,Zn=/(?<![#\d])(?!000|666|9\d{2})([0-8]\d{2}|0[1-9]\d|00[1-9])[-\s./](?!00)(\d{2})[-\s./](?!0000)(\d{4})(?!\d)/g,es=/(?!000|666|9\d{2})([0-8]\d{2}|0[1-9]\d|00[1-9])[-\s./](?!00)(\d{2})[-\s./](?!0000)(\d{4})(?!\d)/g,ts=/(?<=\bssn[:\s]+|social[:\s]+security[:\s]+(?:number)?[:\s]*)(?!000|666|9\d{2})([0-8]\d{2}|0[1-9]\d|00[1-9])(?!00)(\d{2})(?!0000)(\d{4})(?!\d)/gi,is=/\b(?:ssn[:\s]+|social[:\s]+security[:\s]+(?:number)?[:\s]*)(?!000|666|9\d{2})([0-8]\d{2}|0[1-9]\d|00[1-9])(?!00)(\d{2})(?!0000)(\d{4})(?!\d)/gi;function getSSNPattern(e){return function(){if(null!==Jn)return Jn;try{new RegExp("(?<=a)b"),Jn=!0}catch(e){Jn=!1}return Jn}()?e?Zn:ts:e?es:is}var rs={visa:/\b4\d{3}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{1,4}\b/g,mastercard:/\b(?:5[1-5]\d{2}|222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/g,amex:/\b3[47]\d{2}[-\s]?\d{6}[-\s]?\d{5}\b/g,discover:/\b(?:6011|65\d{2}|64[4-9]\d|6221[2-9]\d|622[2-8]\d{2}|6229[01]\d|62292[0-5])[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{0,4}\b/g},ns=/\b(?:\d{4}[-\s]?){3,4}\d{1,4}\b/g,ss=/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g,os={"а":"a","е":"e","о":"o","р":"p","с":"c","у":"y","х":"x","і":"i","ј":"j","ѕ":"s","А":"A","В":"B","Е":"E","К":"K","М":"M","Н":"H","О":"O","Р":"P","С":"C","Т":"T","Х":"X","З":"Z","Α":"A","Β":"B","Ε":"E","Η":"H","Ι":"I","Κ":"K","Μ":"M","Ν":"N","Ο":"O","Ρ":"P","Τ":"T","Χ":"X","Υ":"Y","α":"a","ο":"o","ρ":"p","υ":"u","−":"-","-":"-","@":"@","﹫":"@"};function resetRegex(e){e.lastIndex=0}function isFieldExcluded(e,t){if(t.includes(e))return!0;const i=e.split(".").pop()||"";if(t.includes(i))return!0;for(const i of t)if(i.endsWith(".*")){const t=i.slice(0,-2);if(e.startsWith(t+".")||e===t)return!0}return!1}function isValidSSNFormat(e){const t=e.replace(/[-\s./]/g,"");if(9!==t.length)return!1;const i=parseInt(t.slice(0,3),10),r=parseInt(t.slice(3,5),10),n=parseInt(t.slice(5,9),10);return!(0===i||666===i||i>=900)&&0!==r&&0!==n}function passesLuhnCheck(e){const t=e.replace(/[-\s]/g,"");if(t.length<13||t.length>19)return!1;if(!/^\d+$/.test(t))return!1;let i=0,r=!1;for(let e=t.length-1;e>=0;e--){let n=parseInt(t[e],10);r&&(n*=2,n>9&&(n-=9)),i+=n,r=!r}return i%10==0}function detectSSN(e){const t=getSSNPattern(!0),i=getSSNPattern(!1);let r;for(resetRegex(t);null!==(r=t.exec(e));)if(isValidSSNFormat(r[0]))return resetRegex(t),!0;for(resetRegex(t),resetRegex(i);null!==(r=i.exec(e));)if(isValidSSNFormat(r[0]))return resetRegex(i),!0;return resetRegex(i),!1}function detectCreditCard(e){for(const t of Object.values(rs)){let i;for(resetRegex(t);null!==(i=t.exec(e));)if(passesLuhnCheck(i[0]))return resetRegex(t),!0;resetRegex(t)}let t;for(resetRegex(ns);null!==(t=ns.exec(e));)if(passesLuhnCheck(t[0]))return resetRegex(ns),!0;return resetRegex(ns),!1}function detectEmailInText(e){return function(e,t){resetRegex(e);const i=e.test(t);return resetRegex(e),i}(ss,e)}function checkValueForPII(e,t){const i=[],r=function(e){let t=e.normalize("NFKC");for(const[e,i]of Object.entries(os))t=t.replaceAll(e,i);return t}(e),n=e===r?[e]:[e,r];for(const e of n)t.detectSSN&&detectSSN(e)&&(i.includes("ssn")||i.push("ssn")),t.detectCreditCard&&detectCreditCard(e)&&(i.includes("credit_card")||i.push("credit_card")),t.detectEmail&&detectEmailInText(e)&&(i.includes("email")||i.push("email"));return{types:i}}function traverseObject(e,t,i,r,n){if(!(r>t.maxDepth)&&null!=e){if("string"==typeof e){if(isFieldExcluded(i,t.allowedFields))return;const r=checkValueForPII(e,t);if(r.types.length>0){n.fields.add(i);for(const e of r.types)n.types.add(e)}return}if("number"==typeof e){if(isFieldExcluded(i,t.allowedFields))return;const r=String(e);if(r.length>=9&&r.length<=19){const e=checkValueForPII(r,t);if(e.types.length>0){n.fields.add(i);for(const t of e.types)n.types.add(t)}}return}if(Array.isArray(e))for(let s=0;s<e.length;s++){const o=i?`${i}[${s}]`:`[${s}]`;traverseObject(e[s],t,o,r+1,n)}else if("object"==typeof e){const s=Object.entries(e);for(const[e,o]of s)traverseObject(o,t,i?`${i}.${e}`:e,r+1,n)}}}function detectPII(e,t){var i;const r={...Xn,...t,allowedFields:null!=(i=null==t?void 0:t.allowedFields)?i:Xn.allowedFields};if(null==e)return{hasPII:!1,types:[],fields:[]};const n={types:new Set,fields:new Set};return traverseObject(e,r,"",0,n),{hasPII:n.types.size>0,types:Array.from(n.types),fields:Array.from(n.fields)}}var as=["password","pwd","pass","passwd","secret","credential","credentials","token","apikey","api_key","accesstoken","access_token","refreshtoken","refresh_token","privatekey","private_key","secretkey","secret_key","ssn","socialsecurity","social_security","creditcard","credit_card","cardnumber","card_number","cvv","cvc","pin","securitycode","security_code","accountnumber","account_number","routingnumber","routing_number","diagnosis","prescription","medicalrecord","medical_record","healthrecord","health_record","patientid","patient_id","fingerprint","biometric","faceid","face_id","auth","authorization","bearer","jwt","session","sessionid","session_id","cookie","dob","dateofbirth","date_of_birth","birthdate","birth_date","driversLicense","drivers_license","passportnumber","passport_number"];function normalizeKey(e){return e.toLowerCase().replace(/[-_]/g,"")}function isSuspiciousKey(e,t,i){const r=normalizeKey(e),n=e.toLowerCase();if(i.has(n)||i.has(r))return!1;if(t.has(r))return!0;for(const e of t){if(r.includes(e)&&e.length>=3)return!0;if(e.includes(r)&&(r===e||r.length>=3&&e.startsWith(r)))return!0}return!1}function validateRecursive(e,t,i,r,n,s,o){if(!(n>s||null==e)&&"object"==typeof e)if(Array.isArray(e))for(let a=0;a<e.length;a++){const c=t?`${t}[${a}]`:`[${a}]`;validateRecursive(e[a],c,i,r,n+1,s,o)}else for(const[a,c]of Object.entries(e)){const e=t?`${t}.${a}`:a;isSuspiciousKey(a,i,r)&&o.push(e),null!==c&&"object"==typeof c&&validateRecursive(c,e,i,r,n+1,s,o)}}function buildWarningMessage(e,t){return[`[Overvio SDK] Suspicious property keys detected in ${t}`,` Keys: ${e.map(e=>`"${e}"`).join(", ")}`," These keys suggest sensitive data that should not be tracked."," If intentional, add them to 'allowedKeys' in the privacy config."].join("\n")}function validatePropertyKeys(e,t){var i,r,n,s,o;if(!e||"object"!=typeof e)return{valid:!0,suspiciousKeys:[]};const a=null!=(i=null==t?void 0:t.warnOnly)&&i,c=null!=(r=null==t?void 0:t.maxDepth)?r:5,l=null!=(n=null==t?void 0:t.context)?n:"event properties",u=[];return validateRecursive(e,"",new Set([...as,...null!=(s=null==t?void 0:t.additionalKeys)?s:[]].map(normalizeKey)),new Set((null!=(o=null==t?void 0:t.allowedKeys)?o:[]).map(e=>e.toLowerCase())),0,c,u),0===u.length?{valid:!0,suspiciousKeys:[]}:{valid:a,suspiciousKeys:u,warningMessage:buildWarningMessage(u,l)}}var cs=["token","access_token","accesstoken","refresh_token","refreshtoken","id_token","idtoken","auth","auth_token","authtoken","authorization","api_key","apikey","key","secret","client_secret","clientsecret","app_secret","appsecret","password","pwd","passwd","pass","credential","credentials","session","sessionid","session_id","sid","ssid","jwt","bearer","jwt_token","code","state","nonce","reset_token","resettoken","verification_token","verificationtoken","confirm_token","confirmtoken","invite_token","invitetoken","magic_token","magictoken","private_key","privatekey","signing_key","signingkey","encryption_key","encryptionkey","ssn","social_security","credit_card","creditcard","card_number","cardnumber","cvv","cvc"],ls=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"];function isSensitiveParam(e,t,i){const r=e.normalize("NFKC").toLowerCase();if(i.has(r))return!1;if(t.has(r))return!0;for(const e of t)if(r.includes(e)||e.includes(r))return!0;return!1}function sanitizeUrlParams(e,t){var i,r,n;if(!e||"string"!=typeof e)return{url:null!=e?e:"",wasModified:!1,redactedParams:[]};let s;try{const t=!e.includes("://")&&!e.startsWith("//");s=new URL(e,t?"https://placeholder.local":void 0)}catch(t){return{url:e,wasModified:!1,redactedParams:[]}}if(!s.search)return{url:e,wasModified:!1,redactedParams:[]};const o=null!=(i=null==t?void 0:t.redactValue)?i:"[REDACTED]",a=!1!==(null==t?void 0:t.preserveUtmParams),c=new Set([...cs,...null!=(r=null==t?void 0:t.additionalParams)?r:[]].map(e=>e.toLowerCase())),l=new Set([...null!=(n=null==t?void 0:t.preserveParams)?n:[],...a?ls:[]].map(e=>e.toLowerCase())),u=[],d=new URLSearchParams;for(const[e,t]of s.searchParams)isSensitiveParam(e,c,l)?(d.set(e,o),u.push(e)):d.set(e,t);return 0===u.length?{url:e,wasModified:!1,redactedParams:[]}:(s.search=d.toString(),{url:e.includes("://")||e.startsWith("//")?s.toString():`${s.pathname}${s.search}${s.hash}`,wasModified:!0,redactedParams:u})}function sanitizeUrlForTracking(e,t){return sanitizeUrlParams(e,t).url}var us={},ds=["url","referrer","page.url","page.referrer","context.page.url","context.page.referrer"],hs=new Set(["__proto__","constructor","prototype"]);function deepClone(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(deepClone);if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);const t={};for(const[i,r]of Object.entries(e))hs.has(i)||(t[i]=deepClone(r));return t}function getNestedValue(e,t){const i=t.split(".");let r=e;for(const e of i){if(null==r||"object"!=typeof r)return;const t=e.match(/^(.+?)\[(\d+)\]$/);if(t){const[,e,i]=t;if(void 0===e||void 0===i)return;if(r=r[e],!Array.isArray(r))return;r=r[parseInt(i,10)]}else r=r[e]}return r}function setNestedValue(e,t,i){const r=t.split(".");let n=e;for(let e=0;e<r.length-1;e++){const t=r[e];if(void 0===t)continue;const i=t.match(/^(.+?)\[(\d+)\]$/);if(i){const[,e,t]=i;if(void 0===e||void 0===t)continue;n[e]||(n[e]=[]);const r=n[e],s=parseInt(t,10);r[s]||(r[s]={}),n=r[s]}else n[t]&&"object"==typeof n[t]||(n[t]={}),n=n[t]}const s=r[r.length-1];if(void 0!==s){const e=s.match(/^(.+?)\[(\d+)\]$/);if(e){const[,t,r]=e;void 0!==t&&void 0!==r&&(n[t]||(n[t]=[]),n[t][parseInt(r,10)]=i)}else n[s]=i}}function isDevEnvironment(){var e;if("undefined"!=typeof process)return!1;try{if("production"===(null==(e=us.env)?void 0:e.MODE))return!1}catch(e){}return!0}function protectPayload(e,t){var i,r,n,s,o,a,c,l,u,d;const h=null!=(i=null==t?void 0:t.mode)?i:"warn",g=null!=(r=null==t?void 0:t.context)?r:"event",p=null!=(n=null==t?void 0:t.redactValue)?n:"[REDACTED]",m=!1!==(null==t?void 0:t.validateKeys),f=!1!==(null==t?void 0:t.sanitizeUrls),y=null!=(s=null==t?void 0:t.urlFields)?s:ds,v=[];let b,S,w=e,C=!1;if("off"===h)return{allowed:!0,payload:w,piiDetected:!1,keysValidated:!1,urlsSanitized:!1,warnings:[]};if(f){const e=function(e,t){const i=deepClone(e),r=[];for(const e of t){const t=getNestedValue(i,e);if("string"==typeof t&&t.length>0){const n=sanitizeUrlParams(t);n.wasModified&&(setNestedValue(i,e,n.url),r.push(e))}}return{payload:i,sanitizedFields:r}}(w,y);e.sanitizedFields.length>0&&(w=e.payload,S=e.sanitizedFields)}const E={detectSSN:!1!==(null==(o=null==t?void 0:t.detectTypes)?void 0:o.ssn),detectCreditCard:!1!==(null==(a=null==t?void 0:t.detectTypes)?void 0:a.creditCard),detectEmail:!1!==(null==(c=null==t?void 0:t.detectTypes)?void 0:c.email)};(null==t?void 0:t.allowedFields)&&(E.allowedFields=t.allowedFields);const _=detectPII(w,E);if(C=_.hasPII,C){const e={piiTypes:_.types,fields:_.fields,mode:h,context:g,timestamp:Date.now()};switch(null==(l=null==t?void 0:t.onDetection)||l.call(t,e),h){case"warn":v.push(`[Overvio SDK] PII detected in ${g}: ${_.types.join(", ")} in fields: ${_.fields.join(", ")}`),isDevEnvironment()&&console.warn(v[v.length-1]);break;case"redact":w=function(e,t,i){const r=deepClone(e);for(const e of t)void 0!==getNestedValue(r,e)&&setNestedValue(r,e,i);return r}(w,_.fields,p),v.push(`[Overvio SDK] PII redacted from ${g}: fields ${_.fields.join(", ")}`);break;case"block":{const e={allowed:!1,payload:void 0,piiDetected:!0,piiResult:_,keysValidated:m,urlsSanitized:f&&(null!=(u=null==S?void 0:S.length)?u:0)>0,blockReason:`PII detected in ${g}: ${_.types.join(", ")} in fields: ${_.fields.join(", ")}`,warnings:v};return void 0!==b&&(e.keyValidationResult=b),void 0!==S&&(e.sanitizedUrlFields=S),e}}}if(m){const e={warnOnly:!0,context:g};(null==t?void 0:t.allowedFields)&&(e.allowedKeys=t.allowedFields),(null==t?void 0:t.additionalSuspiciousKeys)&&(e.additionalKeys=t.additionalSuspiciousKeys),b=validatePropertyKeys(w,e),b.suspiciousKeys.length>0&&(v.push(`[Overvio SDK] Suspicious property keys in ${g}: ${b.suspiciousKeys.join(", ")}`),isDevEnvironment()&&b.warningMessage&&console.warn(b.warningMessage))}const I={allowed:!0,payload:w,piiDetected:C,keysValidated:m,urlsSanitized:f&&(null!=(d=null==S?void 0:S.length)?d:0)>0,warnings:v};return void 0!==_&&(I.piiResult=_),void 0!==b&&(I.keyValidationResult=b),void 0!==S&&(I.sanitizedUrlFields=S),I}h();var gs=class _Overvio{constructor(e){var t,i,r,n,s,o,a,c,l,u,d,h,g,p,m,f,y,v,b,S;__publicField(this,"_config"),__publicField(this,"_pluginManager"),__publicField(this,"_events"),__publicField(this,"_moduleLoader"),__publicField(this,"_anonymousIdManager"),__publicField(this,"_identityManager"),__publicField(this,"_crossDomainLinker"),__publicField(this,"_linkDecorator"),__publicField(this,"_userId"),__publicField(this,"_sessionId"),__publicField(this,"_initialized",!1),__publicField(this,"_cart",null),__publicField(this,"_httpClient",null),__publicField(this,"_searchClient",null),__publicField(this,"_widgetConfigManager",null),__publicField(this,"_storage"),__publicField(this,"_consentAwareStorage",null),__publicField(this,"_proxyEventSender",null),__publicField(this,"_securityLogger"),__publicField(this,"_consentManager"),__publicField(this,"_cookieStorage",null),__publicField(this,"_gpcApplied",!1),__publicField(this,"_l1HttpClient",null),__publicField(this,"_sessionManager",null),__publicField(this,"_sessionApiClient",null),__publicField(this,"_identifyApiClient",null),__publicField(this,"_sessionService",null),__publicField(this,"_sessionInitPromise",null),this._config=e,e.csp.nonce&&function(e){Ve=e}({nonce:e.csp.nonce}),e.csp.enableTrustedTypes&&setGlobalTrustedTypesConfig({enabled:!0,policyName:e.csp.trustedTypesPolicyName})&&e.debug&&this.log("info","Trusted Types policy initialized",{policyName:e.csp.trustedTypesPolicyName}),this._events=new T({onListenerError:(e,t)=>{this._config.debug&&console.error(`[Overvio] Listener error for event '${String(e)}':`,t)}});const w={getUserId:()=>this._userId,getSessionId:()=>this._sessionId,getApiKey:()=>this._config.apiKey,isDebugMode:()=>this._config.debug,log:(e,t,i)=>this.log(e,t,i),getConfig:e=>this.getConfigValue(e),hasConsent:e=>this.hasConsent(e),now:()=>new Date};let C;if(this._pluginManager=new jn({sdkContext:w,defaultTimeout:this._config.pluginTimeout,continueOnError:!0}),this._moduleLoader=function(e={}){return new Vr(e)}({debug:this._config.debug}),this._securityLogger=this.initializeSecurityLogger(),"custom"===this._config.storage.type&&this._config.storage.adapter)C=this._config.storage.adapter;else if(this._config.storage.disablePersistence)C=new Dn;else{const e={cookiePath:null!=(i=null==(t=this._config.storage.cookie)?void 0:t.path)?i:"/",crossSubdomain:!!(null==(r=this._config.storage.cookie)?void 0:r.domain)};switch(void 0!==(null==(n=this._config.storage.cookie)?void 0:n.domain)&&(e.cookieDomain=this._config.storage.cookie.domain),void 0!==(null==(s=this._config.storage.cookie)?void 0:s.secure)&&(e.secure=this._config.storage.cookie.secure),this._config.debug&&(e.onDebug=(e,t)=>this.log("debug",`[Storage] ${e}`,t)),this._config.storage.type){case"memory":C=new Dn;break;case"localStorage":C=createLocalStorageAdapter();break;case"sessionStorage":C=new Dn,this.log("warn","sessionStorage type not fully implemented, using memory adapter");break;default:if(this._config.consent.waitForConsent){const t=function(e={}){var t;const i=e.onDebug;if(!e.requireConsent)return createConsentWrapper(createSessionStorage(e),!0,e,i);const r=null!=(t=e.hasConsent)&&t;return null==i||i("[ConsentStorage] Creating consent-aware storage",{requireConsent:!0,initialConsent:r}),r?createConsentWrapper(createSessionStorage(e),!0,e,i):createConsentWrapper(createMemoryAdapter(),!1,e,i)}({...e,requireConsent:!0,hasConsent:null!=(o=this._config.consent.analytics)&&o});C=t,this._consentAwareStorage=t}else C=createSessionStorage(e)}}this._storage=C;const E={cookiePath:null!=(c=null==(a=this._config.storage.cookie)?void 0:a.path)?c:"/",crossSubdomain:!!(null==(l=this._config.storage.cookie)?void 0:l.domain),disablePersistence:this._config.storage.disablePersistence};void 0!==(null==(u=this._config.storage.cookie)?void 0:u.domain)&&(E.cookieDomain=this._config.storage.cookie.domain),void 0!==(null==(d=this._config.storage.cookie)?void 0:d.secure)&&(E.secure=this._config.storage.cookie.secure),this._config.debug&&(E.onDebug=(e,t)=>this.log("debug",`[IdentityStorage] ${e}`,t));const{persistentStorage:_}=function(e={}){var t;const i=e.onDebug;if(e.disablePersistence){null==i||i("[IdentityStorage] Creating memory-only storage (persistence disabled)");const e=createMemoryAdapter();return{sessionStorage:e,persistentStorage:e}}const r=function(e){var t,i,r;const n=null!=(t=e.sessionTimeoutMs)?t:mn,s=resolveCookieDomain(e),o={path:null!=(i=e.cookiePath)?i:"/",secure:null!=(r=e.secure)?r:isSecureContext2(),sameSite:"Lax",maxAge:Math.floor(n/1e3)};return void 0!==s&&(o.domain=s),o}(e),n=function(e){var t,i,r;const n=null!=(t=e.persistentExpiryMs)?t:31536e6,s=resolveCookieDomain(e),o={path:null!=(i=e.cookiePath)?i:"/",secure:null!=(r=e.secure)?r:isSecureContext2(),sameSite:"Lax",maxAge:Math.floor(n/1e3)};return void 0!==s&&(o.domain=s),o}(e);return null==i||i("[IdentityStorage] Creating cookie-first storage",{sessionMaxAge:r.maxAge,persistentMaxAge:n.maxAge,domain:null!=(t=r.domain)?t:"(current domain)",secure:r.secure}),{sessionStorage:createStorageAdapter(r,"SessionStorage",i),persistentStorage:createStorageAdapter(n,"PersistentStorage",i)}}(E);this._anonymousIdManager=new Br({storage:_}),this._identityManager=new pn({storage:_,emitter:this._events,anonymousIdManager:this._anonymousIdManager,securityLogger:this._securityLogger,...this._config.debug&&{onDebug:(e,t)=>this.log("debug",`[Identity] ${e}`,t)}}),this._cookieStorage=new An({path:"/",secure:null==(g=null==(h=this._config.storage.cookie)?void 0:h.secure)||g,sameSite:null!=(m=null==(p=this._config.storage.cookie)?void 0:p.sameSite)?m:"Lax",...(null==(f=this._config.storage.cookie)?void 0:f.domain)&&{domain:this._config.storage.cookie.domain}});let I=this._config.consent.marketing,k=!1;if(!1!==this._config.respectGPC){const e=detectGPCWithContext();e.enabled&&(I=!1,k=!0,this.log("info","GPC signal detected, disabling marketing consent",{source:e.source}),this._securityLogger.log({type:"SYS_CONFIG_CHANGED",action:"gpc_enforced",outcome:"success",metadata:{component:"ConsentManager",gpcSource:e.source,previousMarketingConsent:this._config.consent.marketing,newMarketingConsent:!1}}))}if(this._consentManager=new vr(this._cookieStorage,{emitter:this._events,defaultConsent:{analytics:this._config.consent.analytics,marketing:I,functional:this._config.consent.functional},waitForConsent:null!=(y=this._config.consent.waitForConsent)&&y,requiredCategories:["analytics"],cookieName:"consent",cookieSecure:null==(b=null==(v=this._config.storage.cookie)?void 0:v.secure)||b,...(null==(S=this._config.storage.cookie)?void 0:S.domain)&&{cookieDomain:this._config.storage.cookie.domain},enableCrossTabSync:!0,debug:this._config.debug,onConsentChange:(e,t)=>{if(this._securityLogger.log({type:"SYS_CONFIG_CHANGED",action:"consent_changed",outcome:"success",metadata:{component:"ConsentManager",previousConsent:t,newConsent:e}}),this._consentAwareStorage&&null!==t){const i=!0===e.analytics,r=!0===t.analytics;i&&!r?(this._consentAwareStorage.grantConsent().catch(e=>{this.log("warn","Failed to migrate storage after consent granted",{error:e})}),this.log("debug","Storage consent granted, migrating to persistent storage")):!i&&r&&(this._consentAwareStorage.revokeConsent().catch(e=>{this.log("warn","Failed to clear storage after consent revoked",{error:e})}),this.log("debug","Storage consent revoked, cleared persistent storage"))}}}),this._gpcApplied=k,this._consentManager.init().catch(e=>{this.log("warn","Failed to initialize consent manager",{error:e})}),this._sessionManager=function(e,t,i){return new Qn(e,t,i)}(this._storage,this._events,{config:{sessionTimeoutMs:18e5,enableCrossTabSync:!0,...this._config.debug&&{onDebug:(e,t)=>this.log("debug",`[Session] ${e}`,t)}},onSessionStarted:(e,t)=>{this._sessionId=e.sessionId,this.log("debug","Session "+(t?"started":"resumed"),{sessionId:redactId(e.sessionId)})},onSessionExpired:(e,t)=>{this.log("debug",`Session expired: ${t}`,{sessionId:redactId(e)})}}),this._sessionApiClient=(x={httpClient:this.getL1HttpClient(),...this._config.debug&&{onDebug:(e,t)=>this.log("debug",`[SessionApi] ${e}`,t)}},new Gn(x)),this._identifyApiClient=function(e){return new Qr(e)}({httpClient:this.getL1HttpClient(),...this._config.debug&&{onDebug:(e,t)=>this.log("debug",`[IdentifyApi] ${e}`,t)}}),this._sessionService=function(e){return new Yn(e)}({sessionManager:this._sessionManager,sessionApiClient:this._sessionApiClient,anonymousIdManager:this._anonymousIdManager,apiKey:this._config.apiKey,getCookieName:()=>"overvio-user",requireServerSession:!1,maxRetries:3,retryDelayMs:1e3,...this._config.debug&&{onDebug:(e,t)=>this.log("debug",`[SessionService] ${e}`,t)},onServerSessionCreated:e=>{this._sessionId=e.sessionId,e.userId&&!this._userId&&(this._userId=e.userId),this._securityLogger.log({type:"SYS_INITIALIZATION",action:"server_session_created",outcome:"success",metadata:{sessionId:e.sessionId,isNew:e.isNew}})},onServerSessionFailed:e=>{this.log("warn","Server session creation failed, using local session",{error:e.message})}}),this._sessionInitPromise=this._sessionService.initialize().catch(e=>{var t,i,r,n;return this.log("error","Session initialization failed",{error:e}),{success:!1,sessionId:null!=(n=null==(t=this._sessionManager)?void 0:t.getSessionId())?n:createSessionId(null!=(r=null==(i=crypto.randomUUID)?void 0:i.call(crypto))?r:Date.now().toString()),hasServerSession:!1,error:e instanceof Error?e:new Error(String(e))}}),this._config.crossDomain.enabled){const e={anonymousIdManager:this._anonymousIdManager,acceptIncoming:this._config.crossDomain.acceptIncoming,expiryMs:this._config.crossDomain.expiryMs,autoCleanUrl:this._config.crossDomain.autoCleanUrl,...this._config.crossDomain.allowedDomains&&{allowedDomains:this._config.crossDomain.allowedDomains},...this._config.crossDomain.signatureSecret&&{signatureSecret:this._config.crossDomain.signatureSecret},...this._config.debug&&{onDebug:(e,t)=>this.log("debug",`[CrossDomain] ${e}`,t)}};if(this._crossDomainLinker=new sn(e),this._config.crossDomain.decorateLinks){const e={crossDomainLinker:this._crossDomainLinker,selector:this._config.crossDomain.linkSelector,...this._config.debug&&{onDebug:(e,t)=>this.log("debug",`[LinkDecorator] ${e}`,t)}};this._linkDecorator=new an(e)}else this._linkDecorator=null;this._config.crossDomain.acceptIncoming&&"undefined"!=typeof window&&this._crossDomainLinker.applyLinkerParams().then(e=>{var t;this._config.debug&&e.applied&&this.log("info","Applied cross-domain linker params",{anonymousId:null==(t=e.params)?void 0:t.anonymousId})})}else this._crossDomainLinker=null,this._linkDecorator=null;var x;if("server-proxy"===this._config.trackingMode&&this._config.proxyEndpoint&&(this._proxyEventSender=new Wn({apiKey:this._config.apiKey,proxyEndpoint:this._config.proxyEndpoint,batchSize:this._config.queue.maxSize>10?10:this._config.queue.maxSize,flushInterval:this._config.queue.flushInterval,maxRetries:this._config.queue.maxRetries}),this._proxyEventSender.setIdentityProvider(()=>{const e={};void 0!==this._userId&&(e.userId=this._userId);const t=this._anonymousIdManager.getOrCreate();return void 0!==t&&(e.anonymousId=t),void 0!==this._sessionId&&(e.sessionId=this._sessionId),e}),this._proxyEventSender.start(),this._config.debug&&this.log("info","Proxy event sender initialized",{endpoint:this._config.proxyEndpoint,trackingMode:this._config.trackingMode})),this._config.debug&&this.runSecurityAudit(),this._config.respectGPC){const e=detectGPCWithContext();e.enabled&&(this._config.consent.marketing=!1,this._securityLogger.log({type:"SYS_CONFIG_CHANGED",action:"gpc_signal_detected",outcome:"success",metadata:{component:"Overvio",gpcSource:e.source,marketingDisabled:!0}}),this._config.debug&&this.log("info","Global Privacy Control (GPC) detected - marketing consent disabled",{source:e.source}))}this._initialized=!0,this._securityLogger.log({type:"SYS_INITIALIZATION",action:"sdk_initialized",outcome:"success",metadata:{component:"Overvio",sdkVersion:"1.0.0",modules:this._config.modules,trackingMode:this._config.trackingMode,debugMode:this._config.debug,crossDomainEnabled:this._config.crossDomain.enabled,securityLoggingEnabled:this._config.securityLogging.enabled}})}static getInstance(){return _Overvio._instance}static resetInstance(){_Overvio._instance=null,_Overvio._initPromise=null,_Overvio._initConfig=null}static setInstance(e){_Overvio._instance=e}static getInitConfig(){return _Overvio._initConfig}static setInitConfig(e){_Overvio._initConfig=e}static isInitializing(){return null!==_Overvio._initPromise}static setInitPromise(e){_Overvio._initPromise=e}initializeSecurityLogger(){const e=this._config.securityLogging;if(!e.enabled)return createDisabledLogger();if(!e.endpoint&&!e.callback)return this.log("warn","Security logging enabled but no endpoint or callback configured"),createDisabledLogger();const t=new zn({enabled:!0,...void 0!==e.endpoint&&{endpoint:e.endpoint},...void 0!==e.callback&&{callback:e.callback},flushIntervalMs:e.flushIntervalMs,maxQueueSize:e.maxQueueSize,maxRetries:e.maxRetries,headers:e.headers});return this._config.debug&&this.log("info","Security logger initialized",{endpoint:e.endpoint,hasCallback:!!e.callback,flushIntervalMs:e.flushIntervalMs,maxQueueSize:e.maxQueueSize,redactPII:e.redactPII}),t}runSecurityAudit(){var e;e=function(e){const t=[];t.push(...function(e){const t=[];return e?(e.startsWith("https://")||t.push({code:"INSECURE_ENDPOINT",message:`API endpoint "${e}" does not use HTTPS`,severity:"high",recommendation:"Use HTTPS for all API endpoints to protect data in transit"}),t):t}(e.apiEndpoint)),t.push(...function(e){const t=[];return e&&e.enabled?(e.allowedDomains&&0!==e.allowedDomains.length||t.push({code:"CROSS_DOMAIN_NO_WHITELIST",message:"Cross-domain tracking is enabled without an allowedDomains whitelist",severity:"critical",recommendation:"Configure allowedDomains to explicitly list trusted destination domains. This prevents identity leakage to unauthorized third-party domains."}),e.acceptIncoming&&t.push({code:"CROSS_DOMAIN_ACCEPT_INCOMING_ENABLED",message:"acceptIncoming is enabled, which allows identity injection from URL params",severity:"medium",recommendation:"Ensure this is intentional. Only enable acceptIncoming on domains that should receive cross-domain identity from trusted sources."}),e.hasSignatureSecret||t.push({code:"NO_SIGNATURE_SECRET",message:"Cross-domain tracking does not use signature verification",severity:"medium",recommendation:"Configure signatureSecret to prevent tampering with linker params. The same secret must be configured on both source and destination domains."}),t):t}(e.crossDomain)),t.push(...function(e,t){const i=[];return e?(t&&!1===e.secure&&i.push({code:"COOKIE_INSECURE_ON_HTTPS",message:"Cookie secure flag is disabled on an HTTPS site",severity:"high",recommendation:"Enable the secure flag for cookies when serving over HTTPS to prevent cookies from being sent over unencrypted connections."}),"none"!==e.sameSite||e.secure||i.push({code:"COOKIE_SAMESITE_NONE_WITHOUT_SECURE",message:"Cookie has SameSite=None but Secure flag is not set",severity:"high",recommendation:"Cookies with SameSite=None must also have the Secure flag set. Modern browsers will reject these cookies without the Secure flag."}),i):i}(e.cookie,e.isSecureContext));const i={critical:t.filter(e=>"critical"===e.severity).length,high:t.filter(e=>"high"===e.severity).length,medium:t.filter(e=>"medium"===e.severity).length,low:t.filter(e=>"low"===e.severity).length};return{secure:0===i.critical&&0===i.high,warnings:t,summary:i}}({...this._config.endpoints.events&&{apiEndpoint:this._config.endpoints.events},crossDomain:{enabled:this._config.crossDomain.enabled,acceptIncoming:this._config.crossDomain.acceptIncoming,hasSignatureSecret:!!this._config.crossDomain.signatureSecret,...this._config.crossDomain.allowedDomains&&{allowedDomains:this._config.crossDomain.allowedDomains}},isSecureContext:"undefined"!=typeof window&&window.isSecureContext}),"undefined"==typeof process&&(e.secure||(console.warn("[Overvio Security] Configuration has security issues:",`${e.summary.critical} critical, ${e.summary.high} high, ${e.summary.medium} medium, ${e.summary.low} low`),e.warnings.forEach(e=>{const t="critical"===e.severity||"high"===e.severity?"⚠️ ":"";console.warn(`${t}[${e.severity.toUpperCase()}] ${e.code}: ${e.message}`),e.recommendation&&console.info(` Recommendation: ${e.recommendation}`)})))}getUserId(){return this._userId}getSessionId(){return this._sessionId}get session(){return this._sessionService}async waitForSession(){var e;return this._sessionInitPromise?this._sessionInitPromise:{success:!1,sessionId:null!=(e=this._sessionId)?e:createSessionId(Date.now().toString()),hasServerSession:!1,error:new Error("Session service not initialized")}}hasServerSession(){var e,t;return null!=(t=null==(e=this._sessionService)?void 0:e.hasServerSessionEstablished())&&t}getApiKey(){return this._config.apiKey}isDebugMode(){return this._config.debug}log(e,t,i){const r={none:0,error:1,warn:2,info:3,debug:4},n=r[this._config.logLevel];if(r[e]<=n){const r=`[Overvio] ${t}`;switch(e){case"debug":break;case"info":console.info(r,void 0!==i?i:"");break;case"warn":console.warn(r,void 0!==i?i:"");break;case"error":console.error(r,void 0!==i?i:"")}}}getConfig(e){return this.getConfigValue(e)}hasConsent(e){return this._consentManager.isInitialized?this._consentManager.hasConsent(e):!0===this._config.consent[e]}now(){return new Date}get events(){return this._events}get plugins(){return this._pluginManager}get config(){return this._config}get initialized(){return this._initialized}get anonymousId(){return this._anonymousIdManager}getAnonymousId(){const e=this._anonymousIdManager.get();return null!==e?String(e):void 0}get crossDomainLinker(){return this._crossDomainLinker}get linkDecorator(){return this._linkDecorator}get cart(){return this._cart||(this._cart=new lr),this._cart}setCart(e){this._cart=e}get securityLogger(){return this._securityLogger}get identity(){return this._identityManager}get consent(){return this._consentManager}get gpcApplied(){return this._gpcApplied}get isProxyMode(){return null!==this._proxyEventSender}get proxyPendingCount(){var e,t;return null!=(t=null==(e=this._proxyEventSender)?void 0:e.pendingCount)?t:0}async flushProxyEvents(){this._proxyEventSender&&await this._proxyEventSender.flush()}async flush(){await this.flushProxyEvents()}getHttpClient(){var e;if(!this._httpClient){const t=null!=(e=this._config.endpoints.search)?e:rr,i={baseUrl:t,debug:this._config.debug,retry:{maxAttempts:3,initialDelayMs:1e3,jitter:"full"}};this._httpClient=new Lr(i),this.log("debug","HTTP client initialized",{baseUrl:t})}return this._httpClient}getL1HttpClient(){var e,t;if(!this._l1HttpClient){const i=null!=(e=this._config.endpoints.events)?e:ir;this._l1HttpClient=(t={baseUrl:i,timeout:1e4,headers:{"x-api-key":this._config.apiKey}},new Mr(t)),this.log("debug","L1 HTTP client initialized",{baseUrl:i})}return this._l1HttpClient}get searchClient(){if(!this._searchClient){const{createSearchClient:e}=(Ee(),__toCommonJS(Ce));this._searchClient=e({httpClient:this.getHttpClient(),apiKey:this._config.apiKey,debug:this._config.debug}),this.log("debug","SearchClient initialized")}return this._searchClient}getWidgetConfigManager(){if(!this._widgetConfigManager){const{createWidgetConfigManager:e}=(Be(),__toCommonJS($e));this._widgetConfigManager=e({httpClient:this.getHttpClient(),storage:this._storage,apiKey:this._config.apiKey,debug:this._config.debug}),this.log("debug","WidgetConfigManager initialized")}return this._widgetConfigManager}async mountSearchWidget(e,t){var i;const{createSearchWidget:r}=(dt(),__toCommonJS(ot)),n=r(Object.assign({searchClient:this.searchClient,configManager:this.getWidgetConfigManager(),debug:null!=(i=null==t?void 0:t.debug)?i:this._config.debug},(null==t?void 0:t.onResultClick)?{onResultClick:t.onResultClick}:{},(null==t?void 0:t.onSearch)?{onSearch:t.onSearch}:{},(null==t?void 0:t.onError)?{onError:t.onError}:{}));return await n.mount(e),this.log("debug","Search widget mounted",{target:"string"==typeof e?e:"HTMLElement"}),n}setUserId(e){this._userId=e}setSessionId(e){this._sessionId=e}updateConsent(e){const t={};void 0!==e.analytics&&(t.analytics=e.analytics),void 0!==e.marketing&&(t.marketing=e.marketing),void 0!==e.functional&&(t.functional=e.functional),this._consentManager.updateConsent(t),this._config.consent={...this._config.consent,...e,necessary:!0}}async loadModule(e){return this.log("debug",`Loading module: ${e}`),this._moduleLoader.loadModule(e)}isModuleLoaded(e){return this._moduleLoader.isModuleLoaded(e)}isModuleLoading(e){return this._moduleLoader.isModuleLoading(e)}getModuleLoaderStats(){return this._moduleLoader.getStats()}get search(){return this._moduleLoader.getModuleOrThrow("search")}get banners(){return this._moduleLoader.getModuleOrThrow("banners")}get recommendations(){return this._moduleLoader.getModuleOrThrow("recommendations")}async track(e,t){var i,r;const n=Date.now(),s=function(e){if(e in ur){const t=ur[e];if(void 0!==t)return t}return"analytics"}(e);if(!this.hasConsent(s))return this.log("debug",`Event blocked by consent: ${e}`,{requiredConsent:s,hasConsent:!1}),{success:!1,blockedByConsent:!0,requiredConsent:s,blockReason:`Missing '${s}' consent for event '${e}'`,timestamp:n};let o={type:"track",event:e,timestamp:n,properties:null!=t?t:{},context:{page:this.getPageContext(),anonymousId:this._anonymousIdManager.getOrCreate()},...void 0!==this._userId&&{userId:this._userId},...void 0!==this._sessionId&&{sessionId:this._sessionId}};const a=this._config.privacy;if("off"!==a.piiProtection.mode){const t=protectPayload(o,{mode:a.piiProtection.mode,allowedFields:a.piiProtection.allowedFields,detectTypes:a.piiProtection.detectTypes,validateKeys:a.validatePropertyKeys,additionalSuspiciousKeys:a.additionalSuspiciousKeys,sanitizeUrls:!1,context:`${e} event`});if(!t.allowed)return this.log("debug",`Event blocked by payload protection: ${e}`,{reason:t.blockReason}),{success:!1,blockReason:null!=(i=t.blockReason)?i:"Event blocked by PII protection",timestamp:n};if(t.payload&&"type"in t.payload){const e=t.payload;void 0!==e.properties&&(o={...o,properties:e.properties})}t.piiDetected&&t.warnings.length>0&&this.log("debug",`Payload protection warnings for ${e}`,{warnings:t.warnings})}this.log("debug",`Tracking event: ${e}`,{properties:t});try{const t=await this._pluginManager.executeChain("track",o);if(t.aborted)return this.log("debug",`Event blocked by plugin: ${e}`,{reason:t.abortReason}),{success:!1,blockedByPlugin:!0,blockReason:null!=(r=t.abortReason)?r:"Blocked by plugin",timestamp:n};if(this._proxyEventSender){const i=createIdempotencyKey(`track_${e}_${n}_${secureRandomHex(4)}`);try{await this._proxyEventSender.send(t.event,"track",i)}catch(t){this.log("warn",`Failed to send event to proxy: ${e}`,{error:t})}}return this._events.emit("track",{event:t.event,success:!0}),this.log("debug",`Event tracked: ${e}`),{success:!0,timestamp:n}}catch(t){return this.log("error",`Failed to track event: ${e}`,{error:t}),{success:!1,blockReason:t instanceof Error?t.message:"Unknown error",timestamp:n}}}async page(e,t){const i=this.getPageContext();return this.track("page_view",{...i,...t,...e&&{name:e}})}async identify(e,t){var i,r;const n=Date.now(),s="string"==typeof e?createUserId(e):e;this._userId=s,this.log("debug","User identified",{userId:s,traits:t});let o={type:"identify",userId:s,traits:t,timestamp:n,context:{page:this.getPageContext(),anonymousId:this._anonymousIdManager.getOrCreate()}};const a=this._config.privacy;if("off"!==a.piiProtection.mode&&t){const e=protectPayload({traits:t},{mode:a.piiProtection.mode,allowedFields:["email","phone","name",...a.piiProtection.allowedFields],detectTypes:a.piiProtection.detectTypes,validateKeys:a.validatePropertyKeys,additionalSuspiciousKeys:a.additionalSuspiciousKeys,sanitizeUrls:!1,context:"identify traits"});if(!e.allowed)return this.log("warn","Identify event blocked by payload protection",{reason:e.blockReason}),{success:!1,blockReason:null!=(i=e.blockReason)?i:"Traits blocked by payload protection",timestamp:n};e.payload&&"traits"in e.payload&&(o={...o,traits:e.payload.traits}),e.piiDetected&&e.warnings.length>0&&this.log("debug","Payload protection warnings for identify",{warnings:e.warnings})}try{const e=await this._pluginManager.executeChain("identify",o);if(e.aborted)return{success:!1,blockedByPlugin:!0,blockReason:null!=(r=e.abortReason)?r:"Blocked by plugin",timestamp:n};if(this._proxyEventSender){const t=createIdempotencyKey(`identify_${s}_${n}_${secureRandomHex(4)}`);try{await this._proxyEventSender.send(e.event,"identify",t)}catch(e){this.log("warn","Failed to send identify event to proxy",{error:e})}}if(this._identifyApiClient){const e=this._anonymousIdManager.getOrCreate();try{const i=await this._identifyApiClient.identify({anonymousId:e,userId:s,traits:t});this.log("debug","Backend identify succeeded",{linked:i.linked,wasReidentified:i.wasReidentified,previousUserId:i.previousUserId})}catch(t){this.log("debug","Backend identify failed (non-blocking)",{error:t instanceof Error?t.message:String(t),userId:s,anonymousId:e})}}return this._events.emit("identify",{user:{userId:s,traits:t}}),{success:!0,timestamp:n}}catch(e){return this.log("error","Failed to identify user",{error:e}),{success:!1,blockReason:e instanceof Error?e.message:"Unknown error",timestamp:n}}}reset(){this._userId=void 0,this._anonymousIdManager.reset(),this.log("debug","User identity reset")}destroy(){this.log("debug","Destroying SDK instance"),this._securityLogger.log({type:"SYS_SHUTDOWN",action:"sdk_destroyed",outcome:"success",metadata:{component:"Overvio"}}),this._proxyEventSender&&(this._proxyEventSender.destroy(),this._proxyEventSender=null),this._sessionManager&&(this._sessionManager.destroy(),this._sessionManager=null),this._sessionService=null,this._sessionApiClient=null,this._identifyApiClient=null,this._l1HttpClient=null,this._sessionInitPromise=null,this._linkDecorator&&(this._linkDecorator.destroy(),this._linkDecorator=null),this._consentManager.destroy(),this._securityLogger.destroy(),this._events.removeAllListeners(),this._userId=void 0,this._sessionId=void 0,this._initialized=!1,_Overvio.resetInstance(),this.log("debug","SDK instance destroyed")}getPageContext(){if("undefined"==typeof window)return{};let e=window.location.href,t=document.referrer;const i=this._config.privacy;return i.sanitizeUrlParams&&(e=sanitizeUrlForTracking(e,{additionalParams:i.additionalSensitiveParams,preserveParams:i.preserveParams}),t&&(t=sanitizeUrlForTracking(t,{additionalParams:i.additionalSensitiveParams,preserveParams:i.preserveParams}))),i.excludeReferrer&&(t=""),{url:e,path:window.location.pathname,search:window.location.search,title:document.title,referrer:t}}getConfigValue(e){const t=e.split(".");let i=this._config;for(const e of t){if(null==i||"object"!=typeof i)return;i=i[e]}return i}};__publicField(gs,"_instance",null),__publicField(gs,"_initPromise",null),__publicField(gs,"_initConfig",null),__publicField(gs,"init");var ps=gs,ms=class{constructor(){__publicField(this,"config",{}),__publicField(this,"plugins",[])}withApiKey(e){return this.config.apiKey=e,this}withModules(...e){return this.config.modules=e,this}withConsent(e){return this.config.consent={...this.config.consent,...e},this}withEndpoints(e){return this.config.endpoints={...this.config.endpoints,...e},this}withDebug(e=!0){return this.config.debug=e,e&&(this.config.logLevel="debug"),this}withLogLevel(e){return this.config.logLevel=e,this}withPlugin(e,t){return this.plugins.push({plugin:e,config:t}),this}withQueue(e){return this.config.queue={...this.config.queue,...e},this}withStorage(e){return this.config.storage={...this.config.storage,...e},this}withCrossDomain(e){return this.config.crossDomain={...this.config.crossDomain,...e},this}withSecurityLogging(e){return this.config.securityLogging={...this.config.securityLogging,...e},this}withCSP(e){return this.config.csp={...this.config.csp,...e},this}withPluginTimeout(e){return this.config.pluginTimeout=e,this}withTrackingMode(e){return this.config.trackingMode=e,this}withProxyEndpoint(e){return this.config.proxyEndpoint=e,this}withRespectGPC(e=!0){return this.config.respectGPC=e,this}withPrivacyUrls(e){return void 0!==e.privacyPolicyUrl&&(this.config.privacyPolicyUrl=e.privacyPolicyUrl),void 0!==e.cookiePolicyUrl&&(this.config.cookiePolicyUrl=e.cookiePolicyUrl),this}withPrivacy(e){var t,i,r,n;return this.config.privacy={...this.config.privacy,...e,piiProtection:{...null==(t=this.config.privacy)?void 0:t.piiProtection,...e.piiProtection,detectTypes:{...null==(r=null==(i=this.config.privacy)?void 0:i.piiProtection)?void 0:r.detectTypes,...null==(n=e.piiProtection)?void 0:n.detectTypes}}},this}build(){var e,t,i,r;if(!this.config.apiKey)throw sr.missingRequired("apiKey","string (pk_live_* or pk_test_*)");if("string"!=typeof this.config.apiKey||0===this.config.apiKey.length)throw sr.invalidValue("apiKey","non-empty string (pk_live_* or pk_test_*)",this.config.apiKey);if(void 0!==(null==(e=this.config.queue)?void 0:e.maxSize)&&this.config.queue.maxSize<=0)throw sr.invalidValue("queue.maxSize","positive integer",this.config.queue.maxSize);if(void 0!==(null==(t=this.config.queue)?void 0:t.flushInterval)&&this.config.queue.flushInterval<0)throw sr.invalidValue("queue.flushInterval","non-negative integer",this.config.queue.flushInterval);if(void 0!==(null==(i=this.config.queue)?void 0:i.maxRetries)&&this.config.queue.maxRetries<0)throw sr.invalidValue("queue.maxRetries","non-negative integer",this.config.queue.maxRetries);if(void 0!==this.config.pluginTimeout&&this.config.pluginTimeout<=0)throw sr.invalidValue("pluginTimeout","positive integer",this.config.pluginTimeout);if(void 0!==this.config.trackingMode&&"direct"!==this.config.trackingMode&&"server-proxy"!==this.config.trackingMode)throw sr.invalidValue("trackingMode",'"direct" | "server-proxy"',this.config.trackingMode);if("server-proxy"===(null!=(r=this.config.trackingMode)?r:"direct")){if(!this.config.proxyEndpoint)throw sr.missingRequired("proxyEndpoint",'string (URL or relative path). When trackingMode is "server-proxy", you must specify a proxyEndpoint like "/api/track" or "https://example.com/api/track"');if("string"!=typeof this.config.proxyEndpoint||""===this.config.proxyEndpoint.trim())throw sr.invalidValue("proxyEndpoint","non-empty string (URL or relative path)",this.config.proxyEndpoint);const e=this.config.proxyEndpoint.trim();if(!function(e){if(!e||""===e.trim())return!1;const t=e.trim();if(t.startsWith("/"))return/^\/[a-zA-Z0-9._/-]*$/.test(t);try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol}catch(e){return!1}}(e))throw sr.invalidValue("proxyEndpoint",'valid URL or relative path (e.g., "/api/track" or "https://example.com/api/track")',this.config.proxyEndpoint);e.startsWith("http://")&&"undefined"!=typeof process&&console.warn("[Overvio] Warning: Using HTTP (not HTTPS) for proxyEndpoint in production. This may expose tracking data to interception. Consider using HTTPS.")}const n=this.resolveConfig(this.config.apiKey);return n.plugins=[...this.plugins],new ps(n)}resolveConfig(e){var t,i,r,n,s,o,a,c,l,u,d,h,g;return{apiKey:e,modules:null!=(t=this.config.modules)?t:nr.modules,consent:{...nr.consent,...this.config.consent,necessary:!0},endpoints:{...nr.endpoints,...this.config.endpoints},queue:{...nr.queue,...this.config.queue},storage:{...nr.storage,...this.config.storage,..."custom"===(null==(i=this.config.storage)?void 0:i.type)&&void 0!==this.config.storage.adapter?{adapter:this.config.storage.adapter}:{},cookie:{...nr.storage.cookie,...null==(r=this.config.storage)?void 0:r.cookie}},crossDomain:{...nr.crossDomain,...this.config.crossDomain},securityLogging:{...nr.securityLogging,...this.config.securityLogging},csp:{...nr.csp,...this.config.csp},debug:null!=(n=this.config.debug)?n:nr.debug,logLevel:null!=(s=this.config.logLevel)?s:nr.logLevel,plugins:null!=(o=this.config.plugins)?o:nr.plugins,pluginTimeout:null!=(a=this.config.pluginTimeout)?a:nr.pluginTimeout,trackingMode:null!=(c=this.config.trackingMode)?c:nr.trackingMode,proxyEndpoint:null==(l=this.config.proxyEndpoint)?void 0:l.trim(),respectGPC:null!=(u=this.config.respectGPC)?u:nr.respectGPC,privacyPolicyUrl:this.config.privacyPolicyUrl,cookiePolicyUrl:this.config.cookiePolicyUrl,privacy:{...nr.privacy,...this.config.privacy,piiProtection:{...nr.privacy.piiProtection,...null==(d=this.config.privacy)?void 0:d.piiProtection,detectTypes:{...nr.privacy.piiProtection.detectTypes,...null==(g=null==(h=this.config.privacy)?void 0:h.piiProtection)?void 0:g.detectTypes}}}}}};function createOvervioBuilder(){return new ms}function isSSR2(){return"undefined"==typeof window||"undefined"==typeof document}ps.init=function(e){const t=ps.getInstance();if(null==t?void 0:t.initialized){const i=ps.getInitConfig();if(i){const t=function(e,t){var i,r,n,s,o,a;const c=[];e.apiKey!==t.apiKey&&c.push("apiKey");const l=null!=(r=null==(i=e.modules)?void 0:i.slice().sort())?r:[],u=null!=(s=null==(n=t.modules)?void 0:n.slice().sort())?s:[];return JSON.stringify(l)!==JSON.stringify(u)&&c.push("modules"),e.trackingMode!==t.trackingMode&&c.push("trackingMode"),e.proxyEndpoint!==t.proxyEndpoint&&c.push("proxyEndpoint"),e.debug!==t.debug&&c.push("debug"),JSON.stringify(e.endpoints)!==JSON.stringify(t.endpoints)&&c.push("endpoints"),(null==(o=e.crossDomain)?void 0:o.enabled)!==(null==(a=t.crossDomain)?void 0:a.enabled)&&c.push("crossDomain.enabled"),c}(e,i);t.length>0&&console.warn(`[Overvio] init() called with different config after initialization. Differences in: ${t.join(", ")}. Returning existing instance. Call destroy() first to re-initialize with new config.`)}return t}ps.isInitializing()&&console.warn("[Overvio] init() called while initialization is in progress. This may indicate a race condition.");const i=(new ms).withApiKey(e.apiKey);if(e.modules&&i.withModules(...e.modules),e.consent&&i.withConsent(e.consent),e.endpoints&&i.withEndpoints(e.endpoints),e.queue&&i.withQueue(e.queue),e.storage&&i.withStorage(e.storage),e.crossDomain&&i.withCrossDomain(e.crossDomain),e.securityLogging&&i.withSecurityLogging(e.securityLogging),e.csp&&i.withCSP(e.csp),void 0!==e.debug&&i.withDebug(e.debug),e.logLevel&&i.withLogLevel(e.logLevel),void 0!==e.pluginTimeout&&i.withPluginTimeout(e.pluginTimeout),e.trackingMode&&i.withTrackingMode(e.trackingMode),e.proxyEndpoint&&i.withProxyEndpoint(e.proxyEndpoint),void 0!==e.respectGPC&&i.withRespectGPC(e.respectGPC),void 0!==e.privacyPolicyUrl&&i.withPrivacyUrls({privacyPolicyUrl:e.privacyPolicyUrl}),void 0!==e.cookiePolicyUrl&&i.withPrivacyUrls({cookiePolicyUrl:e.cookiePolicyUrl}),e.privacy&&i.withPrivacy(e.privacy),e.plugins)for(const{plugin:t,config:r}of e.plugins)i.withPlugin(t,r);const r=i.build();return ps.setInstance(r),ps.setInitConfig(e),r};var fs=["events"],ys="[data-overvio-search]";function parseModules(e){if(!e)return fs;const t=new Set(["events","cart","search","banners","recommendations"]),i=e.split(",").map(e=>e.trim().toLowerCase()).filter(e=>t.has(e));return i.length>0?i:fs}function parseBoolean(e){return!!e&&("true"===e||"1"===e||""===e)}function parseSearchWidgetOptions(e){var t,i,r;return{placeholder:null!=(i=null!=(t=e.getAttribute("placeholder"))?t:e.getAttribute("data-placeholder"))?i:"Search...",theme:null!=(r=e.getAttribute("data-theme"))?r:"auto"}}function mountSearchWidgets(e){const t=document.querySelectorAll(ys);if(0!==t.length){try{e.search}catch(e){return void console.warn('[Overvio] Search widget elements found but search module is not loaded.\nAdd data-modules="search" to your script tag.')}t.forEach(t=>{const i=parseSearchWidgetOptions(t),r=Object.assign({},i.placeholder?{placeholder:i.placeholder}:{},i.theme?{theme:i.theme}:{});e.mountSearchWidget(t,r).then(()=>{t.setAttribute("data-overvio-mounted","true")}).catch(e=>{console.error("[Overvio] Failed to mount search widget:",e)})})}}function observeSearchWidgets(e){if("undefined"==typeof MutationObserver)return;try{e.search}catch(e){return}const mountElement=t=>{if(t.getAttribute("data-overvio-mounted"))return;const i=parseSearchWidgetOptions(t),r=Object.assign({},i.placeholder?{placeholder:i.placeholder}:{},i.theme?{theme:i.theme}:{});e.mountSearchWidget(t,r).then(()=>{t.setAttribute("data-overvio-mounted","true")}).catch(e=>{console.error("[Overvio] Failed to mount dynamic search widget:",e)})};new MutationObserver(e=>{var t,i;for(const r of e)for(const e of r.addedNodes){if(e.nodeType!==Node.ELEMENT_NODE)continue;const r=e;(null==(t=r.matches)?void 0:t.call(r,ys))&&mountElement(r);const n=null==(i=r.querySelectorAll)?void 0:i.call(r,ys);null==n||n.forEach(e=>mountElement(e))}}).observe(document.body,{childList:!0,subtree:!0})}function autoInit(){if(!isBrowser())return;const e=function(){if(document.currentScript&&document.currentScript instanceof HTMLScriptElement)return document.currentScript;const e=document.querySelectorAll("script[data-api-key]");return e.length>0?e[e.length-1]:null}();if(!e)return;const t=function(e){const t=e.getAttribute("data-api-key");if(!t)return console.error('[Overvio] data-api-key attribute is required on the script tag.\nExample: <script src="sdk.js" data-api-key="pk_live_abc123..."><\/script>'),null;const i=e.getAttribute("data-endpoint");return{apiKey:t,modules:parseModules(e.getAttribute("data-modules")),debug:parseBoolean(e.getAttribute("data-debug")),autoTrack:parseBoolean(e.getAttribute("data-auto-track")),...i&&{endpoint:i}}}(e);if(t){t.debug&&(t.apiKey.substring(0,10),t.modules,t.autoTrack);try{const e=ps.init({apiKey:t.apiKey,modules:t.modules,debug:t.debug,...t.endpoint&&{endpoints:{events:t.endpoint,ml:t.endpoint}}});return"undefined"!=typeof window&&(window.overvio=e),t.autoTrack&&e.page().then(e=>{t.debug&&e.success}).catch(e=>{console.error("[Overvio] Failed to auto-track page view:",e)}),t.modules.includes("search")&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{mountSearchWidgets(e),observeSearchWidgets(e)}):(mountSearchWidgets(e),observeSearchWidgets(e))),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("overvio:ready",{detail:{sdk:e}})),t.debug,e}catch(e){return void console.error("[Overvio] Auto-initialization failed:",e)}}}function isAutoInitAvailable(){return!!isBrowser()&&!!document.querySelector("script[data-api-key]")}var vs={verbose:0,debug:1,info:2,warn:3,error:4,silent:5},bs={track:"color: #4CAF50; font-weight: bold;",identify:"color: #2196F3; font-weight: bold;",page:"color: #9C27B0; font-weight: bold;",prefix:"color: #FF9800; font-weight: bold;",timestamp:"color: #9E9E9E;",eventName:"color: #333; font-weight: bold;",reset:""};function supportsStyledConsole(){return"undefined"!=typeof window&&"undefined"!=typeof navigator}var Ss=class{constructor(e){var t,i,r,n,s,o;__publicField(this,"name","overvio-console"),__publicField(this,"version","1.0.0"),__publicField(this,"type","after"),__publicField(this,"config"),__publicField(this,"loaded",!1),__publicField(this,"useStyles"),this.config={logLevel:null!=(t=null==e?void 0:e.logLevel)?t:"debug",prefix:null!=(i=null==e?void 0:e.prefix)?i:"[Overvio]",colorize:null==(r=null==e?void 0:e.colorize)||r,showTimestamp:null==(n=null==e?void 0:e.showTimestamp)||n,expandProperties:null==(s=null==e?void 0:e.expandProperties)||s,logger:null!=(o=null==e?void 0:e.logger)?o:console},this.useStyles=this.config.colorize&&supportsStyledConsole()}init(e){const t=e.config;"string"==typeof t.logLevel&&t.logLevel in vs&&(this.config.logLevel=t.logLevel),"string"==typeof t.prefix&&(this.config.prefix=t.prefix),"boolean"==typeof t.colorize&&(this.config.colorize=t.colorize,this.useStyles=this.config.colorize&&supportsStyledConsole()),"boolean"==typeof t.showTimestamp&&(this.config.showTimestamp=t.showTimestamp),"boolean"==typeof t.expandProperties&&(this.config.expandProperties=t.expandProperties),t.logger&&"object"==typeof t.logger&&(this.config.logger=t.logger),this.loaded=!0,this.logMessage("debug","Console plugin initialized",{config:this.getPublicConfig()})}track(e){return this.logEvent("track",e.event.event,e.event),e.event}identify(e){return this.logEvent("identify",`User: ${String(e.event.userId)}`,e.event),e.event}page(e){var t,i;const r=null!=(i=null!=(t=e.event.name)?t:e.event.category)?i:"Unknown";return this.logEvent("page",`Page: ${r}`,e.event),e.event}isLoaded(){return this.loaded}unload(){this.logMessage("debug","Console plugin unloaded"),this.loaded=!1}getPublicConfig(){const{logger:e,...t}=this.config;return t}shouldLog(e){const t=vs[this.config.logLevel];return vs[e]>=t}logEvent(e,t,i){if(!this.shouldLog("info"))return;const r=this.config.showTimestamp?this.formatTimestamp(i.timestamp):"",{logger:n}=this.config;if(this.useStyles){const s=[],o=[];s.push(`%c${this.config.prefix}`),o.push(bs.prefix),r&&(s.push(`%c${r}`),o.push(bs.timestamp)),s.push(`%c[${e.toUpperCase()}]`),o.push(bs[e]),s.push(`%c${t}`),o.push(bs.eventName);const a=s.join(" ");this.config.expandProperties?n.log(a,...o,"\n",this.formatEventData(i)):n.log(a,...o)}else{const s=[this.config.prefix];r&&s.push(r),s.push(`[${e.toUpperCase()}]`),s.push(t),this.config.expandProperties?n.info(s.join(" "),this.formatEventData(i)):n.info(s.join(" "))}}logMessage(e,t,i){if(!this.shouldLog(e))return;const{logger:r}=this.config,n=this.config.prefix,s=this.config.showTimestamp?this.formatTimestamp():"",o=[n];s&&o.push(s),o.push(t);const a=o.join(" ");switch(e){case"verbose":case"debug":void 0!==i?r.debug(a,i):r.debug(a);break;case"info":void 0!==i?r.info(a,i):r.info(a);break;case"warn":void 0!==i?r.warn(a,i):r.warn(a);break;case"error":void 0!==i?r.error(a,i):r.error(a)}}formatTimestamp(e){const t=void 0!==e?new Date(e):new Date;return`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")}.${t.getMilliseconds().toString().padStart(3,"0")}`}formatEventData(e){const t={};return"track"===e.type?(t.event=e.event,e.properties&&Object.keys(e.properties).length>0&&(t.properties=e.properties)):"identify"===e.type?(t.userId=e.userId,e.traits&&Object.keys(e.traits).length>0&&(t.traits=e.traits)):"page"===e.type&&(e.name&&(t.name=e.name),e.category&&(t.category=e.category),e.properties&&Object.keys(e.properties).length>0&&(t.properties=e.properties)),e.userId&&(t.userId=e.userId),"sessionId"in e&&e.sessionId&&(t.sessionId=e.sessionId),e.context&&Object.keys(e.context).length>0&&(t.context=e.context),t}};function createConsolePlugin(e){return new Ss(e)}ee();var ws={enabled:!0,allowedFields:[],context:"data",logLevel:"warn"},Cs=new Map,Es={ssn:"Social Security Number",credit_card:"Credit Card Number",email:"Email Address"};var _s={warn:(e,t)=>{void 0!==t?console.warn(`[Overvio Validation] ${e}`,t):console.warn(`[Overvio Validation] ${e}`)},error:(e,t)=>{void 0!==t?console.error(`[Overvio Validation] ${e}`,t):console.error(`[Overvio Validation] ${e}`)}},Is=["url","referrer","page_url","href"];function isNonEmptyString(e){return"string"==typeof e&&e.trim().length>0}function getObjectDepth(e,t=0){if(null===e||"object"!=typeof e)return t;if(Array.isArray(e))return Math.max(t,...e.map(e=>getObjectDepth(e,t+1)));const i=Object.values(e).map(e=>getObjectDepth(e,t+1));return Math.max(t,...i,0)}function countProperties(e){return null===e||"object"!=typeof e?0:Array.isArray(e)?e.reduce((e,t)=>e+countProperties(t),0):Object.entries(e).reduce((e,[,t])=>e+1+countProperties(t),0)}var ks=class{constructor(e){var t,i,r,n,s,o,a,c,l,u,d,h;__publicField(this,"name","overvio-validation"),__publicField(this,"version","1.0.0"),__publicField(this,"type","before"),__publicField(this,"config"),__publicField(this,"loaded",!1),this.config={strict:null!=(t=null==e?void 0:e.strict)&&t,warnOnInvalid:null==(i=null==e?void 0:e.warnOnInvalid)||i,maxEventNameLength:null!=(r=null==e?void 0:e.maxEventNameLength)?r:256,maxPropertyDepth:null!=(n=null==e?void 0:e.maxPropertyDepth)?n:10,maxPropertyCount:null!=(s=null==e?void 0:e.maxPropertyCount)?s:100,customRules:null!=(o=null==e?void 0:e.customRules)?o:{},logger:null!=(a=null==e?void 0:e.logger)?a:_s,validateEmailFormat:null==(c=null==e?void 0:e.validateEmailFormat)||c,validateUrlFormat:null==(l=null==e?void 0:e.validateUrlFormat)||l,warnOnPII:null==(u=null==e?void 0:e.warnOnPII)||u,allowedPIIFields:null!=(d=null==e?void 0:e.allowedPIIFields)?d:["email","phone"],securityLogger:null==e?void 0:e.securityLogger,logValidationFailures:null==(h=null==e?void 0:e.logValidationFailures)||h}}init(e){const t=e.config;"boolean"==typeof t.strict&&(this.config.strict=t.strict),"boolean"==typeof t.warnOnInvalid&&(this.config.warnOnInvalid=t.warnOnInvalid),"number"==typeof t.maxEventNameLength&&(this.config.maxEventNameLength=t.maxEventNameLength),"number"==typeof t.maxPropertyDepth&&(this.config.maxPropertyDepth=t.maxPropertyDepth),"number"==typeof t.maxPropertyCount&&(this.config.maxPropertyCount=t.maxPropertyCount),t.customRules&&"object"==typeof t.customRules&&(this.config.customRules=t.customRules),t.logger&&"object"==typeof t.logger&&(this.config.logger=t.logger),"boolean"==typeof t.validateEmailFormat&&(this.config.validateEmailFormat=t.validateEmailFormat),"boolean"==typeof t.validateUrlFormat&&(this.config.validateUrlFormat=t.validateUrlFormat),"boolean"==typeof t.warnOnPII&&(this.config.warnOnPII=t.warnOnPII),Array.isArray(t.allowedPIIFields)&&(this.config.allowedPIIFields=t.allowedPIIFields),void 0!==t.securityLogger&&(this.config.securityLogger=t.securityLogger),"boolean"==typeof t.logValidationFailures&&(this.config.logValidationFailures=t.logValidationFailures),this.loaded=!0}track(e){const t=this.validateTrackEvent(e.event);if(t.push(...this.validateUrlFields(e.event.properties,"properties")),this.runPIIWarning(e.event.properties,"track event properties"),this.config.customRules.track){const i=this.config.customRules.track(e.event);i.valid||t.push(i)}return this.handleValidationErrors(e,t,"track")}identify(e){const t=this.validateIdentifyEvent(e.event);if(t.push(...this.validateUrlFields(e.event.traits,"traits")),this.runPIIWarning(e.event.traits,"identify event traits"),this.config.customRules.identify){const i=this.config.customRules.identify(e.event);i.valid||t.push(i)}return this.handleValidationErrors(e,t,"identify")}page(e){const t=this.validatePageEvent(e.event);if(t.push(...this.validateUrlFields(e.event.properties,"properties")),this.runPIIWarning(e.event.properties,"page event properties"),this.config.customRules.page){const i=this.config.customRules.page(e.event);i.valid||t.push(i)}return this.handleValidationErrors(e,t,"page")}isLoaded(){return this.loaded}unload(){this.loaded=!1}validateTrackEvent(e){const t=[];return isNonEmptyString(e.event)?e.event.length>this.config.maxEventNameLength&&t.push({valid:!1,message:`Event name exceeds maximum length of ${this.config.maxEventNameLength}`,field:"event",expected:`string <= ${this.config.maxEventNameLength} chars`,received:`string of ${e.event.length} chars`}):t.push({valid:!1,message:"Track event must have a non-empty event name",field:"event",expected:"non-empty string",received:typeof e.event}),void 0!==e.properties&&t.push(...this.validateProperties(e.properties,"properties")),void 0!==e.context&&t.push(...this.validateContext(e.context)),t}validateIdentifyEvent(e){const t=[];if(e.userId&&isNonEmptyString(String(e.userId))||t.push({valid:!1,message:"Identify event must have a non-empty userId",field:"userId",expected:"non-empty UserId",received:e.userId?String(e.userId):"undefined"}),void 0!==e.traits&&(t.push(...this.validateProperties(e.traits,"traits")),this.config.validateEmailFormat&&void 0!==e.traits.email)){const i=function(e){const t={...$};if("string"!=typeof e)return{valid:!1,reason:"Email must be a string"};if(0===e.length)return{valid:!1,reason:"Email cannot be empty"};if(e.length>t.maxEmailLength)return{valid:!1,reason:`Email exceeds maximum length of ${t.maxEmailLength} characters`};const i=e.indexOf("@");if(-1===i)return{valid:!1,reason:"Email must contain @ symbol"};if(0===i)return{valid:!1,reason:"Email must have content before @ symbol"};const r=e.slice(0,i),n=e.slice(i+1);return r.length>t.maxLocalPartLength?{valid:!1,reason:`Local part exceeds maximum length of ${t.maxLocalPartLength} characters`}:0===n.length?{valid:!1,reason:"Email must have content after @ symbol"}:n.includes(".")?N.test(e)?{valid:!1,reason:"Email contains dangerous characters"}:F.test(e)?{valid:!0}:{valid:!1,reason:"Email format is invalid"}:{valid:!1,reason:"Email must have a domain with at least one dot"}}(e.traits.email);i.valid||t.push({valid:!1,message:`Invalid email format: ${i.reason}`,field:"traits.email",expected:"valid email address",received:"string"==typeof e.traits.email?"invalid email":typeof e.traits.email})}return void 0!==e.context&&t.push(...this.validateContext(e.context)),t}validatePageEvent(e){const t=[];return e.name||e.category||this.config.warnOnInvalid&&this.config.logger.warn("Page event should have a name or category",{type:e.type}),e.name&&e.name.length>this.config.maxEventNameLength&&t.push({valid:!1,message:`Page name exceeds maximum length of ${this.config.maxEventNameLength}`,field:"name",expected:`string <= ${this.config.maxEventNameLength} chars`,received:`string of ${e.name.length} chars`}),e.category&&e.category.length>this.config.maxEventNameLength&&t.push({valid:!1,message:`Page category exceeds maximum length of ${this.config.maxEventNameLength}`,field:"category",expected:`string <= ${this.config.maxEventNameLength} chars`,received:`string of ${e.category.length} chars`}),void 0!==e.properties&&t.push(...this.validateProperties(e.properties,"properties")),void 0!==e.context&&t.push(...this.validateContext(e.context)),t}validateProperties(e,t){const i=[];if("object"!=typeof e||null===e||Array.isArray(e))return i.push({valid:!1,message:`${t} must be an object`,field:t,expected:"object",received:Array.isArray(e)?"array":typeof e}),i;const r=getObjectDepth(e);r>this.config.maxPropertyDepth&&i.push({valid:!1,message:`${t} exceeds maximum nesting depth of ${this.config.maxPropertyDepth}`,field:t,expected:`depth <= ${this.config.maxPropertyDepth}`,received:`depth of ${r}`});const n=countProperties(e);return n>this.config.maxPropertyCount&&i.push({valid:!1,message:`${t} exceeds maximum property count of ${this.config.maxPropertyCount}`,field:t,expected:`<= ${this.config.maxPropertyCount} properties`,received:`${n} properties`}),i}validateContext(e){const t=[];return("object"!=typeof e||null===e||Array.isArray(e))&&t.push({valid:!1,message:"context must be an object",field:"context",expected:"object",received:Array.isArray(e)?"array":typeof e}),t}validateUrlFields(e,t){const i=[];if(!this.config.validateUrlFormat||!e)return i;for(const r of Is){const n=e[r];if(void 0!==n&&"string"==typeof n&&n.length>0){const e=validateUrl(n);e.valid||i.push({valid:!1,message:`Invalid URL format in ${t}.${r}: ${e.reason}`,field:`${t}.${r}`,expected:"valid URL",received:"invalid URL"})}}return i}runPIIWarning(e,t){this.config.warnOnPII&&e&&function(e,t){var i;const r={...ws,...t,allowedFields:null!=(i=null==t?void 0:t.allowedFields)?i:ws.allowedFields},n=detectPII(e,{allowedFields:r.allowedFields}),s={...n,warningLogged:!1};if(!r.enabled||!n.hasPII)return s;const o=`${r.context}:${n.fields.sort().join(",")}`;if(function(e){const t=Cs.get(e);return void 0!==t&&Date.now()-t<6e4}(o))return s;const a=function(e,t){var i,r;return[`[Overvio SDK] Potential PII detected in ${t}`,` PII Types: ${r=e.types,0===r.length?"None":1===r.length?Es[r[0]]||r[0]:r.map(e=>Es[e]||e).join(", ")}`,` Fields: ${i=e.fields,0===i.length?"None":i.map(e=>`"${e}"`).join(", ")}`," Note: Review these fields to ensure compliance with privacy regulations."].join("\n")}(n,r.context);var c;"error"===r.logLevel?console.error(a):console.warn(a),c=o,Cs.set(c,Date.now()),s.warningLogged=!0}(e,{context:t,allowedFields:this.config.allowedPIIFields})}handleValidationErrors(e,t,i){var r;if(0===t.length)return e.event;if(this.config.warnOnInvalid)for(const e of t)(this.config.strict?this.config.logger.error:this.config.logger.warn).call(this.config.logger,null!=(r=e.message)?r:"Validation failed",{eventType:i,field:e.field,expected:e.expected,received:e.received});if(this.config.securityLogger&&this.config.logValidationFailures&&this.config.securityLogger.log({type:"INPUT_VALIDATION_FAIL",action:"event_validation_failed",outcome:"failure",metadata:{component:"ValidationPlugin",eventType:i,errorCount:t.length,errors:t.map(e=>({field:e.field,message:e.message,expected:e.expected,received:e.received})),blocked:this.config.strict}}),this.config.strict){const i=t.map(e=>e.message).join("; ");return e.abort(`Validation failed: ${i}`),null}return e.event}};function createValidationPlugin(e){return new ks(e)}var xs="data-overvio-track",Ts="data-overvio-props",As=["click"];function parseProps(e,t){if(!e)return{};try{const i=JSON.parse(e);return"object"!=typeof i||null===i||Array.isArray(i)?(t&&console.warn("[Overvio] data-overvio-props must be a JSON object, got:",typeof i),{}):i}catch(i){return t&&(console.error("[Overvio] Failed to parse data-overvio-props:",i),console.error("[Overvio] Invalid JSON:",e)),{}}}function setupDeclarativeTracking(e){if(!isBrowser())return()=>{};const{sdk:t,debug:i=!1,eventTypes:r=As,trackAttribute:n=xs,propsAttribute:s=Ts}=e;if(!t)return console.error("[Overvio] SDK is required for declarative tracking"),()=>{};const handleEvent=e=>{const r=function(e,t){return e&&e instanceof Element?e.closest(`[${t}]`):null}(e.target,n);if(!r)return;const o=r.getAttribute(n);if(!o)return;const a=parseProps(r.getAttribute(s),i),c={...function(e,t){const i={};return t.tagName&&(i.elementTag=t.tagName.toLowerCase()),t.id&&(i.elementId=t.id),t instanceof HTMLAnchorElement&&t.href&&(i.href=t.href),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(i.inputType=t.type),t instanceof HTMLFormElement&&(i.formAction=t.action,i.formMethod=t.method),i}(0,r),...a,triggerEvent:e.type,timestamp:Date.now()};try{t.track(o,c)}catch(e){console.error("[Overvio] Failed to track declarative event:",e)}},o=[];for(const e of r){const t="submit"===e;document.addEventListener(e,handleEvent,t),o.push({type:e,handler:handleEvent})}return()=>{for(const{type:e,handler:t}of o){const i="submit"===e;document.removeEventListener(e,t,i)}}}function initDeclarativeTracking(e={}){var t;if(!isBrowser())return()=>{};const i=null!=(t=e.debug)&&t,r=window.overvio;if(r)return setupDeclarativeTracking({...e,sdk:r});let n,cleanup=()=>{};const handleReady=t=>{var i;const r=t;(null==(i=r.detail)?void 0:i.sdk)&&(cleanup=setupDeclarativeTracking({...e,sdk:r.detail.sdk}))};window.addEventListener("overvio:ready",handleReady,{once:!0});let s=0;const pollForSdk=()=>{s++;const t=window.overvio;if(t)return window.removeEventListener("overvio:ready",handleReady),void(cleanup=setupDeclarativeTracking({...e,sdk:t}));s<50?n=setTimeout(pollForSdk,100):i&&console.warn("[Overvio] SDK not found after 5 seconds, declarative tracking not initialized")};return n=setTimeout(pollForSdk,100),()=>{window.removeEventListener("overvio:ready",handleReady),n&&clearTimeout(n),cleanup()}}function trackElementEvent(e,t){const i=e.getAttribute(xs);if(!i)return void console.warn("[Overvio] Element does not have data-overvio-track attribute");const r=parseProps(e.getAttribute(Ts),!1);t.track(i,{...r,manual:!0,timestamp:Date.now()})}oi(),W(),W(),W();var Rs=e.OvervioError.isOvervioError.bind(e.OvervioError),Ps=e.NetworkError.isNetworkError.bind(e.NetworkError),Ds=e.ValidationError.isValidationError.bind(e.ValidationError),Ls=sr.isConfigurationError.bind(sr),Ms=e.RateLimitError.isRateLimitError.bind(e.RateLimitError),Os=Or.isConsentError.bind(Or),$s=$r.isPluginError.bind($r),Ns=Nr.isQueueError.bind(Nr),Fs=e.TimeoutError.isTimeoutError.bind(e.TimeoutError),qs={Overvio:ps,OvervioBuilder:ms,createOvervioBuilder:createOvervioBuilder,init:ps.init,createUserId:createUserId,createSessionId:createSessionId,createClientUuid:createClientUuid,createProductId:createProductId,createOrderId:createOrderId,createIdempotencyKey:createIdempotencyKey,isUserId:isUserId,isSessionId:isSessionId,isClientUuid:isClientUuid,isProductId:isProductId,isOrderId:isOrderId,isIdempotencyKey:isIdempotencyKey,isAnyBrandedId:isAnyBrandedId,ErrorCode:e.ErrorCode,ALL_ERROR_CODES:e.ALL_ERROR_CODES,OvervioError:e.OvervioError,NetworkError:e.NetworkError,ValidationError:e.ValidationError,ConfigurationError:sr,RateLimitError:e.RateLimitError,ConsentError:Or,PluginError:$r,QueueError:Nr,TimeoutError:e.TimeoutError,isOvervioError:Rs,isNetworkError:Ps,isValidationError:Ds,isConfigurationError:Ls,isRateLimitError:Ms,isConsentError:Os,isPluginError:$s,isQueueError:Ns,isTimeoutError:Fs,definePlugin:definePlugin,isOvervioPlugin:isOvervioPlugin,isValidPluginType:isValidPluginType,PLUGIN_TYPE_ORDER:Hn,CONSENT_CATEGORIES:Bn,PluginManager:jn,createPluginManager:createPluginManager,ConsolePlugin:Ss,createConsolePlugin:createConsolePlugin,ValidationPlugin:ks,createValidationPlugin:createValidationPlugin,MemoryAdapter:Dn,createMemoryAdapter:createMemoryAdapter,STORAGE_KEY_PREFIX:kn,DEFAULT_TTL_MS:xn,buildStorageKey:buildStorageKey,parseStorageKey:parseStorageKey,isStorageAdapter:isStorageAdapter,autoInit:autoInit,isAutoInitAvailable:isAutoInitAvailable,setupDeclarativeTracking:setupDeclarativeTracking,initDeclarativeTracking:initDeclarativeTracking,trackElementEvent:trackElementEvent,isBrowser:isBrowser,isSSR:isSSR2,getRuntime:getRuntime,isServer:isServer,isEdge:isEdge,isWorker:isWorker,getCapabilities:getCapabilities,CART_STORAGE_KEY:ar,CART_STATE_VERSION:1,MAX_CART_ITEMS:100,isCartItem:isCartItem,isCartState:isCartState,createEmptyCartState:createEmptyCartState,isSearchResult:isSearchResult,isProduct:isProduct,DEFAULT_SEARCH_LIMIT:e.DEFAULT_SEARCH_LIMIT,DEFAULT_AUTOCOMPLETE_LIMIT:e.DEFAULT_AUTOCOMPLETE_LIMIT,EventType:e.EventType,createBaseEvent:createBaseEvent,isBaseEvent:isBaseEvent,version:Rr,SDK_VERSION:Rr,SDK_NAME:Pr,SDK_FULL_NAME:Dr};return"undefined"!=typeof window&&(window.Overvio=qs),e.CART_STATE_VERSION=1,e.CART_STORAGE_KEY=ar,e.CONSENT_CATEGORIES=Bn,e.ConfigurationError=sr,e.ConsentError=Or,e.ConsolePlugin=Ss,e.DEFAULT_TTL_MS=xn,e.MAX_CART_ITEMS=100,e.MemoryAdapter=Dn,e.Overvio=ps,e.OvervioBuilder=ms,e.PLUGIN_TYPE_ORDER=Hn,e.PluginError=$r,e.PluginManager=jn,e.QueueError=Nr,e.SDK_FULL_NAME=Dr,e.SDK_NAME=Pr,e.SDK_VERSION=Rr,e.STORAGE_KEY_PREFIX=kn,e.ValidationPlugin=ks,e.autoInit=autoInit,e.buildStorageKey=buildStorageKey,e.createBaseEvent=createBaseEvent,e.createClientUuid=createClientUuid,e.createConsolePlugin=createConsolePlugin,e.createEmptyCartState=createEmptyCartState,e.createIdempotencyKey=createIdempotencyKey,e.createMemoryAdapter=createMemoryAdapter,e.createOrderId=createOrderId,e.createOvervioBuilder=createOvervioBuilder,e.createPluginManager=createPluginManager,e.createProductId=createProductId,e.createSessionId=createSessionId,e.createUserId=createUserId,e.createValidationPlugin=createValidationPlugin,e.definePlugin=definePlugin,e.getCapabilities=getCapabilities,e.getRuntime=getRuntime,e.initDeclarativeTracking=initDeclarativeTracking,e.isAnyBrandedId=isAnyBrandedId,e.isAutoInitAvailable=isAutoInitAvailable,e.isBaseEvent=isBaseEvent,e.isBrowser=isBrowser,e.isCartItem=isCartItem,e.isCartState=isCartState,e.isClientUuid=isClientUuid,e.isConfigurationError=Ls,e.isConsentError=Os,e.isEdge=isEdge,e.isIdempotencyKey=isIdempotencyKey,e.isNetworkError=Ps,e.isOrderId=isOrderId,e.isOvervioError=Rs,e.isOvervioPlugin=isOvervioPlugin,e.isPluginError=$s,e.isProduct=isProduct,e.isProductId=isProductId,e.isQueueError=Ns,e.isRateLimitError=Ms,e.isSSR=isSSR2,e.isSearchResult=isSearchResult,e.isServer=isServer,e.isSessionId=isSessionId,e.isStorageAdapter=isStorageAdapter,e.isTimeoutError=Fs,e.isUserId=isUserId,e.isValidPluginType=isValidPluginType,e.isValidationError=Ds,e.isWorker=isWorker,e.parseStorageKey=parseStorageKey,e.setupDeclarativeTracking=setupDeclarativeTracking,e.trackElementEvent=trackElementEvent,e}({});//# sourceMappingURL=overvio.min.js.map
|