@contentful/optimization-web 0.1.0-alpha → 0.1.0-alpha5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -2
- package/dist/AutoEntryViewTracking.d.ts +2 -0
- package/dist/AutoEntryViewTracking.d.ts.map +1 -1
- package/dist/Optimization.d.ts +74 -0
- package/dist/Optimization.d.ts.map +1 -1
- package/dist/analyzer.html +1 -1
- package/dist/contentful-optimization-web.umd.cjs.map +1 -1
- package/dist/contentful-optimization-web.umd.js +2 -0
- package/dist/dev.d.ts +2 -0
- package/dist/dev.d.ts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1116 -1051
- package/dist/index.js.map +1 -1
- package/dist/storage/LocalStore.d.ts +0 -36
- package/dist/storage/LocalStore.d.ts.map +1 -1
- package/dist/visualizer.html +1 -1
- package/package.json +2 -2
- package/dist/contentful-optimization-web.umd.cjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(ke,Y){typeof exports=="object"&&typeof module<"u"?module.exports=Y():typeof define=="function"&&define.amd?define(Y):(ke=typeof globalThis<"u"?globalThis:ke||self,ke.Optimization=Y())})(this,function(){"use strict";var ke=Symbol.for("preact-signals");function Y(){if(G>1)G--;else{for(var t,e=!1;Ae!==void 0;){var n=Ae;for(Ae=void 0,pt++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&nn(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(pt=0,G--,e)throw t}}function fe(t){if(G>0)return t();G++;try{return t()}finally{Y()}}var y=void 0;function ft(t){var e=y;y=void 0;try{return t()}finally{y=e}}var Ae=void 0,G=0,pt=0,qe=0;function tn(t){if(y!==void 0){var e=t.n;if(e===void 0||e.t!==y)return e={i:0,S:t,p:y.s,n:void 0,t:y,e:void 0,x:void 0,r:e},y.s!==void 0&&(y.s.n=e),y.s=e,t.n=e,32&y.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=y.s,e.n=void 0,y.s.n=e,y.s=e),e}}function I(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}I.prototype.brand=ke,I.prototype.h=function(){return!0},I.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:ft(function(){var r;(r=e.W)==null||r.call(e)}))},I.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,r=t.x;n!==void 0&&(n.x=r,t.e=void 0),r!==void 0&&(r.e=n,t.x=void 0),t===this.t&&(this.t=r,r===void 0&&ft(function(){var i;(i=e.Z)==null||i.call(e)}))}},I.prototype.subscribe=function(t){var e=this;return O(function(){var n=e.value,r=y;y=void 0;try{t(n)}finally{y=r}},{name:"sub"})},I.prototype.valueOf=function(){return this.value},I.prototype.toString=function(){return this.value+""},I.prototype.toJSON=function(){return this.value},I.prototype.peek=function(){var t=y;y=void 0;try{return this.value}finally{y=t}},Object.defineProperty(I.prototype,"value",{get:function(){var t=tn(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(pt>100)throw new Error("Cycle detected");this.v=t,this.i++,qe++,G++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Y()}}}});function pe(t,e){return new I(t,e)}function nn(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function rn(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function on(t){for(var e=t.s,n=void 0;e!==void 0;){var r=e.p;e.i===-1?(e.S.U(e),r!==void 0&&(r.n=e.n),e.n!==void 0&&(e.n.p=r)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=r}t.s=n}function ne(t,e){I.call(this,void 0),this.x=t,this.s=void 0,this.g=qe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ne.prototype=new I,ne.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===qe))return!0;if(this.g=qe,this.f|=1,this.i>0&&!nn(this))return this.f&=-2,!0;var t=y;try{rn(this),y=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return y=t,on(this),this.f&=-2,!0},ne.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}I.prototype.S.call(this,t)},ne.prototype.U=function(t){if(this.t!==void 0&&(I.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},ne.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(ne.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=tn(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function sn(t,e){return new ne(t,e)}function an(t){var e=t.u;if(t.u=void 0,typeof e=="function"){G++;var n=y;y=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,ht(t),r}finally{y=n,Y()}}}function ht(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,an(t)}function Vr(t){if(y!==this)throw new Error("Out-of-order effect");on(this),y=t,this.f&=-2,8&this.f&&ht(this),Y()}function he(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}he.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},he.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,an(this),rn(this),G++;var t=y;return y=this,Vr.bind(this,t)},he.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ae,Ae=this)},he.prototype.d=function(){this.f|=8,1&this.f||ht(this)},he.prototype.dispose=function(){this.d()};function O(t,e){var n=new he(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}const gt={resolve(t){return t?t.reduce((e,{key:n,value:r})=>{const i=typeof r=="object"&&r!==null&&"value"in r&&typeof r.value=="object"?r.value:r;return e[n]=i,e},{}):{}}};function p(t,e,n){function r(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(const d in s.prototype)d in a||Object.defineProperty(a,d,{value:s.prototype[d].bind(a)});a._zod.constr=s,a._zod.def=c}const i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:t});function s(a){var c;const u=n?.Parent?new o:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}class ge extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Nr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Lr={};function ve(t){return Lr}function jr(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,i])=>e.indexOf(+r)===-1).map(([r,i])=>i)}function Ur(t,e){return typeof e=="bigint"?e.toString():e}function cn(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function un(t){return t==null}function vt(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}const ln=Symbol("evaluating");function w(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==ln)return r===void 0&&(r=ln,r=n()),r},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function yt(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function dn(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}const fn="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function He(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function mt(t){if(He(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(He(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Zr(t){return mt(t)?{...t}:t}const Dr=new Set(["string","number","symbol"]);function _t(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bt(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function C(t){return{}}function Br(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function Fr(t,e){if(!mt(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const i=dn(t._zod.def,{get shape(){const o={...t._zod.def.shape,...e};return yt(this,"shape",o),o},checks:[]});return bt(t,i)}function qr(t,e,n){const r=dn(e._zod.def,{get shape(){const i=e._zod.def.shape,o={...i};for(const s in i)o[s]=t?new t({type:"optional",innerType:i[s]}):i[s];return yt(this,"shape",o),o},checks:[]});return bt(e,r)}function $e(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function ye(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Ke(t){return typeof t=="string"?t:t?.message}function me(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const i=Ke(t.inst?._zod.def?.error?.(t))??Ke(e?.error?.(t))??Ke(n.customError?.(t))??Ke(n.localeError?.(t))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function pn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Hr(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const hn=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Ur,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Kr=p("$ZodError",hn),We=p("$ZodError",hn,{Parent:Error}),Wr=(t=>(e,n,r,i)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new ge;if(s.issues.length){const a=new(i?.Err??t)(s.issues.map(c=>me(c,o,ve())));throw fn(a,i?.callee),a}return s.value})(We),Yr=(t=>async(e,n,r,i)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(i?.Err??t)(s.issues.map(c=>me(c,o,ve())));throw fn(a,i?.callee),a}return s.value})(We),gn=(t=>(e,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=e._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new ge;return o.issues.length?{success:!1,error:new(t??Kr)(o.issues.map(s=>me(s,i,ve())))}:{success:!0,data:o.value}})(We),vn=(t=>async(e,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>me(s,i,ve())))}:{success:!0,data:o.value}})(We),Gr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function Jr(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Qr(t){const e=Jr({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Gr}T(?:${r})$`)}const Xr=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},ei=/^-?\d+(?:\.\d+)?/i,ti=/true|false/i,ni=/null/i,Ye=p("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),ri=p("$ZodCheckMinLength",(t,e)=>{var n;Ye.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!un(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const i=r.value;if(i.length>=e.minimum)return;const s=pn(i);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),ii=p("$ZodCheckLengthEquals",(t,e)=>{var n;Ye.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!un(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=r=>{const i=r.value,o=i.length;if(o===e.length)return;const s=pn(i),a=o>e.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),oi=p("$ZodCheckStringFormat",(t,e)=>{var n,r;Ye.init(t,e),t._zod.onattach.push(i=>{const o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),si={major:4,minor:1,patch:5},z=p("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=si;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const i of r)for(const o of i._zod.onattach)o(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const i=(s,a,c)=>{let u=$e(s),d;for(const m of a){if(m._zod.def.when){if(!m._zod.def.when(s))continue}else if(u)continue;const b=s.issues.length,S=m._zod.check(s);if(S instanceof Promise&&c?.async===!1)throw new ge;if(d||S instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await S,s.issues.length!==b&&(u||(u=$e(s,b)))});else{if(s.issues.length===b)continue;u||(u=$e(s,b))}}return d?d.then(()=>s):s},o=(s,a,c)=>{if($e(s))return s.aborted=!0,s;const u=i(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new ge;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){const u=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>o(d,s,a)):o(u,s,a)}const c=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new ge;return c.then(u=>i(u,r,a))}return i(c,r,a)}}t["~standard"]={validate:i=>{try{const o=gn(t,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return vn(t,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),yn=p("$ZodString",(t,e)=>{z.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Xr(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),mn=p("$ZodStringFormat",(t,e)=>{oi.init(t,e),yn.init(t,e)}),ai=p("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Qr(e)),mn.init(t,e)}),ci=p("$ZodNumber",(t,e)=>{z.init(t,e),t._zod.pattern=t._zod.bag.pattern??ei,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...o?{received:o}:{}}),n}}),ui=p("$ZodBoolean",(t,e)=>{z.init(t,e),t._zod.pattern=ti,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),n}}),li=p("$ZodNull",(t,e)=>{z.init(t,e),t._zod.pattern=ni,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{const i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),n}}),di=p("$ZodAny",(t,e)=>{z.init(t,e),t._zod.parse=n=>n}),fi=p("$ZodUnknown",(t,e)=>{z.init(t,e),t._zod.parse=n=>n});function _n(t,e,n){t.issues.length&&e.issues.push(...ye(n,t.issues)),e.value[n]=t.value}const pi=p("$ZodArray",(t,e)=>{z.init(t,e),t._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),n;n.value=Array(i.length);const o=[];for(let s=0;s<i.length;s++){const a=i[s],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?o.push(c.then(u=>_n(u,n,s))):_n(c,n,s)}return o.length?Promise.all(o).then(()=>n):n}});function Ge(t,e,n,r){t.issues.length&&e.issues.push(...ye(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function hi(t){const e=Object.keys(t.shape);for(const r of e)if(!t.shape[r]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=Br(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function gi(t,e,n,r,i,o){const s=[],a=i.keySet,c=i.catchall._zod,u=c.def.type;for(const d of Object.keys(e)){if(a.has(d))continue;if(u==="never"){s.push(d);continue}const m=c.run({value:e[d],issues:[]},r);m instanceof Promise?t.push(m.then(b=>Ge(b,n,d,e))):Ge(m,n,d,e)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),t.length?Promise.all(t).then(()=>n):n}const vi=p("$ZodObject",(t,e)=>{z.init(t,e);const n=cn(()=>hi(e));w(t._zod,"propValues",()=>{const s=e.shape,a={};for(const c in s){const u=s[c]._zod;if(u.values){a[c]??(a[c]=new Set);for(const d of u.values)a[c].add(d)}}return a});const r=He,i=e.catchall;let o;t._zod.parse=(s,a)=>{o??(o=n.value);const c=s.value;if(!r(c))return s.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),s;s.value={};const u=[],d=o.shape;for(const m of o.keys){const S=d[m]._zod.run({value:c[m],issues:[]},a);S instanceof Promise?u.push(S.then(_=>Ge(_,s,m,c))):Ge(S,s,m,c)}return i?gi(u,c,s,a,n.value,t):u.length?Promise.all(u).then(()=>s):s}});function bn(t,e,n,r){for(const o of t)if(o.issues.length===0)return e.value=o.value,e;const i=t.filter(o=>!$e(o));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(s=>me(s,r,ve())))}),e)}const wn=p("$ZodUnion",(t,e)=>{z.init(t,e),w(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),w(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),w(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),w(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){const i=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>vt(o.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const c of e.options){const u=c._zod.run({value:i.value,issues:[]},o);if(u instanceof Promise)a.push(u),s=!0;else{if(u.issues.length===0)return u;a.push(u)}}return s?Promise.all(a).then(c=>bn(c,i,t,o)):bn(a,i,t,o)}}),yi=p("$ZodDiscriminatedUnion",(t,e)=>{wn.init(t,e);const n=t._zod.parse;w(t._zod,"propValues",()=>{const i={};for(const o of e.options){const s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const[a,c]of Object.entries(s)){i[a]||(i[a]=new Set);for(const u of c)i[a].add(u)}}return i});const r=cn(()=>{const i=e.options,o=new Map;for(const s of i){const a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const c of a){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,s)}}return o});t._zod.parse=(i,o)=>{const s=i.value;if(!He(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),i;const a=r.value.get(s?.[e.discriminator]);return a?a._zod.run(i,o):e.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:s,path:[e.discriminator],inst:t}),i)}}),mi=p("$ZodRecord",(t,e)=>{z.init(t,e),t._zod.parse=(n,r)=>{const i=n.value;if(!mt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),n;const o=[];if(e.keyType._zod.values){const s=e.keyType._zod.values;n.value={};for(const c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const u=e.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&n.issues.push(...ye(c,d.issues)),n.value[c]=d.value})):(u.issues.length&&n.issues.push(...ye(c,u.issues)),n.value[c]=u.value)}let a;for(const c in i)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:a})}else{n.value={};for(const s of Reflect.ownKeys(i)){if(s==="__proto__")continue;const a=e.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(u=>me(u,r,ve())),input:s,path:[s],inst:t}),n.value[a.value]=a.value;continue}const c=e.valueType._zod.run({value:i[s],issues:[]},r);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&n.issues.push(...ye(s,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...ye(s,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),_i=p("$ZodEnum",(t,e)=>{z.init(t,e);const n=jr(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(i=>Dr.has(typeof i)).map(i=>typeof i=="string"?_t(i):i.toString()).join("|")})$`),t._zod.parse=(i,o)=>{const s=i.value;return r.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:t}),i}}),bi=p("$ZodLiteral",(t,e)=>{if(z.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?_t(n):n?_t(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,r)=>{const i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),n}}),wi=p("$ZodTransform",(t,e)=>{z.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Nr(t.constructor.name);const i=e.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(n.value=s,n));if(i instanceof Promise)throw new ge;return n.value=i,n}});function En(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const Ei=p("$ZodOptional",(t,e)=>{z.init(t,e),t._zod.optin="optional",t._zod.optout="optional",w(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),w(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${vt(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>En(o,n.value)):En(i,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),Si=p("$ZodNullable",(t,e)=>{z.init(t,e),w(t._zod,"optin",()=>e.innerType._zod.optin),w(t._zod,"optout",()=>e.innerType._zod.optout),w(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${vt(n.source)}|null)$`):void 0}),w(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),zi=p("$ZodPrefault",(t,e)=>{z.init(t,e),t._zod.optin="optional",w(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Ti=p("$ZodPipe",(t,e)=>{z.init(t,e),w(t._zod,"values",()=>e.in._zod.values),w(t._zod,"optin",()=>e.in._zod.optin),w(t._zod,"optout",()=>e.out._zod.optout),w(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const o=e.out._zod.run(n,r);return o instanceof Promise?o.then(s=>Je(s,e.in,r)):Je(o,e.in,r)}const i=e.in._zod.run(n,r);return i instanceof Promise?i.then(o=>Je(o,e.out,r)):Je(i,e.out,r)}});function Je(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const ki=p("$ZodLazy",(t,e)=>{z.init(t,e),w(t._zod,"innerType",()=>e.getter()),w(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),w(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),w(t._zod,"optin",()=>t._zod.innerType._zod.optin??void 0),w(t._zod,"optout",()=>t._zod.innerType._zod.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),Ai=p("$ZodCustom",(t,e)=>{Ye.init(t,e),z.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,i=e.fn(r);if(i instanceof Promise)return i.then(o=>Sn(o,n,r,t));Sn(i,n,r,t)}});function Sn(t,e,n,r){if(!t){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),e.issues.push(Hr(i))}}function $i(t,e){return new t({type:"string",...C()})}function Pi(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C()})}function Ii(t,e){return new t({type:"number",checks:[],...C()})}function Ci(t,e){return new t({type:"boolean",...C()})}function Ri(t,e){return new t({type:"null",...C()})}function Oi(t){return new t({type:"any"})}function Mi(t){return new t({type:"unknown"})}function xi(t,e){return new ri({check:"min_length",...C(),minimum:t})}function Vi(t,e){return new ii({check:"length_equals",...C(),length:t})}function Ni(t,e,n){const r=C();return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}const T=p("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");z.init(t,e),t.def=e,t.type=e.type,t.parse=(n,r)=>Wr(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>gn(t,n,r),t.parseAsync=async(n,r)=>Yr(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>vn(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>bt(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t)}),zn=p("ZodMiniString",(t,e)=>{yn.init(t,e),T.init(t,e)});function l(t){return $i(zn)}const Li=p("ZodMiniStringFormat",(t,e)=>{mn.init(t,e),zn.init(t,e)}),ji=p("ZodMiniNumber",(t,e)=>{ci.init(t,e),T.init(t,e)});function $(t){return Ii(ji)}const Ui=p("ZodMiniBoolean",(t,e)=>{ui.init(t,e),T.init(t,e)});function B(t){return Ci(Ui)}const Zi=p("ZodMiniNull",(t,e)=>{li.init(t,e),T.init(t,e)});function wt(t){return Ri(Zi)}const Di=p("ZodMiniAny",(t,e)=>{di.init(t,e),T.init(t,e)});function Tn(){return Oi(Di)}const Bi=p("ZodMiniUnknown",(t,e)=>{fi.init(t,e),T.init(t,e)});function Fi(){return Mi(Bi)}const qi=p("ZodMiniArray",(t,e)=>{pi.init(t,e),T.init(t,e)});function k(t,e){return new qi({type:"array",element:t,...C()})}const Hi=p("ZodMiniObject",(t,e)=>{vi.init(t,e),T.init(t,e),w(t,"shape",()=>e.shape)});function h(t,e){const n={type:"object",get shape(){return yt(this,"shape",{...t}),this.shape},...C()};return new Hi(n)}function g(t,e){return Fr(t,e)}function Ki(t,e){return qr(An,t)}function Qe(t,e){return t.clone({...t._zod.def,catchall:e})}const Wi=p("ZodMiniUnion",(t,e)=>{wn.init(t,e),T.init(t,e)});function J(t,e){return new Wi({type:"union",options:t,...C()})}const Yi=p("ZodMiniDiscriminatedUnion",(t,e)=>{yi.init(t,e),T.init(t,e)});function Pe(t,e,n){return new Yi({type:"union",options:e,discriminator:t,...C()})}const Gi=p("ZodMiniRecord",(t,e)=>{mi.init(t,e),T.init(t,e)});function re(t,e,n){return new Gi({type:"record",keyType:t,valueType:e,...C()})}const Ji=p("ZodMiniEnum",(t,e)=>{_i.init(t,e),T.init(t,e),t.options=Object.values(e.entries)});function kn(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Ji({type:"enum",entries:n,...C()})}const Qi=p("ZodMiniLiteral",(t,e)=>{bi.init(t,e),T.init(t,e)});function v(t,e){return new Qi({type:"literal",values:Array.isArray(t)?t:[t],...C()})}const Xi=p("ZodMiniTransform",(t,e)=>{wi.init(t,e),T.init(t,e)});function eo(t){return new Xi({type:"transform",transform:t})}const An=p("ZodMiniOptional",(t,e)=>{Ei.init(t,e),T.init(t,e)});function f(t){return new An({type:"optional",innerType:t})}const to=p("ZodMiniNullable",(t,e)=>{Si.init(t,e),T.init(t,e)});function Xe(t){return new to({type:"nullable",innerType:t})}const no=p("ZodMiniPrefault",(t,e)=>{zi.init(t,e),T.init(t,e)});function H(t,e){return new no({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Zr(e)}})}const ro=p("ZodMiniPipe",(t,e)=>{Ti.init(t,e),T.init(t,e)});function io(t,e){return new ro({type:"pipe",in:t,out:e})}const oo=p("ZodMiniLazy",(t,e)=>{ki.init(t,e),T.init(t,e)});function so(t){return new oo({type:"lazy",getter:t})}const ao=p("ZodMiniCustom",(t,e)=>{Ai.init(t,e),T.init(t,e)});function co(t,e){return Ni(ao,()=>!0)}function Q(){const t=so(()=>J([l(),$(),B(),wt(),k(t),re(l(),t)]));return t}const uo=p("$ZodISODateTime",(t,e)=>{ai.init(t,e),Li.init(t,e)});function Et(t){return Pi(uo)}const et=Qe(h({}),Q()),lo=h({sys:h({type:v("Link"),linkType:l(),id:l()})}),fo=h({sys:h({type:v("Link"),linkType:v("ContentType"),id:l()})}),po=h({sys:h({type:v("Link"),linkType:v("Environment"),id:l()})}),ho=h({sys:h({type:v("Link"),linkType:v("Space"),id:l()})}),go=h({sys:h({type:v("Link"),linkType:v("TaxonomyConcept"),id:l()})}),vo=h({sys:h({type:v("Link"),linkType:v("Tag"),id:l()})}),$n=h({type:v("Entry"),contentType:fo,publishedVersion:$(),id:l(),createdAt:Tn(),updatedAt:Tn(),locale:f(l()),revision:$(),space:ho,environment:po}),Ie=h({fields:et,metadata:h({tags:k(vo),concepts:f(k(go))}),sys:$n});function yo(t){return Ie.safeParse(t).success}const mo=g(et,{nt_audience_id:l(),nt_name:f(l()),nt_description:f(l())}),Pn=g(Ie,{fields:mo});g(Pn,{contentTypeId:v("nt_audience")});const _o=g(Ie,{fields:h({nt_name:l(),nt_fallback:f(l()),nt_mergetag_id:l()}),sys:g($n,{contentType:h({sys:h({type:v("Link"),linkType:v("ContentType"),id:v("nt_mergetag")})})})}),St=h({id:l(),hidden:H(B(),!1)});function bo(t){return St.safeParse(t).success}const wo=h({type:f(v("EntryReplacement")),baseline:St,variants:k(St)});function Eo(t){return t.type==="EntryReplacement"||t.type===void 0}const In=h({value:J([l(),B(),wt(),$(),re(l(),Q())])}),So=kn(["Boolean","Number","Object","String"]),zo=h({type:v("InlineVariable"),key:l(),valueType:So,baseline:In,variants:k(In)}),To=Pe("type",[wo,zo]),ko=k(To),Ao=h({distribution:f(H(k($()),[.5,.5])),traffic:f(H($(),0)),components:f(H(ko,[{type:"EntryReplacement",baseline:{id:""},variants:[{id:""}]}])),sticky:f(H(B(),!1))}),$o=J([v("nt_experiment"),v("nt_personalization")]),Po=g(et,{nt_name:l(),nt_description:f(Xe(l())),nt_type:$o,nt_config:io(f(H(Xe(Ao),null)),eo(t=>t??{traffic:0,distribution:[.5,.5],components:[],sticky:!1})),nt_audience:f(Xe(Pn)),nt_variants:f(H(k(co()),[])),nt_experience_id:l()}),zt=g(Ie,{fields:Po});g(zt,{contentTypeId:v("nt_experience")});function tt(t){return zt.safeParse(t).success}const Io=k(J([lo,zt])),Co=g(Ie,{fields:g(et,{nt_experiences:Io})});function Tt(t){return Co.safeParse(t).success}const Ro=f(h({name:l(),version:l()})),Cn=h({name:f(l()),source:f(l()),medium:f(l()),term:f(l()),content:f(l())}),Oo=J([v("mobile"),v("server"),v("web")]),Mo=re(l(),l()),xo=2,Vo=h({latitude:$(),longitude:$()}),kt=h({coordinates:f(Vo),city:f(l()),postalCode:f(l()),region:f(l()),regionCode:f(l()),country:f(l()),countryCode:f(l().check(Vi(xo))),continent:f(l()),timezone:f(l())}),No=h({name:l(),version:l()}),_e=Qe(h({path:l(),query:Mo,referrer:l(),search:l(),title:f(l()),url:l()}),Q()),nt=re(l(),Q()),At=Qe(h({name:l()}),Q()),$t=re(l(),Q()),Lo=h({id:l(),isReturningVisitor:B(),landingPage:_e,count:$(),activeSessionLength:$(),averageSessionLength:$()}),rt=h({id:l(),stableId:l(),random:$(),audiences:k(l()),traits:$t,location:kt,session:Lo}),jo=Qe(h({id:l()}),Q()),Rn=h({data:h(),message:l(),error:Xe(B())}),Uo=h({profiles:f(k(rt))}),Zo=g(Rn,{data:Uo}),Do=["Variable"],On=h({key:l(),type:J([kn(Do),l()]),meta:h({experienceId:l(),variantIndex:$()})}),Bo=J([l(),B(),wt(),$(),re(l(),Q())]);g(On,{type:l(),value:Fi()});const Fo=g(On,{type:v("Variable"),value:Bo}),qo=Pe("type",[Fo]),Mn=k(qo),Pt=h({app:Ro,campaign:Cn,gdpr:h({isConsentGiven:B()}),library:No,locale:l(),location:f(kt),userAgent:f(l())}),ie=h({channel:Oo,context:g(Pt,{page:f(_e),screen:f(At)}),messageId:l(),originalTimestamp:Et(),sentAt:Et(),timestamp:Et(),userId:f(l())}),xn=g(ie,{type:v("alias")}),It=g(ie,{type:v("component"),componentType:J([v("Entry"),v("Variable")]),componentId:l(),experienceId:f(l()),variantIndex:$()}),Vn=g(ie,{type:v("group")}),Nn=g(ie,{type:v("identify"),traits:$t}),Ln=g(Pt,{page:_e}),jn=g(ie,{type:v("page"),name:f(l()),properties:_e,context:Ln}),Un=g(Pt,{screen:At}),Zn=g(ie,{type:v("screen"),name:l(),properties:f(nt),context:Un}),Dn=g(ie,{type:v("track"),event:l(),properties:nt}),oe={anonymousId:l()},Ho=Pe("type",[g(xn,oe),g(It,oe),g(Vn,oe),g(Nn,oe),g(jn,oe),g(Zn,oe),g(Dn,oe)]);k(Ho);const Bn=Pe("type",[xn,It,Vn,Nn,jn,Zn,Dn]),it=k(Bn),Ko=h({features:f(k(l()))});h({events:it.check(xi(1)),options:f(Ko)});const Wo=h({experienceId:l(),variantIndex:$(),variants:re(l(),l()),sticky:f(H(B(),!1))}),Fn=k(Wo),Yo=h({profile:rt,experiences:Fn,changes:Mn}),Ct=g(Rn,{data:Yo}),qn=Pe("type",[It]),Go=k(qn),Jo=h({profile:jo,events:Go}),Qo=k(Jo);var Rt=[],Xo=t=>new RegExp(t.replace(/\*/g,".*")+"$"),es=t=>{Rt=t.split(/[\s,]+/).map(Xo)},be=(t,e,n,...r)=>{for(let i=Rt.length;i--;)if(Rt[i].test(t))return e({name:t,level:n,messages:r})},ts=t=>{let e="";const n=console[t.level==="fatal"?"error":t.level];t.name&&(e+=`[${t.name}] `),typeof t.messages[0]=="object"?n(e,...t.messages):n(e+t.messages.shift(),...t.messages)},Hn=(t,e)=>({fatal:be.bind(0,t,e=e||ts,"fatal"),error:be.bind(0,t,e,"error"),warn:be.bind(0,t,e,"warn"),debug:be.bind(0,t,e,"debug"),info:be.bind(0,t,e,"info"),log:be.bind(0,t,e,"log")}),we=Hn("");we.fatal,we.error,we.warn,we.debug,we.info,we.log;class ns{name="@contentful/optimization";PREFIX_PARTS=["Ctfl","O10n"];DELIMITER=":";diary;sinks=[];constructor(){this.diary=Hn(this.name,this.onLogEvent.bind(this)),es(this.name)}assembleLocationPrefix(e){return`[${[...this.PREFIX_PARTS,e].join(this.DELIMITER)}]`}addSink(e){this.sinks=[...this.sinks.filter(n=>n.name!==e.name),e]}removeSink(e){this.sinks=this.sinks.filter(n=>n.name!==e)}removeSinks(){this.sinks=[]}debug(e,n,...r){this.diary.debug(`${this.assembleLocationPrefix(e)} ${n}`,...r)}info(e,n,...r){this.diary.info(`${this.assembleLocationPrefix(e)} ${n}`,...r)}log(e,n,...r){this.diary.log(`${this.assembleLocationPrefix(e)} ${n}`,...r)}warn(e,n,...r){this.diary.warn(`${this.assembleLocationPrefix(e)} ${n}`,...r)}error(e,n,...r){this.diary.error(`${this.assembleLocationPrefix(e)} ${n}`,...r)}fatal(e,n,...r){this.diary.fatal(`${this.assembleLocationPrefix(e)} ${n}`,...r)}onLogEvent(e){this.sinks.forEach(n=>{n.ingest(e)})}}const se=new ns;function R(t){return{debug:(e,...n)=>{se.debug(t,e,...n)},info:(e,...n)=>{se.info(t,e,...n)},log:(e,...n)=>{se.log(t,e,...n)},warn:(e,...n)=>{se.warn(t,e,...n)},error:(e,...n)=>{se.error(t,e,...n)},fatal:(e,...n)=>{se.fatal(t,e,...n)}}}class rs{}var Ee={fatal:60,error:50,warn:40,info:30,debug:20,log:10},is=(t,e)=>e in Ee&&t in Ee?Ee[e]===Ee[t]?0:Ee[e]<Ee[t]?1:-1:0;const os={debug:(...t)=>{console.debug(...t)},info:(...t)=>{console.info(...t)},log:(...t)=>{console.log(...t)},warn:(...t)=>{console.warn(...t)},error:(...t)=>{console.error(...t)},fatal:(...t)=>{console.error(...t)}},ss=0;class as extends rs{name="ConsoleLogSink";verbosity;constructor(e){super(),this.verbosity=e??"error"}ingest(e){is(this.verbosity,e.level)>ss||os[e.level](...e.messages)}}function cs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ot={},Mt,Kn;function us(){if(Kn)return Mt;Kn=1;function t(e,n){typeof n=="boolean"&&(n={forever:n}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=n||{},this._maxRetryTime=n&&n.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Mt=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var n=new Date().getTime();if(e&&n-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},r),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,n){this._fn=e,n&&(n.timeout&&(this._operationTimeout=n.timeout),n.cb&&(this._operationTimeoutCb=n.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},n=null,r=0,i=0;i<this._errors.length;i++){var o=this._errors[i],s=o.message,a=(e[s]||0)+1;e[s]=a,a>=r&&(n=o,r=a)}return n},Mt}var Wn;function ls(){return Wn||(Wn=1,function(t){var e=us();t.operation=function(n){var r=t.timeouts(n);return new e(r,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},t.timeouts=function(n){if(n instanceof Array)return[].concat(n);var r={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in n)r[i]=n[i];if(r.minTimeout>r.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],s=0;s<r.retries;s++)o.push(this.createTimeout(s,r));return n&&n.forever&&!o.length&&o.push(this.createTimeout(s,r)),o.sort(function(a,c){return a-c}),o},t.createTimeout=function(n,r){var i=r.randomize?Math.random()+1:1,o=Math.round(i*Math.max(r.minTimeout,1)*Math.pow(r.factor,n));return o=Math.min(o,r.maxTimeout),o},t.wrap=function(n,r,i){if(r instanceof Array&&(i=r,r=null),!i){i=[];for(var o in n)typeof n[o]=="function"&&i.push(o)}for(var s=0;s<i.length;s++){var a=i[s],c=n[a];n[a]=(function(d){var m=t.operation(r),b=Array.prototype.slice.call(arguments,1),S=b.pop();b.push(function(_){m.retry(_)||(_&&(arguments[0]=m.mainError()),S.apply(this,arguments))}),m.attempt(function(){d.apply(n,b)})}).bind(n,c),n[a].options=r}}}(Ot)),Ot}var xt,Yn;function ds(){return Yn||(Yn=1,xt=ls()),xt}var fs=ds();const ps=cs(fs),hs=Object.prototype.toString,gs=t=>hs.call(t)==="[object Error]",vs=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function ys(t){return t&&gs(t)&&t.name==="TypeError"&&typeof t.message=="string"?t.message==="Load failed"?t.stack===void 0:vs.has(t.message):!1}class ms extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const Gn=(t,e,n)=>{const r=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=r,t};async function _s(t,e){return new Promise((n,r)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;const i=ps.operation(e),o=()=>{i.stop(),r(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});const s=()=>{e.signal?.removeEventListener("abort",o),i.stop()};i.attempt(async a=>{try{const c=await t(a);s(),n(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof ms)throw c.originalError;if(c instanceof TypeError&&!ys(c))throw c;if(Gn(c,a,e),await e.shouldRetry(c)||(i.stop(),r(c)),await e.onFailedAttempt(c),!i.retry(c))throw i.mainError()}catch(u){Gn(u,a,e),s(),r(u)}}})})}const Vt=R("ApiClient:Retry"),bs=0,ws=1,Nt=503,Es=500;class ot extends Error{status;constructor(e,n=Es){super(e),Object.setPrototypeOf(this,ot.prototype),this.status=n}}function Ss({apiName:t="Optimization",controller:e,fetchMethod:n=fetch,init:r,url:i}){return async()=>{try{const o=await n(i,r);if(o.status===Nt)throw new ot(`${t} API request to "${i.toString()}" failed with status: "[${o.status}] ${o.statusText}".`,Nt);if(!o.ok){const s=new Error(`Request to "${i.toString()}" failed with status: [${o.status}] ${o.statusText} - traceparent: ${o.headers.get("traceparent")}`);Vt.error("Request failed with non-OK status:",s),e.abort();return}return Vt.debug(`Response from "${i.toString()}":`,o),o}catch(o){if(o instanceof ot&&o.status===Nt)throw o;Vt.error(`Request to "${i.toString()}" failed:`,o),e.abort()}}}function zs({apiName:t="Optimization",fetchMethod:e=fetch,intervalTimeout:n=bs,onFailedAttempt:r,retries:i=ws}={}){return async(o,s)=>{const a=new AbortController;let c;try{c=await _s(Ss({apiName:t,controller:a,fetchMethod:e,init:s,url:o}),{minTimeout:n,onFailedAttempt:u=>r?.({...u,apiName:t}),retries:i,signal:a.signal})}catch(u){if(!(u instanceof Error)||u.name!=="AbortError")throw u}if(!c)throw new Error(`${t} API request to "${o.toString()}" may not be retried.`);return c}}const Ts=R("ApiClient:Timeout"),ks=3e3;function As({apiName:t="Optimization",fetchMethod:e=fetch,onRequestTimeout:n,requestTimeout:r=ks}={}){return async(i,o)=>{const s=new AbortController,a=setTimeout(()=>{typeof n=="function"?n({apiName:t}):Ts.error(`Request to "${i.toString()}" timed out`,new Error("Request timeout")),s.abort()},r),c=await e(i,{...o,signal:s.signal});return clearTimeout(a),c}}const Jn=R("ApiClient:Fetch");function $s(t){try{const e=As(t);return zs({...t,fetchMethod:e})}catch(e){throw e instanceof Error&&(e.name==="AbortError"?Jn.warn("Request aborted due to network issues. This request may not be retried."):Jn.error("Request failed:",e)),e}}const Ps={create:$s},Qn=R("ApiClient"),Is="main";class Xn{name;clientId;environment;fetch;constructor(e,{fetchOptions:n,clientId:r,environment:i}){this.clientId=r,this.environment=i??Is,this.name=e,this.fetch=Ps.create({...n??{},apiName:e})}logRequestError(e,{requestName:n}){e instanceof Error&&(e.name==="AbortError"?Qn.warn(`[${this.name}] "${n}" request aborted due to network issues. This request may not be retried.`):Qn.error(`[${this.name}] "${n}" request failed:`,e))}}const L=R("ApiClient:Experience"),Cs="https://experience.ninetailed.co/";class Rs extends Xn{baseUrl;enabledFeatures;ip;locale;plainText;preflight;constructor(e){super("Experience",e);const{baseUrl:n,enabledFeatures:r,ip:i,locale:o,plainText:s,preflight:a}=e;this.baseUrl=n||Cs,this.enabledFeatures=r,this.ip=i,this.locale=o,this.plainText=s,this.preflight=a}async getProfile(e,n={}){if(!e)throw new Error("Valid profile ID required.");const r="Get Profile";L.info(`Sending "${r}" request`);try{const i=await this.fetch(this.constructUrl(`v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${e}`,n),{method:"GET"}),{data:{changes:o,experiences:s,profile:a}}=Ct.parse(await i.json()),c={changes:o,personalizations:s,profile:a};return L.debug(`"${r}" request successfully completed`),c}catch(i){throw this.logRequestError(i,{requestName:r}),i}}async makeProfileMutationRequest({url:e,body:n,options:r}){return await this.fetch(this.constructUrl(e,r),{method:"POST",headers:this.constructHeaders(r),body:JSON.stringify(n),keepalive:!0})}async createProfile({events:e},n={}){const r="Create Profile";L.info(`Sending "${r}" request`);const i={events:it.parse(e),options:this.constructBodyOptions(n)};L.debug(`"${r}" request body:`,i);try{const o=await this.makeProfileMutationRequest({url:`v2/organizations/${this.clientId}/environments/${this.environment}/profiles`,body:i,options:n}),{data:{changes:s,experiences:a,profile:c}}=Ct.parse(await o.json()),u={changes:s,personalizations:a,profile:c};return L.debug(`"${r}" request successfully completed`),u}catch(o){throw this.logRequestError(o,{requestName:r}),o}}async updateProfile({profileId:e,events:n},r={}){if(!e)throw new Error("Valid profile ID required.");const i="Update Profile";L.info(`Sending "${i}" request`);const o={events:it.parse(n),options:this.constructBodyOptions(r)};L.debug(`"${i}" request body:`,o);try{const s=await this.makeProfileMutationRequest({url:`v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${e}`,body:o,options:r}),{data:{changes:a,experiences:c,profile:u}}=Ct.parse(await s.json()),d={changes:a,personalizations:c,profile:u};return L.debug(`"${i}" request successfully completed`),d}catch(s){throw this.logRequestError(s,{requestName:i}),s}}async upsertProfile({profileId:e,events:n},r){return e?await this.updateProfile({profileId:e,events:n},r):await this.createProfile({events:n},r)}async upsertManyProfiles({events:e},n={}){const r="Upsert Many Profiles";L.info(`Sending "${r}" request`);const i={events:it.parse(e),options:this.constructBodyOptions(n)};L.debug(`"${r}" request body:`,i);try{const o=await this.makeProfileMutationRequest({url:`v2/organizations/${this.clientId}/environments/${this.environment}/events`,body:i,options:{plainText:!1,...n}}),{data:{profiles:s}}=Zo.parse(await o.json());return L.debug(`"${r}" request successfully completed`),s}catch(o){throw this.logRequestError(o,{requestName:r}),o}}constructUrl(e,n){const r=new URL(e,this.baseUrl),i=n.locale??this.locale,o=n.preflight??this.preflight;return i&&r.searchParams.set("locale",i),o&&r.searchParams.set("type","preflight"),r.toString()}constructHeaders({ip:e=this.ip,plainText:n=this.plainText}){const r=new Map;return e&&r.set("X-Force-IP",e),n??this.plainText??!0?r.set("Content-Type","text/plain"):r.set("Content-Type","application/json"),Object.fromEntries(r)}constructBodyOptions=({enabledFeatures:e=this.enabledFeatures})=>{const n={};return e&&Array.isArray(e)&&e.length>0?n.features=e:n.features=["ip-enrichment","location"],n}}const Ce=R("ApiClient:Insights"),Os="https://ingest.insights.ninetailed.co/";class Ms extends Xn{baseUrl;beaconHandler;constructor(e){super("Insights",e);const{baseUrl:n,beaconHandler:r}=e;this.baseUrl=n??Os,this.beaconHandler=r}async sendBatchEvents(e,n={}){const{beaconHandler:r=this.beaconHandler}=n,i=new URL(`v1/organizations/${this.clientId}/environments/${this.environment}/events`,this.baseUrl),o=Qo.parse(e);if(typeof r=="function"){if(Ce.debug("Queueing events via beaconHandler"),r(i,o))return!0;Ce.warn("beaconHandler failed to queue events; events will be emitted immediately via fetch")}const s="Event Batches";Ce.info(`Sending "${s}" request`),Ce.debug(`"${s}" request body:`,o);try{return await this.fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0}),Ce.debug(`"${s}" request successfully completed`),!0}catch(a){return this.logRequestError(a,{requestName:s}),!1}}}class xs{config;experience;insights;constructor(e){const{personalization:n,analytics:r,...i}=e;this.config=i,this.experience=new Rs({...i,...n}),this.insights=new Ms({...i,...r})}}function Vs(){}function er(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function tr(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const Ns="[object RegExp]",Ls="[object String]",js="[object Number]",Us="[object Boolean]",nr="[object Arguments]",Zs="[object Symbol]",Ds="[object Date]",Bs="[object Map]",Fs="[object Set]",qs="[object Array]",Hs="[object Function]",Ks="[object ArrayBuffer]",Lt="[object Object]",Ws="[object Error]",Ys="[object DataView]",Gs="[object Uint8Array]",Js="[object Uint8ClampedArray]",Qs="[object Uint16Array]",Xs="[object Uint32Array]",ea="[object BigUint64Array]",ta="[object Int8Array]",na="[object Int16Array]",ra="[object Int32Array]",ia="[object BigInt64Array]",oa="[object Float32Array]",sa="[object Float64Array]";function st(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function at(t){return t==="__proto__"}function Se(t,e){const n=Object.keys(e);for(let r=0;r<n.length;r++){const i=n[r];if(at(i))continue;const o=e[i],s=t[i];Array.isArray(o)?Array.isArray(s)?t[i]=Se(s,o):t[i]=Se([],o):st(o)?st(s)?t[i]=Se(s,o):t[i]=Se({},o):(s===void 0||o!==void 0)&&(t[i]=o)}return t}function aa(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function ca(t,e,n){return Re(t,e,void 0,void 0,void 0,void 0,n)}function Re(t,e,n,r,i,o,s){const a=s(t,e,n,r,i,o);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Oe(t,e,o,s)}return Oe(t,e,o,s)}function Oe(t,e,n,r){if(Object.is(t,e))return!0;let i=tr(t),o=tr(e);if(i===nr&&(i=Lt),o===nr&&(o=Lt),i!==o)return!1;switch(i){case Ls:return t.toString()===e.toString();case js:{const c=t.valueOf(),u=e.valueOf();return aa(c,u)}case Us:case Ds:case Zs:return Object.is(t.valueOf(),e.valueOf());case Ns:return t.source===e.source&&t.flags===e.flags;case Hs:return t===e}n=n??new Map;const s=n.get(t),a=n.get(e);if(s!=null&&a!=null)return s===e;n.set(t,e),n.set(e,t);try{switch(i){case Bs:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Re(u,e.get(c),c,t,e,n,r))return!1;return!0}case Fs:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let d=0;d<c.length;d++){const m=c[d],b=u.findIndex(S=>Re(m,S,void 0,t,e,n,r));if(b===-1)return!1;u.splice(b,1)}return!0}case qs:case Gs:case Js:case Qs:case Xs:case ea:case ta:case na:case ra:case ia:case oa:case sa:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Re(t[c],e[c],c,t,e,n,r))return!1;return!0}case Ks:return t.byteLength!==e.byteLength?!1:Oe(new Uint8Array(t),new Uint8Array(e),n,r);case Ys:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Oe(new Uint8Array(t),new Uint8Array(e),n,r);case Ws:return t.name===e.name&&t.message===e.message;case Lt:{if(!(Oe(t.constructor,e.constructor,n,r)||st(t)&&st(e)))return!1;const u=[...Object.keys(t),...er(t)],d=[...Object.keys(e),...er(e)];if(u.length!==d.length)return!1;for(let m=0;m<u.length;m++){const b=u[m],S=t[b];if(!Object.hasOwn(e,b))return!1;const _=e[b];if(!Re(S,_,b,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function jt(t,e){return ca(t,e,Vs)}const Me=h({campaign:f(Cn),locale:f(l()),location:f(kt),page:f(_e),screen:f(At),userAgent:f(l())}),ua=g(Me,{componentId:l(),experienceId:f(l()),variantIndex:f($()),sticky:f(B())}),la=g(Me,{traits:f($t),userId:l()}),da=g(Me,{properties:f(Ki(_e))}),fa=g(Me,{name:l(),properties:nt}),pa=g(Me,{event:l(),properties:f(H(nt,{}))}),rr={path:"",query:{},referrer:"",search:"",title:"",url:""};class ha{app;channel;library;getLocale;getPageProperties;getUserAgent;constructor(e){const{app:n,channel:r,library:i,getLocale:o,getPageProperties:s,getUserAgent:a}=e;this.app=n,this.channel=r,this.library=i,this.getLocale=o??(()=>"en-US"),this.getPageProperties=s??(()=>rr),this.getUserAgent=a??(()=>{})}buildUniversalEventProperties({campaign:e={},locale:n,location:r,page:i,screen:o,userAgent:s}){const a=new Date().toISOString();return{channel:this.channel,context:{app:this.app,campaign:e,gdpr:{isConsentGiven:!0},library:this.library,locale:n??this.getLocale()??"en-US",location:r,page:i??this.getPageProperties(),screen:o,userAgent:s??this.getUserAgent()},messageId:crypto.randomUUID(),originalTimestamp:a,sentAt:a,timestamp:a}}buildComponentView(e){const{componentId:n,experienceId:r,variantIndex:i,...o}=ua.parse(e);return{...this.buildUniversalEventProperties(o),type:"component",componentType:"Entry",componentId:n,experienceId:r,variantIndex:i??0}}buildFlagView(e){return{...this.buildComponentView(e),componentType:"Variable"}}buildIdentify(e){const{traits:n={},userId:r,...i}=la.parse(e);return{...this.buildUniversalEventProperties(i),type:"identify",traits:n,userId:r}}buildPageView(e={}){const{properties:n={},...r}=da.parse(e),i=this.getPageProperties(),o=Se({...i,title:i.title??rr.title},n),{context:{screen:s,...a},...c}=this.buildUniversalEventProperties(r),u=Ln.parse(a);return{...c,context:u,type:"page",properties:o}}buildScreenView(e){const{name:n,properties:r,...i}=fa.parse(e),{context:{page:o,...s},...a}=this.buildUniversalEventProperties(i),c=Un.parse(s);return{...a,context:c,type:"screen",name:n,properties:r}}buildTrack(e){const{event:n,properties:r={},...i}=pa.parse(e);return{...this.buildUniversalEventProperties(i),type:"track",event:n,properties:r}}}function ga(t){switch(typeof t){case"number":case"symbol":return!1;case"string":return t.includes(".")||t.includes("[")||t.includes("]")}}function va(t){return typeof t=="string"||typeof t=="symbol"?t:Object.is(t?.valueOf?.(),-0)?"-0":String(t)}function ya(t){const e=[],n=t.length;if(n===0)return e;let r=0,i="",o="",s=!1;for(t.charCodeAt(0)===46&&(e.push(""),r++);r<n;){const a=t[r];o?a==="\\"&&r+1<n?(r++,i+=t[r]):a===o?o="":i+=a:s?a==='"'||a==="'"?o=a:a==="]"?(s=!1,e.push(i),i=""):i+=a:a==="["?(s=!0,i&&(e.push(i),i="")):a==="."?i&&(e.push(i),i=""):i+=a,r++}return i&&e.push(i),e}function Ut(t,e,n){if(t==null)return n;switch(typeof e){case"string":{if(at(e))return n;const r=t[e];return r===void 0?ga(e)?Ut(t,ya(e),n):n:r}case"number":case"symbol":{typeof e=="number"&&(e=va(e));const r=t[e];return r===void 0?n:r}default:{if(Array.isArray(e))return ma(t,e,n);if(Object.is(e?.valueOf(),-0)?e="-0":e=String(e),at(e))return n;const r=t[e];return r===void 0?n:r}}}function ma(t,e,n){if(e.length===0)return n;let r=t;for(let i=0;i<e.length;i++){if(r==null||at(e[i]))return n;r=r[e[i]]}return r===void 0?n:r}const ir=R("Personalization"),or="Could not resolve Merge Tag value:",xe={isMergeTagEntry(t){return _o.safeParse(t).success},normalizeSelectors(t){return t.split("_").map((e,n,r)=>{const i=r.slice(0,n).join("."),o=r.slice(n).join("_");return[i,o].filter(s=>s!=="").join(".")})},getValueFromProfile(t,e){const r=xe.normalizeSelectors(t).find(o=>Ut(e,o));if(!r)return;const i=Ut(e,r);if(!(!i||typeof i!="string"&&typeof i!="number"&&typeof i!="boolean"))return`${i}`},resolve(t,e){if(!xe.isMergeTagEntry(t)){ir.warn(`${or} supplied entry is not a Merge Tag entry`);return}const{fields:{nt_fallback:n}}=t;return rt.safeParse(e).success?xe.getValueFromProfile(t.fields.nt_mergetag_id,e)??n:(ir.warn(`${or} no valid profile`),n)}},X=R("Personalization"),Ve="Could not resolve personalized entry variant:",ze={getPersonalizationEntry({personalizedEntry:t,selectedPersonalizations:e},n=!1){return!n&&(!e.length||!Tt(t))?void 0:t.fields.nt_experiences.filter(i=>tt(i)).find(i=>e.some(({experienceId:o})=>o===i.fields.nt_experience_id))},getSelectedPersonalization({personalizationEntry:t,selectedPersonalizations:e},n=!1){return!n&&(!e.length||!tt(t))?void 0:e.find(({experienceId:i})=>i===t.fields.nt_experience_id)},getSelectedVariant({personalizedEntry:t,personalizationEntry:e,selectedVariantIndex:n},r=!1){if(!r&&(!Tt(t)||!tt(e)))return;const i=e.fields.nt_config?.components?.filter(o=>Eo(o)&&!o.baseline.hidden).find(o=>o.baseline.id===t.sys.id)?.variants;if(i?.length)return i.at(n-1)},getSelectedVariantEntry({personalizationEntry:t,selectedVariant:e},n=!1){if(!n&&(!tt(t)||!bo(e)))return;const r=t.fields.nt_variants?.find(i=>i.sys.id===e.id);return yo(r)?r:void 0},resolve(t,e){if(X.debug(`Resolving personalized entry for baseline entry ${t.sys.id}`),!e?.length)return X.warn(`${Ve} no selectedPersonalizations exist for the current profile`),{entry:t};if(!Tt(t))return X.warn(`${Ve} entry ${t.sys.id} is not personalized`),{entry:t};const n=ze.getPersonalizationEntry({personalizedEntry:t,selectedPersonalizations:e},!0);if(!n)return X.warn(`${Ve} could not find a personalization entry for ${t.sys.id}`),{entry:t};const r=ze.getSelectedPersonalization({personalizationEntry:n,selectedPersonalizations:e},!0),i=r?.variantIndex??0;if(i===0)return X.debug(`Resolved personalization entry for entry ${t.sys.id} is baseline`),{entry:t};const o=ze.getSelectedVariant({personalizedEntry:t,personalizationEntry:n,selectedVariantIndex:i},!0);if(!o)return X.warn(`${Ve} could not find a valid replacement variant entry for ${t.sys.id}`),{entry:t};const s=ze.getSelectedVariantEntry({personalizationEntry:n,selectedVariant:o},!0);if(s)X.debug(`Entry ${t.sys.id} has been resolved to variant entry ${s.sys.id}`);else return X.warn(`${Ve} could not find a valid replacement variant entry for ${t.sys.id}`),{entry:t};return{entry:s,personalization:r}}},ee=pe(),j=pe(),K=pe(),Zt=sn(()=>gt.resolve(ee.value??[])),Ne=pe(!0),F=pe(),A=pe();function U(t){return{subscribe(e){return{unsubscribe:O(()=>{e(t.value)})}}}}const Le={changes:ee,consent:j,event:K,flags:Zt,online:Ne,personalizations:F,profile:A},_a={batch:fe,computed:sn,effect:O,untracked:ft},ct=t=>typeof t=="function",ba=t=>typeof t=="string"?t:typeof t=="symbol"?t.description??String(t):String(t),wa=t=>typeof t=="string"||typeof t=="symbol",Ea=t=>Object.prototype.toString.call(t)==="[object AsyncFunction]";function q(t,e){return function(n,r){const i=ba(r.name);r.addInitializer(function(){const s=Reflect.get(this,r.name);if(!ct(s))return;const a=s,c=Ea(a),u=_=>{const{[t]:D}=_;if(!ct(D))throw new TypeError(`@guardedBy expects predicate "${String(t)}" to be a synchronous function.`);return D},d=(_,D)=>{const V=!!u(_).call(_,i,D);return e?.invert===!0?!V:V},m=(_,D)=>{const{onBlocked:P}=e??{};if(P!==void 0){if(ct(P)){P.call(_,i,D);return}if(wa(P)){const{[P]:V}=_;ct(V)&&V.call(_,i,D)}}},b=()=>c?Promise.resolve(void 0):void 0,S=function(..._){return d(this,_)?a.call(this,..._):(m(this,_),b())};Reflect.set(this,r.name,S)})}}class Sa{#e;constructor(e){const n=new Map;e&&Object.entries(e).map(([r,i])=>n.set(r.length?r:void 0,new Set(i))),this.#e=n}isPresent(e,n){return this.#e.get(e)?.has(n)??!1}addValue(e,n){const r=this.#e.get(e);r?r.add(n):this.#e.set(e,new Set([n]))}removeValue(e,n){this.#e.get(e)?.delete(n)}reset(e){e!==void 0?this.#e.get(e)?.clear():this.#e.clear()}}const za=["page","identify"];class sr{allowedEventTypes;builder;api;duplicationDetector;interceptors;constructor(e){const{api:n,builder:r,config:i,interceptors:o}=e;this.allowedEventTypes=i?.allowedEventTypes??za,this.api=n,this.builder=r,this.duplicationDetector=new Sa(i?.preventedComponentEvents),this.interceptors=o}}class Ta extends sr{}var ka=Object.create,ar=Object.defineProperty,Aa=Object.getOwnPropertyDescriptor,cr=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),ur=t=>{throw TypeError(t)},lr=(t,e,n)=>e in t?ar(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$a=t=>[,,,ka(t?.[cr("metadata")]??null)],dr=["class","method","getter","setter","accessor","field","value","get","set"],fr=t=>t!==void 0&&typeof t!="function"?ur("Function expected"):t,Pa=(t,e,n,r,i)=>({kind:dr[t],name:e,metadata:r,addInitializer:o=>n._?ur("Already initialized"):i.push(fr(o||null))}),Ia=(t,e)=>lr(e,cr("metadata"),t[3]),Ca=(t,e,n,r)=>{for(var i=0,o=t[e>>1],s=o&&o.length;i<s;i++)o[i].call(n);return r},pr=(t,e,n,r,i,o)=>{for(var s,a,c,u,d=e&7,m=!1,b=!1,S=2,_=dr[d+5],D=t[S]||(t[S]=[]),P=(i=i.prototype,Aa(i,n)),V=r.length-1;V>=0;V--)c=Pa(d,n,a={},t[3],D),c.static=m,c.private=b,u=c.access={has:de=>n in de},u.get=de=>de[n],s=(0,r[V])(P[_],c),a._=1,fr(s)&&(P[_]=s);return P&&ar(i,n,P),i},hr=(t,e,n)=>lr(t,typeof e!="symbol"?e+"":e,n),gr,vr,Dt,je;const W=R("Analytics"),Ra=25;class ut extends(Dt=Ta,vr=[q("isNotDuplicated",{onBlocked:"onBlockedByDuplication"}),q("hasConsent",{onBlocked:"onBlockedByConsent"})],gr=[q("isNotDuplicated",{onBlocked:"onBlockedByDuplication"}),q("hasConsent",{onBlocked:"onBlockedByConsent"})],Dt){constructor(e){const{api:n,builder:r,config:i,interceptors:o}=e;super({api:n,builder:r,config:i,interceptors:o}),Ca(je,5,this),hr(this,"queue",new Map),hr(this,"states",{eventStream:U(K),profile:U(A)});const{defaults:s}=i??{};if(s?.profile!==void 0){const{profile:a}=s;A.value=a}O(()=>{const a=A.value?.id;W.info(`Analytics ${j.value?"will":"will not"} be collected due to consent (${j.value})`),W.debug(`Profile ${a&&`with ID ${a}`} has been ${a?"set":"cleared"}`)}),O(()=>{Ne.value&&this.flush()})}reset(){fe(()=>{K.value=void 0,A.value=void 0})}hasConsent(e){return!!j.value||(this.allowedEventTypes??[]).includes(e==="trackComponentView"||e==="trackFlagView"?"component":e)}onBlockedByConsent(e,n){W.warn(`Event "${e}" was blocked due to lack of consent; payload: ${JSON.stringify(n)}`)}isNotDuplicated(e,n){const[{componentId:r},i]=n,o=this.duplicationDetector.isPresent(i,r);return o||this.duplicationDetector.addValue(i,r),!o}onBlockedByDuplication(e,n){const r=e==="trackFlagView"?"flag":"component";W.debug(`Duplicate "${r} view" event detected, skipping; payload: ${JSON.stringify(n)}`)}async trackComponentView(e,n=""){W.info(`Processing "component view" event for ${e.componentId}`),await this.enqueueEvent(this.builder.buildComponentView(e))}async trackFlagView(e,n=""){W.debug(`Processing "flag view" event for ${e.componentId}`),await this.enqueueEvent(this.builder.buildFlagView(e))}async enqueueEvent(e){const{value:n}=A;if(!n){W.warn("Attempting to emit an event without an Optimization profile");return}const r=await this.interceptors.event.run(e),i=qn.parse(r);W.debug(`Queueing ${i.type} event for profile ${n.id}`,i);const o=this.queue.get(n);K.value=i,o?o.push(i):this.queue.set(n,[i]),await this.flushMaxEvents()}async flushMaxEvents(){this.queue.values().toArray().flat().length>=Ra&&await this.flush()}async flush(){W.debug("Flushing event queue");const e=[];if(this.queue.forEach((r,i)=>e.push({profile:i,events:r})),!e.length)return;await this.api.insights.sendBatchEvents(e)&&this.queue.clear()}}je=$a(Dt),pr(je,1,"trackComponentView",vr,ut),pr(je,1,"trackFlagView",gr,ut),Ia(je,ut);const Oa="0.1.0-alpha5",lt="ctfl-opt-aid",Bt="__ctfl_opt_anonymous_id__",Ft="__ctfl_opt_consent__",qt="__ctfl_opt_changes__",Ht="__ctfl_opt_debug__",Kt="__ctfl_opt_profile__",Wt="__ctfl_opt_personalizations__",yr="ntaid",mr="__nt_anonymous_id__";class _r{interceptors=new Map;nextId=0;add(e){const{nextId:n}=this;return this.nextId+=1,this.interceptors.set(n,e),n}remove(e){return this.interceptors.delete(e)}clear(){this.interceptors.clear()}count(){return this.interceptors.size}async run(e){const n=Array.from(this.interceptors.values());let r=e;for(const i of n)r=await i(r);return r}}class Ma{api;eventBuilder;config;interceptors={event:new _r,state:new _r};constructor(e){this.config=e;const{analytics:n,personalization:r,eventBuilder:i,logLevel:o,environment:s,clientId:a}=e;se.addSink(new as(o));const c={...n,...r,clientId:a,environment:s};this.api=new xs(c),this.eventBuilder=new ha(i??{channel:"server",library:{name:"Optimization Core",version:Oa}})}getCustomFlag(e,n){return this.personalization.getCustomFlag(e,n)}personalizeEntry(e,n){return this.personalization.personalizeEntry(e,n)}getMergeTagValue(e,n){return this.personalization.getMergeTagValue(e,n)}async identify(e){return await this.personalization.identify(e)}async page(e){return await this.personalization.page(e)}async screen(e){return await this.personalization.screen(e)}async track(e){return await this.personalization.track(e)}async trackComponentView(e,n){if(e.sticky)return await this.personalization.trackComponentView(e,n);await this.analytics.trackComponentView(e,n)}async trackFlagView(e,n){await this.analytics.trackFlagView(e,n)}}class xa extends sr{flagsResolver=gt;mergeTagValueResolver=xe;personalizedEntryResolver=ze;getCustomFlag(e,n){return gt.resolve(n)[e]}personalizeEntry(e,n){return ze.resolve(e,n)}getMergeTagValue(e,n){return xe.resolve(e,n)}}var Va=Object.create,br=Object.defineProperty,Na=Object.getOwnPropertyDescriptor,wr=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Er=t=>{throw TypeError(t)},Sr=(t,e,n)=>e in t?br(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,La=t=>[,,,Va(t?.[wr("metadata")]??null)],zr=["class","method","getter","setter","accessor","field","value","get","set"],Tr=t=>t!==void 0&&typeof t!="function"?Er("Function expected"):t,ja=(t,e,n,r,i)=>({kind:zr[t],name:e,metadata:r,addInitializer:o=>n._?Er("Already initialized"):i.push(Tr(o||null))}),Ua=(t,e)=>Sr(e,wr("metadata"),t[3]),Za=(t,e,n,r)=>{for(var i=0,o=t[e>>1],s=o&&o.length;i<s;i++)o[i].call(n);return r},Ue=(t,e,n,r,i,o)=>{for(var s,a,c,u,d=e&7,m=!1,b=!1,S=2,_=zr[d+5],D=t[S]||(t[S]=[]),P=(i=i.prototype,Na(i,n)),V=r.length-1;V>=0;V--)c=ja(d,n,a={},t[3],D),c.static=m,c.private=b,u=c.access={has:de=>n in de},u.get=de=>de[n],s=(0,r[V])(P[_],c),a._=1,Tr(s)&&(P[_]=s);return P&&br(i,n,P),i},Yt=(t,e,n)=>Sr(t,typeof e!="symbol"?e+"":e,n),kr,Ar,$r,Pr,Ir,Gt,te;const M=R("Personalization");class ae extends(Gt=xa,Ir=[q("hasConsent",{onBlocked:"onBlockedByConsent"})],Pr=[q("hasConsent",{onBlocked:"onBlockedByConsent"})],$r=[q("hasConsent",{onBlocked:"onBlockedByConsent"})],Ar=[q("hasConsent",{onBlocked:"onBlockedByConsent"})],kr=[q("isNotDuplicated",{onBlocked:"onBlockedByDuplication"}),q("hasConsent",{onBlocked:"onBlockedByConsent"})],Gt){constructor(e){const{api:n,builder:r,config:i,interceptors:o}=e;super({api:n,builder:r,config:i,interceptors:o}),Za(te,5,this),Yt(this,"offlineQueue",new Set),Yt(this,"states",{eventStream:U(K),flags:U(Zt),profile:U(A),personalizations:U(F)}),Yt(this,"getAnonymousId");const{defaults:s,getAnonymousId:a}=i??{};if(s){const{changes:c,personalizations:u,profile:d}=s;fe(()=>{ee.value=c,F.value=u,A.value=d})}if(s?.consent!==void 0){const{consent:c}=s;j.value=c}this.getAnonymousId=a??(()=>{}),O(()=>{M.debug(`Profile ${A.value&&`with ID ${A.value.id}`} has been ${A.value?"set":"cleared"}`)}),O(()=>{M.debug(`Variants have been ${F.value?.length?"populated":"cleared"}`)}),O(()=>{M.info(`Personalization ${j.value?"will":"will not"} take effect due to consent (${j.value})`)}),O(()=>{Ne.value&&this.flush()})}reset(){fe(()=>{ee.value=void 0,K.value=void 0,A.value=void 0,F.value=void 0})}getCustomFlag(e,n=ee.value){return super.getCustomFlag(e,n)}personalizeEntry(e,n=F.value){return super.personalizeEntry(e,n)}getMergeTagValue(e,n=A.value){return super.getMergeTagValue(e,n)}hasConsent(e){return!!j.value||(this.allowedEventTypes??[]).includes(e==="trackComponentView"||e==="trackFlagView"?"component":e)}onBlockedByConsent(e,n){M.warn(`Event "${e}" was blocked due to lack of consent; payload: ${JSON.stringify(n)}`)}isNotDuplicated(e,n){const[{componentId:r},i]=n,o=this.duplicationDetector.isPresent(i,r);return o||this.duplicationDetector.addValue(i,r),!o}onBlockedByDuplication(e,n){M.debug(`Duplicate "component view" event detected, skipping; payload: ${JSON.stringify(n)}`)}async identify(e){M.info('Sending "identify" event');const n=this.builder.buildIdentify(e);return await this.sendOrEnqueueEvent(n)}async page(e){M.info('Sending "page" event');const n=this.builder.buildPageView(e);return await this.sendOrEnqueueEvent(n)}async screen(e){M.info(`Sending "screen" event for "${e.name}"`);const n=this.builder.buildScreenView(e);return await this.sendOrEnqueueEvent(n)}async track(e){M.info(`Sending "track" event "${e.event}"`);const n=this.builder.buildTrack(e);return await this.sendOrEnqueueEvent(n)}async trackComponentView(e,n=""){M.info(`Sending "track personalization" event for ${e.componentId}`);const r=this.builder.buildComponentView(e);return await this.sendOrEnqueueEvent(r)}async sendOrEnqueueEvent(e){const n=await this.interceptors.event.run(e),r=Bn.parse(n);if(K.value=r,Ne.value)return await this.upsertProfile([r]);M.debug(`Queueing ${r.type} event`,r),this.offlineQueue.add(r)}async flush(){this.offlineQueue.size!==0&&(M.debug("Flushing offline event queue"),await this.upsertProfile(Array.from(this.offlineQueue)),this.offlineQueue.clear())}async upsertProfile(e){const n=this.getAnonymousId();n&&M.debug(`Anonymous ID found: ${n}`);const r=await this.api.experience.upsertProfile({profileId:n??A.value?.id,events:e});return await this.updateOutputSignals(r),r}async updateOutputSignals(e){const n=await this.interceptors.state.run(e),{changes:r,personalizations:i,profile:o}=n;fe(()=>{jt(ee.value,r)||(ee.value=r),jt(A.value,o)||(A.value=o),jt(F.value,i)||(F.value=i)})}}te=La(Gt),Ue(te,1,"identify",Ir,ae),Ue(te,1,"page",Pr,ae),Ue(te,1,"screen",$r,ae),Ue(te,1,"track",Ar,ae),Ue(te,1,"trackComponentView",kr,ae),Ua(te,ae);class Da extends Ma{analytics;personalization;constructor(e){super(e);const{allowedEventTypes:n,defaults:r,getAnonymousId:i,preventedComponentEvents:o}=e;if(r?.consent!==void 0){const{consent:s}=r;j.value=s}this.analytics=new ut({api:this.api,builder:this.eventBuilder,config:{allowedEventTypes:n,preventedComponentEvents:o,defaults:{consent:r?.consent,profile:r?.profile}},interceptors:this.interceptors}),this.personalization=new ae({api:this.api,builder:this.eventBuilder,config:{allowedEventTypes:n,getAnonymousId:i,preventedComponentEvents:o,defaults:{consent:r?.consent,changes:r?.changes,profile:r?.profile,personalizations:r?.personalizations}},interceptors:this.interceptors})}get states(){return{consent:U(j),eventStream:U(K),flags:U(Zt),personalizations:U(F),profile:U(A)}}reset(){fe(()=>{K.value=void 0,ee.value=void 0,A.value=void 0,F.value=void 0})}async flush(){await this.analytics.flush(),await this.personalization.flush()}consent(e){j.value=e}online(e){Ne.value=e}registerPreviewPanel(e){e.signals=Le,e.signalFns=_a}}/*! js-cookie v3.0.5 | MIT */function dt(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}var Ba={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Jt(t,e){function n(i,o,s){if(!(typeof document>"u")){s=dt({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var c in s)s[c]&&(a+="; "+c,s[c]!==!0&&(a+="="+s[c].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+a}}function r(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},a=0;a<o.length;a++){var c=o[a].split("="),u=c.slice(1).join("=");try{var d=decodeURIComponent(c[0]);if(s[d]=t.read(u,d),i===d)break}catch{}}return i?s[i]:s}}return Object.create({set:n,get:r,remove:function(i,o){n(i,"",dt({},o,{expires:-1}))},withAttributes:function(i){return Jt(this.converter,dt({},this.attributes,i))},withConverter:function(i){return Jt(dt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Te=Jt(Ba,{path:"/"});const Qt=R("Web:AutoTracking");function Ze(t){if(!(typeof HTMLElement<"u"&&typeof SVGElement<"u")||!t||t.nodeType!==1||!("dataset"in t)||!t.dataset||typeof t.dataset!="object"||!("ctflEntryId"in t.dataset))return!1;const{dataset:{ctflEntryId:n}}=t;return typeof n=="string"&&n.trim().length>0}function Cr(t){return!t||typeof t!="object"?!1:"entryId"in t&&typeof t.entryId=="string"&&!!t.entryId.trim().length}function Fa(t){return(t?.trim().toLowerCase()??"")==="true"}function qa(t){if(t===void 0||!/^\d+$/.test(t))return;const e=Number(t);return Number.isSafeInteger(e)?e:void 0}const Ha=t=>async(e,n)=>{if(!Cr(n.data)&&!Ze(e))return;let r,i,o,s,a;if(Cr(n.data))({data:{duplicationScope:r,entryId:i,personalizationId:o,sticky:s,variantIndex:a}}=n);else if(Ze(e)){({dataset:{ctflDuplicationScope:r,ctflEntryId:i,ctflPersonalizationId:o}}=e);const{dataset:{ctflSticky:c,ctflVariantIndex:u}}=e;s=Fa(c),a=qa(u)}if(!i){Qt.warn("No entry data found in entry view observer callback; please add data attributes or observe with data info");return}await t.trackComponentView({componentId:i,experienceId:o,sticky:s,variantIndex:a},r)};function Rr(t){if(Ze(t))return t;const e=t.querySelector("[data-ctfl-entry-id]")??void 0;return Ze(e)?e:void 0}const Ka=(t,e=!1)=>({onRemoved:n=>{n.forEach(r=>{const i=Rr(r);!i||!t.getStats(i)||(Qt.info("Auto-unobserving element (remove):",i),t.unobserve(i))})},onAdded:e?n=>{n.forEach(r=>{const i=Rr(r);i&&(Qt.info("Auto-observing element (add):",i),t.observe(i))})}:void 0}),Wa=R("Web:EventBuilder");function Ya(t){return new URL(t).searchParams.entries().reduce((e,[n,r])=>(e[n]=r,e),{})}function Ga(){const{languages:t,language:e}=navigator;return t[0]??e}function Ja(){try{const t=new URL(window.location.href),{referrer:e,title:n}=document;return{hash:window.location.hash,height:window.innerHeight,path:t.pathname,query:Ya(t),referrer:e,search:t.search,title:n,url:t.toString(),width:window.innerWidth}}catch(t){return t instanceof Error&&Wa.error("Failed to get page properties:",t),{path:"",query:{},referrer:"",search:"",title:"",url:""}}}function Qa(){return navigator.userAgent}const Xa="0.1.0-alpha5",x=typeof window<"u"&&typeof document<"u"&&typeof document.addEventListener=="function";function ec(t,e){const n=new Blob([JSON.stringify(e)],{type:"text/plain"});return window.navigator.sendBeacon(t,n)}const tc=R("Web:Network");function nc(t){if(!x)return()=>{};const e=i=>{(async()=>{try{await t(i)}catch(o){tc.error("Error in online state callback:",o)}})()},n=()=>{e(!0)},r=()=>{e(!1)};return window.addEventListener("online",n),window.addEventListener("offline",r),e(typeof navigator.onLine=="boolean"?navigator.onLine:!0),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}const rc=R("Web:Visibility");function ic(t){if(!x)return()=>{};let e=!1;const n=a=>{e||(e=!0,(async()=>{try{await t(a)}catch(c){rc.error("Error handling page visibility change:",c)}})())},r=()=>{e=!1},i=a=>{document.visibilityState==="hidden"?n(a):r()},o=a=>{n(a)},s=()=>{r()};return document.addEventListener("visibilitychange",i),window.addEventListener("pagehide",o),window.addEventListener("pageshow",s),()=>{document.removeEventListener("visibilitychange",i),window.removeEventListener("pagehide",o),window.removeEventListener("pageshow",s)}}const De=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),Be=()=>x?document.visibilityState==="visible":!0,ce={DWELL_MS:1e3,RATIO:.1,MAX_RETRIES:2,BACKOFF_MS:300,MULTIPLIER:2,JITTER_DIVISOR:2,SWEEP_INTERVAL_MS:3e4},oc=t=>t+Math.floor(Math.random()*Math.max(1,Math.floor(t/ce.JITTER_DIVISOR))),N={n:(t,e)=>typeof t=="number"?t:e,clamp01:(t,e)=>Math.min(1,Math.max(0,N.n(t,e))),nonNeg:(t,e)=>Math.max(0,N.n(t,e)),atLeast1:(t,e)=>Math.max(1,N.n(t,e))},ue=t=>{t.fireTimer!==null&&(clearTimeout(t.fireTimer),t.fireTimer=null)},le=t=>{t.retryTimer!==null&&(clearTimeout(t.retryTimer),t.retryTimer=null),t.retryScheduledAt=null},Xt=t=>{if(t.ref&&typeof t.ref.deref=="function"){const e=t.ref.deref();if(e)return e}return t.strongRef??null},Or=100,Mr=250,sc=16,ac=1,cc=x&&typeof MutationObserver<"u",xr=x&&typeof window.requestIdleCallback=="function",uc=x&&typeof window.cancelIdleCallback=="function";class Z{observer;root;idleTimeoutMs;maxChunk;onChange;onAdded;onRemoved;onError;pendingRecords=[];scheduled=!1;idleHandle=null;disconnected=!1;constructor(e={}){const{root:n,idleTimeoutMs:r=Or,maxChunk:i=Mr,onChange:o,onAdded:s,onRemoved:a,onError:c}=e;this.root=Z.isNode(n)?n:x?document:null,this.idleTimeoutMs=Z.sanitizeInt(r,Or,sc),this.maxChunk=Z.sanitizeInt(i,Mr,ac),this.onChange=o,this.onAdded=s,this.onRemoved=a,this.onError=c,cc&&this.root&&(this.observer=new MutationObserver(u=>{for(const d of u)(d.addedNodes.length>0||d.removedNodes.length>0)&&this.pendingRecords.push(d);this.pendingRecords.length>0&&this.scheduleProcess()}),this.observer.observe(this.root,{childList:!0,subtree:!0}))}isActive(){return!!this.observer&&!this.disconnected}disconnect(){this.disconnected||(this.disconnected=!0,this.observer?.disconnect(),this.pendingRecords=[],this.idleHandle!==null&&(Z.cancelIdle(this.idleHandle),this.idleHandle=null),this.scheduled=!1)}flush(){this.isActive()&&(this.idleHandle!==null&&(Z.cancelIdle(this.idleHandle),this.idleHandle=null),!(!this.scheduled&&this.pendingRecords.length===0)&&(this.scheduled=!1,this.processNow()))}scheduleProcess(){if(!this.isActive()||this.scheduled)return;this.scheduled=!0;const e=()=>{this.idleHandle=null,this.scheduled=!1,this.processNow()};this.idleHandle=xr?window.requestIdleCallback(e,{timeout:this.idleTimeoutMs}):window.setTimeout(e,this.idleTimeoutMs)}processNow(){if(!this.isActive()||this.pendingRecords.length===0)return;const e=this.drainPending(),{addedNodes:n,removedNodes:r}=Z.coalesce(e),{added:i,removed:o}=Z.toElementSets(n,r);i.size===0&&o.size===0||(this.deliverAggregate(i,o,e),this.deliverPerKind(o,i))}static isNode(e){return x&&typeof Node<"u"&&e instanceof Node}static sanitizeInt(e,n,r){if(typeof e!="number"||!Number.isFinite(e))return n;const i=Math.trunc(e);return i>=r?i:r}static coalesce(e){const n=new Set,r=new Set;for(const i of e){for(const o of i.addedNodes)r.delete(o)||n.add(o);for(const o of i.removedNodes)n.delete(o)||r.add(o)}return{addedNodes:n,removedNodes:r}}static toElementSets(e,n){const r=Z.flattenElements(e,!0),i=Z.flattenElements(n,!1);return{added:r,removed:i}}static flattenElements(e,n){const r=new Set;for(const i of e){if(i instanceof Element){(!n||i.isConnected)&&r.add(i),i.querySelectorAll("*").forEach(o=>{(!n||o.isConnected)&&r.add(o)});continue}i instanceof DocumentFragment&&i.querySelectorAll("*").forEach(o=>{(!n||o.isConnected)&&r.add(o)})}return r}static cancelIdle(e){uc?window.cancelIdleCallback(e):x&&window.clearTimeout(e)}drainPending(){const{pendingRecords:e}=this;return this.pendingRecords=[],e}deliverAggregate(e,n,r){if(!this.onChange)return;const i={added:e,removed:n,records:r};this.safeCall(()=>this.onChange?.(i))}deliverPerKind(e,n){const r=e.size>0?[...e]:[],i=n.size>0?[...n]:[];this.onRemoved&&r.length>0&&this.dispatchChunked(r,this.onRemoved),this.onAdded&&i.length>0&&this.dispatchChunked(i,this.onAdded)}dispatchChunked(e,n){if(!this.isActive()||e.length===0)return;if(e.length<=this.maxChunk){this.safeCall(()=>n(e));return}let r=0;const i=()=>{if(!this.isActive())return;const o=Math.min(e.length,r+this.maxChunk),s=e.slice(r,o);r=o,this.safeCall(()=>n(s)),r<e.length&&(xr?window.requestIdleCallback(i,{timeout:this.idleTimeoutMs}):x&&window.setTimeout(i,this.idleTimeoutMs))};i()}safeCall(e){try{const n=e();Promise.resolve(n).catch(r=>{this.onError?.(r)})}catch(n){this.onError?.(n)}}}class Fe{callback;opts;io;states=new WeakMap;activeStates=new Set;boundVisibilityHandler=null;sweepInterval=null;constructor(e,n){this.callback=e,this.opts=Fe.initOptions(n),this.io=new IntersectionObserver(r=>{this.onIntersect(r)},{root:this.opts.root??null,rootMargin:this.opts.rootMargin,threshold:this.opts.minVisibleRatio===0?[0]:[0,this.opts.minVisibleRatio]}),x&&(this.boundVisibilityHandler=()=>{this.onPageVisibilityChange()},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}observe(e,n){let r=this.states.get(e);r||(r=this.createState(e,n),this.states.set(e,r),this.activeStates.add(r),this.ensureSweeper()),this.io.observe(e)}unobserve(e){this.io.unobserve(e);const n=this.states.get(e);n&&(ue(n),le(n),n.done=!0,this.activeStates.delete(n),n.strongRef===e&&(n.strongRef=null),this.states.delete(e),this.maybeStopSweeper())}disconnect(){this.io.disconnect();for(const e of this.activeStates)ue(e),le(e),e.done=!0,e.strongRef=null;this.activeStates.clear(),x&&this.boundVisibilityHandler&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null),this.stopSweeper()}getStats(e){const n=this.states.get(e);return n?{accumulatedMs:n.accumulatedMs,visibleSince:n.visibleSince,attempts:n.attempts,done:n.done,inFlight:n.inFlight,pendingRetry:n.pendingRetry,lastKnownVisible:n.lastKnownVisible}:null}static initOptions(e){return{dwellTimeMs:N.nonNeg(e?.dwellTimeMs,ce.DWELL_MS),minVisibleRatio:N.clamp01(e?.minVisibleRatio,ce.RATIO),root:e?.root??null,rootMargin:e?.rootMargin??"0px",maxRetries:N.nonNeg(e?.maxRetries,ce.MAX_RETRIES),retryBackoffMs:N.nonNeg(e?.retryBackoffMs,ce.BACKOFF_MS),backoffMultiplier:N.atLeast1(e?.backoffMultiplier,ce.MULTIPLIER)}}createState(e,n){const r={dwellTimeMs:N.nonNeg(n?.dwellTimeMs,this.opts.dwellTimeMs),maxRetries:N.nonNeg(n?.maxRetries,this.opts.maxRetries),retryBackoffMs:N.nonNeg(n?.retryBackoffMs,this.opts.retryBackoffMs),backoffMultiplier:N.atLeast1(n?.backoffMultiplier,this.opts.backoffMultiplier)},i=typeof WeakRef=="function";return{ref:i?new WeakRef(e):null,strongRef:i?null:e,opts:r,data:n?.data,accumulatedMs:0,visibleSince:null,fireTimer:null,retryTimer:null,retryScheduledAt:null,retryDelayMs:null,pendingRetry:!1,attempts:0,done:!1,inFlight:!1,lastKnownVisible:!1}}onPageVisibilityChange(){const e=De(),n=!Be();for(const r of this.activeStates)n?Fe.onHidden(r,e):this.onResume(r,e);this.sweepOrphans()}static onHidden(e,n){if(!e.done&&(e.visibleSince!==null&&(e.accumulatedMs+=n-e.visibleSince,e.visibleSince=null),ue(e),e.retryTimer!==null)){const r=e.retryScheduledAt?n-e.retryScheduledAt:0,i=e.retryDelayMs!==null?Math.max(0,e.retryDelayMs-r):null;le(e),i!==null&&(e.pendingRetry=!0,e.retryDelayMs=i,e.retryScheduledAt=null)}}onResume(e,n){e.done||(e.lastKnownVisible&&e.visibleSince===null&&(e.visibleSince=n,this.scheduleFireIfDue(e,n)),e.pendingRetry&&!e.inFlight&&e.lastKnownVisible&&e.retryDelayMs!==null&&this.scheduleRetry(e,e.retryDelayMs))}onIntersect(e){const n=De();for(const r of e){const i=this.states.get(r.target);if(!i||i.done)continue;r.isIntersecting&&r.intersectionRatio>=this.opts.minVisibleRatio&&Be()?this.onVisible(i,n):Fe.onNotVisible(i,n)}this.sweepOrphans()}onVisible(e,n){if(e.lastKnownVisible=!0,e.visibleSince===null){e.visibleSince=n,e.attempts=0,e.pendingRetry&&!e.inFlight&&e.retryDelayMs!==null?this.scheduleRetry(e,e.retryDelayMs):this.scheduleFireIfDue(e,n);return}!e.pendingRetry&&e.fireTimer===null&&!e.inFlight&&this.scheduleFireIfDue(e,n)}static onNotVisible(e,n){e.lastKnownVisible=!1,e.visibleSince!==null&&(e.accumulatedMs+=n-e.visibleSince,e.visibleSince=null),ue(e),(e.pendingRetry||e.retryTimer!==null)&&(le(e),e.pendingRetry=!1,e.attempts=0)}scheduleFireIfDue(e,n){if(e.done||e.inFlight||e.fireTimer!==null||e.pendingRetry)return;const r=e.accumulatedMs+(e.visibleSince!==null?n-e.visibleSince:0),i=e.opts.dwellTimeMs-r;if(i<=0){this.trigger(e);return}e.fireTimer=setTimeout(()=>{!e.done&&e.lastKnownVisible&&Be()?this.trigger(e):ue(e)},Math.ceil(i))}scheduleRetry(e,n){e.pendingRetry=!0,e.retryDelayMs=Math.max(0,Math.ceil(n)),!(!Be()||!e.lastKnownVisible||e.done||e.inFlight)&&(e.retryScheduledAt=De(),e.retryTimer=setTimeout(()=>{e.retryTimer=null,e.retryScheduledAt=null,this.attemptCallback(e)},e.retryDelayMs))}trigger(e){if(e.done||e.inFlight)return;const n=De(),r=e.accumulatedMs+(e.visibleSince!==null?n-e.visibleSince:0);le(e),e.pendingRetry=!1,ue(e),this.attemptCallback(e,r)}async attemptCallback(e,n){if(e.done||e.inFlight)return;const r=Xt(e);if(!r){this.finalizeDroppedState(e);return}const i=e.attempts+1;e.attempts=i,e.inFlight=!0;const o=n??e.accumulatedMs+(e.visibleSince!==null?De()-e.visibleSince:0);try{await this.callback(r,{totalVisibleMs:o,attempts:i,data:e.data}),this.onAttemptSuccess(e,r)}catch{this.onAttemptFailure(e)}}onAttemptSuccess(e,n){e.inFlight=!1,e.done=!0,this.safeAutoUnobserve(n,e)}onAttemptFailure(e){if(e.inFlight=!1,e.attempts>e.opts.maxRetries){this.onRetriesExceeded(e);return}const n=e.opts.retryBackoffMs*Math.pow(e.opts.backoffMultiplier,e.attempts-1),r=oc(n);if(!e.lastKnownVisible||!Be()){e.pendingRetry=!0,e.retryDelayMs=Math.ceil(r),e.retryScheduledAt=null;return}this.scheduleRetry(e,r)}onRetriesExceeded(e){le(e),e.pendingRetry=!1,e.done=!0;const n=Xt(e);n?this.safeAutoUnobserve(n,e):this.finalizeDroppedState(e)}finalizeDroppedState(e){ue(e),le(e),e.done=!0,this.activeStates.delete(e),e.strongRef&&(this.states.delete(e.strongRef),e.strongRef=null),this.maybeStopSweeper()}safeAutoUnobserve(e,n){try{this.unobserve(e)}catch{this.activeStates.delete(n),n.strongRef===e&&(this.states.delete(e),n.strongRef=null),n.done=!0,this.maybeStopSweeper()}}ensureSweeper(){this.sweepInterval===null&&(this.sweepInterval=setInterval(()=>{this.sweepOrphans()},ce.SWEEP_INTERVAL_MS))}stopSweeper(){this.sweepInterval!==null&&(clearInterval(this.sweepInterval),this.sweepInterval=null)}maybeStopSweeper(){this.activeStates.size===0&&this.stopSweeper()}sweepOrphans(){if(x){for(const e of Array.from(this.activeStates)){const n=Xt(e);if(!n){this.finalizeDroppedState(e);continue}(typeof n.isConnected=="boolean"?n.isConnected:document.contains(n))||this.safeAutoUnobserve(n,e)}this.maybeStopSweeper()}}}const E={reset(t={resetConsent:!1,resetDebug:!1}){t.resetConsent&&localStorage.removeItem(Ft),t.resetDebug&&localStorage.removeItem(Ht),localStorage.removeItem(Bt),localStorage.removeItem(qt),localStorage.removeItem(Kt),localStorage.removeItem(Wt)},get anonymousId(){const t=localStorage.getItem(mr);return t&&localStorage.removeItem(mr),t??localStorage.getItem(Bt)??void 0},set anonymousId(t){E.setCache(Bt,t)},get consent(){switch(localStorage.getItem(Ft)){case"accepted":return!0;case"denied":return!1}},set consent(t){const e=t?"accepted":"denied";E.setCache(Ft,t===void 0?void 0:e)},get debug(){const t=localStorage.getItem(Ht);return t?t==="true":void 0},set debug(t){E.setCache(Ht,t)},get changes(){return E.getCache(qt,Mn)},set changes(t){E.setCache(qt,t)},get profile(){return E.getCache(Kt,rt)},set profile(t){E.setCache(Kt,t)},get personalizations(){return E.getCache(Wt,Fn)},set personalizations(t){E.setCache(Wt,t)},getCache(t,e){const n=localStorage.getItem(t);if(!n)return;const r=e.safeParse(JSON.parse(n));if(r.success)return r.data},setCache(t,e){e===void 0?localStorage.removeItem(t):localStorage.setItem(t,typeof e=="string"?e:JSON.stringify(e))}},en=R("Web:SDK"),lc=365;function dc({app:t,defaults:e,logLevel:n,...r}){const{consent:i=E.consent,profile:o=E.profile,changes:s=E.changes,personalizations:a=E.personalizations}=e??{};return Se({analytics:{beaconHandler:ec},defaults:{consent:i,changes:s,profile:o,personalizations:a},eventBuilder:{app:t,channel:"web",library:{name:"Optimization Web SDK",version:Xa},getLocale:Ga,getPageProperties:Ja,getUserAgent:Qa},getAnonymousId:()=>E.anonymousId,logLevel:E.debug?"debug":n},r)}class fc extends Da{elementViewObserver=void 0;elementExistenceObserver=void 0;autoTrackEntryViews=!1;cookieAttributes=void 0;constructor(e){if(typeof window<"u"&&window.optimization)throw new Error("Optimization is already initialized");const{autoTrackEntryViews:n,...r}=e,i=dc(r);super(i);const o=Te.get(yr),s=o??Te.get(lt);this.autoTrackEntryViews=!0,this.cookieAttributes={domain:i.cookie?.domain,expires:i.cookie?.expires??lc},nc(a=>{this.online(a)}),ic(async()=>{await this.flush()}),O(()=>{const{changes:{value:a}}=Le;E.changes=a}),O(()=>{const{consent:{value:a}}=Le;this.autoTrackEntryViews&&(a?this.startAutoTrackingEntryViews():this.stopAutoTrackingEntryViews()),E.consent=a}),O(()=>{const{profile:{value:a}}=Le;E.profile=a,this.setAnonymousId(a?.id)}),O(()=>{const{personalizations:{value:a}}=Le;E.personalizations=a}),this.initializeFromCookieValues(s,o),typeof window<"u"&&(window.optimization??=this)}initializeFromCookieValues(e,n){n&&Te.remove(yr),e&&e!==E.anonymousId&&(this.reset(),this.setAnonymousId(e))}setAnonymousId(e){if(!e){Te.remove(lt),E.anonymousId=void 0;return}Te.set(lt,e,this.cookieAttributes),E.anonymousId=e}startAutoTrackingEntryViews(e){this.autoTrackEntryViews=!0,this.elementViewObserver=new Fe(Ha(this)),this.elementExistenceObserver=new Z(Ka(this.elementViewObserver,!0)),document.querySelectorAll("[data-ctfl-entry-id]").forEach(r=>{Ze(r)&&(en.info("Auto-observing element (init):",r),this.elementViewObserver?.observe(r,{...e}))})}stopAutoTrackingEntryViews(){this.elementExistenceObserver?.disconnect(),this.elementViewObserver?.disconnect()}trackEntryViewForElement(e,n){en.info("Manually observing element:",e),this.elementViewObserver?.observe(e,n)}untrackEntryViewForElement(e){en.info("Manually unobserving element:",e),this.elementViewObserver?.unobserve(e)}reset(){this.stopAutoTrackingEntryViews(),Te.remove(lt),E.reset(),super.reset()}}return fc});
|
|
2
|
+
//# sourceMappingURL=contentful-optimization-web.umd.cjs.map
|
package/dist/dev.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../src/dev.ts"],"names":[],"mappings":""}
|