@launchdarkly/js-client-sdk 0.7.1 → 0.8.1

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