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