@launchdarkly/js-client-sdk 0.8.2-beta.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/compat.js CHANGED
@@ -1,2 +1,2 @@
1
- var Fi=Object.defineProperty,Ui=Object.defineProperties;var Vi=Object.getOwnPropertyDescriptors;var gt=Object.getOwnPropertySymbols;var je=Object.prototype.hasOwnProperty,He=Object.prototype.propertyIsEnumerable;var Ve=(i,t,e)=>t in i?Fi(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,p=(i,t)=>{for(var e in t||(t={}))je.call(t,e)&&Ve(i,e,t[e]);if(gt)for(var e of gt(t))He.call(t,e)&&Ve(i,e,t[e]);return i},b=(i,t)=>Ui(i,Vi(t));var Bt=(i,t)=>{var e={};for(var n in i)je.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&gt)for(var n of gt(i))t.indexOf(n)<0&&He.call(i,n)&&(e[n]=i[n]);return e};function ji(i){return`/${i.replace(/~/g,"~0").replace(/\//g,"~1")}`}function We(i){return i.indexOf("~")?i.replace(/~1/g,"/").replace(/~0/g,"~"):i}function Hi(i){return(i.startsWith("/")?i.substring(1):i).split("/").map(e=>We(e))}function Bi(i){return!i.startsWith("/")}function Ki(i){return!i.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var A=class{constructor(t,e=!1){if(e){let n=t;this.p=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?ji(n):n}else{if(this.redactionName=t,t===""||t==="/"||!Ki(t)){this.isValid=!1,this.p=[];return}Bi(t)?this.p=[t]:t.indexOf("/",1)<0?this.p=[We(t.slice(1))]:this.p=Hi(t),this.p[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{p:e,isValid:n}=this;if(!n)return;let s=t;for(let r=0;r<e.length;r+=1){let a=e[r];if(s!=null&&Object.prototype.hasOwnProperty.call(s,a)&&typeof s=="object"&&!Array.isArray(s))s=s[a];else return}return s}getComponent(t){return this.p[t]}get depth(){return this.p.length}get isKind(){return this.p.length===1&&this.p[0]==="kind"}compare(t){return this.depth===t.depth&&this.p.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.p]}};A.InvalidReference=new A("");var zt=class{is(t){if(Array.isArray(t))return!1;let n=typeof t;return n==="function"||n==="object"}getType(){return"factory method or object"}},I=class{constructor(t,e){this.kt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.kt}},vt=class{constructor(t,e){this.kt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.kt}},z=class extends I{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},wt=class extends I{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},_t=class{is(t){return typeof t=="function"}getType(){return"function"}},Jt=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},Gi=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,qt=class{is(t){return typeof t=="number"||typeof t=="string"&&Gi.test(t)}getType(){return"date"}},Wt=class extends wt{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},h=class{static createTypeArray(t,e){return new vt(t,e)}static numberWithMin(t){return new z(t)}static stringMatchingRegex(t){return new wt(t)}};h.String=new I("string","");h.Number=new I("number",0);h.ObjectOrFactory=new zt;h.Object=new I("object",{});h.StringArray=new vt("string[]","");h.Boolean=new I("boolean",!0);h.Function=new _t;h.Date=new qt;h.Kind=new Wt;h.NullableBoolean=new Jt;function Ye(i){return"kind"in i?h.String.is(i.kind)&&i.kind!=="multi":!1}function Ze(i){return"kind"in i?h.String.is(i.kind)&&i.kind==="multi":!1}function Xe(i){return!("kind"in i)||i.kind===null||i.kind===void 0}function Et(i,t=[]){if(i===null||typeof i!="object")return JSON.stringify(i);if(t.includes(i))throw new Error("Cycle detected");return Array.isArray(i)?`[${i.map(s=>Et(s,[...t,i])).map(s=>s===void 0?"null":s).join(",")}]`:`{${Object.keys(i).sort().map(n=>{let s=Et(i[n],[...t,i]);if(s!==void 0)return`${JSON.stringify(n)}:${s}`}).filter(n=>n!==void 0).join(",")}}`}var Yt="user";function Be(i){return i.includes("%")||i.includes(":")?i.replace(/%/g,"%25").replace(/:/g,"%3A"):i}function zi(i){return i&&h.Object.is(i)}function Ke(i){return h.Kind.is(i)}function Ge(i){return h.String.is(i)&&i!==""}function Kt(i,t=!1){return i?i.map(e=>new A(e,t)):[]}function _i(i){return i!=null}function Ji(i){let t=b(p({},i.custom||[]),{kind:"user",key:String(i.key)});if(_i(i.anonymous)){let e=!!i.anonymous;delete t.anonymous,t.anonymous=e}return i.name!==null&&i.name!==void 0&&(t.name=i.name),i.ip!==null&&i.ip!==void 0&&(t.ip=i.ip),i.firstName!==null&&i.firstName!==void 0&&(t.firstName=i.firstName),i.lastName!==null&&i.lastName!==void 0&&(t.lastName=i.lastName),i.email!==null&&i.email!==void 0&&(t.email=i.email),i.avatar!==null&&i.avatar!==void 0&&(t.avatar=i.avatar),i.country!==null&&i.country!==void 0&&(t.country=i.country),i.privateAttributeNames!==null&&i.privateAttributeNames!==void 0&&(t._meta={privateAttributes:i.privateAttributeNames}),t}var x=class i{constructor(t,e,n){this.C=!1,this.at=!1,this.re=!1,this.R={},this.kind=e,this.valid=t,this.message=n}static b(t,e){return new i(!1,t,e)}static qe(t,e){if(!(!e||!t.isValid))return t.depth===1&&t.getComponent(0)==="anonymous"?!!(e!=null&&e.anonymous):t.get(e)}ae(t){if(this.C)return this.R[t];if(this.kind===t)return this.m}static We(t){let e=Object.keys(t).filter(c=>c!=="kind"),n=e.every(Ke);if(!e.length)return i.b("multi","A multi-kind context must contain at least one kind");if(!n)return i.b("multi","Context contains invalid kinds");let s={},r=!0,a=e.reduce((c,u)=>{var d;let l=t[u];return zi(l)?(c[u]=l,s[u]=Kt((d=l._meta)==null?void 0:d.privateAttributes)):r=!1,c},{});if(!r)return i.b("multi","Context contained contexts that were not objects");if(!Object.values(a).every(c=>Ge(c.key)))return i.b("multi","Context contained invalid keys");if(e.length===1){let c=e[0],u=new i(!0,c);return u.m=b(p({},a[c]),{kind:c}),u.ot=s,u.at=c==="user",u}let o=new i(!0,t.kind);return o.R=a,o.ot=s,o.C=!0,o}static Ye(t){var c;let{key:e,kind:n}=t,s=Ke(n),r=Ge(e);if(!s)return i.b(n!=null?n:"unknown","The kind was not valid for the context");if(!r)return i.b(n,"The key for the context was not valid");let a=Kt((c=t._meta)==null?void 0:c.privateAttributes),o=new i(!0,n);return o.at=n==="user",o.m=t,o.ot={[n]:a},o}static Ze(t){if(!(t.key!==void 0&&t.key!==null))return i.b("user","The key for the context was not valid");let n=new i(!0,"user");return n.at=!0,n.re=!0,n.m=Ji(t),n.ot={user:Kt(t.privateAttributeNames,!0)},n}static fromLDContext(t){return t?Ye(t)?i.Ye(t):Ze(t)?i.We(t):Xe(t)?i.Ze(t):i.b("unknown","Context was not of a valid kind"):i.b("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;let e=t.getContexts();if(!t.C)return e[0][1];let n={kind:"multi"};return e.forEach(s=>{let r=s[0],a=s[1];n[r]=a}),n}valueForKind(t,e=Yt){return t.isKind?this.kinds:i.qe(t,this.ae(e))}key(t=Yt){var e;return(e=this.ae(t))==null?void 0:e.key}get isMultiKind(){return this.C}get canonicalKey(){return this.at?this.m.key:this.C?Object.keys(this.R).sort().map(t=>`${t}:${Be(this.R[t].key)}`).join(":"):`${this.kind}:${Be(this.m.key)}`}get kinds(){return this.C?Object.keys(this.R):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.R).reduce((t,[e,n])=>(t[e]=n.key,t),{}):{[this.kind]:this.m.key}}privateAttributes(t){var e;return((e=this.ot)==null?void 0:e[t])||[]}getContexts(){return this.C?Object.entries(this.R):[[this.kind,this.m]]}get legacy(){return this.re}canonicalUnfilteredJson(){if(this.valid){if(this.xt)return this.xt;try{this.xt=Et(i.toLDContext(this))}catch(t){}return this.xt}}};x.UserKind=Yt;var qi=["key","kind","_meta","anonymous"].map(i=>new A(i,!0)),Wi=["name","ip","firstName","lastName","email","avatar","country"];function Yi(i,t){return i.depth===t.length&&t.every((e,n)=>e===i.getComponent(n))}function Zi(i,t){let e=[],n={},s=[];for(e.push(...Object.keys(i).map(r=>({key:r,ptr:[r],source:i,parent:n,visited:[i]})));e.length;){let r=e.pop(),a=t.find(o=>Yi(o,r.ptr));if(a)s.push(a.redactionName);else{let o=r.source[r.key];o===null?r.parent[r.key]=o:Array.isArray(o)?r.parent[r.key]=[...o]:typeof o=="object"?r.visited.includes(o)||(r.parent[r.key]={},e.push(...Object.keys(o).map(c=>({key:c,ptr:[...r.ptr,c],source:o,parent:r.parent[r.key],visited:[...r.visited,o]})))):r.parent[r.key]=o}}return{cloned:n,excluded:s.sort()}}var Zt=class{constructor(t,e){this.Xe=t,this.Qe=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.oe(t,n[0][1],n[0][0],e);let s={kind:"multi"};return n.forEach(([r,a])=>{s[r]=this.oe(t,a,r,e)}),s}ti(t,e,n,s){return(s?Object.keys(e).map(r=>new A(r,!0)):[...this.Qe,...t.privateAttributes(n)]).filter(r=>!qi.some(a=>a.compare(r)))}oe(t,e,n,s){let r=this.Xe||s&&e.anonymous===!0,{cloned:a,excluded:o}=Zi(e,this.ti(t,e,n,r));return t.legacy&&Wi.forEach(c=>{c in a&&(a[c]=String(a[c]))}),o.length&&(a._meta||(a._meta={}),a._meta.redactedAttributes=o),a._meta&&(delete a._meta.privateAttributes,Object.keys(a._meta).length===0&&delete a._meta),a}},ze=30*1e3,Xi=.5,Dt=class{constructor(t,e,n=Math.random){this.ei=e,this.ii=n,this.Lt=0,this.ce=Math.max(1,t),this.ni=Math.ceil(Math.log2(ze/this.ce))}T(){let t=Math.min(this.Lt,this.ni),e=this.ce*2**t;return Math.min(e,ze)}si(t){return t-Math.trunc(this.ii()*Xi*t)}success(t=Date.now()){this.St=t}fail(t=Date.now()){this.St!==void 0&&t-this.St>this.ei&&(this.Lt=0),this.St=void 0;let e=this.si(this.T());return this.Lt+=1,e}};var _e;(function(i){i[i.Valid=0]="Valid",i[i.Initializing=1]="Initializing",i[i.Interrupted=2]="Interrupted",i[i.Closed=3]="Closed"})(_e||(_e={}));var O=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=s}},V=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=s}};var xs=120*1e3,Ls=300*1e3;var w;(function(i){i.Unknown="UNKNOWN",i.NetworkError="NETWORK_ERROR",i.ErrorResponse="ERROR_RESPONSE",i.InvalidData="INVALID_DATA"})(w||(w={}));var j;(function(i){i[i.Disabled=0]="Disabled",i[i.Enabled=1]="Enabled"})(j||(j={}));var H;(function(i){i[i.AnalyticsEvents=0]="AnalyticsEvents",i[i.DiagnosticEvent=1]="DiagnosticEvent"})(H||(H={}));var $;(function(i){i[i.Succeeded=0]="Succeeded",i[i.Failed=1]="Failed",i[i.FailedAndMustShutDown=2]="FailedAndMustShutDown"})($||($={}));function U(i){if(typeof i=="string")return i;if(i===void 0)return"undefined";if(i===null)return"null";if(Object.prototype.hasOwnProperty.call(i,"toString"))try{return i.toString()}catch(t){}if(typeof i=="bigint")return`${i}n`;try{return JSON.stringify(i)}catch(t){return t instanceof TypeError&&t.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function Qi(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(Number(i))}function tn(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(parseInt(i,10))}function en(i){return typeof i=="symbol"?"NaN":String(parseFloat(i))}var mt={s:i=>U(i),d:i=>Qi(i),i:i=>tn(i),f:i=>en(i),j:i=>U(i),o:i=>U(i),O:i=>U(i),c:()=>""};function Xt(...i){var e;let t=i.shift();if(h.String.is(t)){let n="",s=0;for(;s<t.length;){let r=t.charAt(s);if(r==="%"){if(s+1<t.length){let o=t.charAt(s+1);if(o in mt&&i.length){let c=i.shift();n+=(e=mt[o])==null?void 0:e.call(mt,c)}else o==="%"?n+="%":n+=`%${o}`;s+=2}}else n+=r,s+=1}return i.length&&(n.length&&(n+=" "),n+=i.map(U).join(" ")),n}return i.map(U).join(" ")}var v;(function(i){i[i.debug=0]="debug",i[i.info=1]="info",i[i.warn=2]="warn",i[i.error=3]="error",i[i.none=4]="none"})(v||(v={}));var nn=["debug","info","warn","error","none"],M=class i{static get(){return new i({})}constructor(t){var e,n,s;if(this.di=(n=v[(e=t.level)!=null?e:"info"])!=null?n:v.info,this.fi=(s=t.name)!=null?s:"LaunchDarkly",this.fe=t.formatter,typeof t.destination=="object")this.pe={[v.debug]:t.destination.debug,[v.info]:t.destination.info,[v.warn]:t.destination.warn,[v.error]:t.destination.error};else if(typeof t.destination=="function"){let{destination:r}=t;this.pe={[v.debug]:r,[v.info]:r,[v.warn]:r,[v.error]:r}}}pi(...t){var e;try{return this.fe?(e=this.fe)==null?void 0:e.call(this,...t):Xt(...t)}catch(n){return Xt(...t)}}gi(t,e){try{t(e)}catch(n){console.error(e)}}k(t,e){var n;if(t>=this.di){let s=`${nn[t]}: [${this.fi}]`;try{let r=(n=this.pe)==null?void 0:n[t];r?this.gi(r,`${s} ${this.pi(...e)}`):console.error(...e)}catch(r){console.error(...e)}}}error(...t){this.k(v.error,t)}warn(...t){this.k(v.warn,t)}info(...t){this.k(v.info,t)}debug(...t){this.k(v.debug,t)}},sn={error:h.Function,warn:h.Function,info:h.Function,debug:h.Function},_=class{constructor(t,e){Object.entries(sn).forEach(([n,s])=>{if(!s.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.mi=e}k(t,e){try{this.t[t](...e)}catch(n){this.mi[t](...e)}}error(...t){this.k("error",t)}warn(...t){this.k("warn",t)}info(...t){this.k("info",t)}debug(...t){this.k("debug",t)}},ue=i=>{let t=new M({level:"info",destination:console.error,formatter:Xt});return i?new _(i,t):t},k=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,n){return`Config option "${t}" had invalid value of ${e}, using minimum of ${n} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,n){return`Config option "${t}" should be of type ${e}, got ${n}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},rn=/^(\w|\.|-)+$/,an=h.stringMatchingRegex(rn),on={is:(i,t)=>an.is(i)?i.length>64?{valid:!1,message:k.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:k.invalidTagValue(t)}},bt=class{constructor(t){let e={},n=t==null?void 0:t.application,s=t==null?void 0:t.logger;n&&Object.entries(n).forEach(([a,o])=>{if(o!=null){let{valid:c,message:u}=on.is(o,`application.${a}`);c?a==="versionName"?e["application-version-name"]=[o]:e[`application-${a}`]=[o]:s==null||s.warn(u)}});let r=Object.keys(e);r.length&&(this.value=r.sort().flatMap(a=>e[a].sort().map(o=>`${a}/${o}`)).join(" "))}},kt=class{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function Gt(i){return i.replace(/\/+$/,"")}function le(i){return i.replace(/^\/+/,"").replace(/\?$/,"")}var R=class i{constructor(t,e,n=i.DEFAULT_EVENTS,s="/bulk",r="/diagnostic",a=!0,o){this.streaming=Gt(t),this.polling=Gt(e),this.events=Gt(n),this.analyticsEventPath=s,this.diagnosticEventPath=r,this.includeAuthorizationHeader=a,this.payloadFilterKey=o}};R.DEFAULT_EVENTS="https://events.launchdarkly.com";function he(i,t=[]){if(t.length===0)return i;let e=t.map(({key:n,value:s})=>`${n}=${s}`);return`${i}?${e.join("&")}`}function Qe(i,t,e){let n=le(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),he(`${i.streaming}/${n}`,s)}function ti(i,t,e=[]){let n=le(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),he(`${i.polling}/${n}`,s)}function Je(i,t,e=[]){let n=le(t);return he(`${i.events}/${n}`,e)}var J=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},q=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},C=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Y(i){return i>=400&&i<500?i===400||i===408||i===429:!0}function cn(i){return i===413?!0:Y(i)}function ei(i,t){let e,n;return{promise:new Promise((r,a)=>{n=r,e=setTimeout(()=>{let o=`${t} timed out after ${i} seconds.`;a(new C(o))},i*1e3)}),cancel:()=>{n(),clearTimeout(e)}}}function de(i){return i==null?i:JSON.parse(JSON.stringify(i))}function Pt(i){return Math.trunc(i*1e3)}var un=i=>JSON.stringify(i)==="{}",Nt=(i,t)=>i&&Object.entries(i).reduce((e,[n,s])=>(s&&!un(s)&&!(t!=null&&t.includes(n))&&(e[n]=typeof s=="object"?Nt(s,t):s),e),{});function G(i,t){if(i===t)return!0;if(i&&t&&typeof i=="object"&&typeof t=="object"){if(i.constructor!==t.constructor)return!1;var e,n,s;if(Array.isArray(i)){if(e=i.length,e!=t.length)return!1;for(n=e;n--!==0;)if(!G(i[n],t[n]))return!1;return!0}if(i instanceof Map&&t instanceof Map){if(i.size!==t.size)return!1;for(n of i.entries())if(!t.has(n[0]))return!1;for(n of i.entries())if(!G(n[1],t.get(n[0])))return!1;return!0}if(i instanceof Set&&t instanceof Set){if(i.size!==t.size)return!1;for(n of i.entries())if(!t.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(i)&&ArrayBuffer.isView(t)){if(e=i.length,e!=t.length)return!1;for(n=e;n--!==0;)if(i[n]!==t[n])return!1;return!0}if(i.constructor===RegExp)return i.source===t.source&&i.flags===t.flags;if(i.valueOf!==Object.prototype.valueOf)return i.valueOf()===t.valueOf();if(i.toString!==Object.prototype.toString)return i.toString()===t.toString();if(s=Object.keys(i),e=s.length,e!==Object.keys(t).length)return!1;for(n=e;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[n]))return!1;for(n=e;n--!==0;){var r=s[n];if(!G(i[r],t[r]))return!1}return!0}return i!==i&&t!==t}function ii(i,t,e,n=!0,s="user-agent"){let{userAgentBase:r,version:a,wrapperName:o,wrapperVersion:c}=t.sdkData(),u={[s]:`${r!=null?r:"NodeJSClient"}/${a}`};return n&&(u.authorization=i),o&&(u["x-launchdarkly-wrapper"]=c?`${o}/${c}`:o),e!=null&&e.value&&(u["x-launchdarkly-tags"]=e.value),u}function B(i,t,e){let n;i.status?n=`error ${i.status}${i.status===401?" (invalid SDK key)":""}`:n=`I/O error (${i.message||"unknown error"})`;let s=e!=null?e:"giving up permanently";return`Received ${n} for ${t} - ${s}`}function ni({status:i}){return i?Y(i):!0}var fe=(i,t)=>t.btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var ln=async(i=1e3)=>new Promise(t=>{setTimeout(t,i)});var Qt=class{constructor(t,e,n){this.h=e,this.yi=n,this.At=[],this.ge=Date.now(),this.me=this.ge,this.ye={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var n,s,r;let t=this.h.info.sdkData(),e=this.h.info.platformData();return{kind:"diagnostic-init",id:this.ye,creationDate:this.ge,sdk:t,configuration:this.yi,platform:p({name:e.name,osArch:(n=e.os)==null?void 0:n.arch,osName:(s=e.os)==null?void 0:s.name,osVersion:(r=e.os)==null?void 0:r.version},e.additional||{})}}recordStreamInit(t,e,n){let s={timestamp:t,failed:e,durationMillis:n};this.At.push(s)}createStatsEventAndReset(t,e,n){let s=Date.now(),r={kind:"diagnostic",id:this.ye,creationDate:s,dataSinceDate:this.me,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.At};return this.At=[],this.me=s,r}},te;(function(i){i.MalformedFlag="MALFORMED_FLAG",i.UserNotSpecified="USER_NOT_SPECIFIED",i.FlagNotFound="FLAG_NOT_FOUND",i.ClientNotReady="CLIENT_NOT_READY",i.WrongType="WRONG_TYPE"})(te||(te={}));var hn=te,xt=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};xt.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var ee=class{constructor(t,e){let{basicConfiguration:n,platform:s}=t,{serviceEndpoints:{analyticsEventPath:r,diagnosticEventPath:a}}=n,{crypto:o,requests:c}=s;this.vi=p({},e),this.ve=Je(n.serviceEndpoints,r,[]),this.wi=Je(n.serviceEndpoints,a,[]),this.I=c,this.Ei=o}async ct(t,e,n,s){let r={status:$.Succeeded},a=b(p({},this.vi),{"content-type":"application/json"});n&&(a["x-launchdarkly-payload-id"]=n,a["x-launchDarkly-event-schema"]="4");let o;try{let{status:c,headers:u}=await this.I.fetch(e,{headers:a,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),l=Date.parse(u.get("date")||"");if(l&&(r.serverTime=l),c<=204)return r;if(o=new J(B({status:c,message:"some events were dropped"},"event posting")),!Y(c))return cn(c)?r.status=$.Failed:r.status=$.FailedAndMustShutDown,r.error=o,r}catch(c){o=c}return o&&!s?(r.status=$.Failed,r.error=o,r):(await ln(),this.ct(t,this.ve,n,!1))}async sendEventData(t,e){let n=t===H.AnalyticsEvents?this.Ei.randomUUID():void 0,s=t===H.AnalyticsEvents?this.ve:this.wi;return this.ct(e,s,n,!0)}};function Lt(i){return i.kind==="feature"}function dn(i){return i.kind==="identify"}function fn(i){return i.kind==="migration_op"}var ie=class{constructor(t,e,n,s,r,a){this.count=t,this.key=e,this.value=n,this.version=r,this.variation=a,this.default=s}increment(){this.count+=1}};function pn(i){return`${i.key}:${i.variation!==null&&i.variation!==void 0?i.variation:""}:${i.version!==null&&i.version!==void 0?i.version:""}`}var St=class{constructor(t=!1,e){this.Di=t,this.x=e,this.X=0,this.ut=0,this.lt={},this.ht={}}summarizeEvent(t){if(Lt(t)&&!t.excludeFromSummaries){this.m||(this.m=t.context);let e=pn(t),n=this.lt[e],s=this.ht[t.key];s||(s=new Set,this.ht[t.key]=s),t.context.kinds.forEach(r=>s.add(r)),n?n.increment():this.lt[e]=new ie(1,t.key,t.value,t.default,t.version,t.variation),(this.X===0||t.creationDate<this.X)&&(this.X=t.creationDate),t.creationDate>this.ut&&(this.ut=t.creationDate)}}getSummary(){var n;let t=Object.values(this.lt).reduce((s,r)=>{let a=s[r.key];a||(a={default:r.default,counters:[],contextKinds:[...this.ht[r.key]]},s[r.key]=a);let o={value:r.value,count:r.count};return r.variation!==void 0&&r.variation!==null&&(o.variation=r.variation),r.version!==void 0&&r.version!==null?o.version=r.version:o.unknown=!0,a.counters.push(o),s},{}),e={startDate:this.X,endDate:this.ut,features:t,kind:"summary",context:this.m!==void 0&&this.Di?(n=this.x)==null?void 0:n.filter(this.m):void 0};return this.bi(),e}bi(){this.X=0,this.ut=0,this.lt={},this.ht={}}},ne=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},se=class{constructor(t,e){this.x=t,this.t=e,this.Q={}}summarizeEvent(t){var e;if(Lt(t)){let n=t.context.canonicalUnfilteredJson();if(!n){t.context.valid&&((e=this.t)==null||e.error("Unable to serialize context, likely the context contains a cycle."));return}let s=this.Q[n];s||(this.Q[n]=new St(!0,this.x),s=this.Q[n]),s.summarizeEvent(t)}}getSummaries(){let t=this.Q;return this.Q={},Object.values(t).map(e=>e.getSummary())}};function yt(i){let t=Math.trunc(i);return t===1?!0:t===0?!1:Math.floor(Math.random()*t)===0}function gn(i){return i.getSummaries!==void 0}var re=class{constructor(t,e,n,s,r,a=!0,o=!1){this.r=t,this.dt=s,this.L=r,this.ft=[],this.we=0,this.It=0,this.Pt=0,this.Nt=!1,this.Ee=0,this.$t=!1,this.Ot=null,this.ki=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.De=new ee(e,n),this.x=new Zt(t.allAttributesPrivate,t.privateAttributes.map(c=>new A(c))),o?this.tt=new se(this.x,this.t):this.tt=new St,a&&this.start()}start(){var t,e;if(((t=this.dt)==null?void 0:t.flushInterval)!==void 0&&(this.Ot=setInterval(()=>{var n;(n=this.dt)==null||n.flush()},this.dt.flushInterval*1e3)),this.xi=setInterval(async()=>{var n;try{await this.flush()}catch(s){(n=this.t)==null||n.debug(`Flush failed: ${s}`)}},this.r.flushInterval*1e3),this.L){let n=this.L.createInitEvent();this.be(n),this.ke=setInterval(()=>{let s=this.L.createStatsEventAndReset(this.It,this.Pt,this.Ee);this.It=0,this.Pt=0,this.be(s)},this.r.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}be(t){this.De.sendEventData(H.DiagnosticEvent,t)}close(){clearInterval(this.xi),this.Ot&&clearInterval(this.Ot),this.ke&&clearInterval(this.ke)}async flush(){var e;if(this.$t)throw new ne("Events cannot be posted because a permanent error has been encountered. This is most likely an invalid SDK key. The specific error information is logged independently.");let t=this.ft;if(this.ft=[],gn(this.tt))this.tt.getSummaries().forEach(s=>{Object.keys(s.features).length&&t.push(s)});else{let n=this.tt.getSummary();Object.keys(n.features).length&&t.push(n)}t.length&&(this.Ee=t.length,(e=this.t)==null||e.debug("Flushing %d events",t.length),await this.ct(t))}sendEvent(t){var c;if(this.$t)return;if(fn(t)){if(yt(t.samplingRatio)){let u=b(p({},t),{context:t.context?this.x.filter(t.context):void 0});u.samplingRatio===1&&delete u.samplingRatio,this.pt(u)}return}this.tt.summarizeEvent(t);let e=Lt(t),n=e&&t.trackEvents||!e,s=this.Li(t),r=dn(t),a=(c=this.dt)==null?void 0:c.processContext(t.context);a||r||(this.Pt+=1),a&&!r&&this.pt(this.Mt({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),n&&yt(t.samplingRatio)&&this.pt(this.Mt(t,!1)),s&&yt(t.samplingRatio)&&this.pt(this.Mt(t,!0))}Mt(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.x.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}pt(t){var e;this.ft.length<this.ki?(this.ft.push(t),this.Nt=!1):(this.Nt||(this.Nt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.It+=1)}Li(t){return Lt(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.we&&t.debugEventsUntilDate>Date.now()}async ct(t){let e=await this.De.sendEventData(H.AnalyticsEvents,t);if(e.status===$.FailedAndMustShutDown&&(this.$t=!0),e.serverTime&&(this.we=e.serverTime),e.error)throw e.error}},Ct=class{constructor(t,e,n,s,r=1,a){this.context=t,this.key=e,this.data=n,this.metricValue=s,this.samplingRatio=r,this.url=a,this.kind="custom",this.creationDate=Date.now(),this.context=t}},W=class{constructor(t,e,n,s,r,a,o,c,u,l,d,f,m=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=m,this.kind="feature",this.creationDate=Date.now(),this.value=s,this.default=r,a!==void 0&&(this.version=a),o!==void 0&&(this.variation=o),c!==void 0&&(this.trackEvents=c),u!==void 0&&(this.prereqOf=u),l!==void 0&&(this.reason=l),d!==void 0&&(this.debugEventsUntilDate=d),f!==void 0&&(this.excludeFromSummaries=f)}},Tt=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},ae=class{close(){}async flush(){}sendEvent(){}},oe=class{constructor(t){this.Rt=t}evalEvent(t){var e;return new W(this.Rt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.Rt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new W(this.Rt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Tt(t,1)}customEvent(t,e,n,s,r=1){return new Ct(e,t,n!=null?n:void 0,s!=null?s:void 0,r)}},At=class{constructor(t,e,n){this.Si=t,this.g=e,this.t=n,this.e=[],this.F=void 0,this.K=!1,this.G=[],this.Ci=s=>{var a;if(this.Ft(),!s.payloads.length)return;let r=s.payloads[0];switch(r==null?void 0:r.intentCode){case"xfer-full":this.K=!0;break;case"xfer-changes":this.K=!1;break;case"none":this.K=!1,this.Ti(r);break;default:(a=this.t)==null||a.warn(`Unable to process intent code '${r==null?void 0:r.intentCode}'.`);return}this.F=r==null?void 0:r.id},this.Ai=s=>{var a;if(!this.F||!s.kind||!s.key||!s.version||!s.object)return;let r=this.Ii(s.kind,s.object);if(!r){(a=this.t)==null||a.warn(`Unable to process object for kind: '${s.kind}'`);return}this.G.push({kind:s.kind,key:s.key,version:s.version,object:r})},this.Pi=s=>{!this.F||!s.kind||!s.key||!s.version||this.G.push({kind:s.kind,key:s.key,version:s.version,deleted:!0})},this.Ti=s=>{if(!s.id||!s.target)return;let r={id:s.id,version:s.target,basis:!1,updates:[]};this.e.forEach(a=>a(r)),this.xe()},this.Ni=s=>{if(!this.F||!s.state||!s.version){this.Ft();return}let r={id:this.F,version:s.version,state:s.state,basis:this.K,updates:this.G};this.e.forEach(a=>a(r)),this.xe()},this.$i=s=>{var r;(r=this.t)==null||r.info(`Goodbye was received from the LaunchDarkly connection with reason: ${s.reason}.`),this.Ft()},this.Oi=s=>{var r;(r=this.t)==null||r.info(`An issue was encountered receiving updates for payload ${this.F} with reason: ${s.reason}.`),this.Mi()}}addPayloadListener(t){this.e.push(t)}removePayloadListener(t){let e=this.e.indexOf(t,0);e>-1&&this.e.splice(e,1)}processEvents(t){t.forEach(e=>{switch(e.event){case"server-intent":{this.Ci(e.data);break}case"put-object":{this.Ai(e.data);break}case"delete-object":{this.Pi(e.data);break}case"payload-transferred":{this.Ni(e.data);break}case"goodbye":{this.$i(e.data);break}case"error":{this.Oi(e.data);break}}})}Ii(t,e){var n,s;return(s=(n=this.Si)[t])==null?void 0:s.call(n,e)}xe(){this.K=!1,this.G=[]}Mi(){this.G=[]}Ft(){this.F=void 0,this.K=!1,this.G=[]}},ce=class{constructor(t,e,n,s){this.g=n,this.t=s,this.z(t,"server-intent"),this.z(t,"put-object"),this.z(t,"delete-object"),this.z(t,"payload-transferred"),this.z(t,"goodbye"),this.z(t,"error"),this.Ut=new At(e,n,s)}addPayloadListener(t){this.Ut.addPayloadListener(t)}removePayloadListener(t){this.Ut.removePayloadListener(t)}z(t,e){t.addEventListener(e,async n=>{var s,r,a,o,c;if(n!=null&&n.data){(s=this.t)==null||s.debug(`Received ${e} event. Data is ${n.data}`);try{this.Ut.processEvents([{event:e,data:JSON.parse(n.data)}])}catch(u){(r=this.t)==null||r.error(`Stream received data that was unable to be processed in "${e}" message`),(a=this.t)==null||a.debug(`Data follows: ${n.data}`),(o=this.g)==null||o.call(this,w.InvalidData,"Malformed data in EventStream.")}}else(c=this.g)==null||c.call(this,w.Unknown,"Event from EventStream missing data.")})}};function mn(i){if(i){let t=Object.keys(i).find(e=>e.toLowerCase()==="x-ld-envid");if(t)return{environmentId:i[t]}}}var qe="unknown plugin";function It(i,t){try{return t.getMetadata().name||qe}catch(e){return i.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),qe}}function yn(i,t,e){let n=[];return e.forEach(s=>{var r;try{let a=(r=s.getHooks)==null?void 0:r.call(s,t);a===void 0?i.error(`Plugin ${It(i,s)} returned undefined from getHooks.`):a&&a.length>0&&n.push(...a)}catch(a){i.error(`Exception thrown getting hooks for plugin ${It(i,s)}. Unable to get hooks.`)}}),n}function vn(i,t,e,n){n.forEach(s=>{try{s.register(e,t)}catch(r){i.error(`Exception thrown registering plugin ${It(i,s)}.`)}})}var L=Object.freeze({__proto__:null,ClientMessages:xt,DiagnosticsManager:Qt,ErrorKinds:hn,EventFactoryBase:oe,EventProcessor:re,InputCustomEvent:Ct,InputEvalEvent:W,InputIdentifyEvent:Tt,NullEventProcessor:ae,PayloadProcessor:At,PayloadStreamReader:ce,canonicalize:Et,initMetadataFromHeaders:mn,isLegacyUser:Xe,isMultiKind:Ze,isSingleKind:Ye,safeGetHooks:yn,safeGetName:It,safeRegisterPlugins:vn,shouldSample:yt});var E;(function(i){i.Initializing="INITIALIZING",i.Valid="VALID",i.Interrupted="INTERRUPTED",i.SetOffline="SET_OFFLINE",i.Closed="CLOSED"})(E||(E={}));function En(i){return i>=200&&i<=299}var $t=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}},ve=class{constructor(t,e,n,s,r){this.I=t,this.Ri=e,this.gt=n,this.Fi=s,this.Ui=r}async requestPayload(){let t;try{let e=await this.I.fetch(this.Ri,{method:this.Fi,headers:this.gt,body:this.Ui});if(En(e.status))return await e.text();t=e.status}catch(e){throw new $t(e==null?void 0:e.message)}throw new $t(`Unexpected status code: ${t}`,t)}};function Pe(i,t,e,n,s,r,a,o,c,u){let l,d="GET",f=p({},r);c&&(d="REPORT",f["content-type"]="application/json",l=i);let m=c?e.pathReport(s,i):e.pathGet(s,i),g=[...a!=null?a:[]];o&&g.push({key:"withReasons",value:"true"}),u&&g.push({key:"h",value:u});let y=ti(t,m,g);return new ve(n,y,f,d,l)}var si=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function Dn(i,t,e=!1){let n,s=new Promise(o=>{n=(c,u)=>{var l;try{(l=i.after)==null||l.call(i,c,u)}catch(d){t==null||t.error(`Error in after callback: ${d}`)}o(c)}}),r=i.before?i.before():Promise.resolve(void 0),a=!1;return{execute:()=>{a&&(t==null||t.error(si)),a=!0,r.then(o=>{i.execute(o).then(c=>n({status:"complete",result:c},o)).catch(c=>n({status:"error",error:c},o))}).catch(o=>{t==null||t.error(o),n({status:"error",error:o},void 0)})},shed:()=>{a&&(t==null||t.error(si)),a=!0,r.then(o=>{n({status:"shed"},o)})},promise:s,sheddable:e}}function bn(i){let t,e=[];function n(){if(!t&&e.length>0){let s=e.shift();t=s.promise.finally(()=>{t=void 0,n()}),s.execute()}}return{execute(s,r=!1){var o,c;let a=Dn(s,i,r);return t?((o=e[e.length-1])!=null&&o.sheddable&&((c=e.pop())==null||c.shed()),e.push(a)):(t=a.promise.finally(()=>{t=void 0,n()}),a.execute()),a.promise},pendingCount(){return e.length}}}var kn={logger:h.Object,maxCachedContexts:h.numberWithMin(0),baseUri:h.String,streamUri:h.String,eventsUri:h.String,capacity:h.numberWithMin(1),diagnosticRecordingInterval:h.numberWithMin(2),flushInterval:h.numberWithMin(2),streamInitialReconnectDelay:h.numberWithMin(0),allAttributesPrivate:h.Boolean,debug:h.Boolean,diagnosticOptOut:h.Boolean,withReasons:h.Boolean,sendEvents:h.Boolean,pollInterval:h.numberWithMin(30),useReport:h.Boolean,privateAttributes:h.StringArray,applicationInfo:h.Object,wrapperName:h.String,wrapperVersion:h.String,payloadFilterKey:h.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:h.createTypeArray("Hook[]",{}),inspectors:h.createTypeArray("LDInspection",{})},xn=300,hi="https://clientsdk.launchdarkly.com",di="https://clientstream.launchdarkly.com";function Ln(i){return i instanceof _?i:ue(i)}var we=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var s,r,a;this.logger=ue(),this.baseUri=hi,this.eventsUri=R.DEFAULT_EVENTS,this.streamUri=di,this.maxCachedContexts=5,this.capacity=100,this.diagnosticRecordingInterval=900,this.flushInterval=30,this.streamInitialReconnectDelay=1,this.allAttributesPrivate=!1,this.debug=!1,this.diagnosticOptOut=!1,this.sendEvents=!0,this.sendLDHeaders=!0,this.useReport=!1,this.withReasons=!1,this.privateAttributes=[],this.pollInterval=xn,this.hooks=[],this.inspectors=[],this.logger=Ln(t.logger),this.Vi(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new R(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=(s=t.useReport)!=null?s:!1,this.tags=new bt({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(a=e.trackEventModifier)!=null?a:(o=>o),this.credentialType=e.credentialType,this.getImplementationHooks=e.getImplementationHooks}Vi(t){let e=[];return Object.entries(t).forEach(([n,s])=>{let r=kn[n];if(r)if(r.is(s))n==="logger"||(this[n]=s!=null?s:void 0);else{let a=r.getType();if(a==="boolean")e.push(k.wrongOptionTypeBoolean(n,typeof s)),this[n]=!!s;else if(a==="boolean | undefined | null")e.push(k.wrongOptionTypeBoolean(n,typeof s)),typeof s!="boolean"&&typeof s!="undefined"&&s!==null&&(this[n]=!!s);else if(r instanceof z&&h.Number.is(s)){let{min:o}=r;e.push(k.optionBelowMinimum(n,s,o)),this[n]=o}else e.push(k.wrongOptionType(n,r.getType(),typeof s))}else e.push(k.unknownOption(n))}),e}};async function fi(i,t){if(i.digest)return i.digest(t);if(i.asyncDigest)return i.asyncDigest(t);throw new Error("Platform must implement digest or asyncDigest")}var pi=async(i,{crypto:t,storage:e})=>{let n=await(e==null?void 0:e.get(i));return n||(n=t.randomUUID(),await(e==null?void 0:e.set(i,n))),n};function gi(i){return async t=>fi(i.createHash("sha256").update(t),"base64")}var S=async i=>i;async function X(i){return(await Promise.all(i.map(e=>e.transform(e.value)))).join("_")}async function Sn(i,t){return X([{value:"LaunchDarkly",transform:S},{value:t,transform:gi(i)}])}async function Cn(i){return X([{value:"LaunchDarkly",transform:S},{value:"AnonymousKeys",transform:S},{value:i,transform:S}])}async function Tn(i){return X([{value:"LaunchDarkly",transform:S},{value:"ContextKeys",transform:S},{value:i,transform:S}])}async function An(i){return X([{value:i,transform:S},{value:"ContextIndex",transform:S}])}async function ri(i,t,e){return X([{value:t,transform:S},{value:e.canonicalKey,transform:gi(i)}])}var{isLegacyUser:In,isSingleKind:pe,isMultiKind:ai}=L,mi="1.0",Pn=i=>{let n=i,{kind:t}=n,e=Bt(n,["kind"]);return{kind:"multi",[t]:e}},Nn=async({crypto:i,info:t},{applicationInfo:e})=>{var a;let{ld_application:n}=t.platformData(),s=(a=Nt(n))!=null?a:{},r=(e==null?void 0:e.id)||(s==null?void 0:s.id);if(r){let o=(e==null?void 0:e.version)||(s==null?void 0:s.version),c=(e==null?void 0:e.name)||(s==null?void 0:s.name),u=(e==null?void 0:e.versionName)||(s==null?void 0:s.versionName);return s=p(p(p(b(p({},s),{id:r}),o?{version:o}:{}),c?{name:c}:{}),u?{versionName:u}:{}),s.key=await fi(i.createHash("sha256").update(r),"base64"),s.envAttributesVersion=s.envAttributesVersion||mi,s}},$n=async i=>{var o,c,u,l;let{ld_device:t,os:e}=i.info.platformData(),n=(o=Nt(t))!=null?o:{},s=(e==null?void 0:e.name)||((c=n.os)==null?void 0:c.name),r=(e==null?void 0:e.version)||((u=n.os)==null?void 0:u.version),a=(l=n.os)==null?void 0:l.family;if((s||r||a)&&(n.os=p(p(p({},s?{name:s}:{}),r?{version:r}:{}),a?{family:a}:{})),Object.keys(n).filter(d=>d!=="key"&&d!=="envAttributesVersion").length){let d=await Tn("ld_device");return n.key=await pi(d,i),n.envAttributesVersion=n.envAttributesVersion||mi,n}},On=async(i,t,e)=>{if(In(i))return i;let n,s;if(pe(i)&&i.kind!=="ld_application"||ai(i)&&!i.ld_application?n=await Nn(t,e):e.logger.warn("Not adding ld_application environment attributes because it already exists."),pe(i)&&i.kind!=="ld_device"||ai(i)&&!i.ld_device?s=await $n(t):e.logger.warn("Not adding ld_device environment attributes because it already exists."),n||s){let r=pe(i)?Pn(i):i;return p(p(p({},r),n?{ld_application:n}:{}),s?{ld_device:s}:{})}return i},{isLegacyUser:Mn,isMultiKind:Rn,isSingleKind:Fn}=L,Ne=async(i,t,e)=>{let{anonymous:n,key:s}=t;if(n&&!s){let r=await Cn(i);t.key=await pi(r,e)}},Un=async(i,t)=>{await Ne(i.kind,i,t)},Vn=async(i,t)=>{let s=i,{kind:e}=s,n=Bt(s,["kind"]);return Promise.all(Object.entries(n).map(([r,a])=>Ne(r,a,t)))},jn=async(i,t)=>{await Ne("user",i,t)},Hn=async(i,t)=>{let e=de(i);return Fn(e)&&await Un(e,t),Rn(e)&&await Vn(e,t),Mn(e)&&await jn(e,t),e},Bn=i=>({customBaseURI:i.serviceEndpoints.polling!==hi,customStreamURI:i.serviceEndpoints.streaming!==di,customEventsURI:i.serviceEndpoints.events!==R.DEFAULT_EVENTS,eventsCapacity:i.capacity,eventsFlushIntervalMillis:Pt(i.flushInterval),reconnectTimeMillis:Pt(i.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Pt(i.diagnosticRecordingInterval),allAttributesPrivate:i.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Kn=(i,t,e)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new L.DiagnosticsManager(i,e,Bn(t))};function ge(i,t){return{value:t!=null?t:null,variationIndex:null,reason:{kind:"ERROR",errorKind:i}}}function oi(i,t,e){return{value:i,variationIndex:t!=null?t:null,reason:e!=null?e:null}}var Gn=(i,t,e,n,s)=>{if(t.sendEvents)return new L.EventProcessor(b(p({},t),{eventsCapacity:t.capacity}),new kt(i,t,e),n,void 0,s,!1,!0)},Ot=class extends L.EventFactoryBase{evalEventClient(t,e,n,s,r,a){let{trackEvents:o,debugEventsUntilDate:c,trackReason:u,flagVersion:l,version:d,variation:f}=s;return super.evalEvent({addExperimentData:u,context:r,debugEventsUntilDate:c,defaultVal:n,flagKey:t,reason:a,trackEvents:!!o,value:e,variation:f,version:l!=null?l:d})}},Z=class i{constructor(){this.container={index:new Array}}static fromJson(t){let e=new i;try{e.container=JSON.parse(t)}catch(n){}return e}toJson(){return JSON.stringify(this.container)}notice(t,e){let n=this.container.index.find(s=>s.id===t);n===void 0?this.container.index.push({id:t,timestamp:e}):n.timestamp=e}prune(t){let e=Math.max(t,0);return this.container.index.length>e?(this.container.index.sort((n,s)=>n.timestamp-s.timestamp),this.container.index.splice(0,this.container.index.length-e)):[]}},Ee=class{constructor(t,e,n,s,r,a,o=()=>Date.now()){this.h=t,this.Vt=e,this.ji=n,this.v=s,this.P=r,this.t=a,this.mt=o,this.Le=An(this.Vt)}async init(t,e){this.P.init(t,e),await this.Se(t)}async upsert(t,e,n){return this.P.upsert(t,e,n)?(await this.Se(t),!0):!1}async loadCached(t){var s,r,a,o;let e=await ri(this.h.crypto,this.Vt,t),n=await((s=this.h.storage)==null?void 0:s.get(e));if(n==null){if(n=await((r=this.h.storage)==null?void 0:r.get(t.canonicalKey)),n==null)return!1;await((a=this.h.storage)==null?void 0:a.set(e,n)),await((o=this.h.storage)==null?void 0:o.clear(t.canonicalKey))}try{let c=JSON.parse(n),u=Object.entries(c).reduce((l,[d,f])=>(l[d]={version:f.version,flag:f},l),{});return this.P.initCached(t,u),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(c){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${c.message}`),!1}}async Hi(){var e;if(this._!==void 0)return this._;let t=await((e=this.h.storage)==null?void 0:e.get(await this.Le));if(!t)return this._=new Z,this._;try{this._=Z.fromJson(t),this.t.debug("Loaded context index from persistent storage")}catch(n){this.t.warn(`Could not load index from persistent storage: ${n.message}`),this._=new Z}return this._}async Se(t){var c,u;let e=await this.Hi(),n=await ri(this.h.crypto,this.Vt,t);e.notice(n,this.mt());let s=e.prune(this.ji);await Promise.all(s.map(async l=>{var d;return(d=this.h.storage)==null?void 0:d.clear(l.id)})),await((c=this.h.storage)==null?void 0:c.set(await this.Le,e.toJson()));let r=this.v.getAll(),a=Object.entries(r).reduce((l,[d,f])=>(f.flag!==null&&f.flag!==void 0&&(l[d]=f.flag),l),{}),o=JSON.stringify(a);await((u=this.h.storage)==null?void 0:u.set(n,o))}},De=class{constructor(){this.et={}}init(t){this.et=Object.entries(t).reduce((e,[n,s])=>(e[n]=s,e),{})}insertOrUpdate(t,e){this.et[t]=e}get(t){if(Object.prototype.hasOwnProperty.call(this.et,t))return this.et[t]}getAll(){return this.et}};function zn(i,t){let e=[];return Object.entries(i).forEach(([n,s])=>{let r=t[n];(!r||!G(s,r))&&e.push(n)}),Object.keys(t).forEach(n=>{i[n]||e.push(n)}),e}var be=class{constructor(t,e){this.it=new Array,this.v=t,this.t=e}init(t,e){this.Ce=t.canonicalKey;let n=this.v.getAll();this.v.init(e);let s=zn(n,e);s.length>0&&this.it.forEach(r=>{try{r(t,s,"init")}catch(a){}})}initCached(t,e){this.Ce!==t.canonicalKey&&this.init(t,e)}upsert(t,e,n){if(this.Ce!==t.canonicalKey)return this.t.warn("Received an update for an inactive context."),!1;let s=this.v.get(e);return s!==void 0&&s.version>=n.version?!1:(this.v.insertOrUpdate(e,n),this.it.forEach(r=>{try{r(t,[e],"patch")}catch(a){}}),!0)}on(t){this.it.push(t)}off(t){let e=this.it.indexOf(t);e>-1&&this.it.splice(e,1)}},ke=class{constructor(t,e,n,s,r=()=>Date.now()){this.v=new De,this.P=new be(this.v,s),this.jt=this.Bi(t,e,n,s,r)}async Bi(t,e,n,s,r=()=>Date.now()){let a=await Sn(t.crypto,e);return new Ee(t,a,n,this.v,this.P,s,r)}get(t){return this.v.get(t)}getAll(){return this.v.getAll()}setBootstrap(t,e){this.P.init(t,e)}async init(t,e){return(await this.jt).init(t,e)}async upsert(t,e,n){return(await this.jt).upsert(t,e,n)}async loadCached(t){return(await this.jt).loadCached(t)}on(t){this.P.on(t)}off(t){this.P.off(t)}},ci="unknown hook",yi="beforeEvaluation",vi="afterEvaluation",_n="afterTrack";function Q(i,t,e,n,s){try{return n()}catch(r){return i==null||i.error(`An error was encountered in "${t}" of the "${e}" hook: ${r}`),s}}function tt(i,t){try{return t.getMetadata().name||ci}catch(e){return i.error("Exception thrown getting metadata for hook. Unable to get hook name."),ci}}function Jn(i,t,e){return t.map(n=>Q(i,yi,tt(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeEvaluation)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function qn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];Q(i,vi,tt(i,a),()=>{var c,u;return(u=(c=a==null?void 0:a.afterEvaluation)==null?void 0:c.call(a,e,o,s))!=null?u:{}},{})}}function Wn(i,t,e){return t.map(n=>Q(i,yi,tt(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeIdentify)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function Yn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];Q(i,vi,tt(i,a),()=>{var c,u;return(u=(c=a==null?void 0:a.afterIdentify)==null?void 0:c.call(a,e,o,s))!=null?u:{}},{})}}function Zn(i,t,e){for(let n=t.length-1;n>=0;n-=1){let s=t[n];Q(i,_n,tt(i,s),()=>{var r;return(r=s==null?void 0:s.afterTrack)==null?void 0:r.call(s,e)},void 0)}}var xe=class{constructor(t,e){this.t=t,this.U=[],this.U.push(...e)}withEvaluation(t,e,n,s){if(this.U.length===0)return s();let r=[...this.U],a={flagKey:t,context:e,defaultValue:n},o=Jn(this.t,r,a),c=s();return qn(this.t,r,a,o,c),c}identify(t,e){let n=[...this.U],s={context:t,timeout:e},r=Wn(this.t,n,s);return a=>{Yn(this.t,n,s,r,a)}}addHook(t){this.U.push(t)}afterTrack(t){if(this.U.length===0)return;let e=[...this.U];Zn(this.t,e,t)}};function Xn(i){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(t,e,n)=>(i.onFlagUsed(t.flagKey,n,t.context),e),afterIdentify(t,e,n){return i.onIdentityChanged(t.context),e}}}function Qn(i,t){return`an inspector: "${t}" of an invalid type (${i}) was configured`}function ts(i,t){return`an inspector: "${t}" of type: "${i}" generated an exception`}function es(i,t){let e=!1,n={method:(...s)=>{try{i.method(...s)}catch(r){e||(e=!0,t.warn(ts(n.type,n.name)))}},type:i.type,name:i.name,synchronous:i.synchronous};return n}var wi="flag-used",Ei="flag-details-changed",Di="flag-detail-changed",bi="client-identity-changed",is=[wi,Ei,Di,bi];function ns(i,t){let e=is.includes(i.type)&&i.method&&typeof i.method=="function";return e||t.warn(Qn(i.type,i.name)),e}var Le=class{constructor(t,e){this.J=[];let n=t.filter(s=>ns(s,e));this.J=n.map(s=>es(s,e))}hasInspectors(){return this.J.length!==0}onFlagUsed(t,e,n){this.J.forEach(s=>{s.type===wi&&s.method(t,e,n)})}onFlagsChanged(t){this.J.forEach(e=>{e.type===Ei&&e.method(t)})}onFlagChanged(t,e){this.J.forEach(n=>{n.type===Di&&n.method(t,e)})}onIdentityChanged(t){this.J.forEach(e=>{e.type===bi&&e.method(t)})}},Se=class{constructor(t){this.t=t,this.e=new Map}on(t,e){var n;this.e.has(t)?(n=this.e.get(t))==null||n.push(e):this.e.set(t,[e])}off(t,e){let n=this.e.get(t);if(n){if(e){let s=n.filter(r=>r!==e);s.length===0?this.e.delete(t):this.e.set(t,s);return}this.e.delete(t)}}Ht(t,e,...n){var s;try{t(...n)}catch(r){(s=this.t)==null||s.error(`Encountered error invoking handler for "${e}", detail: "${r}"`)}}emit(t,...e){let n=this.e.get(t);n==null||n.forEach(s=>this.Ht(s,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,n;return(n=(e=this.e.get(t))==null?void 0:e.length)!=null?n:0}};function ss(i,t,e){let n=t.info.sdkData(),s;e.applicationInfo&&(e.applicationInfo.id&&(s=s!=null?s:{},s.id=e.applicationInfo.id),e.applicationInfo.version&&(s=s!=null?s:{},s.version=e.applicationInfo.version),e.applicationInfo.name&&(s=s!=null?s:{},s.name=e.applicationInfo.name),e.applicationInfo.versionName&&(s=s!=null?s:{},s.versionName=e.applicationInfo.versionName));let r={name:n.userAgentBase,version:n.version};n.wrapperName&&(r.wrapperName=n.wrapperName),n.wrapperVersion&&(r.wrapperVersion=n.wrapperVersion);let a={sdk:r,[e.credentialType]:i};return s&&(a.application=s),a}var{ClientMessages:me,ErrorKinds:ye}=L,rs=5,Mt=class{constructor(t,e,n,s,r,a){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.Bt=15,this.N=new Ot(!1),this.yt=new Ot(!0),this.Kt=!1,this.Ki=bn(),!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.r=new we(s,a),this.logger=this.r.logger,this.Te=ii(this.sdkKey,this.platform.info,this.r.tags,this.r.serviceEndpoints.includeAuthorizationHeader,this.r.userAgentHeaderName),this.S=new ke(this.platform,t,this.r.maxCachedContexts,this.r.logger),this.L=Kn(t,this.r,n),this.w=Gn(t,this.r,n,this.Te,this.L),this.emitter=new Se,this.emitter.on("error",(c,u)=>{this.logger.error(`error: ${u}, context: ${JSON.stringify(c)}`)}),this.S.on((c,u,l)=>{this.Gi(u,l);let d=x.toLDContext(c);this.emitter.emit("change",d,u),u.forEach(f=>{this.emitter.emit(`change:${f}`,d)})}),this.dataManager=r(this.S,this.r,this.Te,this.emitter,this.L);let o=[...this.r.hooks];this.environmentMetadata=ss(this.sdkKey,this.platform,this.r),this.r.getImplementationHooks(this.environmentMetadata).forEach(c=>{o.push(c)}),this.V=new xe(this.logger,o),this.nt=new Le(this.r.inspectors,this.logger),this.nt.hasInspectors()&&this.V.addHook(Xn(this.nt))}allFlags(){return Object.entries(this.S.getAll()).reduce((e,[n,s])=>(s.flag!==null&&s.flag!==void 0&&!s.flag.deleted&&(e[n]=s.flag.value),e),{})}async close(){var t;await this.flush(),(t=this.w)==null||t.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.w)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.D?de(this.D):void 0}getInternalContext(){return this.q}zi(){let t,e;return{identifyPromise:new Promise((s,r)=>{t=s,e=r}),identifyResolve:t,identifyReject:e}}async identify(t,e){let n=await this.identifyResult(t,e);if(n.status==="error")throw n.error;if(n.status==="timeout"){let s=new C(`identify timed out after ${n.timeout} seconds.`);throw this.logger.error(s.message),s}}async identifyResult(t,e){var o,c;let n=(o=e==null?void 0:e.timeout)!=null?o:rs,s=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;n>this.Bt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Bt} seconds. We recommend a timeout of less than ${this.Bt} seconds.`);let r=this.Ki.execute({before:async()=>{let u=await Hn(t,this.platform);this.autoEnvAttributes===j.Enabled&&(u=await On(u,this.platform,this.r));let l=x.fromLDContext(u);if(l.valid){let d=this.V.identify(u,e==null?void 0:e.timeout);return{context:u,checkedContext:l,afterIdentify:d}}return{context:u,checkedContext:l}},execute:async u=>{var y;let{context:l,checkedContext:d}=u;if(!d.valid){let D=new Error("Context was unspecified or had no key");return this.emitter.emit("error",l,D),Promise.reject(D)}this.D=l,this.q=d,(y=this.w)==null||y.sendEvent(this.N.identifyEvent(this.q));let{identifyPromise:f,identifyResolve:m,identifyReject:g}=this.zi();return this.logger.debug(`Identifying ${JSON.stringify(this.q)}`),await this.dataManager.identify(m,g,d,e),f},after:async(u,l)=>{var d,f,m;u.status==="complete"?(d=l==null?void 0:l.afterIdentify)==null||d.call(l,{status:"completed"}):u.status==="shed"?(f=l==null?void 0:l.afterIdentify)==null||f.call(l,{status:"shed"}):u.status==="error"&&((m=l==null?void 0:l.afterIdentify)==null||m.call(l,{status:"error"}))}},(c=e==null?void 0:e.sheddable)!=null?c:!1).then(u=>u.status==="error"?{status:"error",error:u.error}:u.status==="shed"?{status:"shed"}:{status:"completed"});if(s)return r;let a=new Promise(u=>{setTimeout(()=>{u({status:"timeout",timeout:n})},n*1e3)});return Promise.race([r,a])}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){var s,r;if(!this.q||!this.q.valid){this.logger.warn(me.MissingContextKeyNoEvent);return}n!==void 0&&!h.Number.is(n)&&((s=this.logger)==null||s.warn(me.invalidMetricValue(typeof n))),(r=this.w)==null||r.sendEvent(this.r.trackEventModifier(this.N.customEvent(t,this.q,e,n))),this.V.afterTrack({key:t,context:this.D,data:e,metricValue:n})}vt(t,e,n,s){var f,m,g;if(!this.D)return this.logger.debug(me.MissingContextKeyNoEvent),ge(ye.UserNotSpecified,e);let r=x.fromLDContext(this.D),a=this.S.get(t);if(a===void 0||a.flag.deleted){let y=e!=null?e:null,D=new q(`Unknown feature flag "${t}"; returning default value ${y}.`);return this.emitter.emit("error",this.D,D),(f=this.w)==null||f.sendEvent(this.N.unknownFlagEvent(t,y,r)),ge(ye.FlagNotFound,e)}let{reason:o,value:c,variation:u,prerequisites:l}=a.flag;if(s){let[y,D]=s(c);if(!y){(m=this.w)==null||m.sendEvent(n.evalEventClient(t,e,e,a.flag,r,o));let F=new q(`Wrong type "${D}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.D,F),ge(ye.WrongType,e)}}let d=oi(c,u,o);return c==null&&(this.logger.debug("Result value is null. Providing default value."),d.value=e),l==null||l.forEach(y=>{this.vt(y,void 0,this.N)}),(g=this.w)==null||g.sendEvent(n.evalEventClient(t,c,e,a.flag,r,o)),d}variation(t,e){let{value:n}=this.V.withEvaluation(t,this.D,e,()=>this.vt(t,e,this.N));return n}variationDetail(t,e){return this.V.withEvaluation(t,this.D,e,()=>this.vt(t,e,this.yt))}W(t,e,n,s){return this.V.withEvaluation(t,this.D,e,()=>this.vt(t,e,n,s))}boolVariation(t,e){return this.W(t,e,this.N,n=>[h.Boolean.is(n),h.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.W(t,e,this.N,n=>[h.Number.is(n),h.Number.getType()]).value}stringVariation(t,e){return this.W(t,e,this.N,n=>[h.String.is(n),h.String.getType()]).value}boolVariationDetail(t,e){return this.W(t,e,this.yt,n=>[h.Boolean.is(n),h.Boolean.getType()])}numberVariationDetail(t,e){return this.W(t,e,this.yt,n=>[h.Number.is(n),h.Number.getType()])}stringVariationDetail(t,e){return this.W(t,e,this.yt,n=>[h.String.is(n),h.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.V.addHook(t)}setEventSendingEnabled(t,e){var n,s,r,a;this.Kt!==t&&(this.Kt=t,t?(this.logger.debug("Starting event processor"),(n=this.w)==null||n.start()):e?((s=this.logger)==null||s.debug("Flushing event processor before disabling."),this.flush().then(()=>{var o,c;this.Kt||((o=this.logger)==null||o.debug("Stopping event processor."),(c=this.w)==null||c.close())})):((r=this.logger)==null||r.debug("Stopping event processor."),(a=this.w)==null||a.close()))}sendEvent(t){var e;(e=this.w)==null||e.sendEvent(t)}Gi(t,e){if(!this.nt.hasInspectors())return;let n={};t.forEach(s=>{let r=this.S.get(s);if(r!=null&&r.flag&&!r.flag.deleted){let{reason:a,value:o,variation:c}=r.flag;n[s]=oi(o,c,a)}else n[s]={value:void 0,reason:null,variationIndex:null}}),e==="init"?this.nt.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([s,r])=>{this.nt.onFlagChanged(s,r)})}},Ce=class{constructor(t,e,n){this.S=t,this.Gt=e,this.t=n}async handlePut(t,e){this.t.debug(`Got PUT: ${Object.keys(e)}`);let n=Object.entries(e).reduce((s,[r,a])=>(s[r]={version:a.version,flag:a},s),{});await this.S.init(t,n),this.Gt.requestStateUpdate(E.Valid)}async handlePatch(t,e){this.t.debug(`Got PATCH ${JSON.stringify(e,null,2)}`),this.S.upsert(t,e.key,{version:e.version,flag:e})}async handleDelete(t,e){this.t.debug(`Got DELETE ${JSON.stringify(e,null,2)}`),this.S.upsert(t,e.key,{version:e.version,flag:b(p({},e),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})}handleStreamingError(t){this.Gt.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.Gt.reportError(t.kind,t.message,t.status,t.recoverable)}},Te=class{constructor(t,e=()=>Date.now()){this.$=t,this.wt=E.Closed,this.Ae=e(),this.mt=e}get status(){return{state:this.wt,stateSince:this.Ae,lastError:this._i}}Ie(t,e=!1){let n=t===E.Interrupted&&this.wt===E.Initializing?E.Initializing:t,s=this.wt!==n;s&&(this.wt=n,this.Ae=this.mt()),(s||e)&&this.$.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.Ie(t)}reportError(t,e,n,s=!1){let r={kind:t,message:e,statusCode:n,time:this.mt()};this._i=r,this.Ie(s?E.Interrupted:E.Closed,!0)}};function ui(i){i==null||i.debug("Poll completed after the processor was closed. Skipping processing.")}var Ae=class{constructor(t,e,n,s,r){this.Ji=t,this.qi=e,this.Wi=n,this.g=s,this.t=r,this.u=!1}async Pe(){var r,a,o,c,u,l,d;if(this.u)return;let t=f=>{var m,g,y;(m=this.t)==null||m.error("Polling received invalid data"),(g=this.t)==null||g.debug(`Invalid JSON follows: ${f}`),(y=this.g)==null||y.call(this,new O(w.InvalidData,"Malformed JSON data in polling response"))};(r=this.t)==null||r.debug("Polling LaunchDarkly for feature flag updates");let e=Date.now();try{let f=await this.Ji.requestPayload();try{if(this.u){ui(this.t);return}let m=JSON.parse(f);try{(a=this.Wi)==null||a.call(this,m)}catch(g){(o=this.t)==null||o.error(`Exception from data handler: ${g}`)}}catch(m){t(f)}}catch(f){if(this.u){ui(this.t);return}let m=f;if(m.status!==void 0&&!Y(m.status)){(c=this.t)==null||c.error(B(f,"polling request")),(u=this.g)==null||u.call(this,new O(w.ErrorResponse,m.message,m.status));return}(l=this.t)==null||l.error(B(f,"polling request","will retry"))}let n=Date.now()-e,s=Math.max(this.qi*1e3-n,0);(d=this.t)==null||d.debug("Elapsed: %d ms, sleeping for %d ms",n,s),this.zt=setTimeout(()=>{this.Pe()},s)}start(){this.Pe()}stop(){this.zt&&(clearTimeout(this.zt),this.zt=void 0),this.u=!0}close(){this.stop()}},as=(i,t,e,n)=>{e==null||e.error(`Stream received invalid data in "${i}" message`),e==null||e.debug(`Invalid JSON follows: ${t}`),n==null||n(new V(w.InvalidData,"Malformed JSON data in event stream"))};function os(i,t){t==null||t.debug(`Received ${i} event after processor was closed. Skipping processing.`)}function li(i){i==null||i.debug("Ping completed after processor was closed. Skipping processing.")}var Ie=class{constructor(t,e,n,s,r,a,o,c,u){var f;this.Yi=t,this._t=e,this.e=n,this.I=s,this.Zi=a,this.L=o,this.g=c,this.t=u,this.u=!1;let l;e.useReport&&!s.getEventSourceCapabilities().customMethod?l=e.paths.pathPing(r,t):l=e.useReport?e.paths.pathReport(r,t):e.paths.pathGet(r,t);let d=[...(f=e.queryParameters)!=null?f:[]];this._t.withReasons&&d.push({key:"withReasons",value:"true"}),this.I=s,this.gt=p({},e.baseHeaders),this.t=u,this.Xi=Qe(e.serviceEndpoints,l,d)}Ne(){this.Et=Date.now()}Jt(t){this.Et&&this.L&&this.L.recordStreamInit(this.Et,!t,Date.now()-this.Et),this.Et=void 0}Qi(t){var e,n,s;return ni(t)?((s=this.t)==null||s.warn(B(t,"streaming request","will retry")),this.Jt(!1),this.Ne(),!0):(this.Jt(!1),(e=this.g)==null||e.call(this,new V(w.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(B(t,"streaming request")),!1)}start(){this.Ne();let t;this._t.useReport?(this.gt["content-type"]="application/json",t={method:"REPORT",body:this.Yi}):t={};let e=this.I.createEventSource(this.Xi,b(p({headers:this.gt},t),{errorFilter:n=>this.Qi(n),initialRetryDelayMillis:this._t.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.$e=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var s;(s=this.t)==null||s.info(`Will retry stream connection in ${n.delayMillis} milliseconds`)},this.e.forEach(({deserializeData:n,processJson:s},r)=>{e.addEventListener(r,a=>{var o,c;if(this.u){os(r,this.t);return}if((o=this.t)==null||o.debug(`Received ${r} event`),a!=null&&a.data){this.Jt(!0);let{data:u}=a,l=n(u);if(!l){as(r,u,this.t,this.g);return}s(l)}else(c=this.g)==null||c.call(this,new V(w.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,s,r,a,o,c,u;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let l=await this.Zi.requestPayload();try{if(this.u){li(this.t);return}let d=JSON.parse(l);try{(s=this.e.get("put"))==null||s.processJson(d)}catch(f){(r=this.t)==null||r.error(`Exception from data handler: ${f}`)}}catch(d){(a=this.t)==null||a.error("Polling after ping received invalid data"),(o=this.t)==null||o.debug(`Invalid JSON follows: ${l}`),(c=this.g)==null||c.call(this,new O(w.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){li(this.t);return}let d=l;(u=this.g)==null||u.call(this,new O(w.ErrorResponse,d.message,d.status))}})}stop(){var t;(t=this.$e)==null||t.close(),this.$e=void 0,this.u=!0}close(){this.stop()}},Rt=class{constructor(t,e,n,s,r,a,o,c,u){this.platform=t,this.flagManager=e,this.credential=n,this.config=s,this.getPollingPaths=r,this.getStreamingPaths=a,this.baseHeaders=o,this.emitter=c,this.diagnosticsManager=u,this.closed=!1,this.logger=s.logger,this.dataSourceStatusManager=new Te(c),this.Y=new Ce(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.tn=t}createPollingProcessor(t,e,n,s,r){let a=new Ae(n,this.config.pollInterval,async o=>{await this.Y.handlePut(e,o),s==null||s()},o=>{this.emitter.emit("error",t,o),this.Y.handlePollingError(o),r==null||r(o)},this.logger);this.updateProcessor=this.Oe(a,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,s,r){var o;let a=new Ie(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.tn)==null?void 0:o.queryParameters},this.createStreamListeners(e,s),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,c=>{this.emitter.emit("error",t,c),this.Y.handleStreamingError(c),r==null||r(c)},this.logger);this.updateProcessor=this.Oe(a,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async s=>{await this.Y.handlePut(t,s),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async s=>{this.Y.handlePatch(t,s)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async s=>{this.Y.handleDelete(t,s)}}),n}Oe(t,e){return{start:()=>{e.requestStateUpdate(E.Initializing),t.start()},stop:()=>{t.stop(),e.requestStateUpdate(E.Closed)},close:()=>{t.close(),e.requestStateUpdate(E.Closed)}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function Ft(){return typeof document!==void 0}function $e(){return typeof window!==void 0}function Ut(i,t,e){return Ft()?(document.addEventListener(i,t,e),()=>{document.removeEventListener(i,t,e)}):()=>{}}function Vt(i,t,e){return Ft()?(window.addEventListener(i,t,e),()=>{window.removeEventListener(i,t,e)}):()=>{}}function T(){return $e()?window.location.href:""}function ki(){return $e()?window.location.search:""}function xi(){return $e()?window.location.hash:""}function Li(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function Si(){return Ft()?document.visibilityState:"visibile"}function Ci(i){if(Ft())return document.querySelectorAll(i)}function Ti(i,t){let e=Object.keys(t),n="$flagsState",s="$valid",r=t[n];!r&&e.length&&i.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),t[s]===!1&&i.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let a={};return e.forEach(o=>{if(o!==n&&o!==s){let c;r&&r[o]?c=p({value:t[o]},r[o]):c={value:t[o],version:0},a[o]={version:c.version,flag:c}}}),a}var cs="[BrowserDataManager]",et=class extends Rt{constructor(e,n,s,r,a,o,c,u,l,d){super(e,n,s,r,o,c,u,l,d);this.gn=a;this.st=void 0;this.qt=!1;this.st=a.streaming}M(e,...n){this.logger.debug(`${cs} ${e}`,...n)}async identify(e,n,s,r){if(this.closed){this.M("Identify called after data manager was closed.");return}this.context=s;let a=r;a!=null&&a.hash?this.setConnectionParams({queryParameters:[{key:"h",value:a.hash}]}):this.setConnectionParams(),this.Wt=a==null?void 0:a.hash,a!=null&&a.bootstrap?this.en(s,a.bootstrap,e):(await this.flagManager.loadCached(s)&&this.M("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.nn(s,e,n)),this.Yt()}async nn(e,n,s){var r,a;try{this.dataSourceStatusManager.requestStateUpdate(E.Initializing);let o=JSON.stringify(x.toLDContext(e)),u=await Pe(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Wt).requestPayload();try{let d=this.createStreamListeners(e,n).get("put");d.processJson(d.deserializeData(u))}catch(l){this.dataSourceStatusManager.reportError(w.InvalidData,(r=l.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(w.NetworkError,(a=o.message)!=null?a:"unexpected network error",o.status),s(o)}}en(e,n,s){this.flagManager.setBootstrap(e,Ti(this.logger,n)),this.M("Identify - Initialization completed from bootstrap"),s()}setForcedStreaming(e){this.st=e,this.Yt()}setAutomaticStreamingState(e){this.qt=e,this.Yt()}Yt(){let e=this.st||this.qt&&this.st===void 0;this.M(`Updating streaming state. forced(${this.st}) automatic(${this.qt})`),e?this.sn():this.rn()}rn(){var e;this.updateProcessor&&this.M("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}sn(){if(this.updateProcessor){this.M("Update processor already active. Not changing state.");return}if(!this.context){this.M("Context not set, not starting update processor.");return}this.M("Starting update processor."),this.an(this.context)}an(e,n,s){var c;let r=x.toLDContext(e);(c=this.updateProcessor)==null||c.close();let a=JSON.stringify(x.toLDContext(e)),o=Pe(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Wt);this.createStreamingProcessor(r,e,o,n,s),this.updateProcessor.start()}};function Ai(i){let e=Ut("visibilitychange",()=>{Si()==="hidden"&&i()}),n=Vt("pagehide",i);return()=>{e(),n()}}function it(i){if(typeof i!="string")throw new TypeError("Expected a string");return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function us(i,t,e,n){let r=((i.kind==="substring"||i.kind==="regex")&&n.includes("/")?t:t.replace(n,"")).replace(e,"");switch(i.kind){case"exact":return new RegExp(`^${it(i.url)}/?$`).test(t);case"canonical":return new RegExp(`^${it(i.url)}/?$`).test(r);case"substring":return new RegExp(`.*${it(i.substring)}.*$`).test(r);case"regex":return new RegExp(i.pattern).test(r);default:return!1}}function ls(i,t){let e=[];return t.forEach(n=>{let s=i.target,{selector:r}=n,a=Ci(r);for(;s&&(a!=null&&a.length);){for(let o=0;o<a.length;o+=1)if(s===a[o]){e.push(n);break}s=s.parentNode}}),e}var nt=class{constructor(t,e){let n=t.filter(a=>{var o;return(o=a.urls)==null?void 0:o.some(c=>us(c,T(),ki(),xi()))}),s=n.filter(a=>a.kind==="pageview"),r=n.filter(a=>a.kind==="click");if(s.forEach(a=>e(a)),r.length){let a=o=>{ls(o,r).forEach(c=>{e(c)})};this.Me=Ut("click",a)}}close(){var t;(t=this.Me)==null||t.call(this)}};var hs=300,jt=class{constructor(t){this.Zt=T();let e=()=>{let s=T();s!==this.Zt&&(this.Zt=s,t())};this.Xt=setInterval(e,hs);let n=Vt("popstate",e);this.Re=()=>{n()}}close(){var t;this.Xt&&clearInterval(this.Xt),(t=this.Re)==null||t.call(this)}};var st=class{constructor(t,e,n,s,r,a=o=>new jt(o)){this.I=e;this.ln=s;this.un=r;this.Dt=[];this.Ue=!1;this.bt=`${n}/sdk/goals/${t}`,this.Fe=a(()=>{this.te()})}async initialize(){await this.cn(),this.te()}startTracking(){this.Ue=!0,this.te()}te(){var t;this.Ue&&((t=this.Qt)==null||t.close(),this.Dt&&this.Dt.length&&(this.Qt=new nt(this.Dt,e=>{this.un(T(),e)})))}async cn(){try{let t=await this.I.fetch(this.bt);this.Dt=await t.json()}catch(t){this.ln(new J(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.Fe)==null||t.close(),(e=this.Qt)==null||e.close()}};function Ii(i){return i.kind==="click"}var ds=2,Pi={fetchGoals:!0,eventUrlTransformer:i=>i,streaming:void 0,plugins:[]},fs={fetchGoals:h.Boolean,eventUrlTransformer:h.Function,streaming:h.Boolean,plugins:h.createTypeArray("LDPlugin",{})};function ps(i){var e;let t=p({},i);return(e=t.flushInterval)!=null||(t.flushInterval=ds),t}function Ni(i){let t=ps(i);return Object.keys(Pi).forEach(e=>{delete t[e]}),t}function Oe(i,t){let e=p({},Pi);return Object.entries(fs).forEach(n=>{let[s,r]=n,a=i[s];a!==void 0&&(r.is(a)?e[s]=a:t.warn(k.wrongOptionType(s,r.getType(),typeof a)))}),e}var rt=class{constructor(t,e){this.hn=t;this.Ve=[];switch(e){case"sha1":this.ee="SHA-1";break;case"sha256":this.ee="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Ve.join(""),n=new TextEncoder().encode(e),s=await this.hn.subtle.digest(this.ee,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(s)));case"hex":return[...new Uint8Array(s)].map(r=>r.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Ve.push(t),this}};var gs={start:0,end:3},ms={start:4,end:5},Me={start:6,end:7},Re={start:8,end:8},ys={start:9,end:9},vs={start:10,end:15};function ws(){if(crypto&&crypto.getRandomValues){let t=new Uint8Array(16);return crypto.getRandomValues(t),[...t.values()]}let i=[];for(let t=0;t<16;t+=1)i.push(Math.floor(Math.random()*256));return i}function K(i,t){let e="";for(let n=t.start;n<=t.end;n+=1)e+=i[n].toString(16).padStart(2,"0");return e}function Es(i){return i[Re.start]=(i[Re.start]|128)&191,i[Me.start]=i[Me.start]&15|64,`${K(i,gs)}-${K(i,ms)}-${K(i,Me)}-${K(i,Re)}${K(i,ys)}-${K(i,vs)}`}function Ds(){let i=ws();return Es(i)}function Fe(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Ds()}var at=class{createHash(t){return new rt(Li(),t)}randomUUID(){return Fe()}};function bs(i){let t=Array.from(i,e=>String.fromCodePoint(e)).join("");return btoa(t)}var ot=class{btoa(t){return bs(new TextEncoder().encode(t))}};var ct=class{constructor(t){this.r=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"0.0.0",userAgentBase:"JSClient"};return this.r.wrapperName&&(t.wrapperName=this.r.wrapperName),this.r.wrapperVersion&&(t.wrapperVersion=this.r.wrapperVersion),t}};var ut=class{constructor(t,e){this.bt=t;this.e={};this.T=new Dt(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.je=e.errorFilter,this.He()}He(){this.Z=new EventSource(this.bt),this.Z.onopen=()=>{var t;this.T.success(),(t=this.onopen)==null||t.call(this)},this.Z.onerror=t=>{var e;this.dn(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.e).forEach(([t,e])=>{e.forEach(n=>{var s;(s=this.Z)==null||s.addEventListener(t,n)})})}addEventListener(t,e){var n,s,r;(s=(n=this.e)[t])!=null||(n[t]=[]),this.e[t].push(e),(r=this.Z)==null||r.addEventListener(t,e)}close(){var t,e;clearTimeout(this.ie),this.ie=void 0,(t=this.Z)==null||t.close(),(e=this.onclose)==null||e.call(this)}fn(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.ie=setTimeout(()=>{this.He()},t)}dn(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.je(t))&&this.fn(this.T.fail())}};var lt=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new ut(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function $i(){return typeof localStorage!="undefined"}var ht=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{let n=localStorage.getItem(t);return n!=null?n:null}catch(n){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(s){(n=this.t)==null||n.error(`Error setting key in localStorage: ${t}, reason: ${s}`)}}};var dt=class{constructor(t,e){this.encoding=new ot;this.crypto=new at;this.requests=new lt;$i()&&(this.storage=new ht(t)),this.info=new ct(e)}};var Ue=class extends Mt{constructor(t,e,n={},s){var m;let{logger:r,debug:a}=n,o=r!=null?r:new M({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:a?"debug":"info"}),c=(m=n.baseUri)!=null?m:"https://clientsdk.launchdarkly.com",u=s!=null?s:new dt(o,n),l=Oe(n,o),d=Ni(b(p({},n),{logger:o})),{eventUrlTransformer:f}=l;super(t,e,u,d,(g,y,D,F,Ri)=>new et(u,g,t,y,l,()=>({pathGet(P,N){return`/sdk/evalx/${t}/contexts/${fe(N,P)}`},pathReport(P,N){return`/sdk/evalx/${t}/context`},pathPing(P,N){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(P,N){return`/eval/${t}/${fe(N,P)}`},pathReport(P,N){return`/eval/${t}`},pathPing(P,N){return`/ping/${t}`}}),D,F,Ri),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:g=>new L.InputCustomEvent(g.context,g.key,g.data,g.metricValue,g.samplingRatio,f(T())),getImplementationHooks:g=>L.safeGetHooks(o,g,l.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.Be=l.plugins,l.fetchGoals&&(this.ne=new st(t,u.requests,c,g=>{o.error(g.message)},(g,y)=>{let D=this.getInternalContext();if(!D)return;let F=f(g);Ii(y)?this.sendEvent({kind:"click",url:F,samplingRatio:1,key:y.key,creationDate:Date.now(),context:D,selector:y.selector}):this.sendEvent({kind:"pageview",url:F,samplingRatio:1,key:y.key,creationDate:Date.now(),context:D})}),this.ne.initialize(),l.automaticBackgroundHandling&&Ai(()=>this.flush()))}registerPlugins(t){L.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.Be||[])}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var r;let n=p({},e);(e==null?void 0:e.sheddable)===void 0&&(n.sheddable=!0);let s=await super.identifyResult(t,n);return(r=this.ne)==null||r.startTracking(),s}setStreaming(t){this.dataManager.setForcedStreaming(t)}Ke(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.Ke()}off(t,e){super.off(t,e),this.Ke()}};function Oi(i,t,e={},n){let s=new Ue(i,t,e,n),r={variation:(a,o)=>s.variation(a,o),variationDetail:(a,o)=>s.variationDetail(a,o),boolVariation:(a,o)=>s.boolVariation(a,o),boolVariationDetail:(a,o)=>s.boolVariationDetail(a,o),numberVariation:(a,o)=>s.numberVariation(a,o),numberVariationDetail:(a,o)=>s.numberVariationDetail(a,o),stringVariation:(a,o)=>s.stringVariation(a,o),stringVariationDetail:(a,o)=>s.stringVariationDetail(a,o),jsonVariation:(a,o)=>s.jsonVariation(a,o),jsonVariationDetail:(a,o)=>s.jsonVariationDetail(a,o),track:(a,o,c)=>s.track(a,o,c),on:(a,o)=>s.on(a,o),off:(a,o)=>s.off(a,o),flush:()=>s.flush(),setStreaming:a=>s.setStreaming(a),identify:(a,o)=>s.identifyResult(a,o),getContext:()=>s.getContext(),close:()=>s.close(),allFlags:()=>s.allFlags(),addHook:a=>s.addHook(a),logger:s.logger};return s.registerPlugins(r),r}var Mi=["ready","failed","initialized"],ft=class{constructor(t){this.n=t;this.e=new Map}on(t,e){var n;Mi.includes(t)?this.e.has(t)?(n=this.e.get(t))==null||n.push(e):this.e.set(t,[e]):this.n.on(t,e)}off(t,e){if(Mi.includes(t)){let n=this.e.get(t);if(!n)return;if(e){let s=n.filter(r=>r!==e);s.length===0?this.e.delete(t):this.e.set(t,s);return}this.e.delete(t)}else this.n.off(t,e)}Ht(t,e,...n){try{t(...n)}catch(s){this.n.logger.error(`Encountered error invoking handler for "${e}", detail: "${s}"`)}}emit(t,...e){let n=this.e.get(t);n==null||n.forEach(s=>this.Ht(s,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,n;return(n=(e=this.e.get(t))==null?void 0:e.length)!=null?n:0}};function Ht(i,t){let e=i.then(n=>(t&&setTimeout(()=>{t(null,n)},0),n),n=>{if(t)setTimeout(()=>{t(n,null)},0);else return Promise.reject(n)});return t?void 0:e}var pt=class{constructor(t,e,n){this.se="initializing";let s=n==null?void 0:n.bootstrap,r=n==null?void 0:n.hash,a=p({},n);delete a.bootstrap,delete a.hash,this.n=Oi(t,j.Disabled,n),this.$=new ft(this.n),this.logger=this.n.logger,this.pn(e,s,r)}async pn(t,e,n){var s,r;try{let a=await this.n.identify(t,{noTimeout:!0,bootstrap:e,hash:n,sheddable:!1});if(a.status==="error")throw a.error;if(a.status==="timeout")throw new C("Identify timed out");this.se="success",(s=this.Ge)==null||s.call(this),this.$.emit("initialized")}catch(a){this._e=a,this.se="failure",(r=this.ze)==null||r.call(this,a),this.$.emit("failed",a)}this.$.emit("ready")}allFlags(){return this.n.allFlags()}boolVariation(t,e){return this.n.boolVariation(t,e)}boolVariationDetail(t,e){return this.n.boolVariationDetail(t,e)}jsonVariation(t,e){return this.n.jsonVariation(t,e)}jsonVariationDetail(t,e){return this.n.jsonVariationDetail(t,e)}numberVariation(t,e){return this.n.numberVariation(t,e)}numberVariationDetail(t,e){return this.n.numberVariationDetail(t,e)}off(t,e){this.$.off(t,e)}on(t,e){this.$.on(t,e)}stringVariation(t,e){return this.n.stringVariation(t,e)}stringVariationDetail(t,e){return this.n.stringVariationDetail(t,e)}track(t,e,n){this.n.track(t,e,n)}variation(t,e){return this.n.variation(t,e)}variationDetail(t,e){return this.n.variationDetail(t,e)}addHook(t){this.n.addHook(t)}setStreaming(t){this.n.setStreaming(t)}identify(t,e,n){return Ht(this.n.identify(t,{hash:e,sheddable:!1}).then(s=>{if(s.status==="error")throw s.error;if(s.status==="timeout")throw new C("Identify timed out");return this.allFlags()}),n)}close(t){return Ht(this.n.close().then(),t)}flush(t){return Ht(this.n.flush().then(()=>{}),t)}getContext(){return this.n.getContext()}waitForInitialization(t){var e;if(this.rt)return this.Je(this.rt,t);switch(this.se){case"success":return Promise.resolve();case"failure":return Promise.reject(this._e);case"initializing":break;default:throw new Error("Unexpected initialization state. This represents an implementation error in the SDK.")}return t===void 0&&((e=this.logger)==null||e.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),this.rt||(this.rt=new Promise((n,s)=>{this.Ge=n,this.ze=s})),this.Je(this.rt,t)}async waitUntilReady(){try{await this.waitForInitialization()}catch(t){}}Je(t,e){if(e){let n=ei(e,"waitForInitialization");return Promise.race([t.then(()=>n.cancel()),n.promise]).catch(s=>{var r;throw s instanceof C&&((r=this.logger)==null||r.error(s.message)),s})}return t}};function Ca(i){return new M(i)}function Ia(i,t,e){return new pt(i,t,e)}export{Ca as basicLogger,Ia as initialize};
1
+ var Fi=Object.defineProperty,Ui=Object.defineProperties;var Vi=Object.getOwnPropertyDescriptors;var gt=Object.getOwnPropertySymbols;var je=Object.prototype.hasOwnProperty,He=Object.prototype.propertyIsEnumerable;var Ve=(i,t,e)=>t in i?Fi(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,p=(i,t)=>{for(var e in t||(t={}))je.call(t,e)&&Ve(i,e,t[e]);if(gt)for(var e of gt(t))He.call(t,e)&&Ve(i,e,t[e]);return i},b=(i,t)=>Ui(i,Vi(t));var Bt=(i,t)=>{var e={};for(var n in i)je.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&gt)for(var n of gt(i))t.indexOf(n)<0&&He.call(i,n)&&(e[n]=i[n]);return e};function ji(i){return`/${i.replace(/~/g,"~0").replace(/\//g,"~1")}`}function We(i){return i.indexOf("~")?i.replace(/~1/g,"/").replace(/~0/g,"~"):i}function Hi(i){return(i.startsWith("/")?i.substring(1):i).split("/").map(e=>We(e))}function Bi(i){return!i.startsWith("/")}function Ki(i){return!i.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var A=class{constructor(t,e=!1){if(e){let n=t;this.p=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?ji(n):n}else{if(this.redactionName=t,t===""||t==="/"||!Ki(t)){this.isValid=!1,this.p=[];return}Bi(t)?this.p=[t]:t.indexOf("/",1)<0?this.p=[We(t.slice(1))]:this.p=Hi(t),this.p[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{p:e,isValid:n}=this;if(!n)return;let s=t;for(let r=0;r<e.length;r+=1){let a=e[r];if(s!=null&&Object.prototype.hasOwnProperty.call(s,a)&&typeof s=="object"&&!Array.isArray(s))s=s[a];else return}return s}getComponent(t){return this.p[t]}get depth(){return this.p.length}get isKind(){return this.p.length===1&&this.p[0]==="kind"}compare(t){return this.depth===t.depth&&this.p.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.p]}};A.InvalidReference=new A("");var zt=class{is(t){if(Array.isArray(t))return!1;let n=typeof t;return n==="function"||n==="object"}getType(){return"factory method or object"}},I=class{constructor(t,e){this.kt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.kt}},vt=class{constructor(t,e){this.kt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.kt}},z=class extends I{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},wt=class extends I{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},_t=class{is(t){return typeof t=="function"}getType(){return"function"}},Jt=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},Gi=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,qt=class{is(t){return typeof t=="number"||typeof t=="string"&&Gi.test(t)}getType(){return"date"}},Wt=class extends wt{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},h=class{static createTypeArray(t,e){return new vt(t,e)}static numberWithMin(t){return new z(t)}static stringMatchingRegex(t){return new wt(t)}};h.String=new I("string","");h.Number=new I("number",0);h.ObjectOrFactory=new zt;h.Object=new I("object",{});h.StringArray=new vt("string[]","");h.Boolean=new I("boolean",!0);h.Function=new _t;h.Date=new qt;h.Kind=new Wt;h.NullableBoolean=new Jt;function Ye(i){return"kind"in i?h.String.is(i.kind)&&i.kind!=="multi":!1}function Ze(i){return"kind"in i?h.String.is(i.kind)&&i.kind==="multi":!1}function Xe(i){return!("kind"in i)||i.kind===null||i.kind===void 0}function Et(i,t=[]){if(i===null||typeof i!="object")return JSON.stringify(i);if(t.includes(i))throw new Error("Cycle detected");return Array.isArray(i)?`[${i.map(s=>Et(s,[...t,i])).map(s=>s===void 0?"null":s).join(",")}]`:`{${Object.keys(i).sort().map(n=>{let s=Et(i[n],[...t,i]);if(s!==void 0)return`${JSON.stringify(n)}:${s}`}).filter(n=>n!==void 0).join(",")}}`}var Yt="user";function Be(i){return i.includes("%")||i.includes(":")?i.replace(/%/g,"%25").replace(/:/g,"%3A"):i}function zi(i){return i&&h.Object.is(i)}function Ke(i){return h.Kind.is(i)}function Ge(i){return h.String.is(i)&&i!==""}function Kt(i,t=!1){return i?i.map(e=>new A(e,t)):[]}function _i(i){return i!=null}function Ji(i){let t=b(p({},i.custom||[]),{kind:"user",key:String(i.key)});if(_i(i.anonymous)){let e=!!i.anonymous;delete t.anonymous,t.anonymous=e}return i.name!==null&&i.name!==void 0&&(t.name=i.name),i.ip!==null&&i.ip!==void 0&&(t.ip=i.ip),i.firstName!==null&&i.firstName!==void 0&&(t.firstName=i.firstName),i.lastName!==null&&i.lastName!==void 0&&(t.lastName=i.lastName),i.email!==null&&i.email!==void 0&&(t.email=i.email),i.avatar!==null&&i.avatar!==void 0&&(t.avatar=i.avatar),i.country!==null&&i.country!==void 0&&(t.country=i.country),i.privateAttributeNames!==null&&i.privateAttributeNames!==void 0&&(t._meta={privateAttributes:i.privateAttributeNames}),t}var x=class i{constructor(t,e,n){this.C=!1,this.at=!1,this.re=!1,this.R={},this.kind=e,this.valid=t,this.message=n}static b(t,e){return new i(!1,t,e)}static qe(t,e){if(!(!e||!t.isValid))return t.depth===1&&t.getComponent(0)==="anonymous"?!!(e!=null&&e.anonymous):t.get(e)}ae(t){if(this.C)return this.R[t];if(this.kind===t)return this.m}static We(t){let e=Object.keys(t).filter(c=>c!=="kind"),n=e.every(Ke);if(!e.length)return i.b("multi","A multi-kind context must contain at least one kind");if(!n)return i.b("multi","Context contains invalid kinds");let s={},r=!0,a=e.reduce((c,u)=>{var d;let l=t[u];return zi(l)?(c[u]=l,s[u]=Kt((d=l._meta)==null?void 0:d.privateAttributes)):r=!1,c},{});if(!r)return i.b("multi","Context contained contexts that were not objects");if(!Object.values(a).every(c=>Ge(c.key)))return i.b("multi","Context contained invalid keys");if(e.length===1){let c=e[0],u=new i(!0,c);return u.m=b(p({},a[c]),{kind:c}),u.ot=s,u.at=c==="user",u}let o=new i(!0,t.kind);return o.R=a,o.ot=s,o.C=!0,o}static Ye(t){var c;let{key:e,kind:n}=t,s=Ke(n),r=Ge(e);if(!s)return i.b(n!=null?n:"unknown","The kind was not valid for the context");if(!r)return i.b(n,"The key for the context was not valid");let a=Kt((c=t._meta)==null?void 0:c.privateAttributes),o=new i(!0,n);return o.at=n==="user",o.m=t,o.ot={[n]:a},o}static Ze(t){if(!(t.key!==void 0&&t.key!==null))return i.b("user","The key for the context was not valid");let n=new i(!0,"user");return n.at=!0,n.re=!0,n.m=Ji(t),n.ot={user:Kt(t.privateAttributeNames,!0)},n}static fromLDContext(t){return t?Ye(t)?i.Ye(t):Ze(t)?i.We(t):Xe(t)?i.Ze(t):i.b("unknown","Context was not of a valid kind"):i.b("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;let e=t.getContexts();if(!t.C)return e[0][1];let n={kind:"multi"};return e.forEach(s=>{let r=s[0],a=s[1];n[r]=a}),n}valueForKind(t,e=Yt){return t.isKind?this.kinds:i.qe(t,this.ae(e))}key(t=Yt){var e;return(e=this.ae(t))==null?void 0:e.key}get isMultiKind(){return this.C}get canonicalKey(){return this.at?this.m.key:this.C?Object.keys(this.R).sort().map(t=>`${t}:${Be(this.R[t].key)}`).join(":"):`${this.kind}:${Be(this.m.key)}`}get kinds(){return this.C?Object.keys(this.R):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.R).reduce((t,[e,n])=>(t[e]=n.key,t),{}):{[this.kind]:this.m.key}}privateAttributes(t){var e;return((e=this.ot)==null?void 0:e[t])||[]}getContexts(){return this.C?Object.entries(this.R):[[this.kind,this.m]]}get legacy(){return this.re}canonicalUnfilteredJson(){if(this.valid){if(this.xt)return this.xt;try{this.xt=Et(i.toLDContext(this))}catch(t){}return this.xt}}};x.UserKind=Yt;var qi=["key","kind","_meta","anonymous"].map(i=>new A(i,!0)),Wi=["name","ip","firstName","lastName","email","avatar","country"];function Yi(i,t){return i.depth===t.length&&t.every((e,n)=>e===i.getComponent(n))}function Zi(i,t){let e=[],n={},s=[];for(e.push(...Object.keys(i).map(r=>({key:r,ptr:[r],source:i,parent:n,visited:[i]})));e.length;){let r=e.pop(),a=t.find(o=>Yi(o,r.ptr));if(a)s.push(a.redactionName);else{let o=r.source[r.key];o===null?r.parent[r.key]=o:Array.isArray(o)?r.parent[r.key]=[...o]:typeof o=="object"?r.visited.includes(o)||(r.parent[r.key]={},e.push(...Object.keys(o).map(c=>({key:c,ptr:[...r.ptr,c],source:o,parent:r.parent[r.key],visited:[...r.visited,o]})))):r.parent[r.key]=o}}return{cloned:n,excluded:s.sort()}}var Zt=class{constructor(t,e){this.Xe=t,this.Qe=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.oe(t,n[0][1],n[0][0],e);let s={kind:"multi"};return n.forEach(([r,a])=>{s[r]=this.oe(t,a,r,e)}),s}ti(t,e,n,s){return(s?Object.keys(e).map(r=>new A(r,!0)):[...this.Qe,...t.privateAttributes(n)]).filter(r=>!qi.some(a=>a.compare(r)))}oe(t,e,n,s){let r=this.Xe||s&&e.anonymous===!0,{cloned:a,excluded:o}=Zi(e,this.ti(t,e,n,r));return t.legacy&&Wi.forEach(c=>{c in a&&(a[c]=String(a[c]))}),o.length&&(a._meta||(a._meta={}),a._meta.redactedAttributes=o),a._meta&&(delete a._meta.privateAttributes,Object.keys(a._meta).length===0&&delete a._meta),a}},ze=30*1e3,Xi=.5,Dt=class{constructor(t,e,n=Math.random){this.ei=e,this.ii=n,this.Lt=0,this.ce=Math.max(1,t),this.ni=Math.ceil(Math.log2(ze/this.ce))}T(){let t=Math.min(this.Lt,this.ni),e=this.ce*2**t;return Math.min(e,ze)}si(t){return t-Math.trunc(this.ii()*Xi*t)}success(t=Date.now()){this.St=t}fail(t=Date.now()){this.St!==void 0&&t-this.St>this.ei&&(this.Lt=0),this.St=void 0;let e=this.si(this.T());return this.Lt+=1,e}};var _e;(function(i){i[i.Valid=0]="Valid",i[i.Initializing=1]="Initializing",i[i.Interrupted=2]="Interrupted",i[i.Closed=3]="Closed"})(_e||(_e={}));var O=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=s}},V=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=s}};var xs=120*1e3,Ls=300*1e3;var w;(function(i){i.Unknown="UNKNOWN",i.NetworkError="NETWORK_ERROR",i.ErrorResponse="ERROR_RESPONSE",i.InvalidData="INVALID_DATA"})(w||(w={}));var j;(function(i){i[i.Disabled=0]="Disabled",i[i.Enabled=1]="Enabled"})(j||(j={}));var H;(function(i){i[i.AnalyticsEvents=0]="AnalyticsEvents",i[i.DiagnosticEvent=1]="DiagnosticEvent"})(H||(H={}));var $;(function(i){i[i.Succeeded=0]="Succeeded",i[i.Failed=1]="Failed",i[i.FailedAndMustShutDown=2]="FailedAndMustShutDown"})($||($={}));function U(i){if(typeof i=="string")return i;if(i===void 0)return"undefined";if(i===null)return"null";if(Object.prototype.hasOwnProperty.call(i,"toString"))try{return i.toString()}catch(t){}if(typeof i=="bigint")return`${i}n`;try{return JSON.stringify(i)}catch(t){return t instanceof TypeError&&t.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function Qi(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(Number(i))}function tn(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(parseInt(i,10))}function en(i){return typeof i=="symbol"?"NaN":String(parseFloat(i))}var mt={s:i=>U(i),d:i=>Qi(i),i:i=>tn(i),f:i=>en(i),j:i=>U(i),o:i=>U(i),O:i=>U(i),c:()=>""};function Xt(...i){var e;let t=i.shift();if(h.String.is(t)){let n="",s=0;for(;s<t.length;){let r=t.charAt(s);if(r==="%"){if(s+1<t.length){let o=t.charAt(s+1);if(o in mt&&i.length){let c=i.shift();n+=(e=mt[o])==null?void 0:e.call(mt,c)}else o==="%"?n+="%":n+=`%${o}`;s+=2}}else n+=r,s+=1}return i.length&&(n.length&&(n+=" "),n+=i.map(U).join(" ")),n}return i.map(U).join(" ")}var v;(function(i){i[i.debug=0]="debug",i[i.info=1]="info",i[i.warn=2]="warn",i[i.error=3]="error",i[i.none=4]="none"})(v||(v={}));var nn=["debug","info","warn","error","none"],M=class i{static get(){return new i({})}constructor(t){var e,n,s;if(this.di=(n=v[(e=t.level)!=null?e:"info"])!=null?n:v.info,this.fi=(s=t.name)!=null?s:"LaunchDarkly",this.fe=t.formatter,typeof t.destination=="object")this.pe={[v.debug]:t.destination.debug,[v.info]:t.destination.info,[v.warn]:t.destination.warn,[v.error]:t.destination.error};else if(typeof t.destination=="function"){let{destination:r}=t;this.pe={[v.debug]:r,[v.info]:r,[v.warn]:r,[v.error]:r}}}pi(...t){var e;try{return this.fe?(e=this.fe)==null?void 0:e.call(this,...t):Xt(...t)}catch(n){return Xt(...t)}}gi(t,e){try{t(e)}catch(n){console.error(e)}}k(t,e){var n;if(t>=this.di){let s=`${nn[t]}: [${this.fi}]`;try{let r=(n=this.pe)==null?void 0:n[t];r?this.gi(r,`${s} ${this.pi(...e)}`):console.error(...e)}catch(r){console.error(...e)}}}error(...t){this.k(v.error,t)}warn(...t){this.k(v.warn,t)}info(...t){this.k(v.info,t)}debug(...t){this.k(v.debug,t)}},sn={error:h.Function,warn:h.Function,info:h.Function,debug:h.Function},_=class{constructor(t,e){Object.entries(sn).forEach(([n,s])=>{if(!s.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.mi=e}k(t,e){try{this.t[t](...e)}catch(n){this.mi[t](...e)}}error(...t){this.k("error",t)}warn(...t){this.k("warn",t)}info(...t){this.k("info",t)}debug(...t){this.k("debug",t)}},ue=i=>{let t=new M({level:"info",destination:console.error,formatter:Xt});return i?new _(i,t):t},k=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,n){return`Config option "${t}" had invalid value of ${e}, using minimum of ${n} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,n){return`Config option "${t}" should be of type ${e}, got ${n}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},rn=/^(\w|\.|-)+$/,an=h.stringMatchingRegex(rn),on={is:(i,t)=>an.is(i)?i.length>64?{valid:!1,message:k.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:k.invalidTagValue(t)}},bt=class{constructor(t){let e={},n=t==null?void 0:t.application,s=t==null?void 0:t.logger;n&&Object.entries(n).forEach(([a,o])=>{if(o!=null){let{valid:c,message:u}=on.is(o,`application.${a}`);c?a==="versionName"?e["application-version-name"]=[o]:e[`application-${a}`]=[o]:s==null||s.warn(u)}});let r=Object.keys(e);r.length&&(this.value=r.sort().flatMap(a=>e[a].sort().map(o=>`${a}/${o}`)).join(" "))}},kt=class{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function Gt(i){return i.replace(/\/+$/,"")}function le(i){return i.replace(/^\/+/,"").replace(/\?$/,"")}var R=class i{constructor(t,e,n=i.DEFAULT_EVENTS,s="/bulk",r="/diagnostic",a=!0,o){this.streaming=Gt(t),this.polling=Gt(e),this.events=Gt(n),this.analyticsEventPath=s,this.diagnosticEventPath=r,this.includeAuthorizationHeader=a,this.payloadFilterKey=o}};R.DEFAULT_EVENTS="https://events.launchdarkly.com";function he(i,t=[]){if(t.length===0)return i;let e=t.map(({key:n,value:s})=>`${n}=${s}`);return`${i}?${e.join("&")}`}function Qe(i,t,e){let n=le(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),he(`${i.streaming}/${n}`,s)}function ti(i,t,e=[]){let n=le(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),he(`${i.polling}/${n}`,s)}function Je(i,t,e=[]){let n=le(t);return he(`${i.events}/${n}`,e)}var J=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},q=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},C=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Y(i){return i>=400&&i<500?i===400||i===408||i===429:!0}function cn(i){return i===413?!0:Y(i)}function ei(i,t){let e,n;return{promise:new Promise((r,a)=>{n=r,e=setTimeout(()=>{let o=`${t} timed out after ${i} seconds.`;a(new C(o))},i*1e3)}),cancel:()=>{n(),clearTimeout(e)}}}function de(i){return i==null?i:JSON.parse(JSON.stringify(i))}function Pt(i){return Math.trunc(i*1e3)}var un=i=>JSON.stringify(i)==="{}",Nt=(i,t)=>i&&Object.entries(i).reduce((e,[n,s])=>(s&&!un(s)&&!(t!=null&&t.includes(n))&&(e[n]=typeof s=="object"?Nt(s,t):s),e),{});function G(i,t){if(i===t)return!0;if(i&&t&&typeof i=="object"&&typeof t=="object"){if(i.constructor!==t.constructor)return!1;var e,n,s;if(Array.isArray(i)){if(e=i.length,e!=t.length)return!1;for(n=e;n--!==0;)if(!G(i[n],t[n]))return!1;return!0}if(i instanceof Map&&t instanceof Map){if(i.size!==t.size)return!1;for(n of i.entries())if(!t.has(n[0]))return!1;for(n of i.entries())if(!G(n[1],t.get(n[0])))return!1;return!0}if(i instanceof Set&&t instanceof Set){if(i.size!==t.size)return!1;for(n of i.entries())if(!t.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(i)&&ArrayBuffer.isView(t)){if(e=i.length,e!=t.length)return!1;for(n=e;n--!==0;)if(i[n]!==t[n])return!1;return!0}if(i.constructor===RegExp)return i.source===t.source&&i.flags===t.flags;if(i.valueOf!==Object.prototype.valueOf)return i.valueOf()===t.valueOf();if(i.toString!==Object.prototype.toString)return i.toString()===t.toString();if(s=Object.keys(i),e=s.length,e!==Object.keys(t).length)return!1;for(n=e;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[n]))return!1;for(n=e;n--!==0;){var r=s[n];if(!G(i[r],t[r]))return!1}return!0}return i!==i&&t!==t}function ii(i,t,e,n=!0,s="user-agent"){let{userAgentBase:r,version:a,wrapperName:o,wrapperVersion:c}=t.sdkData(),u={[s]:`${r!=null?r:"NodeJSClient"}/${a}`};return n&&(u.authorization=i),o&&(u["x-launchdarkly-wrapper"]=c?`${o}/${c}`:o),e!=null&&e.value&&(u["x-launchdarkly-tags"]=e.value),u}function B(i,t,e){let n;i.status?n=`error ${i.status}${i.status===401?" (invalid SDK key)":""}`:n=`I/O error (${i.message||"unknown error"})`;let s=e!=null?e:"giving up permanently";return`Received ${n} for ${t} - ${s}`}function ni({status:i}){return i?Y(i):!0}var fe=(i,t)=>t.btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var ln=async(i=1e3)=>new Promise(t=>{setTimeout(t,i)});var Qt=class{constructor(t,e,n){this.h=e,this.yi=n,this.At=[],this.ge=Date.now(),this.me=this.ge,this.ye={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var n,s,r;let t=this.h.info.sdkData(),e=this.h.info.platformData();return{kind:"diagnostic-init",id:this.ye,creationDate:this.ge,sdk:t,configuration:this.yi,platform:p({name:e.name,osArch:(n=e.os)==null?void 0:n.arch,osName:(s=e.os)==null?void 0:s.name,osVersion:(r=e.os)==null?void 0:r.version},e.additional||{})}}recordStreamInit(t,e,n){let s={timestamp:t,failed:e,durationMillis:n};this.At.push(s)}createStatsEventAndReset(t,e,n){let s=Date.now(),r={kind:"diagnostic",id:this.ye,creationDate:s,dataSinceDate:this.me,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.At};return this.At=[],this.me=s,r}},te;(function(i){i.MalformedFlag="MALFORMED_FLAG",i.UserNotSpecified="USER_NOT_SPECIFIED",i.FlagNotFound="FLAG_NOT_FOUND",i.ClientNotReady="CLIENT_NOT_READY",i.WrongType="WRONG_TYPE"})(te||(te={}));var hn=te,xt=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};xt.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var ee=class{constructor(t,e){let{basicConfiguration:n,platform:s}=t,{serviceEndpoints:{analyticsEventPath:r,diagnosticEventPath:a}}=n,{crypto:o,requests:c}=s;this.vi=p({},e),this.ve=Je(n.serviceEndpoints,r,[]),this.wi=Je(n.serviceEndpoints,a,[]),this.I=c,this.Ei=o}async ct(t,e,n,s){let r={status:$.Succeeded},a=b(p({},this.vi),{"content-type":"application/json"});n&&(a["x-launchdarkly-payload-id"]=n,a["x-launchDarkly-event-schema"]="4");let o;try{let{status:c,headers:u}=await this.I.fetch(e,{headers:a,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),l=Date.parse(u.get("date")||"");if(l&&(r.serverTime=l),c<=204)return r;if(o=new J(B({status:c,message:"some events were dropped"},"event posting")),!Y(c))return cn(c)?r.status=$.Failed:r.status=$.FailedAndMustShutDown,r.error=o,r}catch(c){o=c}return o&&!s?(r.status=$.Failed,r.error=o,r):(await ln(),this.ct(t,this.ve,n,!1))}async sendEventData(t,e){let n=t===H.AnalyticsEvents?this.Ei.randomUUID():void 0,s=t===H.AnalyticsEvents?this.ve:this.wi;return this.ct(e,s,n,!0)}};function Lt(i){return i.kind==="feature"}function dn(i){return i.kind==="identify"}function fn(i){return i.kind==="migration_op"}var ie=class{constructor(t,e,n,s,r,a){this.count=t,this.key=e,this.value=n,this.version=r,this.variation=a,this.default=s}increment(){this.count+=1}};function pn(i){return`${i.key}:${i.variation!==null&&i.variation!==void 0?i.variation:""}:${i.version!==null&&i.version!==void 0?i.version:""}`}var St=class{constructor(t=!1,e){this.Di=t,this.x=e,this.X=0,this.ut=0,this.lt={},this.ht={}}summarizeEvent(t){if(Lt(t)&&!t.excludeFromSummaries){this.m||(this.m=t.context);let e=pn(t),n=this.lt[e],s=this.ht[t.key];s||(s=new Set,this.ht[t.key]=s),t.context.kinds.forEach(r=>s.add(r)),n?n.increment():this.lt[e]=new ie(1,t.key,t.value,t.default,t.version,t.variation),(this.X===0||t.creationDate<this.X)&&(this.X=t.creationDate),t.creationDate>this.ut&&(this.ut=t.creationDate)}}getSummary(){var n;let t=Object.values(this.lt).reduce((s,r)=>{let a=s[r.key];a||(a={default:r.default,counters:[],contextKinds:[...this.ht[r.key]]},s[r.key]=a);let o={value:r.value,count:r.count};return r.variation!==void 0&&r.variation!==null&&(o.variation=r.variation),r.version!==void 0&&r.version!==null?o.version=r.version:o.unknown=!0,a.counters.push(o),s},{}),e={startDate:this.X,endDate:this.ut,features:t,kind:"summary",context:this.m!==void 0&&this.Di?(n=this.x)==null?void 0:n.filter(this.m):void 0};return this.bi(),e}bi(){this.X=0,this.ut=0,this.lt={},this.ht={}}},ne=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},se=class{constructor(t,e){this.x=t,this.t=e,this.Q={}}summarizeEvent(t){var e;if(Lt(t)){let n=t.context.canonicalUnfilteredJson();if(!n){t.context.valid&&((e=this.t)==null||e.error("Unable to serialize context, likely the context contains a cycle."));return}let s=this.Q[n];s||(this.Q[n]=new St(!0,this.x),s=this.Q[n]),s.summarizeEvent(t)}}getSummaries(){let t=this.Q;return this.Q={},Object.values(t).map(e=>e.getSummary())}};function yt(i){let t=Math.trunc(i);return t===1?!0:t===0?!1:Math.floor(Math.random()*t)===0}function gn(i){return i.getSummaries!==void 0}var re=class{constructor(t,e,n,s,r,a=!0,o=!1){this.r=t,this.dt=s,this.L=r,this.ft=[],this.we=0,this.It=0,this.Pt=0,this.Nt=!1,this.Ee=0,this.$t=!1,this.Ot=null,this.ki=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.De=new ee(e,n),this.x=new Zt(t.allAttributesPrivate,t.privateAttributes.map(c=>new A(c))),o?this.tt=new se(this.x,this.t):this.tt=new St,a&&this.start()}start(){var t,e;if(((t=this.dt)==null?void 0:t.flushInterval)!==void 0&&(this.Ot=setInterval(()=>{var n;(n=this.dt)==null||n.flush()},this.dt.flushInterval*1e3)),this.xi=setInterval(async()=>{var n;try{await this.flush()}catch(s){(n=this.t)==null||n.debug(`Flush failed: ${s}`)}},this.r.flushInterval*1e3),this.L){let n=this.L.createInitEvent();this.be(n),this.ke=setInterval(()=>{let s=this.L.createStatsEventAndReset(this.It,this.Pt,this.Ee);this.It=0,this.Pt=0,this.be(s)},this.r.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}be(t){this.De.sendEventData(H.DiagnosticEvent,t)}close(){clearInterval(this.xi),this.Ot&&clearInterval(this.Ot),this.ke&&clearInterval(this.ke)}async flush(){var e;if(this.$t)throw new ne("Events cannot be posted because a permanent error has been encountered. This is most likely an invalid SDK key. The specific error information is logged independently.");let t=this.ft;if(this.ft=[],gn(this.tt))this.tt.getSummaries().forEach(s=>{Object.keys(s.features).length&&t.push(s)});else{let n=this.tt.getSummary();Object.keys(n.features).length&&t.push(n)}t.length&&(this.Ee=t.length,(e=this.t)==null||e.debug("Flushing %d events",t.length),await this.ct(t))}sendEvent(t){var c;if(this.$t)return;if(fn(t)){if(yt(t.samplingRatio)){let u=b(p({},t),{context:t.context?this.x.filter(t.context):void 0});u.samplingRatio===1&&delete u.samplingRatio,this.pt(u)}return}this.tt.summarizeEvent(t);let e=Lt(t),n=e&&t.trackEvents||!e,s=this.Li(t),r=dn(t),a=(c=this.dt)==null?void 0:c.processContext(t.context);a||r||(this.Pt+=1),a&&!r&&this.pt(this.Mt({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),n&&yt(t.samplingRatio)&&this.pt(this.Mt(t,!1)),s&&yt(t.samplingRatio)&&this.pt(this.Mt(t,!0))}Mt(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.x.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}pt(t){var e;this.ft.length<this.ki?(this.ft.push(t),this.Nt=!1):(this.Nt||(this.Nt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.It+=1)}Li(t){return Lt(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.we&&t.debugEventsUntilDate>Date.now()}async ct(t){let e=await this.De.sendEventData(H.AnalyticsEvents,t);if(e.status===$.FailedAndMustShutDown&&(this.$t=!0),e.serverTime&&(this.we=e.serverTime),e.error)throw e.error}},Ct=class{constructor(t,e,n,s,r=1,a){this.context=t,this.key=e,this.data=n,this.metricValue=s,this.samplingRatio=r,this.url=a,this.kind="custom",this.creationDate=Date.now(),this.context=t}},W=class{constructor(t,e,n,s,r,a,o,c,u,l,d,f,m=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=m,this.kind="feature",this.creationDate=Date.now(),this.value=s,this.default=r,a!==void 0&&(this.version=a),o!==void 0&&(this.variation=o),c!==void 0&&(this.trackEvents=c),u!==void 0&&(this.prereqOf=u),l!==void 0&&(this.reason=l),d!==void 0&&(this.debugEventsUntilDate=d),f!==void 0&&(this.excludeFromSummaries=f)}},Tt=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},ae=class{close(){}async flush(){}sendEvent(){}},oe=class{constructor(t){this.Rt=t}evalEvent(t){var e;return new W(this.Rt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.Rt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new W(this.Rt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Tt(t,1)}customEvent(t,e,n,s,r=1){return new Ct(e,t,n!=null?n:void 0,s!=null?s:void 0,r)}},At=class{constructor(t,e,n){this.Si=t,this.g=e,this.t=n,this.e=[],this.F=void 0,this.K=!1,this.G=[],this.Ci=s=>{var a;if(this.Ft(),!s.payloads.length)return;let r=s.payloads[0];switch(r==null?void 0:r.intentCode){case"xfer-full":this.K=!0;break;case"xfer-changes":this.K=!1;break;case"none":this.K=!1,this.Ti(r);break;default:(a=this.t)==null||a.warn(`Unable to process intent code '${r==null?void 0:r.intentCode}'.`);return}this.F=r==null?void 0:r.id},this.Ai=s=>{var a;if(!this.F||!s.kind||!s.key||!s.version||!s.object)return;let r=this.Ii(s.kind,s.object);if(!r){(a=this.t)==null||a.warn(`Unable to process object for kind: '${s.kind}'`);return}this.G.push({kind:s.kind,key:s.key,version:s.version,object:r})},this.Pi=s=>{!this.F||!s.kind||!s.key||!s.version||this.G.push({kind:s.kind,key:s.key,version:s.version,deleted:!0})},this.Ti=s=>{if(!s.id||!s.target)return;let r={id:s.id,version:s.target,basis:!1,updates:[]};this.e.forEach(a=>a(r)),this.xe()},this.Ni=s=>{if(!this.F||!s.state||!s.version){this.Ft();return}let r={id:this.F,version:s.version,state:s.state,basis:this.K,updates:this.G};this.e.forEach(a=>a(r)),this.xe()},this.$i=s=>{var r;(r=this.t)==null||r.info(`Goodbye was received from the LaunchDarkly connection with reason: ${s.reason}.`),this.Ft()},this.Oi=s=>{var r;(r=this.t)==null||r.info(`An issue was encountered receiving updates for payload ${this.F} with reason: ${s.reason}.`),this.Mi()}}addPayloadListener(t){this.e.push(t)}removePayloadListener(t){let e=this.e.indexOf(t,0);e>-1&&this.e.splice(e,1)}processEvents(t){t.forEach(e=>{switch(e.event){case"server-intent":{this.Ci(e.data);break}case"put-object":{this.Ai(e.data);break}case"delete-object":{this.Pi(e.data);break}case"payload-transferred":{this.Ni(e.data);break}case"goodbye":{this.$i(e.data);break}case"error":{this.Oi(e.data);break}}})}Ii(t,e){var n,s;return(s=(n=this.Si)[t])==null?void 0:s.call(n,e)}xe(){this.K=!1,this.G=[]}Mi(){this.G=[]}Ft(){this.F=void 0,this.K=!1,this.G=[]}},ce=class{constructor(t,e,n,s){this.g=n,this.t=s,this.z(t,"server-intent"),this.z(t,"put-object"),this.z(t,"delete-object"),this.z(t,"payload-transferred"),this.z(t,"goodbye"),this.z(t,"error"),this.Ut=new At(e,n,s)}addPayloadListener(t){this.Ut.addPayloadListener(t)}removePayloadListener(t){this.Ut.removePayloadListener(t)}z(t,e){t.addEventListener(e,async n=>{var s,r,a,o,c;if(n!=null&&n.data){(s=this.t)==null||s.debug(`Received ${e} event. Data is ${n.data}`);try{this.Ut.processEvents([{event:e,data:JSON.parse(n.data)}])}catch(u){(r=this.t)==null||r.error(`Stream received data that was unable to be processed in "${e}" message`),(a=this.t)==null||a.debug(`Data follows: ${n.data}`),(o=this.g)==null||o.call(this,w.InvalidData,"Malformed data in EventStream.")}}else(c=this.g)==null||c.call(this,w.Unknown,"Event from EventStream missing data.")})}};function mn(i){if(i){let t=Object.keys(i).find(e=>e.toLowerCase()==="x-ld-envid");if(t)return{environmentId:i[t]}}}var qe="unknown plugin";function It(i,t){try{return t.getMetadata().name||qe}catch(e){return i.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),qe}}function yn(i,t,e){let n=[];return e.forEach(s=>{var r;try{let a=(r=s.getHooks)==null?void 0:r.call(s,t);a===void 0?i.error(`Plugin ${It(i,s)} returned undefined from getHooks.`):a&&a.length>0&&n.push(...a)}catch(a){i.error(`Exception thrown getting hooks for plugin ${It(i,s)}. Unable to get hooks.`)}}),n}function vn(i,t,e,n){n.forEach(s=>{try{s.register(e,t)}catch(r){i.error(`Exception thrown registering plugin ${It(i,s)}.`)}})}var L=Object.freeze({__proto__:null,ClientMessages:xt,DiagnosticsManager:Qt,ErrorKinds:hn,EventFactoryBase:oe,EventProcessor:re,InputCustomEvent:Ct,InputEvalEvent:W,InputIdentifyEvent:Tt,NullEventProcessor:ae,PayloadProcessor:At,PayloadStreamReader:ce,canonicalize:Et,initMetadataFromHeaders:mn,isLegacyUser:Xe,isMultiKind:Ze,isSingleKind:Ye,safeGetHooks:yn,safeGetName:It,safeRegisterPlugins:vn,shouldSample:yt});var E;(function(i){i.Initializing="INITIALIZING",i.Valid="VALID",i.Interrupted="INTERRUPTED",i.SetOffline="SET_OFFLINE",i.Closed="CLOSED"})(E||(E={}));function En(i){return i>=200&&i<=299}var $t=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}},ve=class{constructor(t,e,n,s,r){this.I=t,this.Ri=e,this.gt=n,this.Fi=s,this.Ui=r}async requestPayload(){let t;try{let e=await this.I.fetch(this.Ri,{method:this.Fi,headers:this.gt,body:this.Ui});if(En(e.status))return await e.text();t=e.status}catch(e){throw new $t(e==null?void 0:e.message)}throw new $t(`Unexpected status code: ${t}`,t)}};function Pe(i,t,e,n,s,r,a,o,c,u){let l,d="GET",f=p({},r);c&&(d="REPORT",f["content-type"]="application/json",l=i);let m=c?e.pathReport(s,i):e.pathGet(s,i),g=[...a!=null?a:[]];o&&g.push({key:"withReasons",value:"true"}),u&&g.push({key:"h",value:u});let y=ti(t,m,g);return new ve(n,y,f,d,l)}var si=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function Dn(i,t,e=!1){let n,s=new Promise(o=>{n=(c,u)=>{var l;try{(l=i.after)==null||l.call(i,c,u)}catch(d){t==null||t.error(`Error in after callback: ${d}`)}o(c)}}),r=i.before?i.before():Promise.resolve(void 0),a=!1;return{execute:()=>{a&&(t==null||t.error(si)),a=!0,r.then(o=>{i.execute(o).then(c=>n({status:"complete",result:c},o)).catch(c=>n({status:"error",error:c},o))}).catch(o=>{t==null||t.error(o),n({status:"error",error:o},void 0)})},shed:()=>{a&&(t==null||t.error(si)),a=!0,r.then(o=>{n({status:"shed"},o)})},promise:s,sheddable:e}}function bn(i){let t,e=[];function n(){if(!t&&e.length>0){let s=e.shift();t=s.promise.finally(()=>{t=void 0,n()}),s.execute()}}return{execute(s,r=!1){var o,c;let a=Dn(s,i,r);return t?((o=e[e.length-1])!=null&&o.sheddable&&((c=e.pop())==null||c.shed()),e.push(a)):(t=a.promise.finally(()=>{t=void 0,n()}),a.execute()),a.promise},pendingCount(){return e.length}}}var kn={logger:h.Object,maxCachedContexts:h.numberWithMin(0),baseUri:h.String,streamUri:h.String,eventsUri:h.String,capacity:h.numberWithMin(1),diagnosticRecordingInterval:h.numberWithMin(2),flushInterval:h.numberWithMin(2),streamInitialReconnectDelay:h.numberWithMin(0),allAttributesPrivate:h.Boolean,debug:h.Boolean,diagnosticOptOut:h.Boolean,withReasons:h.Boolean,sendEvents:h.Boolean,pollInterval:h.numberWithMin(30),useReport:h.Boolean,privateAttributes:h.StringArray,applicationInfo:h.Object,wrapperName:h.String,wrapperVersion:h.String,payloadFilterKey:h.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:h.createTypeArray("Hook[]",{}),inspectors:h.createTypeArray("LDInspection",{})},xn=300,hi="https://clientsdk.launchdarkly.com",di="https://clientstream.launchdarkly.com";function Ln(i){return i instanceof _?i:ue(i)}var we=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var s,r,a;this.logger=ue(),this.baseUri=hi,this.eventsUri=R.DEFAULT_EVENTS,this.streamUri=di,this.maxCachedContexts=5,this.capacity=100,this.diagnosticRecordingInterval=900,this.flushInterval=30,this.streamInitialReconnectDelay=1,this.allAttributesPrivate=!1,this.debug=!1,this.diagnosticOptOut=!1,this.sendEvents=!0,this.sendLDHeaders=!0,this.useReport=!1,this.withReasons=!1,this.privateAttributes=[],this.pollInterval=xn,this.hooks=[],this.inspectors=[],this.logger=Ln(t.logger),this.Vi(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new R(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=(s=t.useReport)!=null?s:!1,this.tags=new bt({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(a=e.trackEventModifier)!=null?a:(o=>o),this.credentialType=e.credentialType,this.getImplementationHooks=e.getImplementationHooks}Vi(t){let e=[];return Object.entries(t).forEach(([n,s])=>{let r=kn[n];if(r)if(r.is(s))n==="logger"||(this[n]=s!=null?s:void 0);else{let a=r.getType();if(a==="boolean")e.push(k.wrongOptionTypeBoolean(n,typeof s)),this[n]=!!s;else if(a==="boolean | undefined | null")e.push(k.wrongOptionTypeBoolean(n,typeof s)),typeof s!="boolean"&&typeof s!="undefined"&&s!==null&&(this[n]=!!s);else if(r instanceof z&&h.Number.is(s)){let{min:o}=r;e.push(k.optionBelowMinimum(n,s,o)),this[n]=o}else e.push(k.wrongOptionType(n,r.getType(),typeof s))}else e.push(k.unknownOption(n))}),e}};async function fi(i,t){if(i.digest)return i.digest(t);if(i.asyncDigest)return i.asyncDigest(t);throw new Error("Platform must implement digest or asyncDigest")}var pi=async(i,{crypto:t,storage:e})=>{let n=await(e==null?void 0:e.get(i));return n||(n=t.randomUUID(),await(e==null?void 0:e.set(i,n))),n};function gi(i){return async t=>fi(i.createHash("sha256").update(t),"base64")}var S=async i=>i;async function X(i){return(await Promise.all(i.map(e=>e.transform(e.value)))).join("_")}async function Sn(i,t){return X([{value:"LaunchDarkly",transform:S},{value:t,transform:gi(i)}])}async function Cn(i){return X([{value:"LaunchDarkly",transform:S},{value:"AnonymousKeys",transform:S},{value:i,transform:S}])}async function Tn(i){return X([{value:"LaunchDarkly",transform:S},{value:"ContextKeys",transform:S},{value:i,transform:S}])}async function An(i){return X([{value:i,transform:S},{value:"ContextIndex",transform:S}])}async function ri(i,t,e){return X([{value:t,transform:S},{value:e.canonicalKey,transform:gi(i)}])}var{isLegacyUser:In,isSingleKind:pe,isMultiKind:ai}=L,mi="1.0",Pn=i=>{let n=i,{kind:t}=n,e=Bt(n,["kind"]);return{kind:"multi",[t]:e}},Nn=async({crypto:i,info:t},{applicationInfo:e})=>{var a;let{ld_application:n}=t.platformData(),s=(a=Nt(n))!=null?a:{},r=(e==null?void 0:e.id)||(s==null?void 0:s.id);if(r){let o=(e==null?void 0:e.version)||(s==null?void 0:s.version),c=(e==null?void 0:e.name)||(s==null?void 0:s.name),u=(e==null?void 0:e.versionName)||(s==null?void 0:s.versionName);return s=p(p(p(b(p({},s),{id:r}),o?{version:o}:{}),c?{name:c}:{}),u?{versionName:u}:{}),s.key=await fi(i.createHash("sha256").update(r),"base64"),s.envAttributesVersion=s.envAttributesVersion||mi,s}},$n=async i=>{var o,c,u,l;let{ld_device:t,os:e}=i.info.platformData(),n=(o=Nt(t))!=null?o:{},s=(e==null?void 0:e.name)||((c=n.os)==null?void 0:c.name),r=(e==null?void 0:e.version)||((u=n.os)==null?void 0:u.version),a=(l=n.os)==null?void 0:l.family;if((s||r||a)&&(n.os=p(p(p({},s?{name:s}:{}),r?{version:r}:{}),a?{family:a}:{})),Object.keys(n).filter(d=>d!=="key"&&d!=="envAttributesVersion").length){let d=await Tn("ld_device");return n.key=await pi(d,i),n.envAttributesVersion=n.envAttributesVersion||mi,n}},On=async(i,t,e)=>{if(In(i))return i;let n,s;if(pe(i)&&i.kind!=="ld_application"||ai(i)&&!i.ld_application?n=await Nn(t,e):e.logger.warn("Not adding ld_application environment attributes because it already exists."),pe(i)&&i.kind!=="ld_device"||ai(i)&&!i.ld_device?s=await $n(t):e.logger.warn("Not adding ld_device environment attributes because it already exists."),n||s){let r=pe(i)?Pn(i):i;return p(p(p({},r),n?{ld_application:n}:{}),s?{ld_device:s}:{})}return i},{isLegacyUser:Mn,isMultiKind:Rn,isSingleKind:Fn}=L,Ne=async(i,t,e)=>{let{anonymous:n,key:s}=t;if(n&&!s){let r=await Cn(i);t.key=await pi(r,e)}},Un=async(i,t)=>{await Ne(i.kind,i,t)},Vn=async(i,t)=>{let s=i,{kind:e}=s,n=Bt(s,["kind"]);return Promise.all(Object.entries(n).map(([r,a])=>Ne(r,a,t)))},jn=async(i,t)=>{await Ne("user",i,t)},Hn=async(i,t)=>{let e=de(i);return Fn(e)&&await Un(e,t),Rn(e)&&await Vn(e,t),Mn(e)&&await jn(e,t),e},Bn=i=>({customBaseURI:i.serviceEndpoints.polling!==hi,customStreamURI:i.serviceEndpoints.streaming!==di,customEventsURI:i.serviceEndpoints.events!==R.DEFAULT_EVENTS,eventsCapacity:i.capacity,eventsFlushIntervalMillis:Pt(i.flushInterval),reconnectTimeMillis:Pt(i.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Pt(i.diagnosticRecordingInterval),allAttributesPrivate:i.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Kn=(i,t,e)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new L.DiagnosticsManager(i,e,Bn(t))};function ge(i,t){return{value:t!=null?t:null,variationIndex:null,reason:{kind:"ERROR",errorKind:i}}}function oi(i,t,e){return{value:i,variationIndex:t!=null?t:null,reason:e!=null?e:null}}var Gn=(i,t,e,n,s)=>{if(t.sendEvents)return new L.EventProcessor(b(p({},t),{eventsCapacity:t.capacity}),new kt(i,t,e),n,void 0,s,!1,!0)},Ot=class extends L.EventFactoryBase{evalEventClient(t,e,n,s,r,a){let{trackEvents:o,debugEventsUntilDate:c,trackReason:u,flagVersion:l,version:d,variation:f}=s;return super.evalEvent({addExperimentData:u,context:r,debugEventsUntilDate:c,defaultVal:n,flagKey:t,reason:a,trackEvents:!!o,value:e,variation:f,version:l!=null?l:d})}},Z=class i{constructor(){this.container={index:new Array}}static fromJson(t){let e=new i;try{e.container=JSON.parse(t)}catch(n){}return e}toJson(){return JSON.stringify(this.container)}notice(t,e){let n=this.container.index.find(s=>s.id===t);n===void 0?this.container.index.push({id:t,timestamp:e}):n.timestamp=e}prune(t){let e=Math.max(t,0);return this.container.index.length>e?(this.container.index.sort((n,s)=>n.timestamp-s.timestamp),this.container.index.splice(0,this.container.index.length-e)):[]}},Ee=class{constructor(t,e,n,s,r,a,o=()=>Date.now()){this.h=t,this.Vt=e,this.ji=n,this.v=s,this.P=r,this.t=a,this.mt=o,this.Le=An(this.Vt)}async init(t,e){this.P.init(t,e),await this.Se(t)}async upsert(t,e,n){return this.P.upsert(t,e,n)?(await this.Se(t),!0):!1}async loadCached(t){var s,r,a,o;let e=await ri(this.h.crypto,this.Vt,t),n=await((s=this.h.storage)==null?void 0:s.get(e));if(n==null){if(n=await((r=this.h.storage)==null?void 0:r.get(t.canonicalKey)),n==null)return!1;await((a=this.h.storage)==null?void 0:a.set(e,n)),await((o=this.h.storage)==null?void 0:o.clear(t.canonicalKey))}try{let c=JSON.parse(n),u=Object.entries(c).reduce((l,[d,f])=>(l[d]={version:f.version,flag:f},l),{});return this.P.initCached(t,u),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(c){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${c.message}`),!1}}async Hi(){var e;if(this._!==void 0)return this._;let t=await((e=this.h.storage)==null?void 0:e.get(await this.Le));if(!t)return this._=new Z,this._;try{this._=Z.fromJson(t),this.t.debug("Loaded context index from persistent storage")}catch(n){this.t.warn(`Could not load index from persistent storage: ${n.message}`),this._=new Z}return this._}async Se(t){var c,u;let e=await this.Hi(),n=await ri(this.h.crypto,this.Vt,t);e.notice(n,this.mt());let s=e.prune(this.ji);await Promise.all(s.map(async l=>{var d;return(d=this.h.storage)==null?void 0:d.clear(l.id)})),await((c=this.h.storage)==null?void 0:c.set(await this.Le,e.toJson()));let r=this.v.getAll(),a=Object.entries(r).reduce((l,[d,f])=>(f.flag!==null&&f.flag!==void 0&&(l[d]=f.flag),l),{}),o=JSON.stringify(a);await((u=this.h.storage)==null?void 0:u.set(n,o))}},De=class{constructor(){this.et={}}init(t){this.et=Object.entries(t).reduce((e,[n,s])=>(e[n]=s,e),{})}insertOrUpdate(t,e){this.et[t]=e}get(t){if(Object.prototype.hasOwnProperty.call(this.et,t))return this.et[t]}getAll(){return this.et}};function zn(i,t){let e=[];return Object.entries(i).forEach(([n,s])=>{let r=t[n];(!r||!G(s,r))&&e.push(n)}),Object.keys(t).forEach(n=>{i[n]||e.push(n)}),e}var be=class{constructor(t,e){this.it=new Array,this.v=t,this.t=e}init(t,e){this.Ce=t.canonicalKey;let n=this.v.getAll();this.v.init(e);let s=zn(n,e);s.length>0&&this.it.forEach(r=>{try{r(t,s,"init")}catch(a){}})}initCached(t,e){this.Ce!==t.canonicalKey&&this.init(t,e)}upsert(t,e,n){if(this.Ce!==t.canonicalKey)return this.t.warn("Received an update for an inactive context."),!1;let s=this.v.get(e);return s!==void 0&&s.version>=n.version?!1:(this.v.insertOrUpdate(e,n),this.it.forEach(r=>{try{r(t,[e],"patch")}catch(a){}}),!0)}on(t){this.it.push(t)}off(t){let e=this.it.indexOf(t);e>-1&&this.it.splice(e,1)}},ke=class{constructor(t,e,n,s,r=()=>Date.now()){this.v=new De,this.P=new be(this.v,s),this.jt=this.Bi(t,e,n,s,r)}async Bi(t,e,n,s,r=()=>Date.now()){let a=await Sn(t.crypto,e);return new Ee(t,a,n,this.v,this.P,s,r)}get(t){return this.v.get(t)}getAll(){return this.v.getAll()}setBootstrap(t,e){this.P.init(t,e)}async init(t,e){return(await this.jt).init(t,e)}async upsert(t,e,n){return(await this.jt).upsert(t,e,n)}async loadCached(t){return(await this.jt).loadCached(t)}on(t){this.P.on(t)}off(t){this.P.off(t)}},ci="unknown hook",yi="beforeEvaluation",vi="afterEvaluation",_n="afterTrack";function Q(i,t,e,n,s){try{return n()}catch(r){return i==null||i.error(`An error was encountered in "${t}" of the "${e}" hook: ${r}`),s}}function tt(i,t){try{return t.getMetadata().name||ci}catch(e){return i.error("Exception thrown getting metadata for hook. Unable to get hook name."),ci}}function Jn(i,t,e){return t.map(n=>Q(i,yi,tt(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeEvaluation)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function qn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];Q(i,vi,tt(i,a),()=>{var c,u;return(u=(c=a==null?void 0:a.afterEvaluation)==null?void 0:c.call(a,e,o,s))!=null?u:{}},{})}}function Wn(i,t,e){return t.map(n=>Q(i,yi,tt(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeIdentify)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function Yn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];Q(i,vi,tt(i,a),()=>{var c,u;return(u=(c=a==null?void 0:a.afterIdentify)==null?void 0:c.call(a,e,o,s))!=null?u:{}},{})}}function Zn(i,t,e){for(let n=t.length-1;n>=0;n-=1){let s=t[n];Q(i,_n,tt(i,s),()=>{var r;return(r=s==null?void 0:s.afterTrack)==null?void 0:r.call(s,e)},void 0)}}var xe=class{constructor(t,e){this.t=t,this.U=[],this.U.push(...e)}withEvaluation(t,e,n,s){if(this.U.length===0)return s();let r=[...this.U],a={flagKey:t,context:e,defaultValue:n},o=Jn(this.t,r,a),c=s();return qn(this.t,r,a,o,c),c}identify(t,e){let n=[...this.U],s={context:t,timeout:e},r=Wn(this.t,n,s);return a=>{Yn(this.t,n,s,r,a)}}addHook(t){this.U.push(t)}afterTrack(t){if(this.U.length===0)return;let e=[...this.U];Zn(this.t,e,t)}};function Xn(i){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(t,e,n)=>(i.onFlagUsed(t.flagKey,n,t.context),e),afterIdentify(t,e,n){return i.onIdentityChanged(t.context),e}}}function Qn(i,t){return`an inspector: "${t}" of an invalid type (${i}) was configured`}function ts(i,t){return`an inspector: "${t}" of type: "${i}" generated an exception`}function es(i,t){let e=!1,n={method:(...s)=>{try{i.method(...s)}catch(r){e||(e=!0,t.warn(ts(n.type,n.name)))}},type:i.type,name:i.name,synchronous:i.synchronous};return n}var wi="flag-used",Ei="flag-details-changed",Di="flag-detail-changed",bi="client-identity-changed",is=[wi,Ei,Di,bi];function ns(i,t){let e=is.includes(i.type)&&i.method&&typeof i.method=="function";return e||t.warn(Qn(i.type,i.name)),e}var Le=class{constructor(t,e){this.J=[];let n=t.filter(s=>ns(s,e));this.J=n.map(s=>es(s,e))}hasInspectors(){return this.J.length!==0}onFlagUsed(t,e,n){this.J.forEach(s=>{s.type===wi&&s.method(t,e,n)})}onFlagsChanged(t){this.J.forEach(e=>{e.type===Ei&&e.method(t)})}onFlagChanged(t,e){this.J.forEach(n=>{n.type===Di&&n.method(t,e)})}onIdentityChanged(t){this.J.forEach(e=>{e.type===bi&&e.method(t)})}},Se=class{constructor(t){this.t=t,this.e=new Map}on(t,e){var n;this.e.has(t)?(n=this.e.get(t))==null||n.push(e):this.e.set(t,[e])}off(t,e){let n=this.e.get(t);if(n){if(e){let s=n.filter(r=>r!==e);s.length===0?this.e.delete(t):this.e.set(t,s);return}this.e.delete(t)}}Ht(t,e,...n){var s;try{t(...n)}catch(r){(s=this.t)==null||s.error(`Encountered error invoking handler for "${e}", detail: "${r}"`)}}emit(t,...e){let n=this.e.get(t);n==null||n.forEach(s=>this.Ht(s,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,n;return(n=(e=this.e.get(t))==null?void 0:e.length)!=null?n:0}};function ss(i,t,e){let n=t.info.sdkData(),s;e.applicationInfo&&(e.applicationInfo.id&&(s=s!=null?s:{},s.id=e.applicationInfo.id),e.applicationInfo.version&&(s=s!=null?s:{},s.version=e.applicationInfo.version),e.applicationInfo.name&&(s=s!=null?s:{},s.name=e.applicationInfo.name),e.applicationInfo.versionName&&(s=s!=null?s:{},s.versionName=e.applicationInfo.versionName));let r={name:n.userAgentBase,version:n.version};n.wrapperName&&(r.wrapperName=n.wrapperName),n.wrapperVersion&&(r.wrapperVersion=n.wrapperVersion);let a={sdk:r,[e.credentialType]:i};return s&&(a.application=s),a}var{ClientMessages:me,ErrorKinds:ye}=L,rs=5,Mt=class{constructor(t,e,n,s,r,a){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.Bt=15,this.N=new Ot(!1),this.yt=new Ot(!0),this.Kt=!1,this.Ki=bn(),!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.r=new we(s,a),this.logger=this.r.logger,this.Te=ii(this.sdkKey,this.platform.info,this.r.tags,this.r.serviceEndpoints.includeAuthorizationHeader,this.r.userAgentHeaderName),this.S=new ke(this.platform,t,this.r.maxCachedContexts,this.r.logger),this.L=Kn(t,this.r,n),this.w=Gn(t,this.r,n,this.Te,this.L),this.emitter=new Se,this.emitter.on("error",(c,u)=>{this.logger.error(`error: ${u}, context: ${JSON.stringify(c)}`)}),this.S.on((c,u,l)=>{this.Gi(u,l);let d=x.toLDContext(c);this.emitter.emit("change",d,u),u.forEach(f=>{this.emitter.emit(`change:${f}`,d)})}),this.dataManager=r(this.S,this.r,this.Te,this.emitter,this.L);let o=[...this.r.hooks];this.environmentMetadata=ss(this.sdkKey,this.platform,this.r),this.r.getImplementationHooks(this.environmentMetadata).forEach(c=>{o.push(c)}),this.V=new xe(this.logger,o),this.nt=new Le(this.r.inspectors,this.logger),this.nt.hasInspectors()&&this.V.addHook(Xn(this.nt))}allFlags(){return Object.entries(this.S.getAll()).reduce((e,[n,s])=>(s.flag!==null&&s.flag!==void 0&&!s.flag.deleted&&(e[n]=s.flag.value),e),{})}async close(){var t;await this.flush(),(t=this.w)==null||t.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.w)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.D?de(this.D):void 0}getInternalContext(){return this.q}zi(){let t,e;return{identifyPromise:new Promise((s,r)=>{t=s,e=r}),identifyResolve:t,identifyReject:e}}async identify(t,e){let n=await this.identifyResult(t,e);if(n.status==="error")throw n.error;if(n.status==="timeout"){let s=new C(`identify timed out after ${n.timeout} seconds.`);throw this.logger.error(s.message),s}}async identifyResult(t,e){var o,c;let n=(o=e==null?void 0:e.timeout)!=null?o:rs,s=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;n>this.Bt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Bt} seconds. We recommend a timeout of less than ${this.Bt} seconds.`);let r=this.Ki.execute({before:async()=>{let u=await Hn(t,this.platform);this.autoEnvAttributes===j.Enabled&&(u=await On(u,this.platform,this.r));let l=x.fromLDContext(u);if(l.valid){let d=this.V.identify(u,e==null?void 0:e.timeout);return{context:u,checkedContext:l,afterIdentify:d}}return{context:u,checkedContext:l}},execute:async u=>{var y;let{context:l,checkedContext:d}=u;if(!d.valid){let D=new Error("Context was unspecified or had no key");return this.emitter.emit("error",l,D),Promise.reject(D)}this.D=l,this.q=d,(y=this.w)==null||y.sendEvent(this.N.identifyEvent(this.q));let{identifyPromise:f,identifyResolve:m,identifyReject:g}=this.zi();return this.logger.debug(`Identifying ${JSON.stringify(this.q)}`),await this.dataManager.identify(m,g,d,e),f},after:async(u,l)=>{var d,f,m;u.status==="complete"?(d=l==null?void 0:l.afterIdentify)==null||d.call(l,{status:"completed"}):u.status==="shed"?(f=l==null?void 0:l.afterIdentify)==null||f.call(l,{status:"shed"}):u.status==="error"&&((m=l==null?void 0:l.afterIdentify)==null||m.call(l,{status:"error"}))}},(c=e==null?void 0:e.sheddable)!=null?c:!1).then(u=>u.status==="error"?{status:"error",error:u.error}:u.status==="shed"?{status:"shed"}:{status:"completed"});if(s)return r;let a=new Promise(u=>{setTimeout(()=>{u({status:"timeout",timeout:n})},n*1e3)});return Promise.race([r,a])}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){var s,r;if(!this.q||!this.q.valid){this.logger.warn(me.MissingContextKeyNoEvent);return}n!==void 0&&!h.Number.is(n)&&((s=this.logger)==null||s.warn(me.invalidMetricValue(typeof n))),(r=this.w)==null||r.sendEvent(this.r.trackEventModifier(this.N.customEvent(t,this.q,e,n))),this.V.afterTrack({key:t,context:this.D,data:e,metricValue:n})}vt(t,e,n,s){var f,m,g;if(!this.D)return this.logger.debug(me.MissingContextKeyNoEvent),ge(ye.UserNotSpecified,e);let r=x.fromLDContext(this.D),a=this.S.get(t);if(a===void 0||a.flag.deleted){let y=e!=null?e:null,D=new q(`Unknown feature flag "${t}"; returning default value ${y}.`);return this.emitter.emit("error",this.D,D),(f=this.w)==null||f.sendEvent(this.N.unknownFlagEvent(t,y,r)),ge(ye.FlagNotFound,e)}let{reason:o,value:c,variation:u,prerequisites:l}=a.flag;if(s){let[y,D]=s(c);if(!y){(m=this.w)==null||m.sendEvent(n.evalEventClient(t,e,e,a.flag,r,o));let F=new q(`Wrong type "${D}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.D,F),ge(ye.WrongType,e)}}let d=oi(c,u,o);return c==null&&(this.logger.debug("Result value is null. Providing default value."),d.value=e),l==null||l.forEach(y=>{this.vt(y,void 0,this.N)}),(g=this.w)==null||g.sendEvent(n.evalEventClient(t,c,e,a.flag,r,o)),d}variation(t,e){let{value:n}=this.V.withEvaluation(t,this.D,e,()=>this.vt(t,e,this.N));return n}variationDetail(t,e){return this.V.withEvaluation(t,this.D,e,()=>this.vt(t,e,this.yt))}W(t,e,n,s){return this.V.withEvaluation(t,this.D,e,()=>this.vt(t,e,n,s))}boolVariation(t,e){return this.W(t,e,this.N,n=>[h.Boolean.is(n),h.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.W(t,e,this.N,n=>[h.Number.is(n),h.Number.getType()]).value}stringVariation(t,e){return this.W(t,e,this.N,n=>[h.String.is(n),h.String.getType()]).value}boolVariationDetail(t,e){return this.W(t,e,this.yt,n=>[h.Boolean.is(n),h.Boolean.getType()])}numberVariationDetail(t,e){return this.W(t,e,this.yt,n=>[h.Number.is(n),h.Number.getType()])}stringVariationDetail(t,e){return this.W(t,e,this.yt,n=>[h.String.is(n),h.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.V.addHook(t)}setEventSendingEnabled(t,e){var n,s,r,a;this.Kt!==t&&(this.Kt=t,t?(this.logger.debug("Starting event processor"),(n=this.w)==null||n.start()):e?((s=this.logger)==null||s.debug("Flushing event processor before disabling."),this.flush().then(()=>{var o,c;this.Kt||((o=this.logger)==null||o.debug("Stopping event processor."),(c=this.w)==null||c.close())})):((r=this.logger)==null||r.debug("Stopping event processor."),(a=this.w)==null||a.close()))}sendEvent(t){var e;(e=this.w)==null||e.sendEvent(t)}Gi(t,e){if(!this.nt.hasInspectors())return;let n={};t.forEach(s=>{let r=this.S.get(s);if(r!=null&&r.flag&&!r.flag.deleted){let{reason:a,value:o,variation:c}=r.flag;n[s]=oi(o,c,a)}else n[s]={value:void 0,reason:null,variationIndex:null}}),e==="init"?this.nt.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([s,r])=>{this.nt.onFlagChanged(s,r)})}},Ce=class{constructor(t,e,n){this.S=t,this.Gt=e,this.t=n}async handlePut(t,e){this.t.debug(`Got PUT: ${Object.keys(e)}`);let n=Object.entries(e).reduce((s,[r,a])=>(s[r]={version:a.version,flag:a},s),{});await this.S.init(t,n),this.Gt.requestStateUpdate(E.Valid)}async handlePatch(t,e){this.t.debug(`Got PATCH ${JSON.stringify(e,null,2)}`),this.S.upsert(t,e.key,{version:e.version,flag:e})}async handleDelete(t,e){this.t.debug(`Got DELETE ${JSON.stringify(e,null,2)}`),this.S.upsert(t,e.key,{version:e.version,flag:b(p({},e),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})}handleStreamingError(t){this.Gt.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.Gt.reportError(t.kind,t.message,t.status,t.recoverable)}},Te=class{constructor(t,e=()=>Date.now()){this.$=t,this.wt=E.Closed,this.Ae=e(),this.mt=e}get status(){return{state:this.wt,stateSince:this.Ae,lastError:this._i}}Ie(t,e=!1){let n=t===E.Interrupted&&this.wt===E.Initializing?E.Initializing:t,s=this.wt!==n;s&&(this.wt=n,this.Ae=this.mt()),(s||e)&&this.$.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.Ie(t)}reportError(t,e,n,s=!1){let r={kind:t,message:e,statusCode:n,time:this.mt()};this._i=r,this.Ie(s?E.Interrupted:E.Closed,!0)}};function ui(i){i==null||i.debug("Poll completed after the processor was closed. Skipping processing.")}var Ae=class{constructor(t,e,n,s,r){this.Ji=t,this.qi=e,this.Wi=n,this.g=s,this.t=r,this.u=!1}async Pe(){var r,a,o,c,u,l,d;if(this.u)return;let t=f=>{var m,g,y;(m=this.t)==null||m.error("Polling received invalid data"),(g=this.t)==null||g.debug(`Invalid JSON follows: ${f}`),(y=this.g)==null||y.call(this,new O(w.InvalidData,"Malformed JSON data in polling response"))};(r=this.t)==null||r.debug("Polling LaunchDarkly for feature flag updates");let e=Date.now();try{let f=await this.Ji.requestPayload();try{if(this.u){ui(this.t);return}let m=JSON.parse(f);try{(a=this.Wi)==null||a.call(this,m)}catch(g){(o=this.t)==null||o.error(`Exception from data handler: ${g}`)}}catch(m){t(f)}}catch(f){if(this.u){ui(this.t);return}let m=f;if(m.status!==void 0&&!Y(m.status)){(c=this.t)==null||c.error(B(f,"polling request")),(u=this.g)==null||u.call(this,new O(w.ErrorResponse,m.message,m.status));return}(l=this.t)==null||l.error(B(f,"polling request","will retry"))}let n=Date.now()-e,s=Math.max(this.qi*1e3-n,0);(d=this.t)==null||d.debug("Elapsed: %d ms, sleeping for %d ms",n,s),this.zt=setTimeout(()=>{this.Pe()},s)}start(){this.Pe()}stop(){this.zt&&(clearTimeout(this.zt),this.zt=void 0),this.u=!0}close(){this.stop()}},as=(i,t,e,n)=>{e==null||e.error(`Stream received invalid data in "${i}" message`),e==null||e.debug(`Invalid JSON follows: ${t}`),n==null||n(new V(w.InvalidData,"Malformed JSON data in event stream"))};function os(i,t){t==null||t.debug(`Received ${i} event after processor was closed. Skipping processing.`)}function li(i){i==null||i.debug("Ping completed after processor was closed. Skipping processing.")}var Ie=class{constructor(t,e,n,s,r,a,o,c,u){var f;this.Yi=t,this._t=e,this.e=n,this.I=s,this.Zi=a,this.L=o,this.g=c,this.t=u,this.u=!1;let l;e.useReport&&!s.getEventSourceCapabilities().customMethod?l=e.paths.pathPing(r,t):l=e.useReport?e.paths.pathReport(r,t):e.paths.pathGet(r,t);let d=[...(f=e.queryParameters)!=null?f:[]];this._t.withReasons&&d.push({key:"withReasons",value:"true"}),this.I=s,this.gt=p({},e.baseHeaders),this.t=u,this.Xi=Qe(e.serviceEndpoints,l,d)}Ne(){this.Et=Date.now()}Jt(t){this.Et&&this.L&&this.L.recordStreamInit(this.Et,!t,Date.now()-this.Et),this.Et=void 0}Qi(t){var e,n,s;return ni(t)?((s=this.t)==null||s.warn(B(t,"streaming request","will retry")),this.Jt(!1),this.Ne(),!0):(this.Jt(!1),(e=this.g)==null||e.call(this,new V(w.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(B(t,"streaming request")),!1)}start(){this.Ne();let t;this._t.useReport?(this.gt["content-type"]="application/json",t={method:"REPORT",body:this.Yi}):t={};let e=this.I.createEventSource(this.Xi,b(p({headers:this.gt},t),{errorFilter:n=>this.Qi(n),initialRetryDelayMillis:this._t.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.$e=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var s;(s=this.t)==null||s.info(`Will retry stream connection in ${n.delayMillis} milliseconds`)},this.e.forEach(({deserializeData:n,processJson:s},r)=>{e.addEventListener(r,a=>{var o,c;if(this.u){os(r,this.t);return}if((o=this.t)==null||o.debug(`Received ${r} event`),a!=null&&a.data){this.Jt(!0);let{data:u}=a,l=n(u);if(!l){as(r,u,this.t,this.g);return}s(l)}else(c=this.g)==null||c.call(this,new V(w.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,s,r,a,o,c,u;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let l=await this.Zi.requestPayload();try{if(this.u){li(this.t);return}let d=JSON.parse(l);try{(s=this.e.get("put"))==null||s.processJson(d)}catch(f){(r=this.t)==null||r.error(`Exception from data handler: ${f}`)}}catch(d){(a=this.t)==null||a.error("Polling after ping received invalid data"),(o=this.t)==null||o.debug(`Invalid JSON follows: ${l}`),(c=this.g)==null||c.call(this,new O(w.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){li(this.t);return}let d=l;(u=this.g)==null||u.call(this,new O(w.ErrorResponse,d.message,d.status))}})}stop(){var t;(t=this.$e)==null||t.close(),this.$e=void 0,this.u=!0}close(){this.stop()}},Rt=class{constructor(t,e,n,s,r,a,o,c,u){this.platform=t,this.flagManager=e,this.credential=n,this.config=s,this.getPollingPaths=r,this.getStreamingPaths=a,this.baseHeaders=o,this.emitter=c,this.diagnosticsManager=u,this.closed=!1,this.logger=s.logger,this.dataSourceStatusManager=new Te(c),this.Y=new Ce(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.tn=t}createPollingProcessor(t,e,n,s,r){let a=new Ae(n,this.config.pollInterval,async o=>{await this.Y.handlePut(e,o),s==null||s()},o=>{this.emitter.emit("error",t,o),this.Y.handlePollingError(o),r==null||r(o)},this.logger);this.updateProcessor=this.Oe(a,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,s,r){var o;let a=new Ie(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.tn)==null?void 0:o.queryParameters},this.createStreamListeners(e,s),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,c=>{this.emitter.emit("error",t,c),this.Y.handleStreamingError(c),r==null||r(c)},this.logger);this.updateProcessor=this.Oe(a,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async s=>{await this.Y.handlePut(t,s),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async s=>{this.Y.handlePatch(t,s)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async s=>{this.Y.handleDelete(t,s)}}),n}Oe(t,e){return{start:()=>{e.requestStateUpdate(E.Initializing),t.start()},stop:()=>{t.stop(),e.requestStateUpdate(E.Closed)},close:()=>{t.close(),e.requestStateUpdate(E.Closed)}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function Ft(){return typeof document!==void 0}function $e(){return typeof window!==void 0}function Ut(i,t,e){return Ft()?(document.addEventListener(i,t,e),()=>{document.removeEventListener(i,t,e)}):()=>{}}function Vt(i,t,e){return Ft()?(window.addEventListener(i,t,e),()=>{window.removeEventListener(i,t,e)}):()=>{}}function T(){return $e()?window.location.href:""}function ki(){return $e()?window.location.search:""}function xi(){return $e()?window.location.hash:""}function Li(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function Si(){return Ft()?document.visibilityState:"visibile"}function Ci(i){if(Ft())return document.querySelectorAll(i)}function Ti(i,t){let e=Object.keys(t),n="$flagsState",s="$valid",r=t[n];!r&&e.length&&i.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),t[s]===!1&&i.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let a={};return e.forEach(o=>{if(o!==n&&o!==s){let c;r&&r[o]?c=p({value:t[o]},r[o]):c={value:t[o],version:0},a[o]={version:c.version,flag:c}}}),a}var cs="[BrowserDataManager]",et=class extends Rt{constructor(e,n,s,r,a,o,c,u,l,d){super(e,n,s,r,o,c,u,l,d);this.gn=a;this.st=void 0;this.qt=!1;this.st=a.streaming}M(e,...n){this.logger.debug(`${cs} ${e}`,...n)}async identify(e,n,s,r){if(this.closed){this.M("Identify called after data manager was closed.");return}this.context=s;let a=r;a!=null&&a.hash?this.setConnectionParams({queryParameters:[{key:"h",value:a.hash}]}):this.setConnectionParams(),this.Wt=a==null?void 0:a.hash,a!=null&&a.bootstrap?this.en(s,a.bootstrap,e):(await this.flagManager.loadCached(s)&&this.M("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.nn(s,e,n)),this.Yt()}async nn(e,n,s){var r,a;try{this.dataSourceStatusManager.requestStateUpdate(E.Initializing);let o=JSON.stringify(x.toLDContext(e)),u=await Pe(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Wt).requestPayload();try{let d=this.createStreamListeners(e,n).get("put");d.processJson(d.deserializeData(u))}catch(l){this.dataSourceStatusManager.reportError(w.InvalidData,(r=l.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(w.NetworkError,(a=o.message)!=null?a:"unexpected network error",o.status),s(o)}}en(e,n,s){this.flagManager.setBootstrap(e,Ti(this.logger,n)),this.M("Identify - Initialization completed from bootstrap"),s()}setForcedStreaming(e){this.st=e,this.Yt()}setAutomaticStreamingState(e){this.qt=e,this.Yt()}Yt(){let e=this.st||this.qt&&this.st===void 0;this.M(`Updating streaming state. forced(${this.st}) automatic(${this.qt})`),e?this.sn():this.rn()}rn(){var e;this.updateProcessor&&this.M("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}sn(){if(this.updateProcessor){this.M("Update processor already active. Not changing state.");return}if(!this.context){this.M("Context not set, not starting update processor.");return}this.M("Starting update processor."),this.an(this.context)}an(e,n,s){var c;let r=x.toLDContext(e);(c=this.updateProcessor)==null||c.close();let a=JSON.stringify(x.toLDContext(e)),o=Pe(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Wt);this.createStreamingProcessor(r,e,o,n,s),this.updateProcessor.start()}};function Ai(i){let e=Ut("visibilitychange",()=>{Si()==="hidden"&&i()}),n=Vt("pagehide",i);return()=>{e(),n()}}function it(i){if(typeof i!="string")throw new TypeError("Expected a string");return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function us(i,t,e,n){let r=((i.kind==="substring"||i.kind==="regex")&&n.includes("/")?t:t.replace(n,"")).replace(e,"");switch(i.kind){case"exact":return new RegExp(`^${it(i.url)}/?$`).test(t);case"canonical":return new RegExp(`^${it(i.url)}/?$`).test(r);case"substring":return new RegExp(`.*${it(i.substring)}.*$`).test(r);case"regex":return new RegExp(i.pattern).test(r);default:return!1}}function ls(i,t){let e=[];return t.forEach(n=>{let s=i.target,{selector:r}=n,a=Ci(r);for(;s&&(a!=null&&a.length);){for(let o=0;o<a.length;o+=1)if(s===a[o]){e.push(n);break}s=s.parentNode}}),e}var nt=class{constructor(t,e){let n=t.filter(a=>{var o;return(o=a.urls)==null?void 0:o.some(c=>us(c,T(),ki(),xi()))}),s=n.filter(a=>a.kind==="pageview"),r=n.filter(a=>a.kind==="click");if(s.forEach(a=>e(a)),r.length){let a=o=>{ls(o,r).forEach(c=>{e(c)})};this.Me=Ut("click",a)}}close(){var t;(t=this.Me)==null||t.call(this)}};var hs=300,jt=class{constructor(t){this.Zt=T();let e=()=>{let s=T();s!==this.Zt&&(this.Zt=s,t())};this.Xt=setInterval(e,hs);let n=Vt("popstate",e);this.Re=()=>{n()}}close(){var t;this.Xt&&clearInterval(this.Xt),(t=this.Re)==null||t.call(this)}};var st=class{constructor(t,e,n,s,r,a=o=>new jt(o)){this.I=e;this.ln=s;this.un=r;this.Dt=[];this.Ue=!1;this.bt=`${n}/sdk/goals/${t}`,this.Fe=a(()=>{this.te()})}async initialize(){await this.cn(),this.te()}startTracking(){this.Ue=!0,this.te()}te(){var t;this.Ue&&((t=this.Qt)==null||t.close(),this.Dt&&this.Dt.length&&(this.Qt=new nt(this.Dt,e=>{this.un(T(),e)})))}async cn(){try{let t=await this.I.fetch(this.bt);this.Dt=await t.json()}catch(t){this.ln(new J(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.Fe)==null||t.close(),(e=this.Qt)==null||e.close()}};function Ii(i){return i.kind==="click"}var ds=2,Pi={fetchGoals:!0,eventUrlTransformer:i=>i,streaming:void 0,plugins:[]},fs={fetchGoals:h.Boolean,eventUrlTransformer:h.Function,streaming:h.Boolean,plugins:h.createTypeArray("LDPlugin",{})};function ps(i){var e;let t=p({},i);return(e=t.flushInterval)!=null||(t.flushInterval=ds),t}function Ni(i){let t=ps(i);return Object.keys(Pi).forEach(e=>{delete t[e]}),t}function Oe(i,t){let e=p({},Pi);return Object.entries(fs).forEach(n=>{let[s,r]=n,a=i[s];a!==void 0&&(r.is(a)?e[s]=a:t.warn(k.wrongOptionType(s,r.getType(),typeof a)))}),e}var rt=class{constructor(t,e){this.hn=t;this.Ve=[];switch(e){case"sha1":this.ee="SHA-1";break;case"sha256":this.ee="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Ve.join(""),n=new TextEncoder().encode(e),s=await this.hn.subtle.digest(this.ee,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(s)));case"hex":return[...new Uint8Array(s)].map(r=>r.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Ve.push(t),this}};var gs={start:0,end:3},ms={start:4,end:5},Me={start:6,end:7},Re={start:8,end:8},ys={start:9,end:9},vs={start:10,end:15};function ws(){if(crypto&&crypto.getRandomValues){let t=new Uint8Array(16);return crypto.getRandomValues(t),[...t.values()]}let i=[];for(let t=0;t<16;t+=1)i.push(Math.floor(Math.random()*256));return i}function K(i,t){let e="";for(let n=t.start;n<=t.end;n+=1)e+=i[n].toString(16).padStart(2,"0");return e}function Es(i){return i[Re.start]=(i[Re.start]|128)&191,i[Me.start]=i[Me.start]&15|64,`${K(i,gs)}-${K(i,ms)}-${K(i,Me)}-${K(i,Re)}${K(i,ys)}-${K(i,vs)}`}function Ds(){let i=ws();return Es(i)}function Fe(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():Ds()}var at=class{createHash(t){return new rt(Li(),t)}randomUUID(){return Fe()}};function bs(i){let t=Array.from(i,e=>String.fromCodePoint(e)).join("");return btoa(t)}var ot=class{btoa(t){return bs(new TextEncoder().encode(t))}};var ct=class{constructor(t){this.r=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"0.9.0",userAgentBase:"JSClient"};return this.r.wrapperName&&(t.wrapperName=this.r.wrapperName),this.r.wrapperVersion&&(t.wrapperVersion=this.r.wrapperVersion),t}};var ut=class{constructor(t,e){this.bt=t;this.e={};this.T=new Dt(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.je=e.errorFilter,this.He()}He(){this.Z=new EventSource(this.bt),this.Z.onopen=()=>{var t;this.T.success(),(t=this.onopen)==null||t.call(this)},this.Z.onerror=t=>{var e;this.dn(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.e).forEach(([t,e])=>{e.forEach(n=>{var s;(s=this.Z)==null||s.addEventListener(t,n)})})}addEventListener(t,e){var n,s,r;(s=(n=this.e)[t])!=null||(n[t]=[]),this.e[t].push(e),(r=this.Z)==null||r.addEventListener(t,e)}close(){var t,e;clearTimeout(this.ie),this.ie=void 0,(t=this.Z)==null||t.close(),(e=this.onclose)==null||e.call(this)}fn(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.ie=setTimeout(()=>{this.He()},t)}dn(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.je(t))&&this.fn(this.T.fail())}};var lt=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new ut(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function $i(){return typeof localStorage!="undefined"}var ht=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{let n=localStorage.getItem(t);return n!=null?n:null}catch(n){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(s){(n=this.t)==null||n.error(`Error setting key in localStorage: ${t}, reason: ${s}`)}}};var dt=class{constructor(t,e){this.encoding=new ot;this.crypto=new at;this.requests=new lt;$i()&&(this.storage=new ht(t)),this.info=new ct(e)}};var Ue=class extends Mt{constructor(t,e,n={},s){var m;let{logger:r,debug:a}=n,o=r!=null?r:new M({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:a?"debug":"info"}),c=(m=n.baseUri)!=null?m:"https://clientsdk.launchdarkly.com",u=s!=null?s:new dt(o,n),l=Oe(n,o),d=Ni(b(p({},n),{logger:o})),{eventUrlTransformer:f}=l;super(t,e,u,d,(g,y,D,F,Ri)=>new et(u,g,t,y,l,()=>({pathGet(P,N){return`/sdk/evalx/${t}/contexts/${fe(N,P)}`},pathReport(P,N){return`/sdk/evalx/${t}/context`},pathPing(P,N){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(P,N){return`/eval/${t}/${fe(N,P)}`},pathReport(P,N){return`/eval/${t}`},pathPing(P,N){return`/ping/${t}`}}),D,F,Ri),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:g=>new L.InputCustomEvent(g.context,g.key,g.data,g.metricValue,g.samplingRatio,f(T())),getImplementationHooks:g=>L.safeGetHooks(o,g,l.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.Be=l.plugins,l.fetchGoals&&(this.ne=new st(t,u.requests,c,g=>{o.error(g.message)},(g,y)=>{let D=this.getInternalContext();if(!D)return;let F=f(g);Ii(y)?this.sendEvent({kind:"click",url:F,samplingRatio:1,key:y.key,creationDate:Date.now(),context:D,selector:y.selector}):this.sendEvent({kind:"pageview",url:F,samplingRatio:1,key:y.key,creationDate:Date.now(),context:D})}),this.ne.initialize(),l.automaticBackgroundHandling&&Ai(()=>this.flush()))}registerPlugins(t){L.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.Be||[])}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var r;let n=p({},e);(e==null?void 0:e.sheddable)===void 0&&(n.sheddable=!0);let s=await super.identifyResult(t,n);return(r=this.ne)==null||r.startTracking(),s}setStreaming(t){this.dataManager.setForcedStreaming(t)}Ke(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.Ke()}off(t,e){super.off(t,e),this.Ke()}};function Oi(i,t,e={},n){let s=new Ue(i,t,e,n),r={variation:(a,o)=>s.variation(a,o),variationDetail:(a,o)=>s.variationDetail(a,o),boolVariation:(a,o)=>s.boolVariation(a,o),boolVariationDetail:(a,o)=>s.boolVariationDetail(a,o),numberVariation:(a,o)=>s.numberVariation(a,o),numberVariationDetail:(a,o)=>s.numberVariationDetail(a,o),stringVariation:(a,o)=>s.stringVariation(a,o),stringVariationDetail:(a,o)=>s.stringVariationDetail(a,o),jsonVariation:(a,o)=>s.jsonVariation(a,o),jsonVariationDetail:(a,o)=>s.jsonVariationDetail(a,o),track:(a,o,c)=>s.track(a,o,c),on:(a,o)=>s.on(a,o),off:(a,o)=>s.off(a,o),flush:()=>s.flush(),setStreaming:a=>s.setStreaming(a),identify:(a,o)=>s.identifyResult(a,o),getContext:()=>s.getContext(),close:()=>s.close(),allFlags:()=>s.allFlags(),addHook:a=>s.addHook(a),logger:s.logger};return s.registerPlugins(r),r}var Mi=["ready","failed","initialized"],ft=class{constructor(t){this.n=t;this.e=new Map}on(t,e){var n;Mi.includes(t)?this.e.has(t)?(n=this.e.get(t))==null||n.push(e):this.e.set(t,[e]):this.n.on(t,e)}off(t,e){if(Mi.includes(t)){let n=this.e.get(t);if(!n)return;if(e){let s=n.filter(r=>r!==e);s.length===0?this.e.delete(t):this.e.set(t,s);return}this.e.delete(t)}else this.n.off(t,e)}Ht(t,e,...n){try{t(...n)}catch(s){this.n.logger.error(`Encountered error invoking handler for "${e}", detail: "${s}"`)}}emit(t,...e){let n=this.e.get(t);n==null||n.forEach(s=>this.Ht(s,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,n;return(n=(e=this.e.get(t))==null?void 0:e.length)!=null?n:0}};function Ht(i,t){let e=i.then(n=>(t&&setTimeout(()=>{t(null,n)},0),n),n=>{if(t)setTimeout(()=>{t(n,null)},0);else return Promise.reject(n)});return t?void 0:e}var pt=class{constructor(t,e,n){this.se="initializing";let s=n==null?void 0:n.bootstrap,r=n==null?void 0:n.hash,a=p({},n);delete a.bootstrap,delete a.hash,this.n=Oi(t,j.Disabled,n),this.$=new ft(this.n),this.logger=this.n.logger,this.pn(e,s,r)}async pn(t,e,n){var s,r;try{let a=await this.n.identify(t,{noTimeout:!0,bootstrap:e,hash:n,sheddable:!1});if(a.status==="error")throw a.error;if(a.status==="timeout")throw new C("Identify timed out");this.se="success",(s=this.Ge)==null||s.call(this),this.$.emit("initialized")}catch(a){this._e=a,this.se="failure",(r=this.ze)==null||r.call(this,a),this.$.emit("failed",a)}this.$.emit("ready")}allFlags(){return this.n.allFlags()}boolVariation(t,e){return this.n.boolVariation(t,e)}boolVariationDetail(t,e){return this.n.boolVariationDetail(t,e)}jsonVariation(t,e){return this.n.jsonVariation(t,e)}jsonVariationDetail(t,e){return this.n.jsonVariationDetail(t,e)}numberVariation(t,e){return this.n.numberVariation(t,e)}numberVariationDetail(t,e){return this.n.numberVariationDetail(t,e)}off(t,e){this.$.off(t,e)}on(t,e){this.$.on(t,e)}stringVariation(t,e){return this.n.stringVariation(t,e)}stringVariationDetail(t,e){return this.n.stringVariationDetail(t,e)}track(t,e,n){this.n.track(t,e,n)}variation(t,e){return this.n.variation(t,e)}variationDetail(t,e){return this.n.variationDetail(t,e)}addHook(t){this.n.addHook(t)}setStreaming(t){this.n.setStreaming(t)}identify(t,e,n){return Ht(this.n.identify(t,{hash:e,sheddable:!1}).then(s=>{if(s.status==="error")throw s.error;if(s.status==="timeout")throw new C("Identify timed out");return this.allFlags()}),n)}close(t){return Ht(this.n.close().then(),t)}flush(t){return Ht(this.n.flush().then(()=>{}),t)}getContext(){return this.n.getContext()}waitForInitialization(t){var e;if(this.rt)return this.Je(this.rt,t);switch(this.se){case"success":return Promise.resolve();case"failure":return Promise.reject(this._e);case"initializing":break;default:throw new Error("Unexpected initialization state. This represents an implementation error in the SDK.")}return t===void 0&&((e=this.logger)==null||e.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),this.rt||(this.rt=new Promise((n,s)=>{this.Ge=n,this.ze=s})),this.Je(this.rt,t)}async waitUntilReady(){try{await this.waitForInitialization()}catch(t){}}Je(t,e){if(e){let n=ei(e,"waitForInitialization");return Promise.race([t.then(()=>n.cancel()),n.promise]).catch(s=>{var r;throw s instanceof C&&((r=this.logger)==null||r.error(s.message)),s})}return t}};function Ca(i){return new M(i)}function Ia(i,t,e){return new pt(i,t,e)}export{Ca as basicLogger,Ia as initialize};
2
2
  //# sourceMappingURL=compat.js.map