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