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