@walkeros/web-destination-optimizely 3.4.0-next-1776749829492
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 +121 -0
- package/dist/dev.d.mts +193 -0
- package/dist/dev.d.ts +193 -0
- package/dist/dev.js +1 -0
- package/dist/dev.js.map +1 -0
- package/dist/dev.mjs +1 -0
- package/dist/dev.mjs.map +1 -0
- package/dist/examples/index.d.mts +152 -0
- package/dist/examples/index.d.ts +152 -0
- package/dist/examples/index.js +228 -0
- package/dist/examples/index.mjs +206 -0
- package/dist/index.browser.js +1 -0
- package/dist/index.d.mts +111 -0
- package/dist/index.d.ts +111 -0
- package/dist/index.es5.js +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -0
- package/dist/walkerOS.json +641 -0
- package/package.json +78 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __export = (target, all) => {
|
|
3
|
+
for (var name in all)
|
|
4
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
// src/examples/env.ts
|
|
8
|
+
var env_exports = {};
|
|
9
|
+
__export(env_exports, {
|
|
10
|
+
init: () => init,
|
|
11
|
+
push: () => push,
|
|
12
|
+
simulation: () => simulation
|
|
13
|
+
});
|
|
14
|
+
var noop = () => {
|
|
15
|
+
};
|
|
16
|
+
function createMockUserContext() {
|
|
17
|
+
return {
|
|
18
|
+
trackEvent: noop,
|
|
19
|
+
setAttribute: noop
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function createMockClient() {
|
|
23
|
+
return {
|
|
24
|
+
onReady: (() => Promise.resolve({ success: true })),
|
|
25
|
+
createUserContext: (() => createMockUserContext()),
|
|
26
|
+
close: noop
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function createMockSDK() {
|
|
30
|
+
return {
|
|
31
|
+
createInstance: (() => createMockClient()),
|
|
32
|
+
createPollingProjectConfigManager: (() => ({})),
|
|
33
|
+
createBatchEventProcessor: (() => ({}))
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
var init = {
|
|
37
|
+
optimizely: createMockSDK()
|
|
38
|
+
};
|
|
39
|
+
var push = {
|
|
40
|
+
optimizely: createMockSDK()
|
|
41
|
+
};
|
|
42
|
+
var simulation = [
|
|
43
|
+
"call:optimizely.createInstance",
|
|
44
|
+
"call:optimizely.client.onReady",
|
|
45
|
+
"call:optimizely.client.createUserContext",
|
|
46
|
+
"call:optimizely.userContext.trackEvent",
|
|
47
|
+
"call:optimizely.userContext.setAttribute",
|
|
48
|
+
"call:optimizely.client.close"
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
// src/examples/step.ts
|
|
52
|
+
var step_exports = {};
|
|
53
|
+
__export(step_exports, {
|
|
54
|
+
attributesOnlySkipTrack: () => attributesOnlySkipTrack,
|
|
55
|
+
consentGranted: () => consentGranted,
|
|
56
|
+
consentRevoked: () => consentRevoked,
|
|
57
|
+
defaultEventForwarding: () => defaultEventForwarding,
|
|
58
|
+
mappedEventName: () => mappedEventName,
|
|
59
|
+
orderCompleteRevenue: () => orderCompleteRevenue,
|
|
60
|
+
signupWithAttributes: () => signupWithAttributes,
|
|
61
|
+
wildcardIgnored: () => wildcardIgnored
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// ../../../core/dist/index.mjs
|
|
65
|
+
var e = Object.defineProperty;
|
|
66
|
+
var c = {};
|
|
67
|
+
((t, n) => {
|
|
68
|
+
for (var o in n) e(t, o, { get: n[o], enumerable: true });
|
|
69
|
+
})(c, { Level: () => u });
|
|
70
|
+
var u = ((e2) => (e2[e2.ERROR = 0] = "ERROR", e2[e2.WARN = 1] = "WARN", e2[e2.INFO = 2] = "INFO", e2[e2.DEBUG = 3] = "DEBUG", e2))(u || {});
|
|
71
|
+
var W = { merge: true, shallow: true, extend: true };
|
|
72
|
+
function L(e2, t = {}, n = {}) {
|
|
73
|
+
n = { ...W, ...n };
|
|
74
|
+
const o = Object.entries(t).reduce((t2, [o2, r]) => {
|
|
75
|
+
const i = e2[o2];
|
|
76
|
+
return n.merge && Array.isArray(i) && Array.isArray(r) ? t2[o2] = r.reduce((e3, t3) => e3.includes(t3) ? e3 : [...e3, t3], [...i]) : (n.extend || o2 in e2) && (t2[o2] = r), t2;
|
|
77
|
+
}, {});
|
|
78
|
+
return n.shallow ? { ...e2, ...o } : (Object.assign(e2, o), e2);
|
|
79
|
+
}
|
|
80
|
+
function fe(e2 = {}) {
|
|
81
|
+
var _a;
|
|
82
|
+
const t = e2.timestamp || (/* @__PURE__ */ new Date()).setHours(0, 13, 37, 0), n = e2.group || "gr0up", o = e2.count || 1, r = L({ name: "entity action", data: { string: "foo", number: 1, boolean: true, array: [0, "text", false], not: void 0 }, context: { dev: ["test", 1] }, globals: { lang: "elb" }, custom: { completely: "random" }, user: { id: "us3r", device: "c00k13", session: "s3ss10n" }, nested: [{ entity: "child", data: { is: "subordinated" }, nested: [], context: { element: ["child", 0] } }], consent: { functional: true }, id: `${t}-${n}-${o}`, trigger: "test", entity: "entity", action: "action", timestamp: t, timing: 3.14, group: n, count: o, version: { source: "3.4.0-next-1776749829492", tagging: 1 }, source: { type: "web", id: "https://localhost:80", previous_id: "http://remotehost:9001" } }, e2, { merge: false });
|
|
83
|
+
if (e2.name) {
|
|
84
|
+
const [t2, n2] = (_a = e2.name.split(" ")) != null ? _a : [];
|
|
85
|
+
t2 && n2 && (r.entity = t2, r.action = n2);
|
|
86
|
+
}
|
|
87
|
+
return r;
|
|
88
|
+
}
|
|
89
|
+
function le(e2 = "entity action", t = {}) {
|
|
90
|
+
const n = t.timestamp || (/* @__PURE__ */ new Date()).setHours(0, 13, 37, 0), o = { data: { id: "ers", name: "Everyday Ruck Snack", color: "black", size: "l", price: 420 } }, r = { data: { id: "cc", name: "Cool Cap", size: "one size", price: 42 } };
|
|
91
|
+
return fe({ ...{ "cart view": { data: { currency: "EUR", value: 2 * o.data.price }, context: { shopping: ["cart", 0] }, globals: { pagegroup: "shop" }, nested: [{ entity: "product", data: { ...o.data, quantity: 2 }, context: { shopping: ["cart", 0] }, nested: [] }], trigger: "load" }, "checkout view": { data: { step: "payment", currency: "EUR", value: o.data.price + r.data.price }, context: { shopping: ["checkout", 0] }, globals: { pagegroup: "shop" }, nested: [{ entity: "product", ...o, context: { shopping: ["checkout", 0] }, nested: [] }, { entity: "product", ...r, context: { shopping: ["checkout", 0] }, nested: [] }], trigger: "load" }, "order complete": { data: { id: "0rd3r1d", currency: "EUR", shipping: 5.22, taxes: 73.76, total: 555 }, context: { shopping: ["complete", 0] }, globals: { pagegroup: "shop" }, nested: [{ entity: "product", ...o, context: { shopping: ["complete", 0] }, nested: [] }, { entity: "product", ...r, context: { shopping: ["complete", 0] }, nested: [] }, { entity: "gift", data: { name: "Surprise" }, context: { shopping: ["complete", 0] }, nested: [] }], trigger: "load" }, "page view": { data: { domain: "www.example.com", title: "walkerOS documentation", referrer: "https://www.walkeros.io/", search: "?foo=bar", hash: "#hash", id: "/docs/" }, globals: { pagegroup: "docs" }, trigger: "load" }, "product add": { ...o, context: { shopping: ["intent", 0] }, globals: { pagegroup: "shop" }, nested: [], trigger: "click" }, "product view": { ...o, context: { shopping: ["detail", 0] }, globals: { pagegroup: "shop" }, nested: [], trigger: "load" }, "product visible": { data: { ...o.data, position: 3, promo: true }, context: { shopping: ["discover", 0] }, globals: { pagegroup: "shop" }, nested: [], trigger: "load" }, "promotion visible": { data: { name: "Setting up tracking easily", position: "hero" }, context: { ab_test: ["engagement", 0] }, globals: { pagegroup: "homepage" }, trigger: "visible" }, "session start": { data: { id: "s3ss10n", start: n, isNew: true, count: 1, runs: 1, isStart: true, storage: true, referrer: "", device: "c00k13" }, user: { id: "us3r", device: "c00k13", session: "s3ss10n", hash: "h4sh", address: "street number", email: "user@example.com", phone: "+49 123 456 789", userAgent: "Mozilla...", browser: "Chrome", browserVersion: "90", deviceType: "desktop", language: "de-DE", country: "DE", region: "HH", city: "Hamburg", zip: "20354", timezone: "Berlin", os: "walkerOS", osVersion: "1.0", screenSize: "1337x420", ip: "127.0.0.0", internal: true, custom: "value" } } }[e2], ...t, name: e2 });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/examples/step.ts
|
|
95
|
+
var defaultEventForwarding = {
|
|
96
|
+
in: le("page view", { timestamp: 1700000100 }),
|
|
97
|
+
out: [["optimizely.trackEvent", "page view", {}]]
|
|
98
|
+
};
|
|
99
|
+
var mappedEventName = {
|
|
100
|
+
in: le("product view", { timestamp: 1700000101 }),
|
|
101
|
+
mapping: {
|
|
102
|
+
name: "product_viewed"
|
|
103
|
+
},
|
|
104
|
+
out: [["optimizely.trackEvent", "product_viewed", {}]]
|
|
105
|
+
};
|
|
106
|
+
var orderCompleteRevenue = {
|
|
107
|
+
in: le("order complete", {
|
|
108
|
+
timestamp: 1700000102,
|
|
109
|
+
data: {
|
|
110
|
+
revenue_cents: 55500,
|
|
111
|
+
total: 555,
|
|
112
|
+
currency: "EUR",
|
|
113
|
+
item_count: 3
|
|
114
|
+
}
|
|
115
|
+
}),
|
|
116
|
+
mapping: {
|
|
117
|
+
name: "purchase",
|
|
118
|
+
settings: {
|
|
119
|
+
revenue: "data.revenue_cents",
|
|
120
|
+
value: "data.total",
|
|
121
|
+
eventTags: {
|
|
122
|
+
map: {
|
|
123
|
+
currency: "data.currency",
|
|
124
|
+
item_count: "data.item_count"
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
out: [
|
|
130
|
+
[
|
|
131
|
+
"optimizely.trackEvent",
|
|
132
|
+
"purchase",
|
|
133
|
+
{ revenue: 55500, value: 555, currency: "EUR", item_count: 3 }
|
|
134
|
+
]
|
|
135
|
+
]
|
|
136
|
+
};
|
|
137
|
+
var signupWithAttributes = {
|
|
138
|
+
in: le("user signup", {
|
|
139
|
+
timestamp: 1700000103,
|
|
140
|
+
data: {
|
|
141
|
+
method: "google",
|
|
142
|
+
source: "referral"
|
|
143
|
+
}
|
|
144
|
+
}),
|
|
145
|
+
mapping: {
|
|
146
|
+
name: "signup",
|
|
147
|
+
settings: {
|
|
148
|
+
attributes: {
|
|
149
|
+
map: {
|
|
150
|
+
signup_method: "data.method",
|
|
151
|
+
referral_source: "data.source"
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
out: [
|
|
157
|
+
["optimizely.setAttribute", "signup_method", "google"],
|
|
158
|
+
["optimizely.setAttribute", "referral_source", "referral"],
|
|
159
|
+
["optimizely.trackEvent", "signup", {}]
|
|
160
|
+
]
|
|
161
|
+
};
|
|
162
|
+
var wildcardIgnored = {
|
|
163
|
+
in: le("debug noise", { timestamp: 1700000104 }),
|
|
164
|
+
mapping: { ignore: true },
|
|
165
|
+
out: []
|
|
166
|
+
};
|
|
167
|
+
var attributesOnlySkipTrack = {
|
|
168
|
+
in: le("profile update", {
|
|
169
|
+
timestamp: 1700000105,
|
|
170
|
+
data: {
|
|
171
|
+
plan: "premium",
|
|
172
|
+
country: "DE"
|
|
173
|
+
}
|
|
174
|
+
}),
|
|
175
|
+
mapping: {
|
|
176
|
+
skip: true,
|
|
177
|
+
settings: {
|
|
178
|
+
attributes: {
|
|
179
|
+
map: {
|
|
180
|
+
plan: "data.plan",
|
|
181
|
+
country: "data.country"
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
},
|
|
186
|
+
out: [
|
|
187
|
+
["optimizely.setAttribute", "plan", "premium"],
|
|
188
|
+
["optimizely.setAttribute", "country", "DE"]
|
|
189
|
+
]
|
|
190
|
+
};
|
|
191
|
+
var consentRevoked = {
|
|
192
|
+
command: "consent",
|
|
193
|
+
in: { analytics: false },
|
|
194
|
+
settings: {},
|
|
195
|
+
out: [["optimizely.close"]]
|
|
196
|
+
};
|
|
197
|
+
var consentGranted = {
|
|
198
|
+
command: "consent",
|
|
199
|
+
in: { analytics: true },
|
|
200
|
+
settings: {},
|
|
201
|
+
out: []
|
|
202
|
+
};
|
|
203
|
+
export {
|
|
204
|
+
env_exports as env,
|
|
205
|
+
step_exports as step
|
|
206
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var Destination=(()=>{var e=Object.create,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,o=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),a=(e,t)=>function(){return t||(0,e[i(e)[0]])((t={exports:{}}).exports,t),t.exports},l=(e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})},u=(e,n,o,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let l of i(n))s.call(e,l)||l===o||t(e,l,{get:()=>n[l],enumerable:!(a=r(n,l))||a.enumerable});return e},c=(r,i,s)=>(s=null!=r?e(n(r)):{},u(!i&&r&&r.__esModule?s:t(s,"default",{value:r,enumerable:!0}),r)),d=a({"../../../../node_modules/json-schema/lib/validate.js"(e,t){var r,i;r=e,i=function(){var e=r;e.Integer={type:"integer"};var t={String:String,Boolean:Boolean,Number:Number,Object:Object,Array:Array,Date:Date};function r(e,t){return r(e,t,{changing:!1})}e.validate=r,e.checkPropertyChange=function(e,t,i){return r(e,t,{changing:i||"property"})};var r=e._validate=function(e,r,i){i||(i={});var n=i.changing;function s(e){return e.type||t[e.name]==e&&e.name.toLowerCase()}var o=[];function a(e,t,r,l){var u;function c(e){o.push({property:r,message:e})}if(r+=r?"number"==typeof l?"["+l+"]":void 0===l?"":"."+l:l,("object"!=typeof t||t instanceof Array)&&(r||"function"!=typeof t)&&(!t||!s(t)))return"function"==typeof t?e instanceof t||c("is not an instance of the class/constructor "+t.name):t&&c("Invalid schema/property definition "+t),null;function d(e,t){if(e){if(!("string"!=typeof e||"any"==e||("null"==e?null===t:typeof t==e)||t instanceof Array&&"array"==e||t instanceof Date&&"date"==e||"integer"==e&&t%1==0))return[{property:r,message:t+" - "+typeof t+" value found, but a "+e+" is required"}];if(e instanceof Array){for(var i=[],n=0;n<e.length&&(i=d(e[n],t)).length;n++);if(i.length)return i}else if("object"==typeof e){var s=o;o=[],a(t,e,r);var l=o;return o=s,l}}return[]}if(n&&t.readonly&&c("is a readonly field, it can not be changed"),t.extends&&a(e,t.extends,r,l),void 0===e)t.required&&c("is missing and it is required");else if(o=o.concat(d(s(t),e)),t.disallow&&!d(t.disallow,e).length&&c(" disallowed value was matched"),null!==e){if(e instanceof Array){if(t.items){var h=t.items instanceof Array,g=t.items;for(l=0,u=e.length;l<u;l+=1)h&&(g=t.items[l]),i.coerce&&(e[l]=i.coerce(e[l],g)),o.concat(a(e[l],g,r,l))}t.minItems&&e.length<t.minItems&&c("There must be a minimum of "+t.minItems+" in the array"),t.maxItems&&e.length>t.maxItems&&c("There must be a maximum of "+t.maxItems+" in the array")}else(t.properties||t.additionalProperties)&&o.concat(function(e,t,r,s){if("object"==typeof t)for(var l in("object"!=typeof e||e instanceof Array)&&o.push({property:r,message:"an object is required"}),t)if(t.hasOwnProperty(l)&&"__proto__"!=l&&"constructor"!=l){var u=e.hasOwnProperty(l)?e[l]:void 0;if(void 0===u&&i.existingOnly)continue;var c=t[l];void 0===u&&c.default&&(u=e[l]=c.default),i.coerce&&l in e&&(u=e[l]=i.coerce(u,c)),a(u,c,r,l)}for(l in e){if(e.hasOwnProperty(l)&&("_"!=l.charAt(0)||"_"!=l.charAt(1))&&t&&!t[l]&&!1===s){if(i.filter){delete e[l];continue}o.push({property:r,message:"The property "+l+" is not defined in the schema and the schema does not allow additional properties"})}var d=t&&t[l]&&t[l].requires;d&&!(d in e)&&o.push({property:r,message:"the presence of the property "+l+" requires that "+d+" also be present"}),u=e[l],!s||t&&"object"==typeof t&&l in t||(i.coerce&&(u=e[l]=i.coerce(u,s)),a(u,s,r,l)),!n&&u&&u.$schema&&(o=o.concat(a(u,u.$schema,r,l)))}return o}(e,t.properties,r,t.additionalProperties));if(t.pattern&&"string"==typeof e&&!e.match(t.pattern)&&c("does not match the regex pattern "+t.pattern),t.maxLength&&"string"==typeof e&&e.length>t.maxLength&&c("may only be "+t.maxLength+" characters long"),t.minLength&&"string"==typeof e&&e.length<t.minLength&&c("must be at least "+t.minLength+" characters long"),void 0!==t.minimum&&typeof e==typeof t.minimum&&t.minimum>e&&c("must have a minimum value of "+t.minimum),void 0!==t.maximum&&typeof e==typeof t.maximum&&t.maximum<e&&c("must have a maximum value of "+t.maximum),t.enum){var p,f=t.enum;u=f.length;for(var v=0;v<u;v++)if(f[v]===e){p=1;break}p||c("does not have a value in the enumeration "+f.join(", "))}"number"==typeof t.maxDecimal&&e.toString().match(new RegExp("\\.[0-9]{"+(t.maxDecimal+1)+",}"))&&c("may only have "+t.maxDecimal+" digits of decimal places")}return null}return r&&a(e,r,"",n||""),!n&&e&&e.$schema&&a(e,e.$schema,"",""),{valid:!o.length,errors:o}};return e.mustBeValid=function(e){if(!e.valid)throw new TypeError(e.errors.map(function(e){return"for property "+e.property+": "+e.message}).join(", \n"))},e},"function"==typeof define&&define.amd?define([],function(){return i()}):"object"==typeof t&&t.exports?t.exports=i():r.jsonSchema=i()}}),h=a({"../../../../node_modules/murmurhash/murmurhash.js"(e,t){!function(){const e=this,r=e=>(new TextEncoder).encode(e);function i(e,t){let i,n,s,o,a,l,u,c;for("string"==typeof e&&(e=r(e)),i=3&e.length,n=e.length-i,s=t,a=3432918353,l=461845907,c=0;c<n;)u=255&e[c]|(255&e[++c])<<8|(255&e[++c])<<16|(255&e[++c])<<24,++c,u=(65535&u)*a+(((u>>>16)*a&65535)<<16)&4294967295,u=u<<15|u>>>17,u=(65535&u)*l+(((u>>>16)*l&65535)<<16)&4294967295,s^=u,s=s<<13|s>>>19,o=5*(65535&s)+((5*(s>>>16)&65535)<<16)&4294967295,s=27492+(65535&o)+(((o>>>16)+58964&65535)<<16);switch(u=0,i){case 3:u^=(255&e[c+2])<<16;case 2:u^=(255&e[c+1])<<8;case 1:u^=255&e[c],u=(65535&u)*a+(((u>>>16)*a&65535)<<16)&4294967295,u=u<<15|u>>>17,u=(65535&u)*l+(((u>>>16)*l&65535)<<16)&4294967295,s^=u}return s^=e.length,s^=s>>>16,s=2246822507*(65535&s)+((2246822507*(s>>>16)&65535)<<16)&4294967295,s^=s>>>13,s=3266489909*(65535&s)+((3266489909*(s>>>16)&65535)<<16)&4294967295,s^=s>>>16,s>>>0}const n=i;if(n.v2=function(e,t){"string"==typeof e&&(e=r(e));let i,n=e.length,s=t^n,o=0;for(;n>=4;)i=255&e[o]|(255&e[++o])<<8|(255&e[++o])<<16|(255&e[++o])<<24,i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16),i^=i>>>24,i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16),s=1540483477*(65535&s)+((1540483477*(s>>>16)&65535)<<16)^i,n-=4,++o;switch(n){case 3:s^=(255&e[o+2])<<16;case 2:s^=(255&e[o+1])<<8;case 1:s^=255&e[o],s=1540483477*(65535&s)+((1540483477*(s>>>16)&65535)<<16)}return s^=s>>>13,s=1540483477*(65535&s)+((1540483477*(s>>>16)&65535)<<16),s^=s>>>15,s>>>0},n.v3=i,void 0!==t)t.exports=n;else{const t=e.murmur;n.noConflict=function(){return e.murmur=t,n},e.murmur=n}}()}}),g=a({"../../../../node_modules/@optimizely/optimizely-sdk/node_modules/mimic-response/index.js"(e,t){var r=["aborted","complete","headers","httpVersion","httpVersionMinor","httpVersionMajor","method","rawHeaders","rawTrailers","setTimeout","socket","statusCode","statusMessage","trailers","url"];t.exports=(e,t)=>{if(t._readableState.autoDestroy)throw new Error("The second stream must have the `autoDestroy` option set to `false`");const i=new Set(Object.keys(e).concat(r)),n={};for(const r of i)r in t||(n[r]={get(){const t=e[r];return"function"==typeof t?t.bind(e):t},set(t){e[r]=t},enumerable:!0,configurable:!1});return Object.defineProperties(t,n),e.once("aborted",()=>{t.destroy(),t.emit("aborted")}),e.once("close",()=>{e.complete&&t.readable?t.once("end",()=>{t.emit("close")}):t.emit("close")}),t}}}),p=a({"../../../../node_modules/@optimizely/optimizely-sdk/node_modules/decompress-response/index.js"(e,t){var{Transform:r,PassThrough:i}=o("stream"),n=o("zlib"),s=g();t.exports=e=>{const t=(e.headers["content-encoding"]||"").toLowerCase();if(delete e.headers["content-encoding"],!["gzip","deflate","br"].includes(t))return e;const o="br"===t;if(o&&"function"!=typeof n.createBrotliDecompress)return e.destroy(new Error("Brotli is not supported on Node.js < 12")),e;let a=!0;const l=new r({transform(e,t,r){a=!1,r(null,e)},flush(e){e()}}),u=new i({autoDestroy:!1,destroy(t,r){e.destroy(),r(t)}}),c=o?n.createBrotliDecompress():n.createUnzip();return c.once("error",t=>{!a||e.readable?u.destroy(t):u.end()}),s(e,u),e.pipe(l).pipe(c).pipe(u),u}}}),f={};l(f,{DestinationOptimizely:()=>tn,default:()=>sn,destinationOptimizely:()=>nn});var v=Object.defineProperty;((e,t)=>{for(var r in t)v(e,r,{get:t[r],enumerable:!0})})({},{Level:()=>y});var m,y=((m=y||{})[m.ERROR=0]="ERROR",m[m.WARN=1]="WARN",m[m.INFO=2]="INFO",m[m.DEBUG=3]="DEBUG",m);function b(e){return Array.isArray(e)}function E(e){return void 0!==e}function I(e){return"number"==typeof e&&!Number.isNaN(e)}function S(e){return"object"==typeof e&&null!==e&&!b(e)&&"[object Object]"===Object.prototype.toString.call(e)}function x(e){return"string"==typeof e}function w(e,t="",r){const i=t.split(".");let n=e;for(let e=0;e<i.length;e++){const t=i[e];if("*"===t&&b(n)){const t=i.slice(e+1).join("."),s=[];for(const e of n){const i=w(e,t,r);s.push(i)}return s}if(n=n instanceof Object?n[t]:void 0,void 0===n)break}return E(n)?n:r}function O(e){return function(e){return"boolean"==typeof e}(e)||x(e)||I(e)||!E(e)||b(e)&&e.every(O)||S(e)&&Object.values(e).every(O)}function k(e){return O(e)?e:void 0}function M(e,t,r){return async function(...i){try{return await e(...i)}catch(e){if(!t)return;return await t(e)}finally{await(null==r?void 0:r())}}}async function R(e,t={},r={}){var i;if(!E(e))return;const n=S(e)&&e.consent||r.consent||(null==(i=r.collector)?void 0:i.consent),s=b(t)?t:[t];for(const t of s){const i=await M(C)(e,t,{...r,consent:n});if(E(i))return i}}async function C(e,t,r={}){const{collector:i,consent:n}=r;return(b(t)?t:[t]).reduce(async(t,s)=>{const o=await t;if(o)return o;const a=x(s)?{key:s}:s;if(!Object.keys(a).length)return;const{condition:l,consent:u,fn:c,key:d,loop:h,map:g,set:p,validate:f,value:v}=a;if(l&&!await M(l)(e,s,i))return;if(u&&!function(e,t={},r={}){const i={...t,...r},n={};let s=!e||0===Object.keys(e).length;return Object.keys(i).forEach(t=>{i[t]&&(n[t]=!0,e&&e[t]&&(s=!0))}),!!s&&n}(u,n))return v;let m=E(v)?v:e;if(c&&(m=await M(c)(e,s,r)),d&&(m=w(e,d,v)),h){const[t,i]=h,n="this"===t?[e]:await R(e,t,r);b(n)&&(m=(await Promise.all(n.map(e=>R(e,i,r)))).filter(E))}else g?m=await Object.entries(g).reduce(async(t,[i,n])=>{const s=await t,o=await R(e,n,r);return E(o)&&(s[i]=o),s},Promise.resolve({})):p&&(m=await Promise.all(p.map(t=>C(e,t,r))));f&&!await M(f)(m)&&(m=void 0);const y=k(m);return E(y)?y:k(v)},Promise.resolve(void 0))}var P={};l(P,{DEBUG:()=>_e,DECISION_NOTIFICATION_TYPES:()=>qt,DECISION_SOURCES:()=>Q,ERROR:()=>Ve,INFO:()=>Ne,LogLevel:()=>N,NOTIFICATION_TYPES:()=>Bt,OptimizelyDecideOption:()=>Kt,WARN:()=>Ue,__platforms:()=>en,clientEngine:()=>Zi,createBatchEventProcessor:()=>Gi,createErrorNotifier:()=>ze,createForwardingEventProcessor:()=>Ji,createInstance:()=>Yi,createLogger:()=>Ke,createOdpManager:()=>Wi,createPollingProjectConfigManager:()=>$i,createStaticProjectConfigManager:()=>xt,createVuidManager:()=>Qi,eventDispatcher:()=>Hi,getSendBeaconEventDispatcher:()=>Xi});var A=[];for(let e=0;e<256;++e)A.push((e+256).toString(16).slice(1));var j=c(o("crypto")),D=new Uint8Array(256),T=D.length;function F(){return T>D.length-16&&(j.default.randomFillSync(D),T=0),D.slice(T,T+=16)}var _={randomUUID:c(o("crypto")).default.randomUUID};var N,U=function(e,t,r){if(_.randomUUID&&!t&&!e)return _.randomUUID();const i=(e=e||{}).random||(e.rng||F)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return(A[e[t+0]]+A[e[t+1]]+A[e[t+2]]+A[e[t+3]]+"-"+A[e[t+4]]+A[e[t+5]]+"-"+A[e[t+6]]+A[e[t+7]]+"-"+A[e[t+8]]+A[e[t+9]]+"-"+A[e[t+10]]+A[e[t+11]]+A[e[t+12]]+A[e[t+13]]+A[e[t+14]]+A[e[t+15]]).toLowerCase()}(i)},V=c(d(),1),L=c(h(),1),K=c(o("http"),1),q=c(o("https"),1),B=c(o("url"),1),z=c(p(),1),H="$opt_bot_filtering",$="$opt_bucketing_id",J="javascript-sdk",G="node-sdk",W="6.3.1",Q={FEATURE_TEST:"feature-test",ROLLOUT:"rollout",EXPERIMENT:"experiment",HOLDOUT:"holdout"},Y="experiment",X="boolean",Z="double",ee="integer",te="string",re="json",ie="Optimizely SDK not configured properly yet.",ne=Math.pow(2,53);function se(e){return"number"==typeof e&&Math.abs(e)<=ne}function oe(e,t){if(!e)return{};const r={};return ae(e,t,r),r}function ae(e,t,r){e&&e.forEach(e=>{r[e[t]]=e})}function le(e){return Object.keys(e).map(t=>e[t])}function ue(e){return Object.keys(e).map(t=>[t,e[t]])}function ce(e,t){let r;for(const i of e)if(t(i)){r=i;break}return r}function de(e,...t){let r=0;return e.replace(/%s/g,function(){const e=t[r++],i=typeof e;return"function"===i?e():"string"===i?e:String(e)})}function he(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}var ge={checkArrayEquality:he,currentTimestamp:function(){return Math.round((new Date).getTime())},isSafeInteger:se,keyBy:oe,uuid:function(){return U()},isNumber:function(e){return"number"==typeof e},getTimestamp:function(){return(new Date).getTime()},groupBy:function(e,t){const r={};return e.forEach(e=>{const i=t(e);r[i]=r[i]||[],r[i].push(e)}),le(r)},objectValues:le,objectEntries:ue,find:ce,sprintf:de},pe=class e extends Error{constructor(t,...r){super(),this.resolved=!1,this.name="OptimizelyError",this.baseMessage=t,this.params=r,Object.setPrototypeOf(this,e.prototype)}setMessage(e){this.resolved||(this.message=de(e.resolve(this.baseMessage),...this.params),this.resolved=!0)}};!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(N||(N={}));var fe={[N.Debug]:"DEBUG",[N.Info]:"INFO",[N.Warn]:"WARN",[N.Error]:"ERROR"},ve={[N.Debug]:"debug",[N.Info]:"info",[N.Warn]:"warn",[N.Error]:"error"},me=class{constructor(e){this.prefix=e||"[OPTIMIZELY]"}log(e,t){const r=`${this.prefix} - ${fe[e]} ${this.getTime()} ${t}`;this.consoleLog(e,r)}getTime(){return(new Date).toISOString()}consoleLog(e,t){(console[ve[e]]||console.log).call(console,t)}},ye=class e{constructor(e){this.prefix="",this.logHandler=e.logHandler,this.infoResolver=e.infoMsgResolver,this.errorResolver=e.errorMsgResolver,this.level=e.level,e.name&&this.setName(e.name)}child(t){return new e({logHandler:this.logHandler,infoMsgResolver:this.infoResolver,errorMsgResolver:this.errorResolver,level:this.level,name:t})}setName(e){this.name=e,this.prefix=`${e}: `}info(e,...t){this.log(N.Info,e,t)}debug(e,...t){this.log(N.Debug,e,t)}warn(e,...t){this.log(N.Warn,e,t)}error(e,...t){this.log(N.Error,e,t)}handleLog(e,t,r){const i=r.length>0?`${this.prefix}${de(t,...r)}`:`${this.prefix}${t}`;this.logHandler.log(e,i)}log(e,t,r){if(e<this.level)return;if(t instanceof Error)return t instanceof pe&&t.setMessage(this.errorResolver),void this.handleLog(e,t.message,[]);let i=this.errorResolver;if(e<N.Warn){if(!this.infoResolver)return;i=this.infoResolver}const n=i.resolve(t);this.handleLog(e,n,r)}},be="30",Ee=["Adding Authorization header with Bearer Token",'Audience "%s" evaluated to %s.',"CMAB cache attributes mismatch for user %s and rule %s, fetching new decision.","Cache hit for user %s and rule %s.","Cache miss for user %s and rule %s.",'Starting to evaluate audience "%s" with conditions: %s.','Failed to parse revenue value "%s" from event tags.','Failed to parse event value "%s" from event tags.',"Feature %s is enabled for user %s.","Feature %s is not enabled for user %s.",'Feature "%s" is not enabled for user %s. Returning the default variable value "%s".',"Ignoring CMAB cache for user %s and rule %s.","Invalidating CMAB cache for user %s and rule %s.","Invalid client engine passed: %s. Defaulting to node-sdk.","Provided decide options is not an array. Using default decide options.","Provided default decide options is not an array.","Experiment key %s is not in datafile. It is either invalid, paused, or archived.","Making datafile request to url %s with headers: %s",'Audience condition %s evaluated to UNKNOWN because no value was passed for user attribute "%s".',"Not activating user %s for experiment %s.",'Parsed event value "%s" from event tags.','Parsed revenue value "%s" from event tags.',"Resetting CMAB cache for user %s and rule %s.","Response status code: %s","Saved last modified header value from response: %s",'Saved user profile for user "%s".',"User %s was previously bucketed into variation with ID %s for experiment %s, but no matching variation was found.",'Experiment %s is not in "Running" state. Not activating user.',"Skipping JSON schema validation.","Tracking event %s for user %s.",'Audience condition %s evaluated to UNKNOWN because a null value was passed for user attribute "%s".',"Updated Optimizely config to revision %s (project id %s)","User %s is not in the forced variation map.","No experiment %s mapped to user %s in the forced variation map.","Set variation %s for experiment %s and user %s in the forced variation map.",'User "%s" is not in any variation or rollout rule. Returning default value for variable "%s" of feature flag "%s".','Got variable value "%s" for variable "%s" of feature flag "%s"','BucketingId is valid: "%s"',"Datafile is valid.","Valid user profile service provided.",'Variable "%s" is not used in variation "%s". Returning default value.',"Variation mapped to experiment %s has been removed for user %s."],Ie="12",Se="27",xe="35",we="53",Oe="57",ke="59",Me="61",Re=["BucketingID attribute is not a string. Defaulted to userId","CMAB decision fetch failed with status: %s","Error evaluating audience condition of type %s: %s","Datafile fetch request failed with status: %s","Error fetching datafile: %s","Event action invalid.","Event data invalid.","Event key %s is not in datafile.","Event store is full. Not saving event with id %d.","Experiment key %s is not in datafile.","Failed to dispatch events, status: %s","failed to send odp events","Feature key %s is not in datafile.","Provided attributes are in an invalid format.","Unable to generate hash for bucketing ID %s: %s","Invalid CMAB fetch response","Provided Optimizely config is in an invalid format.","Datafile is invalid - property %s: %s","Datafile is invalid because it is malformed.","This version of the JavaScript SDK does not support the given datafile version: %s","Provided event tags are in an invalid format.","Experiment ID %s is not in datafile.","Experiment key %s is not in datafile. It is either invalid, paused, or archived.","Group ID %s is not in datafile.","Provided %s is in an invalid format.","JSON object is not valid.","Provided user ID is in an invalid format.","Provided user profile service instance is in an invalid format: %s.","Provided variation key is in an invalid format.","Integration key missing from datafile. All integrations should include a key.","Notification listener for (%s) threw exception: %s","Not tracking user %s.","No datafile specified. Cannot start optimizely.","No event processor is provided","No JSON object to validate against schema.","No project config available. Failing %s.","No status code in response","No variation key %s defined in datafile for experiment %s.","ODP config is not available.","ODP events should have at least one key-value pair in identifiers.","ODP event send failed.","ODP event manager stopped before it could start","ODP Manager is missing. %s failed.","ODP is not integrated","Only POST requests are supported",'Audience condition %s evaluated to UNKNOWN because the number value for user attribute "%s" is not in the range [-2^53, +2^53].',"Promise value is not allowed in sync operation","Request error","Request timeout","Retry cancelled","sendBeacon failed","%s not running",'unable to bind optimizely.close() to page unload event: "%s"',"Unable to cast value %s to type %s, returning null.","Unable to get VUID - VuidManager is not available","Unable to parse & skipped header item","Provided attribute: %s has an undefined value.","Audience condition %s evaluated to UNKNOWN because the condition value is not supported.","Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.",'Audience condition %s evaluated to UNKNOWN because a value of type "%s" was passed for user attribute "%s".',"Audience condition %s has an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK.","Audience condition %s uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK.","Unrecognized attribute %s provided. Pruning before sending event to Optimizely.","Unrecognized decide option %s provided.","Unsupported protocol: %s","User %s is not in the forced variation map. Cannot remove their forced variation.",'Error while looking up user profile for user ID "%s": %s.','Error while saving user profile for user ID "%s": %s.','Variable with key "%s" associated with feature with key "%s" is not in datafile.','Requested variable type "%s", but variable is of type "%s". Use correct API to retrieve value. Returning None.',"Variation ID %s is not in the datafile."],Ce={resolve(e){const t=parseInt(e);return Ee[t]||e}},Pe={resolve(e){const t=parseInt(e);return Re[t]||e}},Ae={level:N.Debug,infoResolver:Ce,errorResolver:Pe},je={level:N.Info,infoResolver:Ce,errorResolver:Pe},De={level:N.Warn,errorResolver:Pe},Te={level:N.Error,errorResolver:Pe},Fe=Symbol(),_e={[Fe]:Ae},Ne={[Fe]:je},Ue={[Fe]:De},Ve={[Fe]:Te},Le=Symbol(),Ke=e=>{const{level:t,infoResolver:r,errorResolver:i}=(e=>{if(!e||"object"!=typeof e||!e[Fe])throw new Error("Invalid level preset");return e[Fe]})(e.level);return e.logHandler&&(e=>{if("object"!=typeof e||"function"!=typeof e.log)throw new Error("Invalid log handler")})(e.logHandler),{[Le]:new ye({name:"Optimizely",level:t,infoMsgResolver:r,errorMsgResolver:i,logHandler:e.logHandler||new me})}},qe=class e{constructor(e,t,r){this.errorHandler=e,this.messageResolver=t,this.name=r||""}notify(e){e instanceof pe&&e.setMessage(this.messageResolver),this.errorHandler.handleError(e)}child(t){return new e(this.errorHandler,this.messageResolver,t)}},Be=Symbol(),ze=e=>((e=>{if(!e||"object"!=typeof e||"function"!=typeof e.handleError)throw new Error("Invalid error handler")})(e),{[Be]:new qe(e,Pe)}),He=["and","or","not"];function $e(e,t){if(Array.isArray(e)){let r=e[0],i=e.slice(1);switch("string"==typeof r&&-1===He.indexOf(r)&&(r="or",i=e),r){case"and":return function(e,t){let r=!1;if(Array.isArray(e)){for(let i=0;i<e.length;i++){const n=$e(e[i],t);if(!1===n)return!1;null===n&&(r=!0)}return!r||null}return null}(i,t);case"not":return function(e,t){if(Array.isArray(e)&&e.length>0){const r=$e(e[0],t);return null===r?null:!r}return null}(i,t);default:return function(e,t){let r=!1;if(Array.isArray(e)){for(let i=0;i<e.length;i++){const n=$e(e[i],t);if(!0===n)return!0;null===n&&(r=!0)}return!!r&&null}return null}(i,t)}}return t(e)}var Je=class e{constructor(t,r,i){var n,s;this.sdkKey=null!==(n=t.sdkKey)&&void 0!==n?n:"",this.environmentKey=null!==(s=t.environmentKey)&&void 0!==s?s:"",this.attributes=t.attributes,this.audiences=e.getAudiences(t),this.events=t.events,this.revision=t.revision;const o=(t.featureFlags||[]).reduce((e,t)=>(e[t.id]=t.variables,e),{}),a=e.getVariableIdMap(t),{experimentsMapById:l,experimentsMapByKey:u}=e.getExperimentsMap(t,o,a,i);this.experimentsMap=u,this.featuresMap=e.getFeaturesMap(t,o,l,a),this.datafile=r}getDatafile(){return this.datafile}static getAudiences(e){const t=[],r=[];return(e.typedAudiences||[]).forEach(e=>{t.push({id:e.id,conditions:JSON.stringify(e.conditions),name:e.name}),r.push(e.id)}),(e.audiences||[]).forEach(e=>{-1===r.indexOf(e.id)&&"$opt_dummy_audience"!=e.id&&t.push({id:e.id,conditions:JSON.stringify(e.conditions),name:e.name})}),t}static getSerializedAudiences(t,r){let i="";if(t){let n="";t.forEach(t=>{let s="";if(t instanceof Array)s=e.getSerializedAudiences(t,r),s=`(${s})`;else if(He.indexOf(t)>-1)n=t.toUpperCase();else{const e=r[t]?r[t].name:t;i||"NOT"===n?(n=""===n?"OR":n,i=""===i?`${n} "${r[t].name}"`:i.concat(` ${n} "${e}"`)):i=`"${e}"`}""!==s&&(""!==i||"NOT"===n?(n=""===n?"OR":n,i=""===i?`${n} ${s}`:i.concat(` ${n} ${s}`)):i=i.concat(s))})}return i}static getExperimentAudiences(t,r){return t.audienceConditions?e.getSerializedAudiences(t.audienceConditions,r.audiencesById):""}static mergeFeatureVariables(e,t,r,i,n){const s=(e[r]||[]).reduce((e,t)=>(e[t.key]={id:t.id,key:t.key,type:t.type,value:t.defaultValue},e),{});return(i||[]).forEach(e=>{const r=t[e.id],i={id:e.id,key:r.key,type:r.type,value:n?e.value:r.defaultValue};s[r.key]=i}),s}static getVariationsMap(t,r,i,n){let s={};return s=t.reduce((t,s)=>{const o=e.mergeFeatureVariables(r,i,n,s.variables,s.featureEnabled);return t[s.key]={id:s.id,key:s.key,featureEnabled:s.featureEnabled,variablesMap:o},t},{}),s}static getVariableIdMap(e){let t={};return t=(e.featureFlags||[]).reduce((e,t)=>(t.variables.forEach(t=>{e[t.id]=t}),e),{}),t}static getDeliveryRules(t,r,i,n,s){return n.map(n=>({id:n.id,key:n.key,audiences:e.getExperimentAudiences(n,t),variationsMap:e.getVariationsMap(n.variations,r,s,i)}))}static getRolloutExperimentIds(e){const t=[];return(e||[]).forEach(e=>{e.experiments.forEach(e=>{t.push(e.id)})}),t}static getExperimentsMap(t,r,i,n){const s=this.getRolloutExperimentIds(t.rollouts),o={},a={};return(t.experiments||[]).forEach(l=>{if(-1!==s.indexOf(l.id))return;const u=t.experimentFeatureMap[l.id];let c="";u&&u.length>0&&(c=u[0]);const d=e.getVariationsMap(l.variations,r,i,c.toString()),h={id:l.id,key:l.key,audiences:e.getExperimentAudiences(l,t),variationsMap:d};o[l.id]=h,a[l.key]&&n&&n.warn(`Duplicate experiment keys found in datafile: ${l.key}`),a[l.key]=h}),{experimentsMapById:o,experimentsMapByKey:a}}static getExperimentsKeyMap(e){const t={};for(const r in e){const i=e[r];t[i.key]=i}return t}static getFeaturesMap(t,r,i,n){const s={};return t.featureFlags.forEach(o=>{const a={},l=[];o.experimentIds.forEach(e=>{const t=i[e];t&&(a[t.key]=t),l.push(i[e])});const u=(o.variables||[]).reduce((e,t)=>(e[t.key]={id:t.id,key:t.key,type:t.type,value:t.defaultValue},e),{});let c=[];const d=t.rolloutIdMap[o.rolloutId];d&&(c=e.getDeliveryRules(t,r,o.id,d.experiments,n)),s[o.key]={id:o.id,key:o.key,experimentRules:l,deliveryRules:c,experimentsMap:a,variablesMap:u}}),s}},Ge=["2","3","4"],We=class{constructor(e,t,r,i){this.apiKey=e,this.apiHost=t,this.pixelUrl=r,this.segmentsToCheck=i}equals(e){return this.apiHost===e.apiHost&&this.apiKey===e.apiKey&&this.pixelUrl===e.pixelUrl&&he(this.segmentsToCheck,e.segmentsToCheck)}},Qe="Running",Ye="$opt_",Xe=e=>{e.holdouts=e.holdouts||[],e.holdoutIdMap=oe(e.holdouts,"id"),e.globalHoldouts=[],e.includedHoldouts={},e.excludedHoldouts={},e.flagHoldoutsMap={};const t=oe(e.featureFlags,"id");e.holdouts.forEach(r=>{r.includedFlags||(r.includedFlags=[]),r.excludedFlags||(r.excludedFlags=[]),r.variationKeyMap=oe(r.variations,"key"),ae(r.variations,"id",e.variationIdMap),0===r.includedFlags.length?(e.globalHoldouts.push(r),r.excludedFlags.forEach(i=>{const n=t[i];if(n){const t=n.key;e.excludedHoldouts[t]||(e.excludedHoldouts[t]=[]),e.excludedHoldouts[t].push(r)}})):r.includedFlags.forEach(i=>{const n=t[i];if(n){const t=n.key;e.includedHoldouts[t]||(e.includedHoldouts[t]=[]),e.includedHoldouts[t].push(r)}})})},Ze=function(e){return e.conditions?et(e.conditions):[]},et=e=>{const t=[];return["and","or","not"].includes(e)?[]:(Array.isArray(e)?e.forEach(e=>t.push(...et(e))):"qualified"===e.match&&t.push(e.value),t)},tt=function(e,t){const r=e.experimentKeyMap[t];if(!r)throw new pe("22",t);return r.status},rt=function(e,t){if(e.experimentKeyMap.hasOwnProperty(t)){const r=e.experimentKeyMap[t];if(r)return r}throw new pe("9",t)},it=function(e,t,r){if(!e)return null;return ce(e.flagVariationsMap[t],e=>e.key===r)||null},nt=function(e,t,r){if(e.featureKeyMap.hasOwnProperty(t)){const r=e.featureKeyMap[t];if(r)return r}return null==r||r.error(Ie,t),null},st=function(e){return!!e.sendFlagDecisions},ot=()=>{};function at(){let e=ot,t=ot;const r=new Promise((r,i)=>{e=r,t=i});return{promise:r,resolve:e,reject:t,then:r.then.bind(r)}}var lt,ut="%s failed to start, reason: %s",ct="%s stopped before running";!function(e){e[e.New=0]="New",e[e.Starting=1]="Starting",e[e.Running=2]="Running",e[e.Stopping=3]="Stopping",e[e.Terminated=4]="Terminated",e[e.Failed=5]="Failed"}(lt||(lt={}));var dt=class{constructor(e=[]){this.disposable=!1,this.state=lt.New,this.startPromise=at(),this.stopPromise=at(),this.startupLogs=e,this.startPromise.promise.catch(()=>{}),this.stopPromise.promise.catch(()=>{})}makeDisposable(){this.disposable=!0}setLogger(e){this.logger=e}printStartupLogs(){if(this.logger)for(const{level:e,message:t,params:r}of this.startupLogs){const i=ve[e];this.logger[i].call(this.logger,t,...r)}}onRunning(){return this.startPromise.promise}onTerminated(){return this.stopPromise.promise}getState(){return this.state}isStarting(){return this.state===lt.Starting}isRunning(){return this.state===lt.Running}isNew(){return this.state===lt.New}isDone(){return[lt.Stopping,lt.Terminated,lt.Failed].includes(this.state)}start(){this.printStartupLogs()}},ht=class{constructor(){this.id=0,this.listeners={}}on(e,t){var r;this.listeners[e]||(this.listeners[e]=new Map);const i=this.id++;return null===(r=this.listeners[e])||void 0===r||r.set(i,t),()=>{var t;null===(t=this.listeners[e])||void 0===t||t.delete(i)}}emit(e,t){const r=this.listeners[e];r&&r.forEach(e=>{e(t)})}removeListeners(e){var t;null===(t=this.listeners[e])||void 0===t||t.clear()}removeAllListeners(){this.listeners={}}},gt=class extends dt{constructor(e){super(),this.eventEmitter=new ht,this.jsonSchemaValidator=e.jsonSchemaValidator,this.datafile=e.datafile,this.datafileManager=e.datafileManager,e.logger&&this.setLogger(e.logger)}setLogger(e){var t;this.logger=e,this.logger.setName("ProjectConfigManager"),null===(t=this.datafileManager)||void 0===t||t.setLogger(e.child())}start(){var e,t,r;this.isNew()&&(this.state=lt.Starting,this.datafile||this.datafileManager?(this.datafile&&this.handleNewDatafile(this.datafile,!0),null===(e=this.datafileManager)||void 0===e||e.start(),null===(t=this.datafileManager)||void 0===t||t.onUpdate(this.handleNewDatafile.bind(this)),null===(r=this.datafileManager)||void 0===r||r.onRunning().catch(e=>{this.handleDatafileManagerError(e)})):this.handleInitError(new Error("sdkKey or datafile must be provided")))}makeDisposable(){var e;super.makeDisposable(),null===(e=this.datafileManager)||void 0===e||e.makeDisposable()}handleInitError(e){var t,r;null===(t=this.logger)||void 0===t||t.error(e),this.state=lt.Failed,null===(r=this.datafileManager)||void 0===r||r.stop(),this.startPromise.reject(e),this.stopPromise.reject(e)}handleDatafileManagerError(e){var t;null===(t=this.logger)||void 0===t||t.error(ut,"DatafileManager",e.message),this.isStarting()&&this.handleInitError(new Error(de(ut,"DatafileManager",e.message)))}handleNewDatafile(e,t=!1){var r,i;if(!this.isDone())try{const t=function(e){var t,r;const i=function(e){if(!e)throw new pe("32");if("string"==typeof e)try{e=JSON.parse(e)}catch(e){throw new pe("18")}if("object"!=typeof e||Array.isArray(e)||null===e)throw new pe("18");if(-1===Ge.indexOf(e.version))throw new pe("19",e.version);return e}(e.datafile);e.jsonSchemaValidator?(e.jsonSchemaValidator(i),null===(t=e.logger)||void 0===t||t.info("38")):null===(r=e.logger)||void 0===r||r.info("28");const n=[i];return"string"==typeof e.datafile&&n.push(e.datafile),function(e,t=null){const r=function(e){var t,r;const i=Object.assign({},e);return i.audiences=(e.audiences||[]).map(e=>Object.assign({},e)),i.experiments=(e.experiments||[]).map(e=>Object.assign({},e)),i.featureFlags=(e.featureFlags||[]).map(e=>Object.assign({},e)),i.groups=(e.groups||[]).map(e=>{const t=Object.assign({},e);return t.experiments=(e.experiments||[]).map(e=>Object.assign({},e)),t}),i.rollouts=(e.rollouts||[]).map(e=>{const t=Object.assign({},e);return t.experiments=(e.experiments||[]).map(e=>Object.assign({},e)),t}),i.environmentKey=null!==(t=e.environmentKey)&&void 0!==t?t:"",i.sdkKey=null!==(r=e.sdkKey)&&void 0!==r?r:"",i}(e);let i;r.region||(r.region="US"),r.__datafileStr=null===t?JSON.stringify(e):t,(r.audiences||[]).forEach(e=>{e.conditions=JSON.parse(e.conditions)}),r.audiencesById={},ae(r.audiences,"id",r.audiencesById),ae(r.typedAudiences,"id",r.audiencesById),r.attributes=r.attributes||[],r.attributeKeyMap={},r.attributeIdMap={},r.attributes.forEach(e=>{r.attributeKeyMap[e.key]=e,r.attributeIdMap[e.id]=e}),r.eventKeyMap=oe(r.events,"key"),r.groupIdMap=oe(r.groups,"id"),Object.keys(r.groupIdMap||{}).forEach(e=>{i=r.groupIdMap[e].experiments,(i||[]).forEach(t=>{t.groupId=e,r.experiments.push(t)})}),r.rolloutIdMap=oe(r.rollouts||[],"id"),le(r.rolloutIdMap||{}).forEach(e=>{(e.experiments||[]).forEach(e=>{e.isRollout=!0,r.experiments.push(e),e.variationKeyMap=oe(e.variations,"key")})});const n=new Set;Object.keys(r.audiencesById).map(e=>Ze(r.audiencesById[e])).forEach(e=>{e.forEach(e=>{n.add(e)})});const s=Array.from(n);let o=!1,a="",l="",u="";return r.integrations&&(r.integrationKeyMap=oe(r.integrations,"key"),r.integrations.forEach(e=>{if(!("key"in e))throw new pe("29");"odp"===e.key&&(o=!0,l=l||e.publicKey||"",a=a||e.host||"",u=u||e.pixelUrl||"")})),r.odpIntegrationConfig=o?{integrated:!0,odpConfig:new We(l,a,u,s)}:{integrated:!1},r.experimentKeyMap=oe(r.experiments,"key"),r.experimentIdMap=oe(r.experiments,"id"),r.variationIdMap={},r.variationVariableUsageMap={},(r.experiments||[]).forEach(e=>{e.variationKeyMap=oe(e.variations,"key"),ae(e.variations,"id",r.variationIdMap),le(e.variationKeyMap||{}).forEach(e=>{e.variables&&(r.variationVariableUsageMap[e.id]=oe(e.variables,"id"))})}),r.experimentFeatureMap={},r.featureKeyMap=oe(r.featureFlags||[],"key"),le(r.featureKeyMap||{}).forEach(e=>{e.variables.forEach(e=>{e.type===te&&e.subType===re&&(e.type=re,delete e.subType)}),e.variableKeyMap=oe(e.variables,"key"),(e.experimentIds||[]).forEach(t=>{r.experimentFeatureMap[t]?r.experimentFeatureMap[t].push(e.id):r.experimentFeatureMap[t]=[e.id]})}),r.flagRulesMap={},(r.featureFlags||[]).forEach(e=>{const t=[];e.experimentIds.forEach(e=>{const i=r.experimentIdMap[e];i&&t.push(i)});const i=r.rolloutIdMap[e.rolloutId];i&&t.push(...i.experiments),r.flagRulesMap[e.key]=t}),r.flagVariationsMap={},ue(r.flagRulesMap||{}).forEach(([e,t])=>{const i=[];t.forEach(e=>{e.variations.forEach(e=>{ce(i,t=>t.id===e.id)||i.push(e)})}),r.flagVariationsMap[e]=i}),Xe(r),r}(...n)}({datafile:e,jsonSchemaValidator:this.jsonSchemaValidator,logger:this.logger});this.isStarting()&&(this.state=lt.Running,this.startPromise.resolve()),(null===(r=this.projectConfig)||void 0===r?void 0:r.revision)!==t.revision&&(this.projectConfig=t,this.optimizelyConfig=void 0,this.eventEmitter.emit("update",t))}catch(e){null===(i=this.logger)||void 0===i||i.error(e),(this.isStarting()&&!this.datafileManager||this.isStarting()&&!t)&&this.handleInitError(new Error("got invalid datafile"))}}getConfig(){return this.projectConfig}getOptimizelyConfig(){var e,t,r;return!this.optimizelyConfig&&this.projectConfig&&(this.optimizelyConfig=(e=this.projectConfig,t=this.projectConfig.__datafileStr,r=this.logger,new Je(e,t,r))),this.optimizelyConfig}onUpdate(e){return this.eventEmitter.on("update",e)}stop(){if(!this.isDone()){if((this.isNew()||this.isStarting())&&this.startPromise.reject(new Error(de(ct,"ProjectConfigManager"))),this.state=lt.Stopping,this.eventEmitter.removeAllListeners(),!this.datafileManager)return this.state=lt.Terminated,void this.stopPromise.resolve();this.datafileManager.stop(),this.datafileManager.onTerminated().then(()=>{this.state=lt.Terminated,this.stopPromise.resolve()}).catch(e=>{this.state=lt.Failed,this.stopPromise.reject(e)})}}};function pt(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}l((i=i.apply(e,t||[])).next())})}var ft=e=>e>=200&&e<400,vt=class extends dt{constructor(e){super(e.startupLogs);const{autoUpdate:t=!1,sdkKey:r,datafileAccessToken:i,customHeaders:n,urlTemplate:s,cache:o,initRetry:a,repeater:l,requestHandler:u,logger:c}=e;this.cache=o,this.cacheKey="opt-datafile-"+r,this.sdkKey=r,this.datafileAccessToken=i,this.customHeaders=n,this.requestHandler=u,this.emitter=new ht,this.autoUpdate=t,this.initRetryRemaining=a,this.repeater=l,c&&this.setLogger(c);const d=s||(i?"https://config.optimizely.com/datafiles/auth/%s.json":"https://cdn.optimizely.com/datafiles/%s.json");this.datafileUrl=de(d,this.sdkKey)}setLogger(e){this.logger=e,this.logger.setName("PollingDatafileManager")}onUpdate(e){return this.emitter.on("update",e)}get(){return this.currentDatafile}start(){this.isNew()&&(super.start(),this.state=lt.Starting,this.setDatafileFromCacheIfAvailable(),this.repeater.setTask(this.syncDatafile.bind(this)),this.repeater.start(!0))}makeDisposable(){var e;super.makeDisposable(),this.initRetryRemaining=Math.min(null!==(e=this.initRetryRemaining)&&void 0!==e?e:5,5)}stop(){var e;this.isDone()||((this.isNew()||this.isStarting())&&this.startPromise.reject(new Error(de(ct,"PollingDatafileManager"))),this.state=lt.Terminated,this.repeater.stop(),null===(e=this.currentRequest)||void 0===e||e.abort(),this.emitter.removeAllListeners(),this.stopPromise.resolve())}handleInitFailure(){this.state=lt.Failed,this.repeater.stop();const e=new Error("Failed to fetch datafile");this.startPromise.reject(e),this.stopPromise.reject(e)}handleError(e){var t,r;this.isDone()||(e instanceof Error?null===(t=this.logger)||void 0===t||t.error("4",e.message,e):null===(r=this.logger)||void 0===r||r.error("3",e),this.isStarting()&&void 0!==this.initRetryRemaining&&(0===this.initRetryRemaining?this.handleInitFailure():this.initRetryRemaining--))}onRequestRejected(e){return pt(this,void 0,void 0,function*(){return this.handleError(e),Promise.reject(e)})}onRequestResolved(e){return pt(this,void 0,void 0,function*(){if(this.isDone())return;if(this.saveLastModified(e.headers),!ft(e.statusCode))return this.handleError(e.statusCode),Promise.reject(new Error);const t=this.getDatafileFromResponse(e);t&&(this.handleDatafile(t),this.autoUpdate&&!this.disposable||this.repeater.stop())})}makeDatafileRequest(){var e,t;const r=Object.assign({},this.customHeaders);return this.lastResponseLastModified&&(r["if-modified-since"]=this.lastResponseLastModified),this.datafileAccessToken&&(null===(e=this.logger)||void 0===e||e.debug("0"),r.Authorization=`Bearer ${this.datafileAccessToken}`),null===(t=this.logger)||void 0===t||t.debug("17",this.datafileUrl,()=>JSON.stringify(r)),this.requestHandler.makeRequest(this.datafileUrl,r,"GET")}syncDatafile(){return pt(this,void 0,void 0,function*(){return this.currentRequest=this.makeDatafileRequest(),this.currentRequest.responsePromise.then(this.onRequestResolved.bind(this),this.onRequestRejected.bind(this)).finally(()=>this.currentRequest=void 0)})}handleDatafile(e){var t;this.isDone()||(this.currentDatafile=e,null===(t=this.cache)||void 0===t||t.set(this.cacheKey,e),this.isStarting()&&(this.startPromise.resolve(),this.state=lt.Running),this.emitter.emit("update",e))}getDatafileFromResponse(e){var t;if(null===(t=this.logger)||void 0===t||t.debug("23",e.statusCode),304!==e.statusCode)return e.body}saveLastModified(e){var t;const r=e["last-modified"]||e["Last-Modified"];void 0!==r&&(this.lastResponseLastModified=r,null===(t=this.logger)||void 0===t||t.debug("24",this.lastResponseLastModified))}setDatafileFromCacheIfAvailable(){return pt(this,void 0,void 0,function*(){if(this.cache)try{const e=yield this.cache.get(this.cacheKey);e&&this.isStarting()&&this.handleDatafile(e)}catch(e){}})}},mt=class{constructor(e,t,r){this.base=e,this.max=t,this.maxJitter=r,this.maxJitter>this.base/2&&(this.maxJitter=this.base/2),this.maxJitter=r,this.current=e}backoff(){const e=this.current+this.maxJitter*Math.random();return this.current=Math.min(2*this.current,this.max),e}reset(){this.current=this.base}},yt=class{constructor(e){this.value=e}backoff(){return this.value}reset(){}},bt=class{constructor(e,t){this.failureCount=0,this.running=!1,this.interval=e,this.backoffController=t}isRunning(){return this.running}handleSuccess(){var e;this.failureCount=0,null===(e=this.backoffController)||void 0===e||e.reset(),this.setTimer(this.interval)}handleFailure(){var e,t;this.failureCount++;const r=null!==(t=null===(e=this.backoffController)||void 0===e?void 0:e.backoff())&&void 0!==t?t:this.interval;this.setTimer(r)}setTimer(e){this.running&&(this.timeoutId=setTimeout(this.executeTask.bind(this),e))}executeTask(){this.task&&this.task(this.failureCount).then(this.handleSuccess.bind(this),this.handleFailure.bind(this))}start(e){var t;this.running=!0,e?(t=this.executeTask.bind(this),"function"==typeof queueMicrotask?queueMicrotask(t):Promise.resolve().then(t)):this.setTimer(this.interval)}stop(){this.running=!1,clearInterval(this.timeoutId)}reset(){var e;this.failureCount=0,null===(e=this.backoffController)||void 0===e||e.reset(),this.stop()}setTask(e){this.task=e}},Et=e=>{const t=[];if(!e||"object"!=typeof e)throw new Error("Invalid store");for(const r of["set","get","remove","getKeys"])"function"!=typeof e[r]&&t.push("Invalid store method %s".replace("%s",r));if(t.length>0)throw new Error(t.join(", "))},It="Invalid config manager",St=Symbol(),xt=e=>({[St]:new gt(e)}),wt=e=>{var t;e.cache&&Et(e.cache);const r=null!==(t=e.updateInterval)&&void 0!==t?t:3e5,i=new mt(1e3,r,500),n=new bt(r,i),s=[];r<3e4&&s.push({level:N.Warn,message:"Polling intervals below 30 seconds are not recommended.",params:[]});const o={sdkKey:e.sdkKey,autoUpdate:e.autoUpdate,urlTemplate:e.urlTemplate,datafileAccessToken:e.datafileAccessToken,customHeaders:e.customHeaders,requestHandler:e.requestHandler,cache:e.cache,repeater:n,startupLogs:s},a=new vt(o);return new gt({datafile:e.datafile,datafileManager:a,jsonSchemaValidator:e.jsonSchemaValidator})},Ot=class{constructor(){this.operation="sync"}},kt=class{constructor(){this.operation="async"}},Mt=(e,t)=>e instanceof Ot?e.getBatched(t):t.map(t=>e.get(t)),Rt=(e,t)=>e instanceof kt?e.getBatched(t):Promise.all(t.map(t=>e.get(t))),Ct=class extends Ot{constructor(e,t,r,i){super(),this.operation="sync",this.store=e,this.prefix=t,this.transformGet=r,this.transformSet=i}addPrefix(e){return`${this.prefix}${e}`}removePrefix(e){return e.substring(this.prefix.length)}set(e,t){return this.store.set(this.addPrefix(e),this.transformSet(t))}get(e){const t=this.store.get(this.addPrefix(e));return t?this.transformGet(t):void 0}remove(e){return this.store.remove(this.addPrefix(e))}getInternalKeys(){return this.store.getKeys().filter(e=>e.startsWith(this.prefix))}getKeys(){return this.getInternalKeys().map(e=>this.removePrefix(e))}getBatched(e){return Mt(this.store,e.map(e=>this.addPrefix(e))).map(e=>e?this.transformGet(e):void 0)}},Pt=class{constructor(e,t,r,i){this.operation="async",this.cache=e,this.prefix=t,this.transformGet=r,this.transformSet=i}addPrefix(e){return`${this.prefix}${e}`}removePrefix(e){return e.substring(this.prefix.length)}set(e,t){return this.cache.set(this.addPrefix(e),this.transformSet(t))}get(e){return pt(this,void 0,void 0,function*(){const t=yield this.cache.get(this.addPrefix(e));return t?this.transformGet(t):void 0})}remove(e){return this.cache.remove(this.addPrefix(e))}getInternalKeys(){return pt(this,void 0,void 0,function*(){return this.cache.getKeys().then(e=>e.filter(e=>e.startsWith(this.prefix)))})}getKeys(){return pt(this,void 0,void 0,function*(){return this.getInternalKeys().then(e=>e.map(e=>this.removePrefix(e)))})}getBatched(e){return pt(this,void 0,void 0,function*(){return(yield Rt(this.cache,e.map(e=>this.addPrefix(e)))).map(e=>e?this.transformGet(e):void 0)})}},At={US:"https://logx.optimizely.com/v1/events",EU:"https://eu.logx.optimizely.com/v1/events"};function jt(e){const t=[],r=e[0];return e.forEach(e=>{if("conversion"===e.type||"impression"===e.type){const r=function(e){const t={snapshots:[],visitor_id:e.user.id,attributes:[]};return e.user.attributes.forEach(e=>{t.attributes.push({entity_id:e.entityId,key:e.key,type:"custom",value:e.value})}),"boolean"==typeof e.context.botFiltering&&t.attributes.push({entity_id:H,key:H,type:"custom",value:e.context.botFiltering}),t}(e);"impression"===e.type?r.snapshots.push(function(e){var t,r;const{layer:i,experiment:n,variation:s,ruleKey:o,flagKey:a,ruleType:l,enabled:u,cmabUuid:c}=e,d=i?i.id:null;return{decisions:[{campaign_id:d,experiment_id:null!==(t=null==n?void 0:n.id)&&void 0!==t?t:"",variation_id:null!==(r=null==s?void 0:s.id)&&void 0!==r?r:"",metadata:{flag_key:a,rule_key:o,rule_type:l,variation_key:s?s.key:"",enabled:u,cmab_uuid:c}}],events:[{entity_id:d,timestamp:e.timestamp,key:"campaign_activated",uuid:e.uuid}]}}(e)):"conversion"===e.type&&r.snapshots.push(function(e){const t=Object.assign({},e.tags);delete t.revenue,delete t.value;const r={entity_id:e.event.id,key:e.event.key,timestamp:e.timestamp,uuid:e.uuid};return e.tags&&(r.tags=e.tags),null!=e.value&&(r.value=e.value),null!=e.revenue&&(r.revenue=e.revenue),{events:[r]}}(e)),t.push(r)}}),{client_name:r.context.clientName,client_version:r.context.clientVersion,account_id:r.context.accountId,project_id:r.context.projectId,revision:r.context.revision,anonymize_ip:r.context.anonymizeIP,enrich_decisions:!0,visitors:t}}function Dt(e){var t;const r=(null===(t=e[0])||void 0===t?void 0:t.context.region)||"US";return{url:At[r]||At.US,httpVerb:"POST",params:jt(e)}}var Tt=(e,t,r,i,n)=>{e().then(e=>{t.resolve(e)}).catch(s=>{var o;if(0===n)return void t.reject(s);if(r.cancelled)return void t.reject(new pe("49"));const a=null!==(o=null==i?void 0:i.backoff())&&void 0!==o?o:0;setTimeout(()=>{Tt(e,t,r,i,n=void 0===n?void 0:n-1)},a)})},Ft=(e,t,r)=>{const i=at(),n={cancelled:!1};return Tt(e,i,n,t,r),{cancelRetry:()=>{n.cancelled=!0},result:i.promise}},_t=class{constructor(){this.idSuffixOffset=0}getId(){const e=1e4+this.idSuffixOffset;return this.idSuffixOffset=(this.idSuffixOffset+1)%1e4,`${Date.now()}${e}`}};function Nt(e){var t,r;return null!==(r=null===(t=e.experiment)||void 0===t?void 0:t.key)&&void 0!==r?r:""}function Ut(e){var t,r;return null!==(r=null===(t=e.variation)||void 0===t?void 0:t.key)&&void 0!==r?r:""}function Vt(e){var t,r;return null!==(r=null===(t=e.variation)||void 0===t?void 0:t.featureEnabled)&&void 0!==r&&r}var Lt,Kt,qt={AB_TEST:"ab-test",FEATURE:"feature",FEATURE_TEST:"feature-test",FEATURE_VARIABLE:"feature-variable",ALL_FEATURE_VARIABLES:"all-feature-variables",FLAG:"flag"},Bt={ACTIVATE:"ACTIVATE",DECISION:"DECISION",LOG_EVENT:"LOG_EVENT",OPTIMIZELY_CONFIG_UPDATE:"OPTIMIZELY_CONFIG_UPDATE",TRACK:"TRACK"};!function(e){e.BOOLEAN="boolean",e.DOUBLE="double",e.INTEGER="integer",e.STRING="string",e.JSON="json"}(Lt||(Lt={})),function(e){e.DISABLE_DECISION_EVENT="DISABLE_DECISION_EVENT",e.ENABLED_FLAGS_ONLY="ENABLED_FLAGS_ONLY",e.IGNORE_USER_PROFILE_SERVICE="IGNORE_USER_PROFILE_SERVICE",e.INCLUDE_REASONS="INCLUDE_REASONS",e.EXCLUDE_VARIABLES="EXCLUDE_VARIABLES",e.IGNORE_CMAB_CACHE="IGNORE_CMAB_CACHE",e.RESET_CMAB_CACHE="RESET_CMAB_CACHE",e.INVALIDATE_USER_CMAB_CACHE="INVALIDATE_USER_CMAB_CACHE"}(Kt||(Kt={}));var zt,Ht,$t=(e,t)=>{const r=e.context,i=t.context;return(r.region||"US")===(i.region||"US")&&r.accountId===i.accountId&&r.projectId===i.projectId&&r.clientName===i.clientName&&r.clientVersion===i.clientVersion&&r.revision===i.revision&&r.anonymizeIP===i.anonymizeIP&&r.botFiltering===i.botFiltering},Jt=({configObj:e,userId:t,userAttributes:r,clientEngine:i,clientVersion:n,type:s})=>({type:s,timestamp:ge.currentTimestamp(),uuid:ge.uuid(),context:{region:e.region,accountId:e.accountId,projectId:e.projectId,revision:e.revision,clientName:i,clientVersion:n,anonymizeIP:e.anonymizeIP||!1,botFiltering:e.botFiltering},user:{id:t,attributes:Gt(e,r)}}),Gt=(e,t,r)=>{if(!t)return[];const i=[];return Object.keys(t).forEach(function(n){const s=t[n];if("object"!=typeof s&&void 0!==s&&(o=s,"string"==typeof n&&("string"==typeof o||"boolean"==typeof o||ge.isNumber(o)&&ge.isSafeInteger(o)))){const t=function(e,t,r){const i=e.attributeKeyMap[t],n=0===t.indexOf(Ye);return i?(n&&(null==r||r.warn("58",t,Ye)),i.id):n?t:(null==r||r.warn("62",t),null)}(e,n,r);t&&i.push({entityId:t,key:n,value:s})}var o}),i},Wt=class extends dt{constructor(e){var t;super(e.startupLogs),this.eventQueue=[],this.idGenerator=new _t,this.runningTask=new Map,this.dispatchingEvents=new Map,this.eventEmitter=new ht,this.eventDispatcher=e.eventDispatcher,this.closingEventDispatcher=e.closingEventDispatcher,this.batchSize=e.batchSize,this.eventStore=e.eventStore,this.retryConfig=e.retryConfig,this.dispatchRepeater=e.dispatchRepeater,this.dispatchRepeater.setTask(()=>this.flush()),this.failedEventRepeater=e.failedEventRepeater,null===(t=this.failedEventRepeater)||void 0===t||t.setTask(()=>this.retryFailedEvents()),e.logger&&this.setLogger(e.logger)}setLogger(e){this.logger=e,this.logger.setName("BatchEventProcessor")}onDispatch(e){return this.eventEmitter.on("dispatch",e)}retryFailedEvents(){return pt(this,void 0,void 0,function*(){if(!this.eventStore)return;const e=(yield this.eventStore.getKeys()).filter(e=>!this.dispatchingEvents.has(e)&&!this.eventQueue.find(t=>t.id===e)),t=yield"sync"===this.eventStore.operation?Mt(this.eventStore,e):Rt(this.eventStore,e),r=[];if(t.forEach(e=>{e&&r.push(e)}),0==r.length)return;r.sort((e,t)=>e.id<t.id?-1:1);const i=[];let n=[];r.forEach(e=>{(n.length===this.batchSize||n.length>0&&!$t(n[0].event,e.event))&&(i.push({request:Dt(n.map(e=>e.event)),events:n}),n=[]),n.push(e)}),n.length>0&&i.push({request:Dt(n.map(e=>e.event)),events:n}),i.forEach(e=>{this.dispatchBatch(e,!1)})})}createNewBatch(){if(0==this.eventQueue.length)return;const e=[],t=[];return this.eventQueue.forEach(r=>{e.push(r.event),t.push(r)}),this.eventQueue=[],{request:Dt(e),events:t}}executeDispatch(e,t=!1){return pt(this,void 0,void 0,function*(){return(t&&this.closingEventDispatcher?this.closingEventDispatcher:this.eventDispatcher).dispatchEvent(e).then(e=>e.statusCode&&!ft(e.statusCode)?Promise.reject(new pe("10",e.statusCode)):Promise.resolve(e))})}dispatchBatch(e,t){const{request:r,events:i}=e;i.forEach(e=>{this.dispatchingEvents.set(e.id,e)});const n=this.retryConfig?Ft(()=>this.executeDispatch(r,t),this.retryConfig.backoffProvider(),this.retryConfig.maxRetries):{result:this.executeDispatch(r,t),cancelRetry:()=>{}};this.eventEmitter.emit("dispatch",r);const s=this.idGenerator.getId();this.runningTask.set(s,n),n.result.then(e=>(i.forEach(e=>{var t;null===(t=this.eventStore)||void 0===t||t.remove(e.id)}),Promise.resolve())).catch(e=>{var t;null===(t=this.logger)||void 0===t||t.error(e)}).finally(()=>{this.runningTask.delete(s),i.forEach(e=>this.dispatchingEvents.delete(e.id))})}flush(e=!1){return pt(this,void 0,void 0,function*(){const t=this.createNewBatch();t&&(this.dispatchRepeater.reset(),this.dispatchBatch(t,e))})}process(e){var t;return pt(this,void 0,void 0,function*(){if(!this.isRunning())return Promise.reject(new pe("51","BatchEventProcessor"));const r={id:this.idGenerator.getId(),event:e};yield Promise.resolve(null===(t=this.eventStore)||void 0===t?void 0:t.set(r.id,r)).catch(e=>{var t;null===(t=this.logger)||void 0===t||t.error(e)}),this.eventQueue.length>0&&!$t(this.eventQueue[0].event,e)&&this.flush(),this.eventQueue.push(r),this.eventQueue.length==this.batchSize?this.flush():this.dispatchRepeater.isRunning()||this.dispatchRepeater.start()})}start(){var e;this.isNew()&&(super.start(),this.state=lt.Running,this.disposable||null===(e=this.failedEventRepeater)||void 0===e||e.start(),this.retryFailedEvents(),this.startPromise.resolve())}makeDisposable(){var e,t,r;super.makeDisposable(),this.batchSize=1,this.retryConfig={maxRetries:Math.min(null!==(t=null===(e=this.retryConfig)||void 0===e?void 0:e.maxRetries)&&void 0!==t?t:5,5),backoffProvider:(null===(r=this.retryConfig)||void 0===r?void 0:r.backoffProvider)||(()=>new mt(200,1e3,500))}}flushImmediately(){return this.isRunning()?this.flush(!0):Promise.resolve()}stop(){var e;this.isDone()||(this.isNew()&&this.startPromise.reject(new Error(de(ct,"BatchEventProcessor"))),this.state=lt.Stopping,this.dispatchRepeater.stop(),null===(e=this.failedEventRepeater)||void 0===e||e.stop(),this.flush(!0),this.runningTask.forEach(e=>e.cancelRetry()),Promise.allSettled(Array.from(this.runningTask.values()).map(e=>e.result)).then(()=>{this.state=lt.Terminated,this.stopPromise.resolve()}))}},Qt=class{constructor(){this.waitPromise=Promise.resolve()}run(e){const t=this.waitPromise.then(e);return this.waitPromise=t.catch(()=>{}),t}},Yt="optly_event:",Xt=class extends dt{constructor(e){super(),this.dispatcher=e,this.eventEmitter=new ht}process(e){const t=Dt([e]),r=this.dispatcher.dispatchEvent(t);return this.eventEmitter.emit("dispatch",t),r}start(){this.isNew()&&(this.state=lt.Running,this.startPromise.resolve())}stop(){this.isDone()||(this.isNew()&&this.startPromise.reject(new Error(de(ct,"ForwardingEventProcessor"))),this.state=lt.Terminated,this.stopPromise.resolve())}onDispatch(e){return this.eventEmitter.on("dispatch",e)}flushImmediately(){return Promise.resolve()}},Zt=Symbol(),er=e=>{if(!e||"object"!=typeof e||"function"!=typeof e.dispatchEvent)throw new Error("Invalid event dispatcher")},tr=e=>({[Zt]:e}),rr=class{constructor(e,t){this.operation="sync",this.data=new Map,this.maxSize=e,this.ttl=t}lookup(e){const t=this.data.get(e);if(t&&(this.data.delete(e),!(t.expiresAt&&t.expiresAt<=Date.now())))return this.data.set(e,t),t.value}save(e,t){if(this.data.delete(e),this.data.size===this.maxSize){const e=this.data.keys().next().value;this.data.delete(e)}this.data.set(e,{value:t,expiresAt:this.ttl?Date.now()+this.ttl:void 0})}remove(e){this.data.delete(e)}reset(){this.data.clear()}getKeys(){return Array.from(this.data.keys())}},ir=class{constructor(e,t,r){this.requestHandler=e,this.requestGenerator=t,r&&this.setLogger(r)}setLogger(e){this.logger=e,this.logger.setName("OdpEventApiManager")}sendEvents(e,t){return pt(this,void 0,void 0,function*(){if(0===t.length)return{};const{method:r,endpoint:i,headers:n,data:s}=this.requestGenerator(e,t);return this.requestHandler.makeRequest(i,n,r,s).responsePromise})}},nr=(e,t)=>{const{apiHost:r,apiKey:i}=e;return{method:"POST",endpoint:`${r}/v3/events`,headers:{"Content-Type":"application/json","x-api-key":i},data:JSON.stringify(t,(e,t)=>t instanceof Map?Object.fromEntries(t):t)}};!function(e){e.VUID="vuid",e.FS_USER_ID="fs_user_id",e.FS_USER_ID_ALIAS="fs-user-id"}(zt||(zt={})),function(e){e.IDENTIFIED="identified",e.INITIALIZED="client_initialized"}(Ht||(Ht={}));var sr,or="fullstack",ar=class extends dt{constructor(e){super(e.startUpLogs),this.queue=[],this.apiManager=e.apiManager,this.batchSize=e.batchSize,this.retryConfig=e.retryConfig,this.repeater=e.repeater,this.repeater.setTask(()=>this.flush())}setLogger(e){this.logger=e,this.logger.setName("OdpEventManager"),this.apiManager.setLogger(e.child())}executeDispatch(e,t){return pt(this,void 0,void 0,function*(){const r=yield this.apiManager.sendEvents(e,t);return r.statusCode&&!ft(r.statusCode)?Promise.reject(new pe("10",r.statusCode)):yield Promise.resolve(r)})}flush(){return pt(this,void 0,void 0,function*(){if(!this.odpIntegrationConfig||!this.odpIntegrationConfig.integrated)return;const e=this.odpIntegrationConfig.odpConfig,t=this.queue;return this.queue=[],this.repeater.reset(),Ft(()=>this.executeDispatch(e,t),this.retryConfig.backoffProvider(),this.retryConfig.maxRetries).result.catch(e=>{var t;null===(t=this.logger)||void 0===t||t.error("11",e)})})}start(){this.isNew()&&(super.start(),this.odpIntegrationConfig?this.goToRunningState():this.state=lt.Starting)}makeDisposable(){super.makeDisposable(),this.retryConfig.maxRetries=Math.min(this.retryConfig.maxRetries,5),this.batchSize=1}updateConfig(e){if(!this.isDone())if(this.isNew())this.odpIntegrationConfig=e;else{if(this.isStarting())return this.odpIntegrationConfig=e,void this.goToRunningState();this.flush(),this.odpIntegrationConfig=e}}goToRunningState(){this.state=lt.Running,this.startPromise.resolve()}flushImmediately(){return this.isRunning()?this.flush():Promise.resolve()}stop(){this.isDone()||(this.isNew()&&this.startPromise.reject(new Error(de(ct,"OdpEventManager"))),this.flush(),this.state=lt.Terminated,this.stopPromise.resolve())}sendEvent(e){var t,r,i,n,s,o;this.isRunning()?(null===(r=this.odpIntegrationConfig)||void 0===r?void 0:r.integrated)?0!==e.identifiers.size?this.isDataValid(e.data)?e.action?(""===e.type&&(e.type=or),Array.from(e.identifiers.entries()).forEach(([t,r])=>{zt.FS_USER_ID_ALIAS!==t.toLowerCase()&&zt.FS_USER_ID!==t.toLowerCase()||(e.identifiers.delete(t),e.identifiers.set(zt.FS_USER_ID,r))}),this.processEvent(e)):null===(o=this.logger)||void 0===o||o.error("5"):null===(s=this.logger)||void 0===s||s.error("6"):null===(n=this.logger)||void 0===n||n.error("39"):null===(i=this.logger)||void 0===i||i.error("43"):null===(t=this.logger)||void 0===t||t.error("51","OdpEventManager")}isDataValid(e){const t=["string","number","boolean"];return Array.from(e.values()).reduce((e,r)=>e&&(null===r||t.includes(typeof r)),!0)}processEvent(e){this.queue.push(e),this.queue.length===this.batchSize?this.flush():this.repeater.isRunning()||this.repeater.start()}},lr=class{constructor(e,t,r,i){this.type=e,this.action=t,this.identifiers=null!=r?r:new Map,this.data=null!=i?i:new Map}},ur=e=>e.startsWith("vuid_")&&e.length>5,cr=class extends dt{constructor(e){if(super(),this.clientEngine=J,this.clientVersion=W,this.segmentManager=e.segmentManager,this.eventManager=e.eventManager,this.configPromise=at(),e.userAgentParser){const{os:t,device:r}=e.userAgentParser.parseUserAgentInfo(),i={os:t.name,os_version:t.version,device_type:r.type,model:r.model};this.userAgentData=new Map(Object.entries(i).filter(([e,t])=>null!=t&&null!=t))}e.logger&&this.setLogger(e.logger)}setLogger(e){this.logger=e,this.logger.setName("OdpManager"),this.eventManager.setLogger(e.child()),this.segmentManager.setLogger(e.child())}setClientInfo(e,t){this.clientEngine=e,this.clientVersion=t}start(){if(!this.isNew())return;this.state=lt.Starting,this.eventManager.start();const e=[this.configPromise,this.eventManager.onRunning()];Promise.all(e).then(()=>{this.handleStartSuccess()}).catch(e=>{this.handleStartFailure(e)})}makeDisposable(){super.makeDisposable(),this.eventManager.makeDisposable()}handleStartSuccess(){this.isDone()||(this.state=lt.Running,this.startPromise.resolve())}handleStartFailure(e){this.isDone()||(this.state=lt.Failed,this.startPromise.reject(e),this.stopPromise.reject(e))}flushImmediately(){return this.isRunning()?this.eventManager.flushImmediately():Promise.resolve()}stop(){this.isDone()||(this.isRunning()||this.startPromise.reject(new Error(de(ct,"OdpManager"))),this.state=lt.Stopping,this.eventManager.stop(),this.eventManager.onTerminated().then(()=>{this.state=lt.Terminated,this.stopPromise.resolve()}).catch(e=>{this.state=lt.Failed,this.stopPromise.reject(e)}))}updateConfig(e){return!(this.odpIntegrationConfig&&(t=this.odpIntegrationConfig,r=e,!(t.integrated!==r.integrated||t.integrated&&r.integrated&&!t.odpConfig.equals(r.odpConfig)))||this.isDone()||(this.odpIntegrationConfig=e,this.configPromise.resolve(),this.segmentManager.updateConfig(e),this.eventManager.updateConfig(e),0));var t,r}fetchQualifiedSegments(e,t=[]){return pt(this,void 0,void 0,function*(){return ur(e)?this.segmentManager.fetchQualifiedSegments(zt.VUID,e,t):this.segmentManager.fetchQualifiedSegments(zt.FS_USER_ID,e,t)})}identifyUser(e,t){const r=new Map;let i=e,n=t;!t&&ur(e)&&(n=e,i=void 0),n&&r.set(zt.VUID,n),i&&r.set(zt.FS_USER_ID,i);const s=new lr(or,Ht.IDENTIFIED,r);this.sendEvent(s)}sendEvent(e){!e.identifiers.has(zt.VUID)&&this.vuid&&e.identifiers.set(zt.VUID,this.vuid),e.data=this.augmentCommonData(e.data),this.eventManager.sendEvent(e)}augmentCommonData(e){const t=new Map(this.userAgentData);return t.set("idempotence_id",U()),t.set("data_source_type","sdk"),t.set("data_source",this.clientEngine),t.set("data_source_version",this.clientVersion),e.forEach((e,r)=>t.set(r,e)),t}setVuid(e){this.vuid=e,this.onRunning().then(()=>{var e;if(null===(e=this.odpIntegrationConfig)||void 0===e?void 0:e.integrated){const e=new lr(or,Ht.INITIALIZED);this.sendEvent(e)}})}},dr={$schema:"http://json-schema.org/draft-04/schema#",title:"Project Config JSON Schema",type:"object",properties:{projectId:{type:"string",required:!0},accountId:{type:"string",required:!0},groups:{type:"array",items:{type:"object",properties:{id:{type:"string",required:!0},policy:{type:"string",required:!0},trafficAllocation:{type:"array",items:{type:"object",properties:{entityId:{type:"string",required:!0},endOfRange:{type:"integer",required:!0}}},required:!0},experiments:{type:"array",items:{type:"object",properties:{id:{type:"string",required:!0},key:{type:"string",required:!0},status:{type:"string",required:!0},layerId:{type:"string",required:!0},variations:{type:"array",items:{type:"object",properties:{id:{type:"string",required:!0},key:{type:"string",required:!0}}},required:!0},trafficAllocation:{type:"array",items:{type:"object",properties:{entityId:{type:"string",required:!0},endOfRange:{type:"integer",required:!0}}},required:!0},audienceIds:{type:"array",items:{type:"string"},required:!0},forcedVariations:{type:"object",required:!0}}},required:!0}}},required:!0},experiments:{type:"array",items:{type:"object",properties:{id:{type:"string",required:!0},key:{type:"string",required:!0},status:{type:"string",required:!0},layerId:{type:"string",required:!0},variations:{type:"array",items:{type:"object",properties:{id:{type:"string",required:!0},key:{type:"string",required:!0}}},required:!0},trafficAllocation:{type:"array",items:{type:"object",properties:{entityId:{type:"string",required:!0},endOfRange:{type:"integer",required:!0}}},required:!0},audienceIds:{type:"array",items:{type:"string"},required:!0},forcedVariations:{type:"object",required:!0},cmab:{type:"object",required:!1,properties:{attributes:{type:"array",items:{type:"string"},required:!0}}}}},required:!0},events:{type:"array",items:{type:"object",properties:{key:{type:"string",required:!0},experimentIds:{type:"array",items:{type:"string",required:!0}},id:{type:"string",required:!0}}},required:!0},audiences:{type:"array",items:{type:"object",properties:{id:{type:"string",required:!0},name:{type:"string",required:!0},conditions:{type:"string",required:!0}}},required:!0},attributes:{type:"array",items:{type:"object",properties:{id:{type:"string",required:!0},key:{type:"string",required:!0}}},required:!0},version:{type:"string",required:!0},revision:{type:"string",required:!0},integrations:{type:"array",items:{type:"object",properties:{key:{type:"string",required:!0},host:{type:"string"},publicKey:{type:"string"},pixelUrl:{type:"string"}}}}}},hr={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://example.com/example.json",title:"ODP Response Schema",type:"object",required:["data"],properties:{data:{title:"The data Schema",type:"object",required:["customer"],properties:{customer:{title:"The customer Schema",type:"object",required:[],properties:{audiences:{title:"The audiences Schema",type:"object",required:["edges"],properties:{edges:{title:"The edges Schema",type:"array",items:{title:"A Schema",type:"object",required:["node"],properties:{node:{title:"The node Schema",type:"object",required:["name","state"],properties:{name:{title:"The name Schema",type:"string",examples:["has_email","has_email_opted_in"]},state:{title:"The state Schema",type:"string",examples:["qualified"]}},examples:[]}},examples:[]},examples:[]}},examples:[]}},examples:[]}},examples:[]},errors:{title:"The errors Schema",type:"array",default:[],items:{title:"A Schema",type:"object",required:["message","locations","extensions"],properties:{message:{title:"The message Schema",type:"string",examples:["Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = asdsdaddddd"]},locations:{title:"The locations Schema",type:"array",items:{title:"A Schema",type:"object",required:["line","column"],properties:{line:{title:"The line Schema",type:"integer",examples:[2]},column:{title:"The column Schema",type:"integer",examples:[3]}},examples:[]},examples:[]},path:{title:"The path Schema",type:"array",items:{title:"A Schema",type:"string",examples:["customer"]},examples:[]},extensions:{title:"The extensions Schema",type:"object",required:["classification"],properties:{classification:{title:"The classification Schema",type:"string",examples:["InvalidIdentifierException"]}},examples:[]}},examples:[]},examples:[]}},examples:[]},gr=[],pr="Audience segments fetch failed",fr=class{constructor(e,t){this.toGraphQLJson=(e,t,r)=>['{"query" : "query {customer',`(${e} : \\"${t}\\") `,"{audiences","(subset: [",...(null==r?void 0:r.map((e,t)=>`\\"${e}\\"${t<r.length-1?",":""}`))||"",']) {edges {node {name state}}}}}"}'].join(""),this.requestHandler=e,t&&this.setLogger(t)}setLogger(e){this.logger=e,this.logger.setName("OdpSegmentApiManager")}fetchSegments(e,t,r,i,n){var s,o,a,l,u,c,d,h,g;return pt(this,void 0,void 0,function*(){if(0===(null==n?void 0:n.length))return gr;const p=`${t}/v3/graphql`,f=this.toGraphQLJson(r,i,n),v=yield this.querySegments(e,p,f);if(!v)return null===(s=this.logger)||void 0===s||s.error(`${pr} (network error)`),null;const m=this.parseSegmentsResponseJson(v);if(!m)return null===(o=this.logger)||void 0===o||o.error(`${pr} (decode error)`),null;if((null===(a=m.errors)||void 0===a?void 0:a.length)>0){const{code:e,classification:t}=m.errors[0].extensions;return"INVALID_IDENTIFIER_EXCEPTION"==e?null===(l=this.logger)||void 0===l||l.error(`${pr} (invalid identifier)`):null===(u=this.logger)||void 0===u||u.error(`${pr} (${t})`),null}const y=null===(h=null===(d=null===(c=null==m?void 0:m.data)||void 0===c?void 0:c.customer)||void 0===d?void 0:d.audiences)||void 0===h?void 0:h.edges;return y?y.filter(e=>"qualified"==e.node.state).map(e=>e.node.name):(null===(g=this.logger)||void 0===g||g.error(`${pr} (decode error)`),null)})}querySegments(e,t,r){return pt(this,void 0,void 0,function*(){const i=t,n={"Content-Type":"application/json","x-api-key":e};try{const e=this.requestHandler.makeRequest(i,n,"POST",r),{statusCode:t,body:s}=yield e.responsePromise;return t>=200&&t<300?s:null}catch(e){return null}})}parseSegmentsResponseJson(e){let t={};try{t=JSON.parse(e)}catch(e){return null}return function(e,t=dr,r=!0){if("object"!=typeof e||null===e)throw new pe("34");const i=(0,V.validate)(e,t);if(i.valid)return!0;if(!r)return!1;if(Array.isArray(i.errors))throw new pe("17",i.errors[0].property,i.errors[0].message);throw new pe("25")}(t,hr,!1)?t:null}};!function(e){e.IGNORE_CACHE="IGNORE_CACHE",e.RESET_CACHE="RESET_CACHE"}(sr||(sr={}));var vr=class{constructor(e,t,r){this.segmentsCache=e,this.odpSegmentApiManager=t,r&&this.setLogger(r)}setLogger(e){this.logger=e,this.logger.setName("OdpSegmentManager"),this.odpSegmentApiManager.setLogger(e.child())}fetchQualifiedSegments(e,t,r){var i,n;return pt(this,void 0,void 0,function*(){if(!this.odpIntegrationConfig)return null===(i=this.logger)||void 0===i||i.warn("38"),null;if(!this.odpIntegrationConfig.integrated)return null===(n=this.logger)||void 0===n||n.warn("43"),null;const s=this.odpIntegrationConfig.odpConfig,o=s.segmentsToCheck;if(!o||o.length<=0)return[];const a=this.makeCacheKey(e,t),l=null==r?void 0:r.includes(sr.IGNORE_CACHE);if((null==r?void 0:r.includes(sr.RESET_CACHE))&&this.segmentsCache.reset(),!l){const e=yield this.segmentsCache.lookup(a);if(e)return e}const u=yield this.odpSegmentApiManager.fetchSegments(s.apiKey,s.apiHost,e,t,o);return u&&!l&&this.segmentsCache.save(a,u),u})}makeCacheKey(e,t){return`${e}-$-${t}`}updateConfig(e){this.odpIntegrationConfig=e,this.segmentsCache.reset()}},mr=Symbol(),yr=e=>{const t=(e=>{return e.segmentsCache&&(e=>{const t=[];if(!e||"object"!=typeof e)throw new Error("Invalid cache");for(const r of["save","lookup","reset"])"function"!=typeof e[r]&&t.push("Invalid cache method %s".replace("%s",r));if(t.length>0)throw new Error(t.join(", "))})(e.segmentsCache),new vr(e.segmentsCache||(t=e.segmentsCacheSize,r=e.segmentsCacheTimeout,new rr(t||1e4,r||6e5)),new fr(e.segmentRequestHandler));var t,r})(e),r=new ar({apiManager:new ir((i=e).eventRequestHandler,i.eventRequestGenerator),batchSize:i.eventBatchSize||100,repeater:new bt(i.eventFlushInterval||1e4),retryConfig:{maxRetries:i.eventMaxRetries||2,backoffProvider:()=>new mt(i.eventMinBackoff||200,i.eventMaxBackoff||1e3,50)}});var i;return new cr({segmentManager:t,eventManager:r,userAgentParser:e.userAgentParser})},br=Symbol(),Er=class{constructor(e,t){this.logger=e,this.errorNotifier=t}report(e,...t){if("string"==typeof e)return e=new pe(e,...t),void this.report(e);this.errorNotifier&&this.errorNotifier.notify(e),this.logger&&this.logger.error(e)}setLogger(e){this.logger=e}setErrorNotifier(e){this.errorNotifier=e}},Ir=class{constructor(e){this.removerId=1,this.eventEmitter=new ht,this.removers=new Map,this.errorReporter=new Er(e.logger,e.errorNotifier)}addNotificationListener(e,t){if(!(le(Bt).indexOf(e)>-1))return-1;const r=this.removerId++,i=this.eventEmitter.on(e,this.wrapWithErrorReporting(e,t));return this.removers.set(r,i),r}wrapWithErrorReporting(e,t){return r=>{try{t(r)}catch(t){const r=t instanceof Error?t.message:String(t);this.errorReporter.report("30",e,r)}}}removeNotificationListener(e){const t=this.removers.get(e);return!!t&&(t(),!0)}clearAllNotificationListeners(){this.eventEmitter.removeAllListeners()}clearNotificationListeners(e){this.eventEmitter.removeListeners(e)}sendNotifications(e,t){this.eventEmitter.emit(e,t)}};function Sr(e,t,r){return{variationKey:null,enabled:!1,variables:{},ruleKey:null,flagKey:e,userContext:t,reasons:r}}var xr="$opt_null_rule_key",wr=class e{constructor({optimizely:e,userId:t,attributes:r}){this._qualifiedSegments=null,this.optimizely=e,this.userId=t,this.attributes=Object.assign({},r),this.forcedDecisionsMap={}}setAttribute(e,t){this.attributes[e]=t}getUserId(){return this.userId}getAttributes(){return Object.assign({},this.attributes)}getOptimizely(){return this.optimizely}get qualifiedSegments(){return this._qualifiedSegments}set qualifiedSegments(e){this._qualifiedSegments=e}decide(e,t=[]){return this.optimizely.decide(this.cloneUserContext(),e,t)}decideAsync(e,t){return this.optimizely.decideAsync(this.cloneUserContext(),e,t)}decideForKeys(e,t=[]){return this.optimizely.decideForKeys(this.cloneUserContext(),e,t)}decideForKeysAsync(e,t){return this.optimizely.decideForKeysAsync(this.cloneUserContext(),e,t)}decideAll(e=[]){return this.optimizely.decideAll(this.cloneUserContext(),e)}decideAllAsync(e=[]){return this.optimizely.decideAllAsync(this.cloneUserContext(),e)}trackEvent(e,t){this.optimizely.track(e,this.userId,this.attributes,t)}setForcedDecision(e,t){var r;const i=e.flagKey,n=null!==(r=e.ruleKey)&&void 0!==r?r:xr,s={variationKey:t.variationKey};return this.forcedDecisionsMap[i]||(this.forcedDecisionsMap[i]={}),this.forcedDecisionsMap[i][n]=s,!0}getForcedDecision(e){return this.findForcedDecision(e)}removeForcedDecision(e){var t;const r=null!==(t=e.ruleKey)&&void 0!==t?t:xr,i=e.flagKey;let n=!1;return this.forcedDecisionsMap.hasOwnProperty(i)&&(this.forcedDecisionsMap[i].hasOwnProperty(r)&&(delete this.forcedDecisionsMap[i][r],n=!0),0===Object.keys(this.forcedDecisionsMap[i]).length&&delete this.forcedDecisionsMap[i]),n}removeAllForcedDecisions(){return this.forcedDecisionsMap={},!0}findForcedDecision(e){var t;let r;const i=null!==(t=e.ruleKey)&&void 0!==t?t:xr,n=e.flagKey;if(this.forcedDecisionsMap.hasOwnProperty(e.flagKey)){const e=this.forcedDecisionsMap[n];if(e.hasOwnProperty(i))return r=e[i].variationKey,{variationKey:r}}return null}cloneUserContext(){const t=new e({optimizely:this.getOptimizely(),userId:this.getUserId(),attributes:this.getAttributes()});return Object.keys(this.forcedDecisionsMap).length>0&&(t.forcedDecisionsMap=Object.assign({},this.forcedDecisionsMap)),t._qualifiedSegments=this._qualifiedSegments,t}fetchQualifiedSegments(e){return pt(this,void 0,void 0,function*(){const t=yield this.optimizely.fetchQualifiedSegments(this.userId,e);return this.qualifiedSegments=t,null!==t})}isQualifiedFor(e){return!!this._qualifiedSegments&&this._qualifiedSegments.indexOf(e)>-1}},Or=Math.pow(2,32),kr=function(e){try{const t=L.default.v3(e,1)/Or;return Math.floor(1e4*t)}catch(t){throw new pe("14",e,t.message)}},Mr="User %s is not in any experiment of group %s.",Rr="User %s is not in experiment %s of group %s.",Cr="User %s is in experiment %s of group %s.",Pr="Assigned bucket %s to user with bucketing ID %s.",Ar="Bucketed into an invalid variation ID. Returning null.",jr=function(e){var t,r,i,n,s;const o=[],a=e.experimentIdMap[e.experimentId],l=null==a?void 0:a.groupId;if(l){const n=e.groupIdMap[l];if(!n)throw new pe("23",l);if("random"===n.policy){const s=Dr(n,e.bucketingId,e.userId,e.logger);if(null===s)return null===(t=e.logger)||void 0===t||t.info(Mr,e.userId,l),o.push([Mr,e.userId,l]),{result:null,reasons:o};if(s!==e.experimentId)return null===(r=e.logger)||void 0===r||r.info(Rr,e.userId,e.experimentKey,l),o.push([Rr,e.userId,e.experimentKey,l]),{result:null,reasons:o};null===(i=e.logger)||void 0===i||i.info(Cr,e.userId,e.experimentKey,l),o.push([Cr,e.userId,e.experimentKey,l])}}const u=`${e.bucketingId}${e.experimentId}`,c=kr(u);null===(n=e.logger)||void 0===n||n.debug(Pr,c,e.userId),o.push([Pr,c,e.userId]);const d=Tr(c,e.trafficAllocationConfig);return e.validateEntity&&null!==d&&!e.variationIdMap[d]?(d&&(null===(s=e.logger)||void 0===s||s.warn(Ar),o.push([Ar])),{result:null,reasons:o}):{result:d,reasons:o}},Dr=function(e,t,r,i){const n=`${t}${e.id}`,s=kr(n);null==i||i.debug(Pr,s,r);const o=e.trafficAllocation;return Tr(s,o)},Tr=function(e,t){for(let r=0;r<t.length;r++)if(e<t[r].endOfRange)return t[r].entityId;return null};function Fr(e){return/^\d+$/.test(e)}function _r(e){const t=e.indexOf("-"),r=e.indexOf("+");return!(t<0)&&(r<0||t<r)}function Nr(e){const t=e.indexOf("-"),r=e.indexOf("+");return!(r<0)&&(t<0||r<t)}function Ur(e,t){let r=e,i="";if(/\s/.test(e))return null==t||t.warn(Me,e),null;if(_r(e)?(r=e.substring(0,e.indexOf("-")),i=e.substring(e.indexOf("-")+1)):Nr(e)&&(r=e.substring(0,e.indexOf("+")),i=e.substring(e.indexOf("+")+1)),"string"!=typeof r||"string"!=typeof i)return null;const n=r.split(".").length-1;if(n>2)return null==t||t.warn(Me,e),null;const s=r.split(".");if(s.length!=n+1)return null==t||t.warn(Me,e),null;for(const r of s)if(!Fr(r))return null==t||t.warn(Me,e),null;return i&&s.push(i),s}var Vr="exact",Lr="exists",Kr="semver_eq",qr="semver_ge",Br="semver_gt",zr="semver_le",Hr="semver_lt",$r="substring",Jr=[Vr,Lr,"gt","ge","lt","le",$r,Kr,Hr,zr,Br,qr],Gr={};Gr[Vr]=Yr,Gr[Lr]=function(e,t,r){return null!=t.getAttributes()[e.name]},Gr.gt=function(e,t,r){const i=t.getAttributes()[e.name],n=e.value;return Xr(e,t,r)&&null!==n?i>n:null},Gr.ge=function(e,t,r){const i=t.getAttributes()[e.name],n=e.value;return Xr(e,t,r)&&null!==n?i>=n:null},Gr.lt=function(e,t,r){const i=t.getAttributes()[e.name],n=e.value;return Xr(e,t,r)&&null!==n?i<n:null},Gr.le=function(e,t,r){const i=t.getAttributes()[e.name],n=e.value;return Xr(e,t,r)&&null!==n?i<=n:null},Gr[$r]=function(e,t,r){const i=t.getAttributes(),n=e.name,s=i[e.name],o=typeof s,a=e.value;return"string"!=typeof a?(null==r||r.warn(Oe,JSON.stringify(e)),null):null===s?(null==r||r.debug(be,JSON.stringify(e),n),null):"string"!=typeof s?(null==r||r.warn(ke,JSON.stringify(e),o,n),null):-1!==s.indexOf(a)},Gr[Kr]=function(e,t,r){const i=Zr(e,t,r);return null===i?null:0===i},Gr[Br]=function(e,t,r){const i=Zr(e,t,r);return null===i?null:i>0},Gr[qr]=function(e,t,r){const i=Zr(e,t,r);return null===i?null:i>=0},Gr[Hr]=function(e,t,r){const i=Zr(e,t,r);return null===i?null:i<0},Gr[zr]=function(e,t,r){const i=Zr(e,t,r);return null===i?null:i<=0};var Wr=e=>({evaluate:(t,r)=>function(e,t,r){const i=t.getAttributes(),n=e.match;if(void 0!==n&&-1===Jr.indexOf(n))return null==r||r.warn(Me,JSON.stringify(e)),null;const s=e.name;if(!i.hasOwnProperty(s)&&n!=Lr)return null==r||r.debug("18",JSON.stringify(e),s),null;let o;return o=n&&Gr[n]||Yr,o(e,t,r)}(t,r,e)});function Qr(e){return"string"==typeof e||"boolean"==typeof e||ge.isNumber(e)}function Yr(e,t,r){const i=t.getAttributes(),n=e.value,s=typeof n,o=e.name,a=i[o],l=typeof a;return!Qr(n)||ge.isNumber(n)&&!ge.isSafeInteger(n)?(null==r||r.warn(Oe,JSON.stringify(e)),null):null===a?(null==r||r.debug(be,JSON.stringify(e),o),null):Qr(a)&&s===l?ge.isNumber(a)&&!ge.isSafeInteger(a)?(null==r||r.warn("45",JSON.stringify(e),o),null):n===a:(null==r||r.warn(ke,JSON.stringify(e),l,o),null)}function Xr(e,t,r){const i=t.getAttributes(),n=e.name,s=i[n],o=typeof s,a=e.value;return null!==a&&ge.isSafeInteger(a)?null===s?(null==r||r.debug(be,JSON.stringify(e),n),!1):ge.isNumber(s)?!!ge.isSafeInteger(s)||(null==r||r.warn("45",JSON.stringify(e),n),!1):(null==r||r.warn(ke,JSON.stringify(e),o,n),!1):(null==r||r.warn(Oe,JSON.stringify(e)),!1)}function Zr(e,t,r){const i=t.getAttributes(),n=e.name,s=i[n],o=typeof s,a=e.value;return"string"!=typeof a?(null==r||r.warn(Oe,JSON.stringify(e)),null):null===s?(null==r||r.debug(be,JSON.stringify(e),n),null):"string"!=typeof s?(null==r||r.warn(ke,JSON.stringify(e),o,n),null):function(e,t,r){const i=Ur(t,r),n=Ur(e,r);if(!i||!n)return null;const s=i.length;for(let r=0;r<n.length;r++){if(s<=r)return _r(e)||Nr(e)?1:-1;if(Fr(i[r])){const e=parseInt(i[r]),t=parseInt(n[r]);if(e>t)return 1;if(e<t)return-1}else{if(i[r]<n[r])return _r(e)&&!_r(t)?1:-1;if(i[r]>n[r])return!_r(e)&&_r(t)?-1:1}}return _r(t)&&!_r(e)?-1:0}(a,s,r)}var ei="qualified",ti=[ei],ri={};ri[ei]=ni;var ii=e=>({evaluate:(t,r)=>function(e,t,r){const i=e.match;if(void 0!==i&&-1===ti.indexOf(i))return null==r||r.warn(Me,JSON.stringify(e)),null;let n;return n=i&&ri[i]||ni,n(e,t)}(t,r,e)});function ni(e,t){return t.isQualifiedFor(e.value)}var si=class{constructor(e,t){this.logger=t,this.typeToEvaluatorMap=Object.assign(Object.assign({},e),{custom_attribute:Wr(this.logger),third_party_dimension:ii(this.logger)})}evaluate(e,t,r){return!e||0===e.length||!!$e(e,e=>{var i,n;const s=t[e];if(s){null===(i=this.logger)||void 0===i||i.debug("5",e,JSON.stringify(s.conditions));const t=$e(s.conditions,this.evaluateConditionWithUserAttributes.bind(this,r)),o=null===t?"UNKNOWN":t.toString().toUpperCase();return null===(n=this.logger)||void 0===n||n.debug("1",e,o),t}return null})}evaluateConditionWithUserAttributes(e,t){var r,i;const n=this.typeToEvaluatorMap[t.type];if(!n)return null===(r=this.logger)||void 0===r||r.warn("60",JSON.stringify(t)),null;try{return n.evaluate(t,e)}catch(e){null===(i=this.logger)||void 0===i||i.error("2",t.type,e.message)}return null}};function oi(e){return"string"==typeof e&&""!==e}var ai=class e{constructor(e,t){this.op=e,this.val=t}get(){return this.val}then(t){if("sync"===this.op){const r=t(this.val);return e.of(this.op,r.get())}return e.of(this.op,this.val.then(t))}static of(t,r){if("sync"===t){if((i=r)&&"function"==typeof i.then)throw new pe("Promise value is not allowed in sync operation");return new e(t,r)}var i;return new e(t,Promise.resolve(r))}};ai.all=(e,t)=>{if("sync"===e){const r=t.map(e=>e.get());return ai.of(e,r)}const r=t.map(e=>e.get());return ai.of(e,Promise.all(r))};var li="Experiment %s is not running.",ui='Returning previously activated variation "%s" of experiment "%s" for user "%s" from user profile.',ci="User %s does not meet conditions to be in experiment %s.",di="User %s is in no variation of experiment %s.",hi="User %s is in variation %s of experiment %s.",gi="User %s is forced in variation %s.",pi="Variation key %s is not in datafile. Not activating user %s.",fi='Evaluating audiences for %s "%s": %s.',vi="Audiences for %s %s collectively evaluated to %s.",mi="User %s is in rollout of feature %s.",yi="User %s is not in rollout of feature %s.",bi="Feature %s is not attached to any experiments.",Ei="User %s does not meet conditions for targeting rule %s.",Ii="User %s not bucketed into targeting rule %s due to traffic allocation. Trying everyone rule.",Si="User %s bucketed into targeting rule %s.",xi="There is no rollout of feature %s.",wi="Invalid rollout ID %s attached to feature %s",Oi="Rollout of feature %s has no experiments",ki="Experiment key %s is improperly formatted.",Mi="Variation %s is mapped to experiment %s and user %s in the forced variation map.",Ri="User %s meets conditions for targeting rule %s.",Ci="Variation (%s) is mapped to flag (%s), rule (%s) and user (%s) in the forced decision map.",Pi="Variation (%s) is mapped to flag (%s) and user (%s) in the forced decision map.",Ai="Invalid variation is mapped to flag (%s), rule (%s) and user (%s) in the forced decision map.",ji="Invalid variation is mapped to flag (%s) and user (%s) in the forced decision map.",Di="Failed to fetch CMAB data for experiment %s.",Ti="Holdout %s is not running.",Fi="User %s meets conditions for holdout %s.",_i="User %s does not meet conditions for holdout %s.",Ni="User %s is in variation %s of holdout %s.",Ui="User %s is in no holdout variation.",Vi=class{constructor(e){var t,r,i;this.logger=e.logger,null===(t=this.logger)||void 0===t||t.setName("DecisionService"),this.audienceEvaluator=(r=e.UNSTABLE_conditionEvaluators,i=this.logger,new si(r,i)),this.forcedVariationMap={},this.userProfileService=e.userProfileService,this.userProfileServiceAsync=e.userProfileServiceAsync,this.cmabService=e.cmabService}isCmab(e){return!!e.cmab}resolveVariation(e,t,r,i,n,s){var o,a,l;const u=i.getUserId(),c=r.key;if(tt(t,c)!==Qe)return null===(o=this.logger)||void 0===o||o.info(li,c),ai.of(e,{result:{},reasons:[[li,c]]});const d=[],h=this.getForcedVariation(t,c,u);d.push(...h.reasons);const g=h.result;if(g)return ai.of(e,{result:{variationKey:g},reasons:d});const p=this.getWhitelistedVariation(r,u);d.push(...p.reasons);let f=p.result;if(f)return ai.of(e,{result:{variationKey:f.key},reasons:d});if(s&&(f=this.getStoredVariation(t,r,u,s.userProfile),f))return null===(a=this.logger)||void 0===a||a.info(ui,f.key,c,u),d.push([ui,f.key,c,u]),ai.of(e,{result:{variationKey:f.key},reasons:d});const v=this.checkIfUserIsInAudience(t,r,Y,i,"");return d.push(...v.reasons),v.result?(this.isCmab(r)?this.getDecisionForCmabExperiment(e,t,r,i,n):this.getDecisionFromBucketer(e,t,r,i)).then(i=>{var n,o;if(d.push(...i.reasons),i.error)return ai.of(e,{error:!0,result:{},reasons:d});const a=i.result.variationId;return f=a?t.variationIdMap[a]:null,f?(null===(o=this.logger)||void 0===o||o.info(hi,u,f.key,c),d.push([hi,u,f.key,c]),s&&!this.isCmab(r)&&this.updateUserProfile(r,f,s),ai.of(e,{result:{variationKey:f.key,cmabUuid:i.result.cmabUuid},reasons:d})):(null===(n=this.logger)||void 0===n||n.debug(di,u,c),d.push([di,u,c]),ai.of(e,{result:{},reasons:d}))}):(null===(l=this.logger)||void 0===l||l.info(ci,u,c),d.push([ci,u,c]),ai.of(e,{result:{},reasons:d}))}getDecisionForCmabExperiment(e,t,r,i,n){if("sync"===e)return ai.of(e,{error:!1,result:{},reasons:[["CMAB is not supported in sync mode."]]});const s=i.getUserId(),o=i.getAttributes(),a=this.getBucketingId(s,o),l=this.buildBucketerParams(t,r,a,s),u=jr(l);if("$"!==u.result)return ai.of(e,{error:!1,result:{},reasons:u.reasons});const c=this.cmabService.getDecision(t,i,r.id,n).then(e=>({error:!1,result:e,reasons:[]})).catch(e=>{var t;return null===(t=this.logger)||void 0===t||t.error(Di,r.key),{error:!0,result:{},reasons:[[Di,r.key]]}});return ai.of(e,c)}getDecisionFromBucketer(e,t,r,i){const n=i.getUserId(),s=i.getAttributes(),o=this.getBucketingId(n,s),a=this.buildBucketerParams(t,r,o,n),l=jr(a);return ai.of(e,{result:{variationId:l.result||void 0},reasons:l.reasons})}getVariation(e,t,r,i={}){const n=i[Kt.IGNORE_USER_PROFILE_SERVICE]?void 0:{isProfileUpdated:!1,userProfile:this.resolveExperimentBucketMap("sync",r.getUserId(),r.getAttributes()).get()},s=this.resolveVariation("sync",e,t,r,i,n).get();return n&&this.saveUserProfile("sync",r.getUserId(),n),{result:s.result.variationKey||null,reasons:s.reasons}}resolveExperimentBucketMap(e,t,r={}){const i=r.$opt_experiment_bucket_map||{};return this.getUserProfile(e,t).then(t=>{const r=(null==t?void 0:t.experiment_bucket_map)||{};return ai.of(e,Object.assign(Object.assign({},r),i))})}getWhitelistedVariation(e,t){var r,i;const n=[];if(e.forcedVariations&&e.forcedVariations.hasOwnProperty(t)){const s=e.forcedVariations[t];return e.variationKeyMap.hasOwnProperty(s)?(null===(r=this.logger)||void 0===r||r.info(gi,t,s),n.push([gi,t,s]),{result:e.variationKeyMap[s],reasons:n}):(null===(i=this.logger)||void 0===i||i.error(pi,s,t),n.push([pi,s,t]),{result:null,reasons:n})}return{result:null,reasons:n}}checkIfUserIsInAudience(e,t,r,i,n){var s,o;const a=[],l=t.audienceConditions||t.audienceIds,u=e.audiencesById;null===(s=this.logger)||void 0===s||s.debug(fi,r,n||t.key,JSON.stringify(l)),a.push([fi,r,n||t.key,JSON.stringify(l)]);const c=this.audienceEvaluator.evaluate(l,u,i);return null===(o=this.logger)||void 0===o||o.info(vi,r,n||t.key,c.toString().toUpperCase()),a.push([vi,r,n||t.key,c.toString().toUpperCase()]),{result:c,reasons:a}}buildBucketerParams(e,t,r,i){let n=!0,s=t.trafficAllocation;return"cmab"in t&&t.cmab&&(s=[{entityId:"$",endOfRange:t.cmab.trafficAllocation}],n=!1),{bucketingId:r,experimentId:t.id,experimentKey:t.key,experimentIdMap:e.experimentIdMap,experimentKeyMap:e.experimentKeyMap,groupIdMap:e.groupIdMap,logger:this.logger,trafficAllocationConfig:s,userId:i,variationIdMap:e.variationIdMap,validateEntity:n}}getVariationForHoldout(e,t,r){var i,n,s,o,a;const l=r.getUserId(),u=[];if("Running"!==t.status){const e=[Ti,t.key];return u.push(e),null===(i=this.logger)||void 0===i||i.info(Ti,t.key),{result:{experiment:null,variation:null,decisionSource:Q.HOLDOUT},reasons:u}}const c=this.checkIfUserIsInAudience(e,t,Y,r);if(u.push(...c.reasons),!c.result){const e=[_i,l,t.key];return u.push(e),null===(n=this.logger)||void 0===n||n.info(_i,l,t.key),{result:{experiment:null,variation:null,decisionSource:Q.HOLDOUT},reasons:u}}const d=[Fi,l,t.key];u.push(d),null===(s=this.logger)||void 0===s||s.info(Fi,l,t.key);const h=r.getAttributes(),g=this.getBucketingId(l,h),p=this.buildBucketerParams(e,t,g,l),f=jr(p);if(u.push(...f.reasons),f.result){const r=e.variationIdMap[f.result];if(r){const e=[Ni,l,t.key,r.key];return u.push(e),null===(o=this.logger)||void 0===o||o.info(Ni,l,t.key,r.key),{result:{experiment:t,variation:r,decisionSource:Q.HOLDOUT},reasons:u}}}const v=[Ui,l];return u.push(v),null===(a=this.logger)||void 0===a||a.info(Ui,l),{result:{experiment:null,variation:null,decisionSource:Q.HOLDOUT},reasons:u}}getStoredVariation(e,t,r,i){var n;if(null==i?void 0:i.hasOwnProperty(t.id)){const s=i[t.id],o=s.variation_id;if(e.variationIdMap.hasOwnProperty(o))return e.variationIdMap[s.variation_id];null===(n=this.logger)||void 0===n||n.info("26",r,o,t.key)}return null}getUserProfile(e,t){var r;const i={user_id:t,experiment_bucket_map:{}};if(this.userProfileService){try{return ai.of(e,this.userProfileService.lookup(t))}catch(e){null===(r=this.logger)||void 0===r||r.error("66",t,e.message)}return ai.of(e,i)}return this.userProfileServiceAsync&&"async"===e?ai.of(e,this.userProfileServiceAsync.lookup(t).catch(e=>{var r;return null===(r=this.logger)||void 0===r||r.error("66",t,e.message),i})):ai.of(e,i)}updateUserProfile(e,t,r){r.userProfile&&(r.userProfile[e.id]={variation_id:t.id},r.isProfileUpdated=!0)}saveUserProfile(e,t,r){var i,n;const{userProfile:s,isProfileUpdated:o}=r;if(!s||!o)return ai.of(e,void 0);if("sync"===e&&!this.userProfileService)return ai.of(e,void 0);if(this.userProfileService){try{this.userProfileService.save({user_id:t,experiment_bucket_map:s}),null===(i=this.logger)||void 0===i||i.info("25",t)}catch(e){null===(n=this.logger)||void 0===n||n.error("67",t,e.message)}return ai.of(e,void 0)}return this.userProfileServiceAsync?ai.of(e,this.userProfileServiceAsync.save({user_id:t,experiment_bucket_map:s}).catch(e=>{var r;null===(r=this.logger)||void 0===r||r.error("67",t,e.message)})):ai.of(e,void 0)}getVariationsForFeatureList(e,t,r,i={}){return this.resolveVariationsForFeatureList("sync",e,t,r,i).get()}resolveVariationsForFeatureList(e,t,r,i,n){const s=i.getUserId(),o=i.getAttributes();return(n[Kt.IGNORE_USER_PROFILE_SERVICE]?ai.of(e,void 0):this.resolveExperimentBucketMap(e,s,o).then(t=>ai.of(e,{isProfileUpdated:!1,userProfile:t}))).then(o=>{const a=r.map(r=>this.resolveVariationForFlag(e,t,r,i,n,o)),l=ai.all(e,a);return l.then(()=>(o&&this.saveUserProfile(e,s,o),l))})}resolveVariationForFlag(e,t,r,i,n,s){const o=[],a=this.findValidatedForcedDecision(t,i,r.key);if(o.push(...a.reasons),a.result)return ai.of(e,{result:{variation:a.result,experiment:null,decisionSource:Q.FEATURE_TEST},reasons:o});const l=((e,t)=>{if(e.flagHoldoutsMap[t])return e.flagHoldoutsMap[t];const r=[...e.globalHoldouts.filter(r=>!(e.excludedHoldouts[t]||[]).includes(r)),...e.includedHoldouts[t]||[]];return e.flagHoldoutsMap[t]=r,r})(t,r.key);for(const r of l){const n=this.getVariationForHoldout(t,r,i);if(o.push(...n.reasons),n.result.variation)return ai.of(e,{result:n.result,reasons:o})}return this.getVariationForFeatureExperiment(e,t,r,i,n,s).then(n=>{var s,a;if(n.error||null!==n.result.variation)return ai.of(e,Object.assign(Object.assign({},n),{reasons:[...o,...n.reasons]}));o.push(...n.reasons);const l=this.getVariationForRollout(t,r,i);o.push(...l.reasons);const u=l.result,c=i.getUserId();return u.variation?(null===(s=this.logger)||void 0===s||s.debug(mi,c,r.key),o.push([mi,c,r.key])):(null===(a=this.logger)||void 0===a||a.debug(yi,c,r.key),o.push([yi,c,r.key])),ai.of(e,{result:u,reasons:o})})}getVariationForFeature(e,t,r,i={}){return this.resolveVariationsForFeatureList("sync",e,[t],r,i).get()[0]}getVariationForFeatureExperiment(e,t,r,i,n,s){var o;return 0===r.experimentIds.length?(null===(o=this.logger)||void 0===o||o.debug(bi,r.key),ai.of(e,{result:{experiment:null,variation:null,decisionSource:Q.FEATURE_TEST},reasons:[[bi,r.key]]})):this.traverseFeatureExperimentList(e,t,r,0,i,[],n,s)}traverseFeatureExperimentList(e,t,r,i,n,s,o,a){const l=r.experimentIds;if(i>=l.length)return ai.of(e,{result:{experiment:null,variation:null,decisionSource:Q.FEATURE_TEST},reasons:s});const u=function(e,t,r){if(e.experimentIdMap.hasOwnProperty(t)){const r=e.experimentIdMap[t];if(r)return r}return null==r||r.error("21",t),null}(t,l[i],this.logger);return u?this.getVariationFromExperimentRule(e,t,r.key,u,n,o,a).then(l=>{if(s.push(...l.reasons),l.error)return ai.of(e,{error:!0,result:{experiment:u,variation:null,decisionSource:Q.FEATURE_TEST},reasons:s});if(!l.result.variationKey)return this.traverseFeatureExperimentList(e,t,r,i+1,n,s,o,a);const c=l.result.variationKey;let d=u.variationKeyMap[c];return d||(d=it(t,r.key,c)),ai.of(e,{result:{cmabUuid:l.result.cmabUuid,experiment:u,variation:d,decisionSource:Q.FEATURE_TEST},reasons:s})}):this.traverseFeatureExperimentList(e,t,r,i+1,n,s,o,a)}getVariationForRollout(e,t,r){var i,n,s;const o=[];let a;if(!t.rolloutId)return null===(i=this.logger)||void 0===i||i.debug(xi,t.key),o.push([xi,t.key]),a={experiment:null,variation:null,decisionSource:Q.ROLLOUT},{result:a,reasons:o};const l=e.rolloutIdMap[t.rolloutId];if(!l)return null===(n=this.logger)||void 0===n||n.error(wi,t.rolloutId,t.key),o.push([wi,t.rolloutId,t.key]),a={experiment:null,variation:null,decisionSource:Q.ROLLOUT},{result:a,reasons:o};const u=l.experiments;if(0===u.length)return null===(s=this.logger)||void 0===s||s.error(Oi,t.rolloutId),o.push([Oi,t.rolloutId]),a={experiment:null,variation:null,decisionSource:Q.ROLLOUT},{result:a,reasons:o};let c,d,h,g,p=0;for(;p<u.length;){if(c=this.getVariationFromDeliveryRule(e,t.key,u,p,r),o.push(...c.reasons),h=c.result,d=c.skipToEveryoneElse,h)return g=e.experimentIdMap[u[p].id],a={experiment:g,variation:h,decisionSource:Q.ROLLOUT},{result:a,reasons:o};p=d?u.length-1:p+1}return a={experiment:null,variation:null,decisionSource:Q.ROLLOUT},{result:a,reasons:o}}getBucketingId(e,t){var r,i;let n=e;return null!=t&&"object"==typeof t&&t.hasOwnProperty($)&&("string"==typeof t[$]?(n=String(t[$]),null===(r=this.logger)||void 0===r||r.debug("37",n)):null===(i=this.logger)||void 0===i||i.warn("0")),n}findValidatedForcedDecision(e,t,r,i){var n,s,o,a;const l=[],u=t.getForcedDecision({flagKey:r,ruleKey:i});let c,d=null;const h=t.getUserId();return e&&u&&(c=u.variationKey,d=it(e,r,c),d?i?(null===(n=this.logger)||void 0===n||n.info(Ci,c,r,i,h),l.push([Ci,c,r,i,h])):(null===(s=this.logger)||void 0===s||s.info(Pi,c,r,h),l.push([Pi,c,r,h])):i?(null===(o=this.logger)||void 0===o||o.info(Ai,r,i,h),l.push([Ai,r,i,h])):(null===(a=this.logger)||void 0===a||a.info(ji,r,h),l.push([ji,r,h]))),{result:d,reasons:l}}removeForcedVariation(e,t,r){var i;if(!e)throw new pe("26");if(!this.forcedVariationMap.hasOwnProperty(e))throw new pe("65",e);delete this.forcedVariationMap[e][t],null===(i=this.logger)||void 0===i||i.debug("41",r,e)}setInForcedVariationMap(e,t,r){var i;this.forcedVariationMap.hasOwnProperty(e)||(this.forcedVariationMap[e]={}),this.forcedVariationMap[e][t]=r,null===(i=this.logger)||void 0===i||i.debug("34",r,t,e)}getForcedVariation(e,t,r){var i,n,s,o,a,l;const u=[],c=this.forcedVariationMap[r];if(!c)return null===(i=this.logger)||void 0===i||i.debug("32",r),{result:null,reasons:u};let d;try{const r=rt(e,t);if(!r.hasOwnProperty("id"))return null===(n=this.logger)||void 0===n||n.error(ki,t),u.push([ki,t]),{result:null,reasons:u};d=r.id}catch(p){return null===(s=this.logger)||void 0===s||s.error(p),u.push(p.message),{result:null,reasons:u}}const h=c[d];if(!h)return null===(o=this.logger)||void 0===o||o.debug("33",t,r),{result:null,reasons:u};const g=(f=h,(p=e).variationIdMap.hasOwnProperty(f)?p.variationIdMap[f].key:null);var p,f;return g?(null===(a=this.logger)||void 0===a||a.debug(Mi,g,t,r),u.push([Mi,g,t,r])):null===(l=this.logger)||void 0===l||l.debug("33",t,r),{result:g,reasons:u}}setForcedVariation(e,t,r,i){var n,s,o,a,l,u;if(null!=i&&!oi(i))return null===(n=this.logger)||void 0===n||n.error("28"),!1;let c;try{const r=rt(e,t);if(!r.hasOwnProperty("id"))return null===(s=this.logger)||void 0===s||s.error(ki,t),!1;c=r.id}catch(e){return null===(o=this.logger)||void 0===o||o.error(e),!1}if(null==i)try{return this.removeForcedVariation(r,c,t),!0}catch(e){return null===(a=this.logger)||void 0===a||a.error(e),!1}const d=function(e,t,r){const i=e.experimentKeyMap[t];return i.variationKeyMap.hasOwnProperty(r)?i.variationKeyMap[r].id:null}(e,t,i);if(!d)return null===(l=this.logger)||void 0===l||l.error("37",i,t),!1;try{return this.setInForcedVariationMap(r,c,d),!0}catch(e){return null===(u=this.logger)||void 0===u||u.error(e),!1}}getVariationFromExperimentRule(e,t,r,i,n,s,o){const a=[],l=this.findValidatedForcedDecision(t,n,r,i.key);a.push(...l.reasons);const u=l.result;return u?ai.of(e,{result:{variationKey:u.key},reasons:a}):this.resolveVariation(e,t,i,n,s,o).then(t=>(a.push(...t.reasons),ai.of(e,{error:t.error,result:t.result,reasons:a})))}getVariationFromDeliveryRule(e,t,r,i,n){var s,o,a,l;const u=[];let c=!1;const d=r[i],h=this.findValidatedForcedDecision(e,n,t,d.key);u.push(...h.reasons);const g=h.result;if(g)return{result:g,reasons:u,skipToEveryoneElse:c};const p=n.getUserId(),f=n.getAttributes(),v=this.getBucketingId(p,f),m=i===r.length-1,y=m?"Everyone Else":i+1;let b,E,I,S=null;const x=this.checkIfUserIsInAudience(e,d,"rule",n,y);var w,O;return u.push(...x.reasons),x.result?(null===(s=this.logger)||void 0===s||s.debug(Ri,p,y),u.push([Ri,p,y]),E=this.buildBucketerParams(e,d,v,p),I=jr(E),u.push(...I.reasons),b=I.result,b&&(O=b,S=(w=e).variationIdMap.hasOwnProperty(O)?w.variationIdMap[O]:null),S?(null===(o=this.logger)||void 0===o||o.debug(Si,p,y),u.push([Si,p,y])):m||(null===(a=this.logger)||void 0===a||a.debug(Ii,p,y),u.push([Ii,p,y]),c=!0)):(null===(l=this.logger)||void 0===l||l.debug(Ei,p,y),u.push([Ei,p,y])),{result:S,reasons:u,skipToEveryoneElse:c}}},Li=class extends dt{constructor(e){var t,r,i,n,s,o,a,l,u,c,d;super(),this.cleanupTasks=new Map,this.nextCleanupTaskId=0;let h=e.clientEngine;h||(null===(t=e.logger)||void 0===t||t.info("13",h),h=G),this.clientEngine=h,this.clientVersion=e.clientVersion||W,this.errorNotifier=e.errorNotifier,this.logger=e.logger,this.projectConfigManager=e.projectConfigManager,this.errorReporter=new Er(this.logger,this.errorNotifier),this.odpManager=e.odpManager,this.vuidManager=e.vuidManager,this.eventProcessor=e.eventProcessor,e.disposable&&(this.projectConfigManager.makeDisposable(),null===(r=this.eventProcessor)||void 0===r||r.makeDisposable(),null===(i=this.odpManager)||void 0===i||i.makeDisposable()),this.logger&&(this.projectConfigManager.setLogger(this.logger.child()),null===(n=this.eventProcessor)||void 0===n||n.setLogger(this.logger.child()),null===(s=this.odpManager)||void 0===s||s.setLogger(this.logger.child()));let g=null!==(o=e.defaultDecideOptions)&&void 0!==o?o:[];Array.isArray(g)||(null===(a=this.logger)||void 0===a||a.debug("15"),g=[]);const p={};let f;if(g.forEach(e=>{var t;Kt[e]?p[e]=!0:null===(t=this.logger)||void 0===t||t.warn("63",e)}),this.defaultDecideOptions=p,this.projectConfigManager=e.projectConfigManager,this.projectConfigManager.onUpdate(e=>{var t;null===(t=this.logger)||void 0===t||t.info("31",e.revision,e.projectId),this.notificationCenter.sendNotifications(Bt.OPTIMIZELY_CONFIG_UPDATE,void 0),this.updateOdpSettings()}),this.eventProcessor=e.eventProcessor,null===(l=this.eventProcessor)||void 0===l||l.onDispatch(e=>{this.notificationCenter.sendNotifications(Bt.LOG_EVENT,e)}),this.odpManager=e.odpManager,e.userProfileService)try{(function(e){if("object"==typeof e&&null!==e){if("function"!=typeof e.lookup)throw new pe(Se,"Missing function 'lookup'");if("function"!=typeof e.save)throw new pe(Se,"Missing function 'save'");return!0}throw new pe(Se,"Not an object")})(e.userProfileService)&&(f=e.userProfileService,null===(u=this.logger)||void 0===u||u.info("39"))}catch(m){null===(c=this.logger)||void 0===c||c.warn(m)}var v,m;this.decisionService=(v={userProfileService:f,userProfileServiceAsync:e.userProfileServiceAsync||void 0,cmabService:e.cmabService,logger:null===(d=this.logger)||void 0===d?void 0:d.child(),UNSTABLE_conditionEvaluators:e.UNSTABLE_conditionEvaluators},new Vi(v)),this.notificationCenter=(m={logger:this.logger,errorNotifier:this.errorNotifier},new Ir(m)),this.start()}start(){var e,t;this.isNew()&&(super.start(),this.state=lt.Starting,this.projectConfigManager.start(),null===(e=this.eventProcessor)||void 0===e||e.start(),null===(t=this.odpManager)||void 0===t||t.start(),Promise.all([this.projectConfigManager.onRunning(),this.eventProcessor?this.eventProcessor.onRunning():Promise.resolve(),this.odpManager?this.odpManager.onRunning():Promise.resolve(),this.vuidManager?this.vuidManager.initialize():Promise.resolve()]).then(()=>{var e,t;this.state=lt.Running,this.startPromise.resolve();const r=null===(e=this.vuidManager)||void 0===e?void 0:e.getVuid();r&&(null===(t=this.odpManager)||void 0===t||t.setVuid(r))}).catch(e=>{this.state=lt.Failed,this.errorReporter.report(e),this.startPromise.reject(e)}))}getProjectConfig(){return this.projectConfigManager.getConfig()||null}activate(e,t,r){var i,n,s;try{const o=this.getProjectConfig();if(!o)return this.errorReporter.report(xe,"activate"),null;if(!this.validateInputs({experiment_key:e,user_id:t},r))return this.notActivatingExperiment(e,t);try{const n=this.getVariation(e,t,r);if(null===n)return this.notActivatingExperiment(e,t);if(tt(s=o,e)!==Qe)return null===(i=this.logger)||void 0===i||i.debug("27",e),n;const a=rt(o,e),l={experiment:a,variation:a.variationKeyMap[n],decisionSource:Q.EXPERIMENT};return this.sendImpressionEvent(l,"",t,!0,r),n}catch(r){return null===(n=this.logger)||void 0===n||n.info("19",t,e),this.errorReporter.report(r),null}}catch(s){return this.errorReporter.report(s),null}}sendImpressionEvent(e,t,r,i,n){var s;if(!this.eventProcessor)return void(null===(s=this.logger)||void 0===s||s.error("33"));const o=this.getProjectConfig();if(!o)return;const a=function({configObj:e,decisionObj:t,userId:r,flagKey:i,enabled:n,userAttributes:s,clientEngine:o,clientVersion:a}){const l=t.decisionSource,u=Nt(t),c=null!==(v=null===(f=t.experiment)||void 0===f?void 0:f.id)&&void 0!==v?v:null,d=Ut(t),h=function(e){var t,r;return null!==(r=null===(t=e.variation)||void 0===t?void 0:t.id)&&void 0!==r?r:null}(t),g=t.cmabUuid,p=null!==c?l===Q.HOLDOUT?"":function(e,t){const r=e.experimentIdMap[t];if(!r)throw new pe("21",t);return r.layerId}(e,c):null;var f,v;return Object.assign(Object.assign({},Jt({configObj:e,userId:r,userAttributes:s,clientEngine:o,clientVersion:a,type:"impression"})),{layer:{id:p},experiment:{id:c,key:u},variation:{id:h,key:d},ruleKey:u,flagKey:i,ruleType:l,enabled:n,cmabUuid:g})}({decisionObj:e,flagKey:t,enabled:i,userId:r,userAttributes:n,clientEngine:this.clientEngine,clientVersion:this.clientVersion,configObj:o});this.eventProcessor.process(a);const l=Dt([a]),u={experiment:null,holdout:null,userId:r,attributes:n,variation:e.variation,logEvent:l};var c;e.experiment&&(void 0!==(c=e.experiment).status&&Array.isArray(c.includedFlags)&&Array.isArray(c.excludedFlags)?u.holdout=e.experiment:u.experiment=e.experiment),this.notificationCenter.sendNotifications(Bt.ACTIVATE,u)}track(e,t,r,i){var n,s,o,a,l,u,c;try{if(!this.eventProcessor)return void(null===(n=this.logger)||void 0===n||n.error("33"));const l=this.getProjectConfig();if(!l)return void this.errorReporter.report(xe,"track");if(!this.validateInputs({user_id:t,event_key:e},r,i))return;if(c=e,!(u=l).eventKeyMap.hasOwnProperty(c))return null===(s=this.logger)||void 0===s||s.warn("7",e),void(null===(o=this.logger)||void 0===o||o.warn("31",t));const d=function({configObj:e,userId:t,userAttributes:r,clientEngine:i,clientVersion:n,eventKey:s,eventTags:o},a){const l=function(e,t){const r=e.eventKeyMap[t];return r?r.id:null}(e,s),u=o?function(e,t){const r=e.revenue;if(null==r)return null;const i="string"==typeof r?parseInt(r):Math.trunc(r);return isFinite(i)?(null==t||t.info("21",i),i):(null==t||t.info("6",r),null)}(o,a):null,c=o?function(e,t){const r=e.value;if(null==r)return null;const i="string"==typeof r?parseFloat(r):r;return isFinite(i)?(null==t||t.info("20",i),i):(null==t||t.info("7",r),null)}(o,a):null;return Object.assign(Object.assign({},Jt({configObj:e,userId:t,userAttributes:r,clientEngine:i,clientVersion:n,type:"conversion"})),{event:{id:l,key:s},revenue:u,value:c,tags:o})}({eventKey:e,eventTags:i=this.filterEmptyValues(i),userId:t,userAttributes:r,clientEngine:this.clientEngine,clientVersion:this.clientVersion,configObj:l},this.logger);null===(a=this.logger)||void 0===a||a.info("29",e,t),this.eventProcessor.process(d);const h=Dt([d]);this.notificationCenter.sendNotifications(Bt.TRACK,{eventKey:e,userId:t,attributes:r,eventTags:i,logEvent:h})}catch(u){this.errorReporter.report(u),null===(l=this.logger)||void 0===l||l.error("31",t)}}getVariation(e,t,r){var i,n,s;try{const o=this.getProjectConfig();if(!o)return this.errorReporter.report(xe,"getVariation"),null;try{if(!this.validateInputs({experiment_key:e,user_id:t},r))return null;const a=o.experimentKeyMap[e];if(!a||a.isRollout)return null===(i=this.logger)||void 0===i||i.debug("16",e),null;const l=this.decisionService.getVariation(o,a,this.createInternalUserContext(t,r)).result,u=(n=o,s=a.id,n.experimentFeatureMap.hasOwnProperty(s)?qt.FEATURE_TEST:qt.AB_TEST);return this.notificationCenter.sendNotifications(Bt.DECISION,{type:u,userId:t,attributes:r||{},decisionInfo:{experimentKey:e,variationKey:l}}),l}catch(e){return this.errorReporter.report(e),null}}catch(e){return this.errorReporter.report(e),null}}setForcedVariation(e,t,r){if(!this.validateInputs({experiment_key:e,user_id:t}))return!1;const i=this.getProjectConfig();if(!i)return!1;try{return this.decisionService.setForcedVariation(i,e,t,r)}catch(e){return this.errorReporter.report(e),!1}}getForcedVariation(e,t){if(!this.validateInputs({experiment_key:e,user_id:t}))return null;const r=this.getProjectConfig();if(!r)return null;try{return this.decisionService.getForcedVariation(r,e,t).result}catch(e){return this.errorReporter.report(e),null}}validateInputs(e,t,r){try{if(e.hasOwnProperty("user_id")){const t=e.user_id;if("string"!=typeof t||null===t||"undefined"===t)throw new pe("24","user_id");delete e.user_id}return Object.keys(e).forEach(t=>{if(!oi(e[t]))throw new pe("24",t)}),t&&function(e){if("object"!=typeof e||Array.isArray(e)||null===e)throw new pe("13");Object.keys(e).forEach(function(t){if(void 0===e[t])throw new pe("56",t)})}(t),r&&function(e){if("object"!=typeof e||Array.isArray(e)||null===e)throw new pe("20")}(r),!0}catch(e){return this.errorReporter.report(e),!1}}notActivatingExperiment(e,t){var r;return null===(r=this.logger)||void 0===r||r.info("19",t,e),null}filterEmptyValues(e){for(const t in e){const r=t;!e.hasOwnProperty(r)||null!==e[r]&&void 0!==e[r]||delete e[r]}return e}isFeatureEnabled(e,t,r){var i,n;try{const s=this.getProjectConfig();if(!s)return this.errorReporter.report(xe,"isFeatureEnabled"),!1;if(!this.validateInputs({feature_key:e,user_id:t},r))return!1;const o=nt(s,e,this.logger);if(!o)return!1;let a={};const l=this.createInternalUserContext(t,r),u=this.decisionService.getVariationForFeature(s,o,l).result,c=u.decisionSource,d=Nt(u),h=Ut(u);let g=Vt(u);c!==Q.FEATURE_TEST&&c!==Q.HOLDOUT||(a={experimentKey:d,variationKey:h}),(c===Q.FEATURE_TEST||c===Q.HOLDOUT||c===Q.ROLLOUT&&st(s))&&this.sendImpressionEvent(u,o.key,t,g,r),!0===g?null===(i=this.logger)||void 0===i||i.info("8",e,t):(null===(n=this.logger)||void 0===n||n.info("9",e,t),g=!1);const p={featureKey:e,featureEnabled:g,source:u.decisionSource,sourceInfo:a};return this.notificationCenter.sendNotifications(Bt.DECISION,{type:qt.FEATURE,userId:t,attributes:r||{},decisionInfo:p}),g}catch(e){return this.errorReporter.report(e),!1}}getEnabledFeatures(e,t){try{const r=[],i=this.getProjectConfig();return i?this.validateInputs({user_id:e})?(le(i.featureKeyMap).forEach(i=>{this.isFeatureEnabled(i.key,e,t)&&r.push(i.key)}),r):r:(this.errorReporter.report(xe,"getEnabledFeatures"),r)}catch(e){return this.errorReporter.report(e),[]}}getFeatureVariable(e,t,r,i){try{return this.getProjectConfig()?this.getFeatureVariableForType(e,t,null,r,i):(this.errorReporter.report(xe,"getFeatureVariable"),null)}catch(e){return this.errorReporter.report(e),null}}getFeatureVariableForType(e,t,r,i,n){var s;if(!this.validateInputs({feature_key:e,variable_key:t,user_id:i},n))return null;const o=this.getProjectConfig();if(!o)return null;const a=nt(o,e,this.logger);if(!a)return null;const l=function(e,t,r,i){const n=e.featureKeyMap[t];if(!n)return null==i||i.error(Ie,t),null;return n.variableKeyMap[r]||(null==i||i.error("68",r,t),null)}(o,e,t,this.logger);if(!l)return null;if(r&&l.type!==r)return null===(s=this.logger)||void 0===s||s.warn("69",r,l.type),null;const u=this.createInternalUserContext(i,n),c=this.decisionService.getVariationForFeature(o,a,u).result,d=Vt(c),h=this.getFeatureVariableValueFromVariation(e,d,c.variation,l,i);let g={};return c.decisionSource===Q.FEATURE_TEST&&null!==c.experiment&&null!==c.variation&&(g={experimentKey:c.experiment.key,variationKey:c.variation.key}),this.notificationCenter.sendNotifications(Bt.DECISION,{type:qt.FEATURE_VARIABLE,userId:i,attributes:n||{},decisionInfo:{featureKey:e,featureEnabled:d,source:c.decisionSource,variableKey:t,variableValue:h,variableType:l.type,sourceInfo:g}}),h}getFeatureVariableValueFromVariation(e,t,r,i,n){var s,o,a,l;const u=this.getProjectConfig();if(!u)return null;let c=i.defaultValue;if(null!==r){const l=function(e,t,r,i){if(!t||!r)return null;if(!e.variationVariableUsageMap.hasOwnProperty(r.id))return null==i||i.error("70",r.id),null;const n=e.variationVariableUsageMap[r.id][t.id];return n?n.value:null}(u,i,r,this.logger);null!==l?t?(c=l,null===(s=this.logger)||void 0===s||s.info("36",c,i.key,e)):null===(o=this.logger)||void 0===o||o.info("10",e,n,c):null===(a=this.logger)||void 0===a||a.info("40",i.key,r.key)}else null===(l=this.logger)||void 0===l||l.info("35",n,i.key,e);return function(e,t,r){let i;switch(t){case X:"true"!==e&&"false"!==e?(null==r||r.error(we,e,t),i=null):i="true"===e;break;case ee:i=parseInt(e,10),isNaN(i)&&(null==r||r.error(we,e,t),i=null);break;case Z:i=parseFloat(e),isNaN(i)&&(null==r||r.error(we,e,t),i=null);break;case re:try{i=JSON.parse(e)}catch(n){null==r||r.error(we,e,t),i=null}break;default:i=e}return i}(c,i.type,this.logger)}getFeatureVariableBoolean(e,t,r,i){try{return this.getProjectConfig()?this.getFeatureVariableForType(e,t,X,r,i):(this.errorReporter.report(xe,"getFeatureVariableBoolean"),null)}catch(e){return this.errorReporter.report(e),null}}getFeatureVariableDouble(e,t,r,i){try{return this.getProjectConfig()?this.getFeatureVariableForType(e,t,Z,r,i):(this.errorReporter.report(xe,"getFeatureVariableDouble"),null)}catch(e){return this.errorReporter.report(e),null}}getFeatureVariableInteger(e,t,r,i){try{return this.getProjectConfig()?this.getFeatureVariableForType(e,t,ee,r,i):(this.errorReporter.report(xe,"getFeatureVariableInteger"),null)}catch(e){return this.errorReporter.report(e),null}}getFeatureVariableString(e,t,r,i){try{return this.getProjectConfig()?this.getFeatureVariableForType(e,t,te,r,i):(this.errorReporter.report(xe,"getFeatureVariableString"),null)}catch(e){return this.errorReporter.report(e),null}}getFeatureVariableJSON(e,t,r,i){try{return this.getProjectConfig()?this.getFeatureVariableForType(e,t,re,r,i):(this.errorReporter.report(xe,"getFeatureVariableJSON"),null)}catch(e){return this.errorReporter.report(e),null}}getAllFeatureVariables(e,t,r){try{const i=this.getProjectConfig();if(!i)return this.errorReporter.report(xe,"getAllFeatureVariables"),null;if(!this.validateInputs({feature_key:e,user_id:t},r))return null;const n=nt(i,e,this.logger);if(!n)return null;const s=this.createInternalUserContext(t,r),o=this.decisionService.getVariationForFeature(i,n,s).result,a=Vt(o),l={};n.variables.forEach(r=>{l[r.key]=this.getFeatureVariableValueFromVariation(e,a,o.variation,r,t)});let u={};return o.decisionSource===Q.FEATURE_TEST&&null!==o.experiment&&null!==o.variation&&(u={experimentKey:o.experiment.key,variationKey:o.variation.key}),this.notificationCenter.sendNotifications(Bt.DECISION,{type:qt.ALL_FEATURE_VARIABLES,userId:t,attributes:r||{},decisionInfo:{featureKey:e,featureEnabled:a,source:o.decisionSource,variableValues:l,sourceInfo:u}}),l}catch(e){return this.errorReporter.report(e),null}}getOptimizelyConfig(){try{return this.getProjectConfig()&&this.projectConfigManager.getOptimizelyConfig()||null}catch(e){return this.errorReporter.report(e),null}}flushImmediately(){const e=[];return this.isRunning()?(this.eventProcessor&&e.push(this.eventProcessor.flushImmediately()),this.odpManager&&e.push(this.odpManager.flushImmediately()),Promise.all(e)):Promise.resolve()}close(){return this.stop(),this.onTerminated()}stop(){var e,t;this.isDone()||(this.isRunning()||this.startPromise.reject(new Error(de(ct,"Client"))),this.state=lt.Stopping,this.projectConfigManager.stop(),null===(e=this.eventProcessor)||void 0===e||e.stop(),null===(t=this.odpManager)||void 0===t||t.stop(),this.notificationCenter.clearAllNotificationListeners(),this.cleanupTasks.forEach(e=>e()),Promise.all([this.projectConfigManager.onTerminated(),this.eventProcessor?this.eventProcessor.onTerminated():Promise.resolve(),this.odpManager?this.odpManager.onTerminated():Promise.resolve()]).then(()=>{this.state=lt.Terminated,this.stopPromise.resolve()}).catch(e=>{this.errorReporter.report(e),this.state=lt.Failed,this.stopPromise.reject(e)}))}onReady(e){let t;"object"==typeof e&&null!==e&&void 0!==e.timeout&&(t=e.timeout),se(t)||(t=3e4);const r=at(),i=this.nextCleanupTaskId++,n=setTimeout(()=>{this.cleanupTasks.delete(i),r.reject(new Error(de("onReady timeout expired after %s ms",t)))},t);return this.cleanupTasks.set(i,()=>{clearTimeout(n),r.reject(new Error("Instance closed"))}),Promise.race([this.onRunning().then(()=>{clearTimeout(n),this.cleanupTasks.delete(i)}),r])}createUserContext(e,t){var r;const i=null!=e?e:null===(r=this.vuidManager)||void 0===r?void 0:r.getVuid();if(void 0===i||!this.validateInputs({user_id:i}))throw new Error("Invalid identifier");if(!this.validateInputs({},t))throw new Error("Invalid attributes");const n=new wr({optimizely:this,userId:i,attributes:t});return this.onRunning().then(()=>{this.odpManager&&this.isOdpIntegrated()&&this.odpManager.identifyUser(i)}).catch(()=>{}),n}createInternalUserContext(e,t){return new wr({optimizely:this,userId:e,attributes:t})}decide(e,t,r=[]){return this.getProjectConfig()?this.decideForKeys(e,[t],r,!0)[t]:(this.errorReporter.report(xe,"decide"),Sr(t,e,[ie]))}decideAsync(e,t,r=[]){return pt(this,void 0,void 0,function*(){return this.getProjectConfig()?(yield this.decideForKeysAsync(e,[t],r,!0))[t]:(this.errorReporter.report(xe,"decide"),Sr(t,e,[ie]))})}getAllDecideOptions(e){var t;const r=Object.assign({},this.defaultDecideOptions);return Array.isArray(e)?e.forEach(e=>{var t;Kt[e]?r[e]=!0:null===(t=this.logger)||void 0===t||t.warn("63",e)}):null===(t=this.logger)||void 0===t||t.debug("14"),r}generateDecision(e,t,r,i,n,s){var o,a,l,u,c,d,h,g,p,f;const v=e.getUserId(),m=e.getAttributes(),y=s.featureKeyMap[t],b=r.decisionSource,E=null!==(a=null===(o=r.experiment)||void 0===o?void 0:o.key)&&void 0!==a?a:null,I=null!==(u=null===(l=r.experiment)||void 0===l?void 0:l.id)&&void 0!==u?u:null,S=null!==(d=null===(c=r.variation)||void 0===c?void 0:c.key)&&void 0!==d?d:null,x=null!==(g=null===(h=r.variation)||void 0===h?void 0:h.id)&&void 0!==g?g:null,w=Vt(r),O={};let k=!1;w?null===(p=this.logger)||void 0===p||p.info("8",t,v):null===(f=this.logger)||void 0===f||f.info("9",t,v),n[Kt.EXCLUDE_VARIABLES]||y.variables.forEach(e=>{O[e.key]=this.getFeatureVariableValueFromVariation(t,w,r.variation,e,v)}),!n[Kt.DISABLE_DECISION_EVENT]&&(b===Q.FEATURE_TEST||b===Q.HOLDOUT||b===Q.ROLLOUT&&st(s))&&(this.sendImpressionEvent(r,t,v,w,m),k=!0);let M=[];n[Kt.INCLUDE_REASONS]&&(M=i.map(e=>de(e[0],...e.slice(1))));const R={flagKey:t,enabled:w,variationKey:S,ruleKey:E,variables:O,reasons:M,decisionEventDispatched:k,experimentId:I,variationId:x};return this.notificationCenter.sendNotifications(Bt.DECISION,{type:qt.FLAG,userId:v,attributes:m,decisionInfo:R}),{variationKey:S,enabled:w,variables:O,ruleKey:E,flagKey:t,userContext:e,reasons:M}}decideForKeys(e,t,r=[],i){return this.getDecisionForKeys("sync",e,t,r,i).get()}decideForKeysAsync(e,t,r=[],i){return this.getDecisionForKeys("async",e,t,r,i).get()}getDecisionForKeys(e,t,r,i=[],n){var s;const o={},a={},l={},u=this.getProjectConfig();if(!u)return this.errorReporter.report(xe,"decideForKeys"),ai.of(e,o);if(0===r.length)return ai.of(e,o);const c=this.getAllDecideOptions(i);n&&delete c[Kt.ENABLED_FLAGS_ONLY];const d=[];for(const e of r){const r=u.featureKeyMap[e];r?d.push(r):(null===(s=this.logger)||void 0===s||s.error(Ie,e),o[e]=Sr(e,t,[de('No flag was found for key "%s".',e)]))}return this.decisionService.resolveVariationsForFeatureList(e,u,d,t,c).then(r=>{for(let e=0;e<d.length;e++){const i=d[e].key,n=r[e];n.error?o[i]=Sr(i,t,n.reasons.map(e=>de(e[0],...e.slice(1)))):(a[i]=n.result,l[i]=n.reasons)}for(const e of d){const r=e.key;if(o[r])continue;const i=this.generateDecision(t,r,a[r],l[r],c,u);c[Kt.ENABLED_FLAGS_ONLY]&&!i.enabled||(o[r]=i)}return ai.of(e,o)})}decideAll(e,t=[]){const r=this.getProjectConfig();if(!r)return this.errorReporter.report(xe,"decideAll"),{};const i=Object.keys(r.featureKeyMap);return this.decideForKeys(e,i,t)}decideAllAsync(e,t=[]){return pt(this,void 0,void 0,function*(){const r=this.getProjectConfig();if(!r)return this.errorReporter.report(xe,"decideAll"),{};const i=Object.keys(r.featureKeyMap);return this.decideForKeysAsync(e,i,t)})}updateOdpSettings(){const e=this.getProjectConfig();e&&this.odpManager&&this.odpManager.updateConfig(e.odpIntegrationConfig)}sendOdpEvent(e,t,r,i){var n,s;if(this.odpManager)try{const n=new lr(t||"",e,r,i);this.odpManager.sendEvent(n)}catch(e){null===(s=this.logger)||void 0===s||s.error("40",e)}else null===(n=this.logger)||void 0===n||n.error("42","sendOdpEvent")}isOdpIntegrated(){var e,t,r;return null!==(r=null===(t=null===(e=this.getProjectConfig())||void 0===e?void 0:e.odpIntegrationConfig)||void 0===t?void 0:t.integrated)&&void 0!==r&&r}fetchQualifiedSegments(e,t){var r;return pt(this,void 0,void 0,function*(){return this.odpManager?yield this.odpManager.fetchQualifiedSegments(e,t):(null===(r=this.logger)||void 0===r||r.error("42","fetchQualifiedSegments"),null)})}getVuid(){var e;if(this.vuidManager)return this.vuidManager.getVuid();null===(e=this.logger)||void 0===e||e.error("54")}},Ki=class{constructor(e){this.predictionEndpointTemplate="https://prediction.cmab.optimizely.com/predict/%s",this.requestHandler=e.requestHandler,this.retryConfig=e.retryConfig,e.predictionEndpointTemplate&&(this.predictionEndpointTemplate=e.predictionEndpointTemplate)}fetchDecision(e,t,r,i){var n,s;return pt(this,void 0,void 0,function*(){const o=de(this.predictionEndpointTemplate,e),a=Object.keys(r).map(e=>({id:e,value:r[e],type:"custom_attribute"})),l={instances:[{visitorId:t,experimentId:e,attributes:a,cmabUUID:i}]};return yield this.retryConfig?Ft(()=>this.doFetch(o,JSON.stringify(l)),null===(s=(n=this.retryConfig).backoffProvider)||void 0===s?void 0:s.call(n),this.retryConfig.maxRetries).result:this.doFetch(o,JSON.stringify(l))})}doFetch(e,t){return pt(this,void 0,void 0,function*(){const r=yield this.requestHandler.makeRequest(e,{"Content-Type":"application/json"},"POST",t).responsePromise;if(!ft(r.statusCode))return Promise.reject(new pe("CMAB decision fetch failed with status: %s",r.statusCode));const i=JSON.parse(r.body);return this.validateResponse(i)?String(i.predictions[0].variation_id):Promise.reject(new pe("Invalid CMAB fetch response"))})}validateResponse(e){return e.predictions&&e.predictions.length>0&&e.predictions[0].variation_id}},qi=class{constructor(e){var t;this.serializers=Array.from({length:1e3},()=>new Qt),this.cmabCache=e.cmabCache,this.cmabClient=e.cmabClient,this.logger=e.logger,null===(t=this.logger)||void 0===t||t.setName("CmabService")}getSerializerIndex(e,t){const r=this.getCacheKey(e,t),i=L.default.v3(r);return Math.abs(i)%1e3}getDecision(e,t,r,i){return pt(this,void 0,void 0,function*(){const n=this.getSerializerIndex(t.getUserId(),r);return this.serializers[n].run(()=>this.getDecisionInternal(e,t,r,i))})}getDecisionInternal(e,t,r,i){var n,s,o,a,l,u;return pt(this,void 0,void 0,function*(){const c=t.getUserId(),d=this.filterAttributes(e,t,r);if(i[Kt.IGNORE_CMAB_CACHE])return null===(n=this.logger)||void 0===n||n.debug("11",c,r),this.fetchDecision(r,c,d);i[Kt.RESET_CMAB_CACHE]&&(null===(s=this.logger)||void 0===s||s.debug("22",c,r),this.cmabCache.reset());const h=this.getCacheKey(c,r);i[Kt.INVALIDATE_USER_CMAB_CACHE]&&(null===(o=this.logger)||void 0===o||o.debug("12",c,r),this.cmabCache.remove(h));const g=yield this.cmabCache.lookup(h),p=JSON.stringify(d,Object.keys(d).sort()),f=String(L.default.v3(p));if(g){if(g.attributesHash===f)return null===(a=this.logger)||void 0===a||a.debug("3",c,r),{variationId:g.variationId,cmabUuid:g.cmabUuid};null===(l=this.logger)||void 0===l||l.debug("2",c,r),this.cmabCache.remove(h)}else null===(u=this.logger)||void 0===u||u.debug("4",c,r);const v=yield this.fetchDecision(r,c,d);return this.cmabCache.save(h,{attributesHash:f,variationId:v.variationId,cmabUuid:v.cmabUuid}),v})}fetchDecision(e,t,r){return pt(this,void 0,void 0,function*(){const i=U();return{variationId:yield this.cmabClient.fetchDecision(e,t,r,i),cmabUuid:i}})}filterAttributes(e,t,r){const i={},n=t.getAttributes(),s=e.experimentIdMap[r];return s&&s.cmab?(s.cmab.attributeIds.forEach(t=>{const r=e.attributeIdMap[t];n.hasOwnProperty(r.key)&&(i[r.key]=n[r.key])}),i):i}getCacheKey(e,t){return`${e.length}-${e}-${t}`}},Bi=e=>{var t,r;const{clientEngine:i,clientVersion:n,jsonSchemaValidator:s,userProfileService:o,userProfileServiceAsync:a,defaultDecideOptions:l,disposable:u,requestHandler:c}=e,d=(e=>{if(!e||"object"!=typeof e)throw new Error(It);if(!e[St])throw new Error(It);return e[St]})(e.projectConfigManager),h=(e=>{if(e&&"object"==typeof e)return e[Zt]})(e.eventProcessor),g=(e=>{if(e&&"object"==typeof e)return e[mr]})(e.odpManager),p=(e=>{if(e&&"object"==typeof e)return e[br]})(e.vuidManager),f=(e=>{if(e&&"object"==typeof e)return e[Be]})(e.errorNotifier),v=(e=>{if(e&&"object"==typeof e)return e[Le]})(e.logger),m=new Ki({requestHandler:c,retryConfig:{maxRetries:1,backoffProvider:()=>new yt(100)},predictionEndpointTemplate:null===(t=e.cmab)||void 0===t?void 0:t.predictionEndpointTemplate}),y=(null===(r=e.cmab)||void 0===r?void 0:r.cache)?((e,t)=>{const r=(e,t)=>{if(void 0!==e)return t(e)},i={lookup:i=>"sync"===e.operation?r(e.lookup(i),t):e.lookup(i).then(e=>r(e,t)),save:(t,r)=>e.save(t,(e=>JSON.stringify(e))(r))};return Object.setPrototypeOf(i,e),i})(e.cmab.cache,e=>JSON.parse(e)):(()=>{var t,r;const i=(null===(t=e.cmab)||void 0===t?void 0:t.cacheSize)||1e4,n=(null===(r=e.cmab)||void 0===r?void 0:r.cacheTtl)||18e5;return new rr(i,n)})(),b={cmabService:new qi({cmabClient:m,cmabCache:y,logger:null==v?void 0:v.child()}),clientEngine:i||J,clientVersion:n||W,jsonSchemaValidator:s,userProfileService:o,userProfileServiceAsync:a,defaultDecideOptions:l,disposable:u,logger:v,errorNotifier:f,projectConfigManager:d,eventProcessor:h,odpManager:g,vuidManager:p,UNSTABLE_conditionEvaluators:e.UNSTABLE_conditionEvaluators};return new Li(b)},zi=class{constructor(e={}){var t;this.logger=e.logger,this.timeout=null!==(t=e.timeout)&&void 0!==t?t:6e4}makeRequest(e,t,r,i){const n=B.default.parse(e);if("https:"!==n.protocol&&"http:"!==n.protocol)return{responsePromise:Promise.reject(new pe("64",n.protocol)),abort:()=>{}};const s=("https:"===n.protocol?q.default:K.default).request(Object.assign(Object.assign({},this.getRequestOptionsFromUrl(n)),{method:r,headers:Object.assign(Object.assign({},t),{"accept-encoding":"gzip,deflate","content-length":String((null==i?void 0:i.length)||0)}),timeout:this.timeout})),o=this.getAbortableRequestFromRequest(s);return i&&s.write(i),s.end(),o}getRequestOptionsFromUrl(e){return{hostname:e.hostname,path:e.path,port:e.port,protocol:e.protocol}}createHeadersFromNodeIncomingMessage(e){const t={};return Object.keys(e.headers).forEach(r=>{const i=e.headers[r];"string"==typeof i?t[r]=i:void 0===i||i.length>0&&(t[r]=i[0])}),t}getAbortableRequestFromRequest(e){let t=!1;return{abort:()=>{t=!0,e.destroy()},responsePromise:new Promise((r,i)=>{e.on("timeout",()=>{t=!0,e.destroy(),i(new pe("48"))}),e.on("error",e=>{e instanceof Error?i(e):i("string"==typeof e?new Error(e):new pe("47"))}),e.once("response",e=>{if(t)return;const n=(0,z.default)(e);n.setEncoding("utf8");let s="";n.on("data",e=>{t||(s+=e)}),n.on("end",()=>{t||(e.statusCode?r({statusCode:e.statusCode,body:s,headers:this.createHeadersFromNodeIncomingMessage(e)}):i(new pe("36")))})})})}}},Hi=new class{constructor(e){this.requestHandler=e}dispatchEvent(e){return pt(this,void 0,void 0,function*(){if("POST"!==e.httpVerb)return Promise.reject(new pe("44"));const t=JSON.stringify(e.params);return this.requestHandler.makeRequest(e.url,{"content-type":"application/json"},"POST",t).responsePromise})}}(new zi),$i=e=>{const t={autoUpdate:!0,requestHandler:new zi};return r=Object.assign(Object.assign({},t),e),{[St]:wt(r)};var r},Ji=(e=Hi)=>{return tr((er(t=e),new Xt(t)));var t},Gi=(e={})=>{var t;const r=e.eventStore?"async"===(i=e.eventStore).operation?new Pt(i,Yt,JSON.parse,JSON.stringify):new Ct(i,Yt,JSON.parse,JSON.stringify):void 0;var i;return((e,t=Wt)=>tr(((e,t=Wt)=>{const{eventDispatcher:r,closingEventDispatcher:i,retryOptions:n,eventStore:s}=e;er(r),i&&er(i),s&&Et(s);const o=n?{maxRetries:n.maxRetries,backoffProvider:()=>{var e,t;const r=null!==(e=null==n?void 0:n.minBackoff)&&void 0!==e?e:200,i=null!==(t=null==n?void 0:n.maxBackoff)&&void 0!==t?t:1e3;return new mt(r,i,50)}}:void 0,a=[],{defaultFlushInterval:l,defaultBatchSize:u}=e;let c=l;void 0===e.flushInterval||e.flushInterval<=0?a.push({level:N.Warn,message:"Invalid flushInterval %s, defaulting to %s",params:[e.flushInterval,l]}):c=e.flushInterval;let d=u;return void 0===e.batchSize||e.batchSize<=0?a.push({level:N.Warn,message:"Invalid batchSize %s, defaulting to %s",params:[e.batchSize,u]}):d=e.batchSize,new t({eventDispatcher:r,closingEventDispatcher:i,dispatchRepeater:new bt(c),failedEventRepeater:e.failedEventRetryInterval?new bt(e.failedEventRetryInterval):void 0,retryConfig:o,batchSize:d,eventStore:s,startupLogs:a})})(e,t)))({eventDispatcher:e.eventDispatcher||Hi,closingEventDispatcher:e.closingEventDispatcher,flushInterval:e.flushInterval,batchSize:e.batchSize,defaultFlushInterval:3e4,defaultBatchSize:10,retryOptions:{maxRetries:null!==(t=e.maxRetries)&&void 0!==t?t:2},failedEventRetryInterval:r?2e4:void 0,eventStore:r})},Wi=(e={})=>{const t=new zi({timeout:e.segmentsApiTimeout||1e4}),r=new zi({timeout:e.eventApiTimeout||1e4});return i=Object.assign(Object.assign({},e),{segmentRequestHandler:t,eventRequestHandler:r,eventBatchSize:e.eventBatchSize||10,eventFlushInterval:e.eventFlushInterval||1e3,eventRequestGenerator:nr}),{[mr]:yr(i)};var i},Qi=(e={})=>({[br]:void 0}),Yi=function(e){const t=Object.assign(Object.assign({},e),{clientEngine:e.clientEngine||G,requestHandler:new zi});return Bi(t)},Xi=function(){},Zi=G,en=["node"],tn={};var rn,nn={type:"optimizely",config:{},async init({config:e,env:t}){var r,i,n,s;const o=e.settings;if(!(null==o?void 0:o.sdkKey))return!1;const a=function(e){return(null==e?void 0:e.optimizely)?e.optimizely:P}(t),l={projectConfigManager:a.createPollingProjectConfigManager({sdkKey:o.sdkKey,autoUpdate:null==(r=o.autoUpdate)||r,updateInterval:null!=(i=o.updateInterval)?i:6e4}),eventProcessor:a.createBatchEventProcessor({batchSize:null!=(n=o.batchSize)?n:10,flushInterval:null!=(s=o.flushInterval)?s:1e3})},u=a.createInstance(l);await u.onReady();const c={client:u};return{...e,settings:{...o,_state:c}}},async push(e,{config:t,rule:r,env:i,collector:n}){const s=t.settings||{},o=s._state||{},a=(null==r?void 0:r.settings)||{};if(!o.client)return;const l=s.userId;let u,c;if(void 0!==l){const t=await R(e,l,{collector:n});x(t)&&(u=t)}if(!u)return;if(void 0!==s.attributes){const t=await R(e,s.attributes,{collector:n});S(t)&&(c=t)}if(u!==o.lastUserId||!o.userContext){const e=o.client.createUserContext(u,c);if(!e)return;o.userContext=e,o.lastUserId=u}const d=o.userContext;if(d){if(void 0!==a.attributes){const t=await R(e,a.attributes,{collector:n});if(S(t))for(const[e,r]of Object.entries(t))d.setAttribute(e,r)}if(!0!==(null==r?void 0:r.skip)){const t=x(null==r?void 0:r.name)?r.name:e.name,i={};if(void 0!==a.eventTags){const t=await R(e,a.eventTags,{collector:n});S(t)&&Object.assign(i,t)}if(void 0!==a.revenue){const t=await R(e,a.revenue,{collector:n});I(t)&&(i.revenue=t)}if(void 0!==a.value){const t=await R(e,a.value,{collector:n});I(t)&&(i.value=t)}d.trackEvent(t,i)}s._state=o}},on(e,t){var r,i,n;if("consent"!==e||!t.data)return;const s=null==(r=t.config)?void 0:r.consent;if(!s||0===Object.keys(s).length)return;const o=t.data,a=Object.keys(s).every(e=>!0===o[e]),l=null==(n=null==(i=t.config)?void 0:i.settings)?void 0:n._state;!a&&(null==l?void 0:l.client)&&(l.client.close(),l.client=void 0,l.userContext=void 0)},destroy({config:e}){const t=((null==e?void 0:e.settings)||{})._state;(null==t?void 0:t.client)&&(t.client.close(),t.client=void 0,t.userContext=void 0)}},sn=nn;return rn=f,u(t({},"__esModule",{value:!0}),rn)})();
|