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