@launchdarkly/js-client-sdk 0.7.0 → 0.7.1

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