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