@launchdarkly/browser 0.1.8 → 0.1.9

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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.9](https://github.com/launchdarkly/js-core/compare/browser-v0.1.8...browser-v0.1.9) (2026-02-25)
4
+
5
+
6
+ ### Dependencies
7
+
8
+ * The following workspace dependencies were updated
9
+ * dependencies
10
+ * @launchdarkly/js-client-sdk bumped from 4.2.0 to 4.2.1
11
+
3
12
  ## [0.1.8](https://github.com/launchdarkly/js-core/compare/browser-v0.1.7...browser-v0.1.8) (2026-02-24)
4
13
 
5
14
 
package/dist/index.cjs CHANGED
@@ -345,7 +345,7 @@ Project ID: ${this.sessionData.projectID}
345
345
  SessionSecureID: ${this.sessionData.sessionSecureID}`),this.options.sessionSecureID=this.sessionData.sessionSecureID,this.zn.postMessage({message:{type:Ne.Initialize,sessionSecureID:this.sessionData.sessionSecureID,backend:this.pn,debug:!!this.debugOptions.clientInteractions,recordingStartTime:this.Bn}});for(let g of this.xn)g.init(this.sessionData.sessionSecureID);if(this.sessionData.userIdentifier&&this.identify(this.sessionData.userIdentifier,this.sessionData.userObject),this.pushPayloadTimerId&&(clearTimeout(this.pushPayloadTimerId),this.pushPayloadTimerId=void 0),this.po||(this.pushPayloadTimerId=setTimeout(()=>{this.Ss()},sg)),this.options.disableSessionRecording){this.logger.log("Highlight is NOT RECORDING a session replay per H.init setting."),this.ready=!0,this.state="Recording",this.manualStopped=!1;return}let f=(g,S)=>{S&&this.logger.log("received isCheckout emit",{event:g}),this.events.push(g)};f.bind(this);let m=!!this.Sn;this.Sn&&(this.Sn(),this.Sn=void 0);let[d,v]=RF(this.privacySetting);this.Sn=Ge({ignoreClass:"highlight-ignore",blockClass:"highlight-block",emit:f,recordCrossOriginIframes:this.options.recordCrossOriginIframe,privacySetting:this.privacySetting,maskAllInputs:d,maskInputOptions:v,recordCanvas:this.enableCanvasRecording,sampling:{canvas:{fps:this.samplingStrategy.canvas,fpsManual:this.samplingStrategy.canvasManualSnapshot,resizeFactor:this.samplingStrategy.canvasFactor,clearWebGLBuffer:this.samplingStrategy.canvasClearWebGLBuffer,initialSnapshotDelay:this.samplingStrategy.canvasInitialSnapshotDelay,dataURLOptions:this.samplingStrategy.dataUrlOptions,maxSnapshotDimension:this.samplingStrategy.canvasMaxSnapshotDimension}},keepIframeSrcFn:g=>!this.options.recordCrossOriginIframe,inlineImages:this.inlineImages,inlineVideos:this.inlineVideos,collectFonts:this.inlineImages,inlineStylesheet:this.inlineStylesheet,plugins:[nW()],logger:typeof this.options.debug=="boolean"&&this.options.debug||typeof this.options.debug=="object"&&this.options.debug.domRecording?{debug:this.logger.log,warn:Ht.bind("RecordSDK","warn")}:void 0}),m||this.options.recordCrossOriginIframe&&this.nl(),document.referrer&&(window&&document.referrer.includes(window.location.origin)||(this.addCustomEvent("Referrer",document.referrer),this.addProperties({referrer:document.referrer},{type:"session"}))),this.rl(),this.ready=!0,this.state="Recording",this.manualStopped=!1}catch(u){Ht("initializeSession _setupWindowListeners","warn",u)}})}ws(e){return Yt(this,null,function*(){if(this.manualStopped){this.logger.log("Ignoring visibility event due to manual stop.");return}new Date().getTime()-this.vs<SX||(this.vs=new Date().getTime(),this.logger.log(`Detected window ${e?"hidden":"visible"}.`),e?(this.addCustomEvent("TabHidden",!0),this.options.disableBackgroundRecording&&this.stop()):(this.options.disableBackgroundRecording&&(yield this.start()),this.addCustomEvent("TabHidden",!1)))})}el(){return Yt(this,null,function*(){this.logger.log("highlight in cross-origin iframe is waiting "),yield new Promise(e=>{let n=r=>{if(r.data.highlight===yb){let i=r.data;this.logger.log("highlight got window message ",i),this.sessionData.projectID=i.projectID,this.sessionData.sessionSecureID=i.sessionSecureID,window.parent.postMessage({highlight:gb},"*"),window.removeEventListener("message",n),e()}};window.addEventListener("message",n)})})}nl(){this.logger.log("highlight setting up cross origin iframe parent notification"),setInterval(()=>{window.document.querySelectorAll("iframe").forEach(e=>{var n;(n=e.contentWindow)==null||n.postMessage({highlight:yb,projectID:this.sessionData.projectID,sessionSecureID:this.sessionData.sessionSecureID},"*")})},sg),window.addEventListener("message",e=>{e.data.highlight===gb&&this.logger.log("highlight got response from initialized iframe")})}rl(){var e;try{let r=this;this.enableSegmentIntegration&&this.listeners.push(VF(o=>{if(o.type==="track"){let s={};s["segment-event"]=o.event,r.addProperties(s,{type:"track",source:"segment"})}else if(o.type==="identify"){let s=o.userId.replace(/^"(.*)"$/,"$1");r.identify(s,o.traits,"segment")}})),this.listeners.push(EF(o=>{this.reloaded?(this.addCustomEvent("Reload",o),this.reloaded=!1,r.addProperties({reload:!0},{type:"session"})):this.addCustomEvent("Navigate",o)})),this.listeners.push(zX(o=>{this.addCustomEvent("Viewport",o)})),this.listeners.push(CF((o,s)=>{let a=null,c=null;if(s&&s.target){let l=s.target;a=_X(l),c=l.textContent,c&&c.length>2e3&&(c=c.substring(0,2e3))}this.addCustomEvent("Click",{clickTarget:o,clickTextContent:c,clickSelector:a})})),this.listeners.push(ZF(o=>{o&&this.addCustomEvent("Focus",o)})),this.sessionShortcut&&NF(this.sessionShortcut,()=>{window.open(this.getCurrentSessionURLWithTimestamp(),"_blank")}),this.gs||((e=window.electron)!=null&&e.ipcRenderer?(window.electron.ipcRenderer.on("highlight.run",({visible:o})=>{this.ws(!o)}),this.logger.log("Set up Electron highlight.run events.")):(kF(o=>this.ws(o)),this.logger.log("Set up document visibility listener.")),this.gs=!0);let i=()=>{this.hasSessionUnloaded=!0,this.pushPayloadTimerId&&(clearTimeout(this.pushPayloadTimerId),this.pushPayloadTimerId=void 0)};window.addEventListener("beforeunload",i),this.listeners.push(()=>window.removeEventListener("beforeunload",i))}catch(r){Ht("initializeSession _setupWindowListeners","warn",r)}let n=()=>{this.addCustomEvent("Page Unload",""),li(this.sessionData.sessionSecureID),In(this.sessionData)};if(window.addEventListener("beforeunload",n),this.listeners.push(()=>window.removeEventListener("beforeunload",n)),navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/iPhone/i)){let r=()=>{this.addCustomEvent("Page Unload",""),li(this.sessionData.sessionSecureID),In(this.sessionData)};window.addEventListener("pagehide",r),this.listeners.push(()=>window.removeEventListener("beforeunload",r))}}stop(e){this.manualStopped=!!e,this.manualStopped&&this.addCustomEvent("Stop","H.stop() was called which stops Highlight from recording."),this.state="NotRecording",e&&this.Sn&&(this.Sn(),this.Sn=void 0),this.listeners.forEach(n=>n()),this.listeners=[]}getCurrentSessionURLWithTimestamp(){let e=new Date().getTime(),{projectID:n,sessionSecureID:r}=this.sessionData,i=(e-this.Bn)/1e3;return`https://${lg}/${n}/sessions/${r}?ts=${i}`}getCurrentSessionURL(){let e=this.sessionData.projectID,n=this.sessionData.sessionSecureID;return e&&n?`https://${lg}/${e}/sessions/${n}`:null}snapshot(e){return Yt(this,null,function*(){yield Ge.snapshotCanvas(e)})}addSessionFeedback({timestamp:e,verbatim:n,user_email:r,user_name:i}){var o;this.zn.postMessage({message:{type:Ne.Feedback,verbatim:n,timestamp:e,userName:i||this.sessionData.userIdentifier,userEmail:r||((o=this.sessionData.userObject)==null?void 0:o.name)}})}Ss(){return Yt(this,null,function*(){var e;try{this.state==="Recording"&&this.listeners&&this.sessionData.sessionStartTime&&Date.now()-this.sessionData.sessionStartTime>vX&&(this.logger.log("Resetting session",{start:this.sessionData.sessionStartTime}),yield this.bs({}));let n;((e=this.options)==null?void 0:e.sendMode)==="local"&&(n=r=>Yt(this,null,function*(){let i=new Blob([JSON.stringify({query:Gb(Mb),variables:r})],{type:"application/json"});return yield window.fetch(`${this.pn}`,{method:"POST",body:i}),0})),yield this.il({sendFn:n}),this.hasPushedData=!0,this.sessionData.lastPushTime=Date.now(),In(this.sessionData)}catch(n){Ht("_save","warn",n)}this.state==="Recording"&&(this.pushPayloadTimerId&&(clearTimeout(this.pushPayloadTimerId),this.pushPayloadTimerId=void 0),this.pushPayloadTimerId=setTimeout(()=>{this.Ss()},bX))})}addCustomEvent(e,n){if(this.state==="NotRecording"){let r,i=()=>{clearInterval(r),this.state==="Recording"&&this.events.length>0?db(e,n):r=setTimeout(i,500)};r=setTimeout(i,500)}else this.state==="Recording"&&(this.events.length>0||this.hasPushedData)&&db(e,n)}il(e){return Yt(this,arguments,function*({sendFn:n}){let r=[...this.events],{bytes:i,time:o}=this.enableCanvasRecording?ag.canvas:ag.normal;this.br>=i&&new Date().getTime()-this.mo>=o&&this.takeFullSnapshot(),this.logger.log(`Sending: ${r.length} events,
346
346
  To: ${this.pn}
347
347
  Org: ${this.organizationID}
348
- SessionSecureID: ${this.sessionData.sessionSecureID}`);let s=FF();n?yield n({session_secure_id:this.sessionData.sessionSecureID,payload_id:(this.sessionData.payloadID++).toString(),events:{events:r},messages:QL({messages:[]}),resources:JSON.stringify({resources:[]}),web_socket_events:JSON.stringify({webSocketEvents:[]}),errors:[],is_beacon:!1,has_session_unloaded:this.hasSessionUnloaded,highlight_logs:s||void 0}):this.zn.postMessage({message:{type:Ne.AsyncEvents,id:this.sessionData.payloadID++,events:r,messages:[],errors:[],resourcesString:JSON.stringify({resources:[]}),webSocketEventsString:JSON.stringify({webSocketEvents:[]}),hasSessionUnloaded:this.hasSessionUnloaded,highlightLogs:s}}),In(this.sessionData),this.events=this.events.slice(r.length),AF(s)})}takeFullSnapshot(){if(!this.Sn){this.logger.log("skipping full snapshot as rrweb is not running");return}this.logger.log("taking full snapshot",{bytesSinceSnapshot:this.br,lastSnapshotTime:this.mo}),Ge.takeFullSnapshot(),this.br=0,this.mo=new Date().getTime()}register(e,n){this.xn.push(new pu(e,n))}getHooks(e){return this.xn.flatMap(n=>{var r,i;return(i=(r=n.getHooks)==null?void 0:r.call(n,e))!=null?i:[]})}getRecordingState(){var e;return(e=this==null?void 0:this.state)!=null?e:"NotRecording"}getSession(){let e=this.sessionData.sessionSecureID,n=ks(e);if(!n)return null;let r=`${this.getFrontendUrl()}/sessions/${e}`;if(!r||!(n!=null&&n.sessionStartTime))return null;let i=new Date().getTime(),o=new URL(r),s=new URL(r),a=(i-this.Bn)/1e3;return s.searchParams.set("ts",a.toString()),{url:o.toString(),urlWithTimestamp:s.toString(),sessionSecureID:e}}getFrontendUrl(){var e,n;let r=this.pn.match(EX);if(r&&(e=r==null?void 0:r.groups)!=null&&e.domain){let i=(n=r.groups.domain)!=null?n:"";return`https://${IX[i]}${TX}`}return wX}},Ci=class extends BX{constructor(e,n){var r=(...f)=>(super(...f),Y(this,"record"),this),i,o,s,a,c,l,u,h,p;try{if(r(n),typeof window>"u"||typeof document>"u"){console.warn("@launchdarkly/session-replay is not initializing because it is not supported in this environment.");return}if(typeof Worker>"u"){console.warn("@launchdarkly/session-replay is not initializing because Worker is not supported.");return}if(!e){console.warn("@launchdarkly/session-replay is not initializing because projectID was passed undefined.");return}let f=Kt(z({},n),{organizationID:e,firstloadVersion:HF,environment:(n==null?void 0:n.environment)||"production",appVersion:n==null?void 0:n.version,sessionSecureID:this.sessionSecureID,privacySetting:(i=n==null?void 0:n.privacySetting)!=null?i:"strict"});this.record=new oh(f),n!=null&&n.manualStart||this.record.start(),Be.load(this.record),!((s=(o=n==null?void 0:n.integrations)==null?void 0:o.mixpanel)!=null&&s.disabled)&&(c=(a=n==null?void 0:n.integrations)==null?void 0:a.mixpanel)!=null&&c.projectToken&&KF(n.integrations.mixpanel),!((u=(l=n==null?void 0:n.integrations)==null?void 0:l.amplitude)!=null&&u.disabled)&&(p=(h=n==null?void 0:n.integrations)==null?void 0:h.amplitude)!=null&&p.apiKey&&YF(n.integrations.amplitude)}catch(f){Ht("Error initializing @launchdarkly/session-replay SDK","error",f)}}getMetadata(){return{name:"@launchdarkly/session-replay"}}register(e,n){var r;(r=this.record)==null||r.register(e,n)}getHooks(e){return[{getMetadata:()=>({name:"@launchdarkly/session-replay/hooks"}),afterIdentify:(n,r,i)=>{var o,s,a,c,l,u,h;for(let p of(a=(s=(o=this.record)==null?void 0:o.getHooks)==null?void 0:s.call(o,e))!=null?a:[])(c=p.afterIdentify)==null||c.call(p,n,r,i);if(i.status==="completed"){let p=DX(n.context),f=YX(n.context);(h=this.record)==null||h.identify(typeof f=="string"?f:(u=(l=f.user)==null?void 0:l.toString())!=null?u:p,Kt(z({key:p},typeof f=="object"?f:{}),{timeout:n.timeout}),"LaunchDarkly")}return r},afterEvaluation:(n,r,i)=>{var o,s,a,c;for(let l of(a=(s=(o=this.record)==null?void 0:o.getHooks)==null?void 0:s.call(o,e))!=null?a:[])(c=l.afterEvaluation)==null||c.call(l,n,r,i);return r},afterTrack:n=>{var r,i,o,s,a;for(let c of(o=(i=(r=this.record)==null?void 0:r.getHooks)==null?void 0:i.call(r,e))!=null?o:[])(s=c.afterTrack)==null||s.call(c,n);(a=this.record)==null||a.track(n.key,{data:n.data,value:n.metricValue})}}]}}});var BF={};Yh(BF,{LDObserve:()=>De,LDRecord:()=>Be,basicLogger:()=>qI,createClient:()=>zF});module.exports=nS(BF);var rS=Object.defineProperty,iS=Object.defineProperties,oS=Object.getOwnPropertyDescriptors,Mi=Object.getOwnPropertySymbols,fp=Object.prototype.hasOwnProperty,mp=Object.prototype.propertyIsEnumerable,Kh=(t,e,n)=>e in t?rS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,st=(t,e)=>{for(var n in e||(e={}))fp.call(e,n)&&Kh(t,n,e[n]);if(Mi)for(var n of Mi(e))mp.call(e,n)&&Kh(t,n,e[n]);return t},me=(t,e)=>iS(t,oS(e)),yp=(t,e)=>{var n={};for(var r in t)fp.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&Mi)for(var r of Mi(t))e.indexOf(r)<0&&mp.call(t,r)&&(n[r]=t[r]);return n};function sS(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function gp(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function aS(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>gp(e))}function lS(t){return!t.startsWith("/")}function cS(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var Nn=class{constructor(t,e=!1){if(e){let n=t;this.m=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?sS(n):n}else{if(this.redactionName=t,t===""||t==="/"||!cS(t)){this.isValid=!1,this.m=[];return}lS(t)?this.m=[t]:t.indexOf("/",1)<0?this.m=[gp(t.slice(1))]:this.m=aS(t),this.m[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{m:e,isValid:n}=this;if(!n)return;let r=t;for(let i=0;i<e.length;i+=1){let o=e[i];if(r!=null&&Object.prototype.hasOwnProperty.call(r,o)&&typeof r=="object"&&!Array.isArray(r))r=r[o];else return}return r}getComponent(t){return this.m[t]}get depth(){return this.m.length}get isKind(){return this.m.length===1&&this.m[0]==="kind"}compare(t){return this.depth===t.depth&&this.m.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.m]}};Nn.InvalidReference=new Nn("");var uS=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},Ln=class{constructor(t,e){this.ft=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.ft}},bp=class{constructor(t,e){this.ft=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.ft}},vp=class extends Ln{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},Sp=class extends Ln{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},hS=class{is(t){return typeof t=="function"}getType(){return"function"}},pS=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},dS=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,fS=class{is(t){return typeof t=="number"||typeof t=="string"&&dS.test(t)}getType(){return"date"}},mS=class extends Sp{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},G=class{static createTypeArray(t,e){return new bp(t,e)}static numberWithMin(t){return new vp(t)}static stringMatchingRegex(t){return new Sp(t)}};G.String=new Ln("string","");G.Number=new Ln("number",0);G.ObjectOrFactory=new uS;G.Object=new Ln("object",{});G.StringArray=new bp("string[]","");G.Boolean=new Ln("boolean",!0);G.Function=new hS;G.Date=new fS;G.Kind=new mS;G.NullableBoolean=new pS;function wp(t){return"kind"in t?G.String.is(t.kind)&&t.kind!=="multi":!1}function Ip(t){return"kind"in t?G.String.is(t.kind)&&t.kind==="multi":!1}function Tp(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function Fi(t,e=[]){if(t===null||typeof t!="object")return JSON.stringify(t);if(e.includes(t))throw new Error("Cycle detected");return Array.isArray(t)?`[${t.map(n=>Fi(n,[...e,t])).map(n=>n===void 0?"null":n).join(",")}]`:`{${Object.keys(t).sort().map(n=>{let r=Fi(t[n],[...e,t]);if(r!==void 0)return`${JSON.stringify(n)}:${r}`}).filter(n=>n!==void 0).join(",")}}`}var Xa="user";function _h(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function yS(t){return t&&G.Object.is(t)}function Hh(t){return G.Kind.is(t)}function zh(t){return G.String.is(t)&&t!==""}function Ca(t,e=!1){return t?t.map(n=>new Nn(n,e)):[]}function gS(t){return t!=null}function bS(t){let e=me(st({},t.custom||[]),{kind:"user",key:String(t.key)});if(gS(t.anonymous)){let n=!!t.anonymous;delete e.anonymous,e.anonymous=n}return t.name!==null&&t.name!==void 0&&(e.name=t.name),t.ip!==null&&t.ip!==void 0&&(e.ip=t.ip),t.firstName!==null&&t.firstName!==void 0&&(e.firstName=t.firstName),t.lastName!==null&&t.lastName!==void 0&&(e.lastName=t.lastName),t.email!==null&&t.email!==void 0&&(e.email=t.email),t.avatar!==null&&t.avatar!==void 0&&(e.avatar=t.avatar),t.country!==null&&t.country!==void 0&&(e.country=t.country),t.privateAttributeNames!==null&&t.privateAttributeNames!==void 0&&(e._meta={privateAttributes:t.privateAttributeNames}),e}var xn=class wt{constructor(e,n,r){this.C=!1,this.Q=!1,this.qt=!1,this.N={},this.kind=n,this.valid=e,this.message=r}static b(e,n){return new wt(!1,e,n)}static Ae(e,n){if(!(!n||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(n!=null&&n.anonymous):e.get(n)}Jt(e){if(this.C)return this.N[e];if(this.kind===e)return this.y}static Pe(e){let n=Object.keys(e).filter(c=>c!=="kind"),r=n.every(Hh);if(!n.length)return wt.b("multi","A multi-kind context must contain at least one kind");if(!r)return wt.b("multi","Context contains invalid kinds");let i={},o=!0,s=n.reduce((c,l)=>{var u;let h=e[l];return yS(h)?(c[l]=h,i[l]=Ca((u=h._meta)==null?void 0:u.privateAttributes)):o=!1,c},{});if(!o)return wt.b("multi","Context contained contexts that were not objects");if(!Object.values(s).every(c=>zh(c.key)))return wt.b("multi","Context contained invalid keys");if(n.length===1){let c=n[0],l=new wt(!0,c);return l.y=me(st({},s[c]),{kind:c}),l.tt=i,l.Q=c==="user",l}let a=new wt(!0,e.kind);return a.N=s,a.tt=i,a.C=!0,a}static Te(e){var n;let{key:r,kind:i}=e,o=Hh(i),s=zh(r);if(!o)return wt.b(i!=null?i:"unknown","The kind was not valid for the context");if(!s)return wt.b(i,"The key for the context was not valid");let a=Ca((n=e._meta)==null?void 0:n.privateAttributes),c=new wt(!0,i);return c.Q=i==="user",c.y=e,c.tt={[i]:a},c}static Ne(e){if(!(e.key!==void 0&&e.key!==null))return wt.b("user","The key for the context was not valid");let n=new wt(!0,"user");return n.Q=!0,n.qt=!0,n.y=bS(e),n.tt={user:Ca(e.privateAttributeNames,!0)},n}static fromLDContext(e){return e?wp(e)?wt.Te(e):Ip(e)?wt.Pe(e):Tp(e)?wt.Ne(e):wt.b("unknown","Context was not of a valid kind"):wt.b("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;let n=e.getContexts();if(!e.C)return n[0][1];let r={kind:"multi"};return n.forEach(i=>{let o=i[0],s=i[1];r[o]=s}),r}valueForKind(e,n=Xa){return e.isKind?this.kinds:wt.Ae(e,this.Jt(n))}key(e=Xa){var n;return(n=this.Jt(e))==null?void 0:n.key}get isMultiKind(){return this.C}get canonicalKey(){return this.Q?this.y.key:this.C?Object.keys(this.N).sort().map(e=>`${e}:${_h(this.N[e].key)}`).join(":"):`${this.kind}:${_h(this.y.key)}`}get kinds(){return this.C?Object.keys(this.N):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.N).reduce((e,[n,r])=>(e[n]=r.key,e),{}):{[this.kind]:this.y.key}}privateAttributes(e){var n;return((n=this.tt)==null?void 0:n[e])||[]}getContexts(){return this.C?Object.entries(this.N):[[this.kind,this.y]]}get legacy(){return this.qt}canonicalUnfilteredJson(){if(this.valid){if(this.pt)return this.pt;try{this.pt=Fi(wt.toLDContext(this))}catch(e){}return this.pt}}};xn.UserKind=Xa;var vS=["key","kind","_meta","anonymous"].map(t=>new Nn(t,!0)),SS=["name","ip","firstName","lastName","email","avatar","country"];function wS(t,e){return t.depth===e.length&&e.every((n,r)=>n===t.getComponent(r))}function IS(t,e){let n=[],r={},i=[];for(n.push(...Object.keys(t).map(o=>({key:o,ptr:[o],source:t,parent:r,visited:[t]})));n.length;){let o=n.pop(),s=e.find(a=>wS(a,o.ptr));if(s)i.push(s.redactionName);else{let a=o.source[o.key];a===null?o.parent[o.key]=a:Array.isArray(a)?o.parent[o.key]=[...a]:typeof a=="object"?o.visited.includes(a)||(o.parent[o.key]={},n.push(...Object.keys(a).map(c=>({key:c,ptr:[...o.ptr,c],source:a,parent:o.parent[o.key],visited:[...o.visited,a]})))):o.parent[o.key]=a}}return{cloned:r,excluded:i.sort()}}var TS=class{constructor(t,e){this.$e=t,this.Re=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.Yt(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([i,o])=>{r[i]=this.Yt(t,o,i,e)}),r}Me(t,e,n,r){return(r?Object.keys(e).map(i=>new Nn(i,!0)):[...this.Re,...t.privateAttributes(n)]).filter(i=>!vS.some(o=>o.compare(i)))}Yt(t,e,n,r){let i=this.$e||r&&e.anonymous===!0,{cloned:o,excluded:s}=IS(e,this.Me(t,e,n,i));return t.legacy&&SS.forEach(a=>{a in o&&(o[a]=String(o[a]))}),s.length&&(o._meta||(o._meta={}),o._meta.redactedAttributes=s),o._meta&&(delete o._meta.privateAttributes,Object.keys(o._meta).length===0&&delete o._meta),o}},Bh=30*1e3,ES=.5,RS=class{constructor(t,e,n=Math.random){this.Fe=e,this.Ue=n,this.gt=0,this.Zt=Math.max(1,t),this.Ve=Math.ceil(Math.log2(Bh/this.Zt))}I(){let t=Math.min(this.gt,this.Ve),e=this.Zt*2**t;return Math.min(e,Bh)}je(t){return t-Math.trunc(this.Ue()*ES*t)}success(t=Date.now()){this.mt=t}fail(t=Date.now()){this.mt!==void 0&&t-this.mt>this.Fe&&(this.gt=0),this.mt=void 0;let e=this.je(this.I());return this.gt+=1,e}},jh;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(jh||(jh={}));var Ai=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},Wa=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},QF=120*1e3,$F=300*1e3,At;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(At||(At={}));var Ji;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(Ji||(Ji={}));var On;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(On||(On={}));var en;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(en||(en={}));function Vn(t){if(typeof t=="string")return t;if(t===void 0)return"undefined";if(t===null)return"null";if(Object.prototype.hasOwnProperty.call(t,"toString"))try{return t.toString()}catch(e){}if(typeof t=="bigint")return`${t}n`;try{return JSON.stringify(t)}catch(e){return e instanceof TypeError&&e.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function CS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function ZS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function kS(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var Za={s:t=>Vn(t),d:t=>CS(t),i:t=>ZS(t),f:t=>kS(t),j:t=>Vn(t),o:t=>Vn(t),O:t=>Vn(t),c:()=>""};function Ua(...t){var e;let n=t.shift();if(G.String.is(n)){let r="",i=0;for(;i<n.length;){let o=n.charAt(i);if(o==="%"){if(i+1<n.length){let s=n.charAt(i+1);if(s in Za&&t.length){let a=t.shift();r+=(e=Za[s])==null?void 0:e.call(Za,a)}else s==="%"?r+="%":r+=`%${s}`;i+=2}}else r+=o,i+=1}return t.length&&(r.length&&(r+=" "),r+=t.map(Vn).join(" ")),r}return t.map(Vn).join(" ")}var Vt;(function(t){t[t.debug=0]="debug",t[t.info=1]="info",t[t.warn=2]="warn",t[t.error=3]="error",t[t.none=4]="none"})(Vt||(Vt={}));var VS=["debug","info","warn","error","none"],Fa=class Ep{static get(){return new Ep({})}constructor(e){var n,r,i;if(this.qe=(r=Vt[(n=e.level)!=null?n:"info"])!=null?r:Vt.info,this.Je=(i=e.name)!=null?i:"LaunchDarkly",this.ie=e.formatter,typeof e.destination=="object")this.ne={[Vt.debug]:e.destination.debug,[Vt.info]:e.destination.info,[Vt.warn]:e.destination.warn,[Vt.error]:e.destination.error};else if(typeof e.destination=="function"){let{destination:o}=e;this.ne={[Vt.debug]:o,[Vt.info]:o,[Vt.warn]:o,[Vt.error]:o}}}Ye(...e){var n;try{return this.ie?(n=this.ie)==null?void 0:n.call(this,...e):Ua(...e)}catch(r){return Ua(...e)}}Ze(e,n){try{e(n)}catch(r){console.error(n)}}k(e,n){var r;if(e>=this.qe){let i=`${VS[e]}: [${this.Je}]`;try{let o=(r=this.ne)==null?void 0:r[e];o?this.Ze(o,`${i} ${this.Ye(...n)}`):console.error(...n)}catch(o){console.error(...n)}}}error(...e){this.k(Vt.error,e)}warn(...e){this.k(Vt.warn,e)}info(...e){this.k(Vt.info,e)}debug(...e){this.k(Vt.debug,e)}},xS={error:G.Function,warn:G.Function,info:G.Function,debug:G.Function},Rp=class{constructor(t,e){Object.entries(xS).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.Xe=e}k(t,e){try{this.t[t](...e)}catch(n){this.Xe[t](...e)}}error(...t){this.k("error",t)}warn(...t){this.k("warn",t)}info(...t){this.k("info",t)}debug(...t){this.k("debug",t)}},Cp=t=>{let e=new Fa({level:"info",destination:console.error,formatter:Ua});return t?new Rp(t,e):e},Ue=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,n){return`Config option "${t}" had invalid value of ${e}, using minimum of ${n} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,n){return`Config option "${t}" should be of type ${e}, got ${n}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},NS=/^(\w|\.|-)+$/,OS=G.stringMatchingRegex(NS),GS={is:(t,e)=>OS.is(t)?t.length>64?{valid:!1,message:Ue.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:Ue.invalidTagValue(e)}},LS=class{constructor(t){let e={},n=t==null?void 0:t.application,r=t==null?void 0:t.logger;n&&Object.entries(n).forEach(([o,s])=>{if(s!=null){let{valid:a,message:c}=GS.is(s,`application.${o}`);a?o==="versionName"?e["application-version-name"]=[s]:e[`application-${o}`]=[s]:r==null||r.warn(c)}});let i=Object.keys(e);i.length&&(this.value=i.sort().flatMap(o=>e[o].sort().map(s=>`${o}/${s}`)).join(" "))}},XS=class{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function ka(t){return t.replace(/\/+$/,"")}function Aa(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var Di=class Zp{constructor(e,n,r=Zp.DEFAULT_EVENTS,i="/bulk",o="/diagnostic",s=!0,a){this.streaming=ka(e),this.polling=ka(n),this.events=ka(r),this.analyticsEventPath=i,this.diagnosticEventPath=o,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}};Di.DEFAULT_EVENTS="https://events.launchdarkly.com";function Ja(t,e=[]){if(e.length===0)return t;let n=e.map(({key:r,value:i})=>`${r}=${i}`);return`${t}?${n.join("&")}`}function WS(t,e,n){let r=Aa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Ja(`${t.streaming}/${r}`,i)}function US(t,e,n=[]){let r=Aa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Ja(`${t.polling}/${r}`,i)}function Qh(t,e,n=[]){let r=Aa(e);return Ja(`${t.events}/${r}`,n)}var kp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},PS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Vp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function _i(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function MS(t){return t===413?!0:_i(t)}function FS(t,e){let n,r;return{promise:new Promise((i,o)=>{r=i,n=setTimeout(()=>{let s=`${e} timed out after ${t} seconds.`;o(new Vp(s))},t*1e3)}),cancel:()=>{r(),clearTimeout(n)}}}function xp(t){return t==null?t:JSON.parse(JSON.stringify(t))}function Va(t){return Math.trunc(t*1e3)}var AS=t=>JSON.stringify(t)==="{}",Da=(t,e)=>t&&Object.entries(t).reduce((n,[r,i])=>(i&&!AS(i)&&!(e!=null&&e.includes(r))&&(n[r]=typeof i=="object"?Da(i,e):i),n),{});function Ui(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;var n,r,i;if(Array.isArray(t)){if(n=t.length,n!=e.length)return!1;for(r=n;r--!==0;)if(!Ui(t[r],e[r]))return!1;return!0}if(t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(r of t.entries())if(!e.has(r[0]))return!1;for(r of t.entries())if(!Ui(r[1],e.get(r[0])))return!1;return!0}if(t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(r of t.entries())if(!e.has(r[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(n=t.length,n!=e.length)return!1;for(r=n;r--!==0;)if(t[r]!==e[r])return!1;return!0}if(t.constructor===RegExp)return t.source===e.source&&t.flags===e.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===e.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===e.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(e,i[r]))return!1;for(r=n;r--!==0;){var o=i[r];if(!Ui(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function JS(t,e,n,r=!0,i="user-agent"){let{userAgentBase:o,version:s,wrapperName:a,wrapperVersion:c}=e.sdkData(),l={[i]:`${o!=null?o:"NodeJSClient"}/${s}`};return r&&(l.authorization=t),a&&(l["x-launchdarkly-wrapper"]=c?`${a}/${c}`:a),n!=null&&n.value&&(l["x-launchdarkly-tags"]=n.value),l}function Gn(t,e,n){let r;t.status?r=`error ${t.status}${t.status===401?" (invalid SDK key)":""}`:r=`I/O error (${t.message||"unknown error"})`;let i=n!=null?n:"giving up permanently";return`Received ${r} for ${e} - ${i}`}function Np({status:t}){return t?_i(t):!0}var $h=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Op=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),DS=class{constructor(t,e,n){this.p=e,this.Qe=n,this.wt=[],this.re=Date.now(),this.se=this.re,this.ae={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var t,e,n;let r=this.p.info.sdkData(),i=this.p.info.platformData();return{kind:"diagnostic-init",id:this.ae,creationDate:this.re,sdk:r,configuration:this.Qe,platform:st({name:i.name,osArch:(t=i.os)==null?void 0:t.arch,osName:(e=i.os)==null?void 0:e.name,osVersion:(n=i.os)==null?void 0:n.version},i.additional||{})}}recordStreamInit(t,e,n){let r={timestamp:t,failed:e,durationMillis:n};this.wt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),i={kind:"diagnostic",id:this.ae,creationDate:r,dataSinceDate:this.se,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.wt};return this.wt=[],this.se=r,i}},Pa;(function(t){t.MalformedFlag="MALFORMED_FLAG",t.UserNotSpecified="USER_NOT_SPECIFIED",t.FlagNotFound="FLAG_NOT_FOUND",t.ClientNotReady="CLIENT_NOT_READY",t.WrongType="WRONG_TYPE"})(Pa||(Pa={}));var YS=Pa,Gp=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};Gp.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var KS=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:o}}=n,{crypto:s,requests:a}=r;this.ti=st({},e),this.oe=Qh(n.serviceEndpoints,i,[]),this.ei=Qh(n.serviceEndpoints,o,[]),this.V=a,this.ii=s}async et(t,e,n,r){let i={status:en.Succeeded},o=me(st({},this.ti),{"content-type":"application/json"});n&&(o["x-launchdarkly-payload-id"]=n,o["x-launchDarkly-event-schema"]="4");let s;try{let{status:a,headers:c}=await this.V.fetch(e,{headers:o,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),l=Date.parse(c.get("date")||"");if(l&&(i.serverTime=l),a<=204)return i;if(s=new kp(Gn({status:a,message:"some events were dropped"},"event posting")),!_i(a))return MS(a)?i.status=en.Failed:i.status=en.FailedAndMustShutDown,i.error=s,i}catch(a){s=a}return s&&!r?(i.status=en.Failed,i.error=s,i):(await Op(),this.et(t,this.oe,n,!1))}async sendEventData(t,e){let n=t===On.AnalyticsEvents?this.ii.randomUUID():void 0,r=t===On.AnalyticsEvents?this.oe:this.ei;return this.et(e,r,n,!0)}};function Yi(t){return t.kind==="feature"}function _S(t){return t.kind==="identify"}function HS(t){return t.kind==="migration_op"}var zS=class{constructor(t,e,n,r,i,o){this.count=t,this.key=e,this.value=n,this.version=i,this.variation=o,this.default=r}increment(){this.count+=1}};function BS(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Lp=class{constructor(t=!1,e){this.ni=t,this.x=e,this.W=0,this.it=0,this.nt={},this.rt={}}summarizeEvent(t){if(Yi(t)&&!t.excludeFromSummaries){this.y||(this.y=t.context);let e=BS(t),n=this.nt[e],r=this.rt[t.key];r||(r=new Set,this.rt[t.key]=r),t.context.kinds.forEach(i=>r.add(i)),n?n.increment():this.nt[e]=new zS(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.it&&(this.it=t.creationDate)}}getSummary(){var t;let e=Object.values(this.nt).reduce((r,i)=>{let o=r[i.key];o||(o={default:i.default,counters:[],contextKinds:[...this.rt[i.key]]},r[i.key]=o);let s={value:i.value,count:i.count};return i.variation!==void 0&&i.variation!==null&&(s.variation=i.variation),i.version!==void 0&&i.version!==null?s.version=i.version:s.unknown=!0,o.counters.push(s),r},{}),n={startDate:this.W,endDate:this.it,features:e,kind:"summary",context:this.y!==void 0&&this.ni?(t=this.x)==null?void 0:t.filter(this.y):void 0};return this.ri(),n}ri(){this.W=0,this.it=0,this.nt={},this.rt={}}},jS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},QS=class{constructor(t,e){this.x=t,this.t=e,this.q={}}summarizeEvent(t){var e;if(Yi(t)){let n=t.context.canonicalUnfilteredJson();if(!n){t.context.valid&&((e=this.t)==null||e.error("Unable to serialize context, likely the context contains a cycle."));return}let r=this.q[n];r||(this.q[n]=new Lp(!0,this.x),r=this.q[n]),r.summarizeEvent(t)}}getSummaries(){let t=this.q;return this.q={},Object.values(t).map(e=>e.getSummary())}};function Pi(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function $S(t){return t.getSummaries!==void 0}var qS=class{constructor(t,e,n,r,i,o=!0,s=!1){this.e=t,this.st=r,this.S=i,this.at=[],this.ce=0,this.Et=0,this.Dt=0,this.bt=!1,this.le=0,this.kt=!1,this.xt=null,this.si=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.ue=new KS(e,n),this.x=new TS(t.allAttributesPrivate,t.privateAttributes.map(a=>new Nn(a))),s?this.J=new QS(this.x,this.t):this.J=new Lp,o&&this.start()}start(){var t,e;if(((t=this.st)==null?void 0:t.flushInterval)!==void 0&&(this.xt=setInterval(()=>{var n;(n=this.st)==null||n.flush()},this.st.flushInterval*1e3)),this.ai=setInterval(async()=>{var n;try{await this.flush()}catch(r){(n=this.t)==null||n.debug(`Flush failed: ${r}`)}},this.e.flushInterval*1e3),this.S){let n=this.S.createInitEvent();this.he(n),this.de=setInterval(()=>{let r=this.S.createStatsEventAndReset(this.Et,this.Dt,this.le);this.Et=0,this.Dt=0,this.he(r)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}he(t){this.ue.sendEventData(On.DiagnosticEvent,t)}close(){clearInterval(this.ai),this.xt&&clearInterval(this.xt),this.de&&clearInterval(this.de)}async flush(){var t;if(this.kt)throw new jS("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 e=this.at;if(this.at=[],$S(this.J))this.J.getSummaries().forEach(n=>{Object.keys(n.features).length&&e.push(n)});else{let n=this.J.getSummary();Object.keys(n.features).length&&e.push(n)}e.length&&(this.le=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.et(e))}sendEvent(t){var e;if(this.kt)return;if(HS(t)){if(Pi(t.samplingRatio)){let a=me(st({},t),{context:t.context?this.x.filter(t.context):void 0});a.samplingRatio===1&&delete a.samplingRatio,this.ot(a)}return}this.J.summarizeEvent(t);let n=Yi(t),r=n&&t.trackEvents||!n,i=this.oi(t),o=_S(t),s=(e=this.st)==null?void 0:e.processContext(t.context);s||o||(this.Dt+=1),s&&!o&&this.ot(this.St({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),r&&Pi(t.samplingRatio)&&this.ot(this.St(t,!1)),i&&Pi(t.samplingRatio)&&this.ot(this.St(t,!0))}St(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.x.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}ot(t){var e;this.at.length<this.si?(this.at.push(t),this.bt=!1):(this.bt||(this.bt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.Et+=1)}oi(t){return Yi(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.ce&&t.debugEventsUntilDate>Date.now()}async et(t){let e=await this.ue.sendEventData(On.AnalyticsEvents,t);if(e.status===en.FailedAndMustShutDown&&(this.kt=!0),e.serverTime&&(this.ce=e.serverTime),e.error)throw e.error}},Xp=class{constructor(t,e,n,r,i=1,o){this.context=t,this.key=e,this.data=n,this.metricValue=r,this.samplingRatio=i,this.url=o,this.kind="custom",this.creationDate=Date.now(),this.context=t}},Ma=class{constructor(t,e,n,r,i,o,s,a,c,l,u,h,p=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=p,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=i,o!==void 0&&(this.version=o),s!==void 0&&(this.variation=s),a!==void 0&&(this.trackEvents=a),c!==void 0&&(this.prereqOf=c),l!==void 0&&(this.reason=l),u!==void 0&&(this.debugEventsUntilDate=u),h!==void 0&&(this.excludeFromSummaries=h)}},Wp=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},tw=class{close(){}async flush(){}sendEvent(){}},ew=class{constructor(t){this.Lt=t}evalEvent(t){var e;return new Ma(this.Lt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.Lt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new Ma(this.Lt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Wp(t,1)}customEvent(t,e,n,r,i=1){return new Xp(e,t,n!=null?n:void 0,r!=null?r:void 0,i)}},qh="FDv1Fallback";function nw(t){return{ci:t,fe:"",useSelector(e){return this.fe=e,this},processFullTransfer(e){let n=[{event:"server-intent",data:{payloads:[{id:qh,target:1,intentCode:"xfer-full",reason:"payload-missing"}]}}];Object.entries((e==null?void 0:e.flags)||[]).forEach(([r,i])=>{n.push({event:"put-object",data:{kind:"flag",key:r,version:i.version||1,object:i}})}),Object.entries((e==null?void 0:e.segments)||[]).forEach(([r,i])=>{n.push({event:"put-object",data:{kind:"segment",key:r,version:i.version||1,object:i}})}),n.push({event:"payload-transferred",data:{state:this.fe,version:1,id:qh}}),this.ci.processEvents(n)}}}var pe={type:"none"};function Up(t,e){let n="inactive",r,i="partial",o=[];function s(g,S){var T;return(T=t[g])==null?void 0:T.call(t,S)}function a(){n="inactive",r=void 0,i="partial",o=[]}function c(){n="changes",i="partial",o=[]}function l(){o=[]}function u(g){return!g.id||!g.target?pe:{type:"payload",payload:{id:g.id,version:g.target,type:"none",updates:[]}}}function h(g){var S;if(!((S=g.payloads)!=null&&S.length))return{type:"error",kind:"MISSING_PAYLOAD",message:"No payload present in server-intent"};let T=g.payloads[0];switch(T==null?void 0:T.intentCode){case"xfer-full":return n="full",o=[],i="full",r=T.id,pe;case"xfer-changes":return n="changes",o=[],i="partial",r=T.id,pe;case"none":return n="changes",o=[],i="partial",r=T.id,u(T);default:return e==null||e.warn(`Unable to process intent code '${T==null?void 0:T.intentCode}'.`),pe}}function p(g){if(n==="inactive"||!r||!g.kind||!g.key||!g.version||!g.object)return pe;let S=s(g.kind,g.object);return S?(o.push({kind:g.kind,key:g.key,version:g.version,object:S}),pe):(e==null||e.warn(`Unable to process object for kind: '${g.kind}'`),pe)}function f(g){return n==="inactive"||!r||!g.kind||!g.key||!g.version||o.push({kind:g.kind,key:g.key,version:g.version,deleted:!0}),pe}function m(g){if(n==="inactive")return{type:"error",kind:"PROTOCOL_ERROR",message:"A payload transferred has been received without an intent having been established."};if(!r||g.state===null||g.state===void 0||!g.version)return a(),pe;let S={type:"payload",payload:{id:r,version:g.version,state:g.state,type:i,updates:o}};return c(),S}function d(g){return e==null||e.info(`Goodbye was received from the LaunchDarkly connection with reason: ${g.reason}.`),a(),{type:"goodbye",reason:g.reason}}function v(g){return e==null||e.info(`An issue was encountered receiving updates for payload ${r} with reason: ${g.reason}.`),l(),{type:"serverError",id:g.payload_id,reason:g.reason}}return{get state(){return n},processEvent(g){switch(g.event){case"server-intent":return h(g.data);case"put-object":return p(g.data);case"delete-object":return f(g.data);case"payload-transferred":return m(g.data);case"goodbye":return d(g.data);case"error":return v(g.data);case"heart-beat":return pe;default:return{type:"error",kind:"UNKNOWN_EVENT",message:`Received an unknown event of type '${g.event}'`}}},reset(){a()}}}function rw(t){return t==="MISSING_PAYLOAD"||t==="PROTOCOL_ERROR"}var Pp=class{constructor(t,e,n){this.g=e,this.t=n,this.n=[],this.li=Up(t,n)}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=>{var n,r;let i=this.li.processEvent(e);switch(i.type){case"payload":this.n.forEach(o=>o(i.payload));break;case"error":rw(i.kind)?(n=this.g)==null||n.call(this,At.InvalidData,i.message):(r=this.t)==null||r.warn(i.message);break}})}},iw=class{constructor(t,e,n,r){this.g=n,this.t=r,this.H(t,"server-intent"),this.H(t,"put-object"),this.H(t,"delete-object"),this.H(t,"payload-transferred"),this.H(t,"goodbye"),this.H(t,"error"),this.Ct=new Pp(e,n,r)}addPayloadListener(t){this.Ct.addPayloadListener(t)}removePayloadListener(t){this.Ct.removePayloadListener(t)}H(t,e){t.addEventListener(e,async n=>{var r,i,o,s,a;if(n!=null&&n.data){(r=this.t)==null||r.debug(`Received ${e} event. Data is ${n.data}`);try{this.Ct.processEvents([{event:e,data:JSON.parse(n.data)}])}catch(c){(i=this.t)==null||i.error(`Stream received data that was unable to be processed in "${e}" message`),(o=this.t)==null||o.debug(`Data follows: ${n.data}`),(s=this.g)==null||s.call(this,At.InvalidData,"Malformed data in EventStream.")}}else(a=this.g)==null||a.call(this,At.Unknown,"Event from EventStream missing data.")})}};function ow(t){if(t){let e=Object.keys(t).find(n=>n.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var tp="unknown plugin";function Ki(t,e){try{return e.getMetadata().name||tp}catch(n){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),tp}}function sw(t,e,n){let r=[];return n.forEach(i=>{var o;try{let s=(o=i.getHooks)==null?void 0:o.call(i,e);s===void 0?t.error(`Plugin ${Ki(t,i)} returned undefined from getHooks.`):s&&s.length>0&&r.push(...s)}catch(s){t.error(`Exception thrown getting hooks for plugin ${Ki(t,i)}. Unable to get hooks.`)}}),r}function aw(t,e,n,r){r.forEach(i=>{try{i.register(n,e)}catch(o){t.error(`Exception thrown registering plugin ${Ki(t,i)}.`)}})}var de=Object.freeze({__proto__:null,ClientMessages:Gp,DiagnosticsManager:DS,ErrorKinds:YS,EventFactoryBase:ew,EventProcessor:qS,FDv1PayloadAdaptor:nw,InputCustomEvent:Xp,InputEvalEvent:Ma,InputIdentifyEvent:Wp,NullEventProcessor:tw,PayloadProcessor:Pp,PayloadStreamReader:iw,canonicalize:Fi,createProtocolHandler:Up,initMetadataFromHeaders:ow,isLegacyUser:Tp,isMultiKind:Ip,isSingleKind:wp,safeGetHooks:sw,safeGetName:Ki,safeRegisterPlugins:aw,shouldSample:Pi}),lw={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function cw(t){return t>=200&&t<=299}var ep=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function np(t,e,n,r,i,o,s,a,c,l){let u,h="GET",p=st({},o);c&&(h="REPORT",p["content-type"]="application/json",u=t);let f=c?n.pathReport(i,t):n.pathGet(i,t),m=[...s!=null?s:[]];a&&m.push({key:"withReasons",value:"true"}),l&&m.push({key:"h",value:l});let d=US(e,f,m);return{async requestPayload(){let v;try{let g=await r.fetch(d,{method:h,headers:p,body:u});if(cw(g.status))return await g.text();v=g.status}catch(g){throw new ep(g==null?void 0:g.message)}throw new ep(`Unexpected status code: ${v}`,v)}}}var rp=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function uw(t,e,n=!1){let r,i=new Promise(a=>{r=(c,l)=>{var u;try{(u=t.after)==null||u.call(t,c,l)}catch(h){e==null||e.error(`Error in after callback: ${h}`)}a(c)}}),o=t.before?t.before():Promise.resolve(void 0),s=!1;return{execute:()=>{s&&(e==null||e.error(rp)),s=!0,o.then(a=>{t.execute(a).then(c=>r({status:"complete",result:c},a)).catch(c=>r({status:"error",error:c},a))}).catch(a=>{e==null||e.error(a),r({status:"error",error:a},void 0)})},shed:()=>{s&&(e==null||e.error(rp)),s=!0,o.then(a=>{r({status:"shed"},a)})},promise:i,sheddable:n}}function hw(t){let e,n=[];function r(){if(!e&&n.length>0){let i=n.shift();e=i.promise.finally(()=>{e=void 0,r()}),i.execute()}}return{execute(i,o=!1){var s,a;let c=uw(i,t,o);return e?((s=n[n.length-1])!=null&&s.sheddable&&((a=n.pop())==null||a.shed()),n.push(c)):(e=c.promise.finally(()=>{e=void 0,r()}),c.execute()),c.promise},pendingCount(){return n.length}}}var pw={logger:G.Object,maxCachedContexts:G.numberWithMin(0),baseUri:G.String,streamUri:G.String,eventsUri:G.String,capacity:G.numberWithMin(1),diagnosticRecordingInterval:G.numberWithMin(2),flushInterval:G.numberWithMin(2),streamInitialReconnectDelay:G.numberWithMin(0),allAttributesPrivate:G.Boolean,debug:G.Boolean,diagnosticOptOut:G.Boolean,withReasons:G.Boolean,sendEvents:G.Boolean,pollInterval:G.numberWithMin(30),useReport:G.Boolean,privateAttributes:G.StringArray,applicationInfo:G.Object,wrapperName:G.String,wrapperVersion:G.String,payloadFilterKey:G.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:G.createTypeArray("Hook[]",{}),inspectors:G.createTypeArray("LDInspection",{}),cleanOldPersistentData:G.Boolean},dw=300,Mp="https://clientsdk.launchdarkly.com",Fp="https://clientstream.launchdarkly.com";function fw(t){return t instanceof Rp?t:Cp(t)}var mw=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var n,r,i;this.logger=Cp(),this.baseUri=Mp,this.eventsUri=Di.DEFAULT_EVENTS,this.streamUri=Fp,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=dw,this.hooks=[],this.inspectors=[],this.logger=fw(t.logger),this.ui(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new Di(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 LS({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(i=e.trackEventModifier)!=null?i:(o=>o),this.credentialType=e.credentialType,this.getImplementationHooks=e.getImplementationHooks}ui(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let i=pw[n];if(i)if(i.is(r))n==="logger"||(this[n]=r!=null?r:void 0);else{let o=i.getType();if(o==="boolean")e.push(Ue.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(o==="boolean | undefined | null")e.push(Ue.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(i instanceof vp&&G.Number.is(r)){let{min:s}=i;e.push(Ue.optionBelowMinimum(n,r,s)),this[n]=s}else e.push(Ue.wrongOptionType(n,i.getType(),typeof r))}else e.push(Ue.unknownOption(n))}),e}};async function Ap(t,e){if(t.digest)return t.digest(e);if(t.asyncDigest)return t.asyncDigest(e);throw new Error("Platform must implement digest or asyncDigest")}var Jp=async(t,{crypto:e,storage:n})=>{let r=await(n==null?void 0:n.get(t));return r||(r=e.randomUUID(),await(n==null?void 0:n.set(t,r))),r};function Dp(t){return async e=>Ap(t.createHash("sha256").update(e),"base64")}var fe=async t=>t;async function gr(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function yw(t,e){return gr([{value:"LaunchDarkly",transform:fe},{value:e,transform:Dp(t)}])}async function gw(t){return gr([{value:"LaunchDarkly",transform:fe},{value:"AnonymousKeys",transform:fe},{value:t,transform:fe}])}async function bw(t){return gr([{value:"LaunchDarkly",transform:fe},{value:"ContextKeys",transform:fe},{value:t,transform:fe}])}async function vw(t){return gr([{value:t,transform:fe},{value:"ContextIndex",transform:fe}])}async function ip(t,e,n){return gr([{value:e,transform:fe},{value:n.canonicalKey,transform:Dp(t)}])}var{isLegacyUser:Sw,isSingleKind:xa,isMultiKind:op}=de,Yp="1.0",ww=t=>{let e=t,{kind:n}=e,r=yp(e,["kind"]);return{kind:"multi",[n]:r}},Iw=async({crypto:t,info:e},{applicationInfo:n})=>{var r;let{ld_application:i}=e.platformData(),o=(r=Da(i))!=null?r:{},s=(n==null?void 0:n.id)||(o==null?void 0:o.id);if(s){let a=(n==null?void 0:n.version)||(o==null?void 0:o.version),c=(n==null?void 0:n.name)||(o==null?void 0:o.name),l=(n==null?void 0:n.versionName)||(o==null?void 0:o.versionName);return o=st(st(st(me(st({},o),{id:s}),a?{version:a}:{}),c?{name:c}:{}),l?{versionName:l}:{}),o.key=await Ap(t.createHash("sha256").update(s),"base64"),o.envAttributesVersion=o.envAttributesVersion||Yp,o}},Tw=async t=>{var e,n,r,i;let{ld_device:o,os:s}=t.info.platformData(),a=(e=Da(o))!=null?e:{},c=(s==null?void 0:s.name)||((n=a.os)==null?void 0:n.name),l=(s==null?void 0:s.version)||((r=a.os)==null?void 0:r.version),u=(i=a.os)==null?void 0:i.family;if((c||l||u)&&(a.os=st(st(st({},c?{name:c}:{}),l?{version:l}:{}),u?{family:u}:{})),Object.keys(a).filter(h=>h!=="key"&&h!=="envAttributesVersion").length){let h=await bw("ld_device");return a.key=await Jp(h,t),a.envAttributesVersion=a.envAttributesVersion||Yp,a}},Ew=async(t,e,n)=>{if(Sw(t))return t;let r,i;if(xa(t)&&t.kind!=="ld_application"||op(t)&&!t.ld_application?r=await Iw(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),xa(t)&&t.kind!=="ld_device"||op(t)&&!t.ld_device?i=await Tw(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),r||i){let o=xa(t)?ww(t):t;return st(st(st({},o),r?{ld_application:r}:{}),i?{ld_device:i}:{})}return t};function Rw(){let t,e;return{set(n,r){t=n,e=r},getContext(){return e},getUnwrappedContext(){return t},newIdentificationPromise(){let n,r;return{identifyPromise:new Promise((i,o)=>{n=i,r=o}),identifyResolve:n,identifyReject:r}},hasContext(){return e!==void 0},hasValidContext(){return this.hasContext()&&e.valid}}}var{isLegacyUser:Cw,isMultiKind:Zw,isSingleKind:kw}=de,Ya=async(t,e,n)=>{let{anonymous:r,key:i}=e;if(r&&!i){let o=await gw(t);e.key=await Jp(o,n)}},Vw=async(t,e)=>{await Ya(t.kind,t,e)},xw=async(t,e)=>{let n=t,{kind:r}=n,i=yp(n,["kind"]);return Promise.all(Object.entries(i).map(([o,s])=>Ya(o,s,e)))},Nw=async(t,e)=>{await Ya("user",t,e)},Ow=async(t,e)=>{let n=xp(t);return kw(n)&&await Vw(n,e),Zw(n)&&await xw(n,e),Cw(n)&&await Nw(n,e),n},Gw=t=>({customBaseURI:t.serviceEndpoints.polling!==Mp,customStreamURI:t.serviceEndpoints.streaming!==Fp,customEventsURI:t.serviceEndpoints.events!==Di.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:Va(t.flushInterval),reconnectTimeMillis:Va(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Va(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Lw=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new de.DiagnosticsManager(t,n,Gw(e))};function sp(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function ap(t,e,n){return st({value:t,variationIndex:e!=null?e:null},n!==void 0&&{reason:n})}var Xw=(t,e,n,r,i)=>{if(e.sendEvents)return new de.EventProcessor(me(st({},e),{eventsCapacity:e.capacity}),new XS(t,e,n),r,void 0,i,!1,!0)},lp=class extends de.EventFactoryBase{evalEventClient(t,e,n,r,i,o){let{trackEvents:s,debugEventsUntilDate:a,trackReason:c,flagVersion:l,version:u,variation:h}=r;return super.evalEvent({addExperimentData:c,context:i,debugEventsUntilDate:a,defaultVal:n,flagKey:t,reason:o,trackEvents:!!s,value:e,variation:h,version:l!=null?l:u})}},Na=class Kp{constructor(){this.container={index:new Array}}static fromJson(e){let n=new Kp;try{n.container=JSON.parse(e)}catch(r){}return n}toJson(){return JSON.stringify(this.container)}notice(e,n){let r=this.container.index.find(i=>i.id===e);r===void 0?this.container.index.push({id:e,timestamp:n}):r.timestamp=n}prune(e){let n=Math.max(e,0);return this.container.index.length>n?(this.container.index.sort((r,i)=>r.timestamp-i.timestamp),this.container.index.splice(0,this.container.index.length-n)):[]}},Ww=class{constructor(t,e,n,r,i,o,s=()=>Date.now()){this.p=t,this.It=e,this.hi=n,this.P=r,this.w=i,this.t=o,this.di=s,this.pe=vw(this.It)}async init(t,e){this.w.init(t,e),await this.ge(t)}async upsert(t,e,n){return this.w.upsert(t,e,n)?(await this.ge(t),!0):!1}async loadCached(t){var e,n,r,i;let o=await ip(this.p.crypto,this.It,t),s=await((e=this.p.storage)==null?void 0:e.get(o));if(s==null){if(s=await((n=this.p.storage)==null?void 0:n.get(t.canonicalKey)),s==null)return!1;await((r=this.p.storage)==null?void 0:r.set(o,s)),await((i=this.p.storage)==null?void 0:i.clear(t.canonicalKey))}try{let a=JSON.parse(s),c=Object.entries(a).reduce((l,[u,h])=>(l[u]={version:h.version,flag:h},l),{});return this.w.initCached(t,c),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(a){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${a.message}`),!1}}async fi(){var t;if(this.B!==void 0)return this.B;let e=await((t=this.p.storage)==null?void 0:t.get(await this.pe));if(!e)return this.B=new Na,this.B;try{this.B=Na.fromJson(e),this.t.debug("Loaded context index from persistent storage")}catch(n){this.t.warn(`Could not load index from persistent storage: ${n.message}`),this.B=new Na}return this.B}async ge(t){var e,n;let r=await this.fi(),i=await ip(this.p.crypto,this.It,t);r.notice(i,this.di());let o=r.prune(this.hi);await Promise.all(o.map(async l=>{var u;return(u=this.p.storage)==null?void 0:u.clear(l.id)})),await((e=this.p.storage)==null?void 0:e.set(await this.pe,r.toJson()));let s=this.P.getAll(),a=Object.entries(s).reduce((l,[u,h])=>(h.flag!==null&&h.flag!==void 0&&(l[u]=h.flag),l),{}),c=JSON.stringify(a);await((n=this.p.storage)==null?void 0:n.set(i,c))}};function Uw(){let t={};return{init(e){t=Object.entries(e).reduce((n,[r,i])=>(n[r]=i,n),{})},insertOrUpdate(e,n){t[e]=n},get(e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},getAll(){return t}}}function Pw(t,e){let n=[];return Object.entries(t).forEach(([r,i])=>{let o=e[r];(!o||!Ui(i,o))&&n.push(r)}),Object.keys(e).forEach(r=>{t[r]||n.push(r)}),n}function Mw(t,e){let n=t,r=e,i,o=new Array;return{handleFlagChanges(s,a){i?o.forEach(c=>{try{c(i,s,a)}catch(l){}}):r.warn("Received a change event without an active context. Changes will not be propagated.")},init(s,a){i=s;let c=n.getAll();n.init(a);let l=Pw(c,a);l.length>0&&this.handleFlagChanges(l,"init")},initCached(s,a){(i==null?void 0:i.canonicalKey)!==s.canonicalKey&&this.init(s,a)},upsert(s,a,c){if((i==null?void 0:i.canonicalKey)!==s.canonicalKey)return r.warn("Received an update for an inactive context."),!1;let l=n.get(a);return l!==void 0&&l.version>=c.version?!1:(n.insertOrUpdate(a,c),this.handleFlagChanges([a],"patch"),!0)},on(s){o.push(s)},off(s){let a=o.indexOf(s);a>-1&&o.splice(a,1)}}}var Fw=class{constructor(t,e,n,r,i=()=>Date.now()){this.P=Uw(),this.w=Mw(this.P,r),this.Ot=this.pi(t,e,n,r,i)}async pi(t,e,n,r,i=()=>Date.now()){let o=await yw(t.crypto,e);return new Ww(t,o,n,this.P,this.w,r,i)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.At(this.r[t]):this.P.get(t)}getAll(){return this.r?st(st({},this.P.getAll()),Object.entries(this.r).reduce((t,[e,n])=>(t[e]=this.At(n),t),{})):this.P.getAll()}presetFlags(t){this.P.init(t)}setBootstrap(t,e){this.w.init(t,e)}async init(t,e){return(await this.Ot).init(t,e)}async upsert(t,e,n){return(await this.Ot).upsert(t,e,n)}async loadCached(t){return(await this.Ot).loadCached(t)}on(t){this.w.on(t)}off(t){this.w.off(t)}At(t){return{flag:{value:t,version:0},version:0}}setOverride(t,e){this.r||(this.r={}),this.r[t]=e,this.w.handleFlagChanges([t],"override")}removeOverride(t){!this.r||!Object.prototype.hasOwnProperty.call(this.r,t)||(delete this.r[t],Object.keys(this.r).length===0&&(this.r=void 0),this.w.handleFlagChanges([t],"override"))}clearAllOverrides(){if(this.r){let t=st({},this.r);this.r=void 0,this.w.handleFlagChanges(Object.keys(t),"override")}}getAllOverrides(){if(!this.r)return{};let t={};return Object.entries(this.r).forEach(([e,n])=>{t[e]=this.At(n)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},cp="unknown hook",_p="beforeEvaluation",Hp="afterEvaluation",Aw="afterTrack";function br(t,e,n,r,i){try{return r()}catch(o){return t==null||t.error(`An error was encountered in "${e}" of the "${n}" hook: ${o}`),i}}function vr(t,e){try{return e.getMetadata().name||cp}catch(n){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),cp}}function Jw(t,e,n){return e.map(r=>br(t,_p,vr(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeEvaluation)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Dw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];br(t,Hp,vr(t,s),()=>{var c,l;return(l=(c=s==null?void 0:s.afterEvaluation)==null?void 0:c.call(s,n,a,i))!=null?l:{}},{})}}function Yw(t,e,n){return e.map(r=>br(t,_p,vr(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeIdentify)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Kw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];br(t,Hp,vr(t,s),()=>{var c,l;return(l=(c=s==null?void 0:s.afterIdentify)==null?void 0:c.call(s,n,a,i))!=null?l:{}},{})}}function _w(t,e,n){for(let r=e.length-1;r>=0;r-=1){let i=e[r];br(t,Aw,vr(t,i),()=>{var o;return(o=i==null?void 0:i.afterTrack)==null?void 0:o.call(i,n)},void 0)}}var Hw=class{constructor(t,e){this.t=t,this.$=[],this.$.push(...e)}withEvaluation(t,e,n,r){if(this.$.length===0)return r();let i=[...this.$],o={flagKey:t,context:e,defaultValue:n},s=Jw(this.t,i,o),a=r();return Dw(this.t,i,o,s,a),a}identify(t,e){let n=[...this.$],r={context:t,timeout:e},i=Yw(this.t,n,r);return o=>{Kw(this.t,n,r,i,o)}}addHook(t){this.$.push(t)}afterTrack(t){if(this.$.length===0)return;let e=[...this.$];_w(this.t,e,t)}};function zw(t){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(e,n,r)=>(t.onFlagUsed(e.flagKey,r,e.context),n),afterIdentify(e,n,r){return t.onIdentityChanged(e.context),n}}}function Bw(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function jw(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function Qw(t,e){let n=!1,r={method:(...i)=>{try{t.method(...i)}catch(o){n||(n=!0,e.warn(jw(r.type,r.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return r}var zp="flag-used",Bp="flag-details-changed",jp="flag-detail-changed",Qp="client-identity-changed",$w=[zp,Bp,jp,Qp];function qw(t,e){let n=$w.includes(t.type)&&t.method&&typeof t.method=="function";return n||e.warn(Bw(t.type,t.name)),n}var tI=class{constructor(t,e){this.z=[];let n=t.filter(r=>qw(r,e));this.z=n.map(r=>Qw(r,e))}hasInspectors(){return this.z.length!==0}onFlagUsed(t,e,n){this.z.forEach(r=>{r.type===zp&&r.method(t,e,n)})}onFlagsChanged(t){this.z.forEach(e=>{e.type===Bp&&e.method(t)})}onFlagChanged(t,e){this.z.forEach(n=>{n.type===jp&&n.method(t,e)})}onIdentityChanged(t){this.z.forEach(e=>{e.type===Qp&&e.method(t)})}},eI=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var n,r;if(typeof t!="string"){(n=this.t)==null||n.warn("Only string event names are supported.");return}this.n.has(t)?(r=this.n.get(t))==null||r.push(e):this.n.set(t,[e])}off(t,e){let n=this.n.get(t);if(n){if(e){let r=n.filter(i=>i!==e);r.length===0?this.n.delete(t):this.n.set(t,r);return}this.n.delete(t)}}gi(t,e,...n){var r;try{t(...n)}catch(i){(r=this.t)==null||r.error(`Encountered error invoking handler for "${e}", detail: "${i}"`)}}emit(t,...e){let n=this.n.get(t);n==null||n.forEach(r=>this.gi(r,t,...e))}eventNames(){return[...this.n.keys()]}listenerCount(t){var e,n;return(n=(e=this.n.get(t))==null?void 0:e.length)!=null?n:0}};function nI(t,e,n){let r=e.info.sdkData(),i;n.applicationInfo&&(n.applicationInfo.id&&(i=i!=null?i:{},i.id=n.applicationInfo.id),n.applicationInfo.version&&(i=i!=null?i:{},i.version=n.applicationInfo.version),n.applicationInfo.name&&(i=i!=null?i:{},i.name=n.applicationInfo.name),n.applicationInfo.versionName&&(i=i!=null?i:{},i.versionName=n.applicationInfo.versionName));let o={name:r.userAgentBase,version:r.version};r.wrapperName&&(o.wrapperName=r.wrapperName),r.wrapperVersion&&(o.wrapperVersion=r.wrapperVersion);let s={sdk:o,[n.credentialType]:t};return i&&(s.application=i),s}var{ClientMessages:up,ErrorKinds:hp}=de,rI=5,iI=class{constructor(t,e,n,r,i,o){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.a=Rw(),this.Pt=15,this.T=new lp(!1),this.ct=new lp(!0),this.Tt=!1,this.mi=hw(),!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.e=new mw(r,o),this.logger=this.e.logger,this.me=JS(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.R=new Fw(this.platform,t,this.e.maxCachedContexts,this.e.logger),this.S=Lw(t,this.e,n),this.E=Xw(t,this.e,n,this.me,this.S),this.emitter=new eI,this.emitter.on("error",(a,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(a)}`)}),this.R.on((a,c,l)=>{this.yi(c,l);let u=xn.toLDContext(a);this.emitter.emit("change",u,c),c.forEach(h=>{this.emitter.emit(`change:${h}`,u)})}),this.dataManager=i(this.R,this.e,this.me,this.emitter,this.S);let s=[...this.e.hooks];if(this.environmentMetadata=nI(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(a=>{s.push(a)}),this.M=new Hw(this.logger,s),this.Y=new tI(this.e.inspectors,this.logger),this.Y.hasInspectors()&&this.M.addHook(zw(this.Y)),r.cleanOldPersistentData&&o!=null&&o.getLegacyStorageKeys&&this.platform.storage)try{this.logger.debug("Cleaning old persistent data."),Promise.all(o.getLegacyStorageKeys().map(a=>{var c;return(c=this.platform.storage)==null?void 0:c.clear(a)})).catch(a=>{this.logger.error(`Error cleaning old persistent data: ${a}`)}).finally(()=>{this.logger.debug("Cleaned old persistent data.")})}catch(a){this.logger.error(`Error cleaning old persistent data: ${a}`)}}allFlags(){return Object.entries(this.R.getAll()).reduce((t,[e,n])=>(n.flag!==null&&n.flag!==void 0&&!n.flag.deleted&&(t[e]=n.flag.value),t),{})}async close(){var t;await this.flush(),(t=this.E)==null||t.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.E)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.a.hasContext()?xp(this.a.getUnwrappedContext()):void 0}getInternalContext(){return this.a.getContext()}presetFlags(t){this.R.presetFlags(t)}async identify(t,e){let n=await this.identifyResult(t,e);if(n.status==="error")throw n.error;if(n.status==="timeout"){let r=new Vp(`identify timed out after ${n.timeout} seconds.`);throw this.logger.error(r.message),r}}async identifyResult(t,e){var n,r;let i=(n=e==null?void 0:e.timeout)!=null?n:rI,o=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Pt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Pt} seconds. We recommend a timeout of less than ${this.Pt} seconds.`);let s=this.mi.execute({before:async()=>{let c=await Ow(t,this.platform);this.autoEnvAttributes===Ji.Enabled&&(c=await Ew(c,this.platform,this.e));let l=xn.fromLDContext(c);if(l.valid){let u=this.M.identify(c,e==null?void 0:e.timeout);return{context:c,checkedContext:l,afterIdentify:u}}return{context:c,checkedContext:l}},execute:async c=>{var l;let{context:u,checkedContext:h}=c;if(!h.valid){let d=new Error("Context was unspecified or had no key");return this.emitter.emit("error",u,d),Promise.reject(d)}this.a.set(u,h),(l=this.E)==null||l.sendEvent(this.T.identifyEvent(h));let{identifyPromise:p,identifyResolve:f,identifyReject:m}=this.a.newIdentificationPromise();return this.logger.debug(`Identifying ${JSON.stringify(h)}`),await this.dataManager.identify(f,m,h,e),p},after:async(c,l)=>{var u,h,p;c.status==="complete"?(u=l==null?void 0:l.afterIdentify)==null||u.call(l,{status:"completed"}):c.status==="shed"?(h=l==null?void 0:l.afterIdentify)==null||h.call(l,{status:"shed"}):c.status==="error"&&((p=l==null?void 0:l.afterIdentify)==null||p.call(l,{status:"error"}))}},(r=e==null?void 0:e.sheddable)!=null?r:!1).then(c=>{if(c.status==="error"){let u={status:"error",error:c.error};return this.maybeSetInitializationResult({status:"failed",error:c.error}),u}if(c.status==="shed")return{status:"shed"};let l={status:"completed"};return this.maybeSetInitializationResult({status:"complete"}),l});if(o)return s;let a=new Promise(c=>{setTimeout(()=>{c({status:"timeout",timeout:i})},i*1e3)});return Promise.race([s,a])}maybeSetInitializationResult(t){this.initializeResult===void 0&&(this.initializeResult=t,this.emitter.emit("ready"),t.status==="complete"&&this.emitter.emit("initialized"),this.initResolve&&(this.initResolve(t),this.initResolve=void 0))}waitForInitialization(t){var e;let n=(e=t==null?void 0:t.timeout)!=null?e:5;return this.initializeResult?Promise.resolve(this.initializeResult):this.initializedPromise?this.promiseWithTimeout(this.initializedPromise,n):(this.initializedPromise||(this.initializedPromise=new Promise(r=>{this.initResolve=r})),this.promiseWithTimeout(this.initializedPromise,n))}promiseWithTimeout(t,e){let n=FS(e,"waitForInitialization");return Promise.race([t.then(r=>(n.cancel(),r)),n.promise.then(()=>({status:"complete"})).catch(()=>({status:"timeout"}))]).catch(r=>{var i;return(i=this.logger)==null||i.error(r.message),{status:"failed",error:r}})}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){var r,i;if(!this.a.hasValidContext()){this.logger.warn(up.MissingContextKeyNoEvent);return}n!==void 0&&!G.Number.is(n)&&((r=this.logger)==null||r.warn(up.invalidMetricValue(typeof n))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.a.getContext(),e,n))),this.M.afterTrack({key:t,context:this.a.getUnwrappedContext(),data:e,metricValue:n})}lt(t,e,n,r){var i,o,s,a,c;let l=this.a.hasContext();l||(i=this.logger)==null||i.warn("Flag evaluation called before client is fully initialized, data from this evaulation could be stale.");let u=this.a.getContext(),h=this.R.get(t);if(h===void 0||h.flag.deleted){let g=e!=null?e:null;return(o=this.logger)==null||o.warn(`Unknown feature flag "${t}"; returning default value ${g}.`),l&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(t,g,u))),sp(hp.FlagNotFound,e)}let{reason:p,value:f,variation:m,prerequisites:d}=h.flag;if(r){let[g,S]=r(f);if(!g){l&&((a=this.E)==null||a.sendEvent(n.evalEventClient(t,e,e,h.flag,u,p)));let T=new PS(`Wrong type "${S}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.a.getUnwrappedContext(),T),sp(hp.WrongType,e)}}let v=ap(f,m,p);return f==null&&(this.logger.debug("Result value is null. Providing default value."),v.value=e),d==null||d.forEach(g=>{this.lt(g,void 0,this.T)}),l&&((c=this.E)==null||c.sendEvent(n.evalEventClient(t,f,e,h.flag,u,p))),v}variation(t,e){let{value:n}=this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,this.T));return n}variationDetail(t,e){return this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,this.ct))}G(t,e,n,r){return this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,n,r))}boolVariation(t,e){return this.G(t,e,this.T,n=>[G.Boolean.is(n),G.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.G(t,e,this.T,n=>[G.Number.is(n),G.Number.getType()]).value}stringVariation(t,e){return this.G(t,e,this.T,n=>[G.String.is(n),G.String.getType()]).value}boolVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.Boolean.is(n),G.Boolean.getType()])}numberVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.Number.is(n),G.Number.getType()])}stringVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.String.is(n),G.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.M.addHook(t)}setEventSendingEnabled(t,e){var n,r,i,o;this.Tt!==t&&(this.Tt=t,t?(this.logger.debug("Starting event processor"),(n=this.E)==null||n.start()):e?((r=this.logger)==null||r.debug("Flushing event processor before disabling."),this.flush().then(()=>{var s,a;this.Tt||((s=this.logger)==null||s.debug("Stopping event processor."),(a=this.E)==null||a.close())})):((i=this.logger)==null||i.debug("Stopping event processor."),(o=this.E)==null||o.close()))}sendEvent(t){var e;(e=this.E)==null||e.sendEvent(t)}getDebugOverrides(){var t,e;return(e=(t=this.R).getDebugOverride)==null?void 0:e.call(t)}yi(t,e){if(!this.Y.hasInspectors())return;let n={};t.forEach(r=>{let i=this.R.get(r);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:o,value:s,variation:a}=i.flag;n[r]=ap(s,a,o)}else n[r]={value:void 0,variationIndex:null}}),e==="init"?this.Y.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,i])=>{this.Y.onFlagChanged(r,i)})}};function oI(t,e,n){n.forEach(r=>{var i;try{(i=r.registerDebug)==null||i.call(r,e)}catch(o){t.error(`Exception thrown registering plugin ${de.safeGetName(t,r)}.`)}})}function $p(t,e){let n=Object.keys(e),r="$flagsState",i="$valid",o=e[r];!o&&n.length&&t.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),e[i]===!1&&t.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let s={};return n.forEach(a=>{if(a!==r&&a!==i){let c;o&&o[a]?c=st({value:e[a]},o[a]):c={value:e[a],version:0},s[a]={version:c.version,flag:c}}}),s}function sI(t,e,n){return{async handlePut(r,i){n.debug(`Got PUT: ${Object.keys(i)}`);let o=Object.entries(i).reduce((s,[a,c])=>(s[a]={version:c.version,flag:c},s),{});await t.init(r,o),e.requestStateUpdate("VALID")},async handlePatch(r,i){n.debug(`Got PATCH ${JSON.stringify(i,null,2)}`),t.upsert(r,i.key,{version:i.version,flag:i})},async handleDelete(r,i){n.debug(`Got DELETE ${JSON.stringify(i,null,2)}`),t.upsert(r,i.key,{version:i.version,flag:me(st({},i),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})},handleStreamingError(r){e.reportError(r.kind,r.message,r.code,r.recoverable)},handlePollingError(r){e.reportError(r.kind,r.message,r.status,r.recoverable)}}}function aI(t,e=()=>Date.now()){let n="CLOSED",r=e(),i;function o(){return{state:n,stateSince:r,lastError:i}}function s(a,c=!1){let l=a==="INTERRUPTED"&&n==="INITIALIZING"?"INITIALIZING":a,u=n!==l;u&&(n=l,r=e()),(u||c)&&t.emit("dataSourceStatus",o())}return{get status(){return o()},requestStateUpdate(a){s(a)},reportError(a,c,l,u=!1){i={kind:a,message:c,statusCode:l,time:e()},s(u?"INTERRUPTED":"CLOSED",!0)}}}function pp(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var lI=class{constructor(t,e,n,r,i){this.vi=t,this.wi=e,this.Ei=n,this.g=r,this.t=i,this.u=!1}async ye(){var t,e,n,r,i,o,s;if(this.u)return;let a=h=>{var p,f,m;(p=this.t)==null||p.error("Polling received invalid data"),(f=this.t)==null||f.debug(`Invalid JSON follows: ${h}`),(m=this.g)==null||m.call(this,new Ai(At.InvalidData,"Malformed JSON data in polling response"))};(t=this.t)==null||t.debug("Polling LaunchDarkly for feature flag updates");let c=Date.now();try{let h=await this.vi.requestPayload();try{if(this.u){pp(this.t);return}let p=JSON.parse(h);try{(e=this.Ei)==null||e.call(this,p)}catch(f){(n=this.t)==null||n.error(`Exception from data handler: ${f}`)}}catch(p){a(h)}}catch(h){if(this.u){pp(this.t);return}let p=h;if(p.status!==void 0&&!_i(p.status)){(r=this.t)==null||r.error(Gn(h,"polling request")),(i=this.g)==null||i.call(this,new Ai(At.ErrorResponse,p.message,p.status));return}(o=this.t)==null||o.error(Gn(h,"polling request","will retry"))}let l=Date.now()-c,u=Math.max(this.wi*1e3-l,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",l,u),this.Nt=setTimeout(()=>{this.ye()},u)}start(){this.ye()}stop(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0),this.u=!0}close(){this.stop()}},cI=(t,e,n,r)=>{n==null||n.error(`Stream received invalid data in "${t}" message`),n==null||n.debug(`Invalid JSON follows: ${e}`),r==null||r(new Wa(At.InvalidData,"Malformed JSON data in event stream"))};function uI(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function dp(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var hI=class{constructor(t,e,n,r,i,o,s,a,c){var l;this.Di=t,this.$t=e,this.n=n,this.V=r,this.bi=o,this.S=s,this.g=a,this.t=c,this.u=!1;let u;e.useReport&&!r.getEventSourceCapabilities().customMethod?u=e.paths.pathPing(i,t):u=e.useReport?e.paths.pathReport(i,t):e.paths.pathGet(i,t);let h=[...(l=e.queryParameters)!=null?l:[]];this.$t.withReasons&&h.push({key:"withReasons",value:"true"}),this.V=r,this.ve=st({},e.baseHeaders),this.t=c,this.ki=WS(e.serviceEndpoints,u,h)}we(){this.ut=Date.now()}Rt(t){this.ut&&this.S&&this.S.recordStreamInit(this.ut,!t,Date.now()-this.ut),this.ut=void 0}xi(t){var e,n,r;return Np(t)?((r=this.t)==null||r.warn(Gn(t,"streaming request","will retry")),this.Rt(!1),this.we(),!0):(this.Rt(!1),(e=this.g)==null||e.call(this,new Wa(At.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(Gn(t,"streaming request")),!1)}start(){this.we();let t;this.$t.useReport?(this.ve["content-type"]="application/json",t={method:"REPORT",body:this.Di}):t={};let e=this.V.createEventSource(this.ki,me(st({headers:this.ve},t),{errorFilter:n=>this.xi(n),initialRetryDelayMillis:this.$t.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.Ee=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var r;(r=this.t)==null||r.info(`Will retry stream connection in ${n.delayMillis} milliseconds`)},this.n.forEach(({deserializeData:n,processJson:r},i)=>{e.addEventListener(i,o=>{var s,a;if(this.u){uI(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),o!=null&&o.data){this.Rt(!0);let{data:c}=o,l=n(c);if(!l){cI(i,c,this.t,this.g);return}r(l)}else(a=this.g)==null||a.call(this,new Wa(At.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,r,i,o,s,a,c;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let l=await this.bi.requestPayload();try{if(this.u){dp(this.t);return}let u=JSON.parse(l);try{(r=this.n.get("put"))==null||r.processJson(u)}catch(h){(i=this.t)==null||i.error(`Exception from data handler: ${h}`)}}catch(u){(o=this.t)==null||o.error("Polling after ping received invalid data"),(s=this.t)==null||s.debug(`Invalid JSON follows: ${l}`),(a=this.g)==null||a.call(this,new Ai(At.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){dp(this.t);return}let u=l;(c=this.g)==null||c.call(this,new Ai(At.ErrorResponse,u.message,u.status))}})}stop(){var t;(t=this.Ee)==null||t.close(),this.Ee=void 0,this.u=!0}close(){this.stop()}},pI=class{constructor(t,e,n,r,i,o,s,a,c){this.platform=t,this.flagManager=e,this.credential=n,this.config=r,this.getPollingPaths=i,this.getStreamingPaths=o,this.baseHeaders=s,this.emitter=a,this.diagnosticsManager=c,this.closed=!1,this.logger=r.logger,this.dataSourceStatusManager=aI(a),this.K=sI(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Si=t}createPollingProcessor(t,e,n,r,i){let o=new lI(n,this.config.pollInterval,async s=>{await this.K.handlePut(e,s),r==null||r()},s=>{this.emitter.emit("error",t,s),this.K.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.De(o,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,i){var o;let s=new hI(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.Si)==null?void 0:o.queryParameters},this.createStreamListeners(e,r),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,a=>{this.emitter.emit("error",t,a),this.K.handleStreamingError(a),i==null||i(a)},this.logger);this.updateProcessor=this.De(s,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.K.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.K.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.K.handleDelete(t,r)}}),n}De(t,e){return{start:()=>{e.requestStateUpdate("INITIALIZING"),t.start()},stop:()=>{t.stop(),e.requestStateUpdate("CLOSED")},close:()=>{t.close(),e.requestStateUpdate("CLOSED")}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function Hi(){return typeof document!==void 0}function Ka(){return typeof window!==void 0}function qp(t,e,n){return Hi()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function td(t,e,n){return Hi()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function yr(){return Ka()?window.location.href:""}function dI(){return Ka()?window.location.search:""}function fI(){return Ka()?window.location.hash:""}function mI(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function yI(){return Hi()?document.visibilityState:"visibile"}function gI(t){if(Hi())return document.querySelectorAll(t)}var bI="[BrowserDataManager]",vI=class extends pI{constructor(t,e,n,r,i,o,s,a,c,l){super(t,e,n,r,o,s,a,c,l),this.Ui=i,this.Z=void 0,this.Mt=!1,this.Z=i.streaming}L(t,...e){this.logger.debug(`${bI} ${t}`,...e)}async identify(t,e,n,r){if(this.closed){this.L("Identify called after data manager was closed.");return}this.context=n;let i=r;i!=null&&i.hash?this.setConnectionParams({queryParameters:[{key:"h",value:i.hash}]}):this.setConnectionParams(),this.Ft=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.Li(n,i,t):(await this.flagManager.loadCached(n)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Ci(n,t,e)),this.Ut()}async Ii(t){let e=JSON.stringify(xn.toLDContext(t)),n=np(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ft),r=3,i;for(let o=0;o<=r;o+=1)try{return await n.requestPayload()}catch(s){if(!Np(s))throw s;i=s,o<r&&(this.L(Gn(s,"initial poll request","will retry")),await Op(1e3))}throw i}async Ci(t,e,n){var r,i;try{this.dataSourceStatusManager.requestStateUpdate(lw.Initializing);let o=await this.Ii(t);try{let s=this.createStreamListeners(t,e).get("put");s.processJson(s.deserializeData(o))}catch(s){this.dataSourceStatusManager.reportError(At.InvalidData,(r=s.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(At.NetworkError,(i=o.message)!=null?i:"unexpected network error",o.status),n(o)}}Li(t,e,n){let{bootstrapParsed:r}=e;r||(r=$p(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,r),this.L("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.Z=t,this.Ut()}setAutomaticStreamingState(t){this.Mt=t,this.Ut()}Ut(){let t=this.Z||this.Mt&&this.Z===void 0;this.L(`Updating streaming state. forced(${this.Z}) automatic(${this.Mt})`),t?this.Oi():this.Ai()}Ai(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}Oi(){if(this.updateProcessor){this.L("Update processor already active. Not changing state.");return}if(!this.context){this.L("Context not set, not starting update processor.");return}this.L("Starting update processor."),this.Pi(this.context)}Pi(t,e,n){var r;let i=xn.toLDContext(t);(r=this.updateProcessor)==null||r.close();let o=JSON.stringify(xn.toLDContext(t)),s=np(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ft);this.createStreamingProcessor(i,t,s,e,n),this.updateProcessor.start()}};function SI(t){let e=qp("visibilitychange",()=>{yI()==="hidden"&&t()}),n=td("pagehide",t);return()=>{e(),n()}}function Oa(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function wI(t,e,n,r){let i=((t.kind==="substring"||t.kind==="regex")&&r.includes("/")?e:e.replace(r,"")).replace(n,"");switch(t.kind){case"exact":return new RegExp(`^${Oa(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${Oa(t.url)}/?$`).test(i);case"substring":return new RegExp(`.*${Oa(t.substring)}.*$`).test(i);case"regex":return new RegExp(t.pattern).test(i);default:return!1}}function II(t,e){let n=[];return e.forEach(r=>{let i=t.target,{selector:o}=r,s=gI(o);for(;i&&s!=null&&s.length;){for(let a=0;a<s.length;a+=1)if(i===s[a]){n.push(r);break}i=i.parentNode}}),n}var TI=class{constructor(t,e){let n=t.filter(o=>{var s;return(s=o.urls)==null?void 0:s.some(a=>wI(a,yr(),dI(),fI()))}),r=n.filter(o=>o.kind==="pageview"),i=n.filter(o=>o.kind==="click");if(r.forEach(o=>e(o)),i.length){let o=s=>{II(s,i).forEach(a=>{e(a)})};this.be=qp("click",o)}}close(){var t;(t=this.be)==null||t.call(this)}},EI=300,RI=class{constructor(t){this.Vt=yr();let e=()=>{let r=yr();r!==this.Vt&&(this.Vt=r,t())};this.jt=setInterval(e,EI);let n=td("popstate",e);this.ke=()=>{n()}}close(){var t;this.jt&&clearInterval(this.jt),(t=this.ke)==null||t.call(this)}},CI=class{constructor(t,e,n,r,i,o=s=>new RI(s)){this.V=e,this.$i=r,this.Ni=i,this.ht=[],this.Se=!1,this.dt=`${n}/sdk/goals/${t}`,this.xe=o(()=>{this.Bt()})}async initialize(){await this.Ti(),this.Bt()}startTracking(){this.Se=!0,this.Bt()}Bt(){var t;this.Se&&((t=this.Ht)==null||t.close(),this.ht&&this.ht.length&&(this.Ht=new TI(this.ht,e=>{this.Ni(yr(),e)})))}async Ti(){try{let t=await this.V.fetch(this.dt);this.ht=await t.json()}catch(t){this.$i(new kp(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.xe)==null||t.close(),(e=this.Ht)==null||e.close()}};function ZI(t){return t.kind==="click"}var kI=2,ed={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},VI={fetchGoals:G.Boolean,eventUrlTransformer:G.Function,streaming:G.Boolean,plugins:G.createTypeArray("LDPlugin",{})};function xI(t){var e;let n=st({},t);return(e=n.flushInterval)!=null||(n.flushInterval=kI),n}function NI(t){let e=xI(t);return Object.keys(ed).forEach(n=>{delete e[n]}),e}function OI(t,e){let n=st({},ed);return Object.entries(VI).forEach(r=>{let[i,o]=r,s=t[i];s!==void 0&&(o.is(s)?n[i]=s:e.warn(Ue.wrongOptionType(i,o.getType(),typeof s)))}),n}var GI=class{constructor(t,e){switch(this.Ri=t,this.Le=[],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.Le.join(""),n=new TextEncoder().encode(e),r=await this.Ri.subtle.digest(this.zt,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(r)));case"hex":return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Le.push(t),this}},LI={start:0,end:3},XI={start:4,end:5},Ga={start:6,end:7},La={start:8,end:8},WI={start:9,end:9},UI={start:10,end:15};function PI(){if(crypto&&crypto.getRandomValues){let e=new Uint8Array(16);return crypto.getRandomValues(e),[...e.values()]}let t=[];for(let e=0;e<16;e+=1)t.push(Math.floor(Math.random()*256));return t}function kn(t,e){let n="";for(let r=e.start;r<=e.end;r+=1)n+=t[r].toString(16).padStart(2,"0");return n}function MI(t){return t[La.start]=(t[La.start]|128)&191,t[Ga.start]=t[Ga.start]&15|64,`${kn(t,LI)}-${kn(t,XI)}-${kn(t,Ga)}-${kn(t,La)}${kn(t,WI)}-${kn(t,UI)}`}function FI(){let t=PI();return MI(t)}function AI(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():FI()}var JI=class{createHash(t){return new GI(mI(),t)}randomUUID(){return AI()}};function DI(t){let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e)}var YI=class{btoa(t){return DI(new TextEncoder().encode(t))}},KI=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"4.2.0",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},_I=class{constructor(t,e){this.dt=t,this.n={},this.I=new RS(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Ce=e.errorFilter,this.Ie()}Ie(){this._=new EventSource(this.dt),this._.onopen=()=>{var t;this.I.success(),(t=this.onopen)==null||t.call(this)},this._.onerror=t=>{var e;this.Mi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this._)==null||r.addEventListener(t,n)})})}addEventListener(t,e){var n,r,i;(r=(n=this.n)[t])!=null||(n[t]=[]),this.n[t].push(e),(i=this._)==null||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Gt),this.Gt=void 0,(t=this._)==null||t.close(),(e=this.onclose)==null||e.call(this)}Fi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Gt=setTimeout(()=>{this.Ie()},t)}Mi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Ce(t))&&this.Fi(this.I.fail())}},HI=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new _I(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function nd(){return typeof localStorage!="undefined"}function zI(){if(!nd())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);n&&t.push(n)}return t}var BI=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{let n=localStorage.getItem(t);return n!=null?n:null}catch(n){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(r){(n=this.t)==null||n.error(`Error setting key in localStorage: ${t}, reason: ${r}`)}}},jI=class{constructor(t,e){this.encoding=new YI,this.crypto=new JI,this.requests=new HI,nd()&&(this.storage=new BI(t)),this.info=new KI(e)}},QI=class extends iI{constructor(t,e,n={},r){var i;let{logger:o,debug:s}=n,a=o!=null?o:new Fa({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:s?"debug":"info"}),c=(i=n.baseUri)!=null?i:"https://clientsdk.launchdarkly.com",l=r!=null?r:new jI(a,n),u=OI(n,a),h=NI(me(st({},n),{logger:a})),{eventUrlTransformer:p}=u;super(t,e,l,h,(f,m,d,v,g)=>new vI(l,f,t,m,u,()=>({pathGet(S,T){return`/sdk/evalx/${t}/contexts/${$h(T,S)}`},pathReport(S,T){return`/sdk/evalx/${t}/context`},pathPing(S,T){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(S,T){return`/eval/${t}/${$h(T,S)}`},pathReport(S,T){return`/eval/${t}`},pathPing(S,T){return`/ping/${t}`}}),d,v,g),{getLegacyStorageKeys:()=>zI().filter(f=>f.startsWith(`ld:${t}:`)),analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:f=>new de.InputCustomEvent(f.context,f.key,f.data,f.metricValue,f.samplingRatio,p(yr())),getImplementationHooks:f=>de.safeGetHooks(a,f,u.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.yo=u.plugins,u.fetchGoals&&(this.Kt=new CI(t,l.requests,c,f=>{a.error(f.message)},(f,m)=>{let d=this.getInternalContext();if(!d)return;let v=p(f);ZI(m)?this.sendEvent({kind:"click",url:v,samplingRatio:1,key:m.key,creationDate:Date.now(),context:d,selector:m.selector}):this.sendEvent({kind:"pageview",url:v,samplingRatio:1,key:m.key,creationDate:Date.now(),context:d})}),this.Kt.initialize(),u.automaticBackgroundHandling&&SI(()=>this.flush()))}registerPlugins(t){de.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.yo||[]);let e=this.getDebugOverrides();e&&oI(this.logger,e,this.yo||[])}setInitialContext(t){this.Wt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var n;if(!this.X)return this.logger.error("Client must be started before it can identify a context, did you forget to call start()?"),{status:"error",error:new Error("Identify called before start")};let r=st({},e);(e==null?void 0:e.sheddable)===void 0&&(r.sheddable=!0);let i=await super.identifyResult(t,r);return(n=this.Kt)==null||n.startTracking(),i}start(t){var e,n;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.X)return this.X;if(!this.Wt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let r=me(st({},(e=t==null?void 0:t.identifyOptions)!=null?e:{}),{sheddable:!1});if(t!=null&&t.bootstrap&&!r.bootstrap&&(r.bootstrap=t.bootstrap),r!=null&&r.bootstrap)try{r.bootstrapParsed||(r.bootstrapParsed=$p(this.logger,r.bootstrap)),this.presetFlags(r.bootstrapParsed)}catch(i){this.logger.error("Failed to bootstrap data",i)}return this.initializedPromise||(this.initializedPromise=new Promise(i=>{this.initResolve=i})),this.X=this.promiseWithTimeout(this.initializedPromise,(n=t==null?void 0:t.timeout)!=null?n:5),this.identifyResult(this.Wt,r),this.X}setStreaming(t){this.dataManager.setForcedStreaming(t)}Oe(){let t=this.dataManager,e=this.emitter.eventNames().some(n=>n.startsWith("change:")||n==="change");t.setAutomaticStreamingState(e)}on(t,e){super.on(t,e),this.Oe()}off(t,e){super.off(t,e),this.Oe()}};function $I(t,e,n,r={},i){let o=new QI(t,n,r,i);o.setInitialContext(e);let s={variation:(a,c)=>o.variation(a,c),variationDetail:(a,c)=>o.variationDetail(a,c),boolVariation:(a,c)=>o.boolVariation(a,c),boolVariationDetail:(a,c)=>o.boolVariationDetail(a,c),numberVariation:(a,c)=>o.numberVariation(a,c),numberVariationDetail:(a,c)=>o.numberVariationDetail(a,c),stringVariation:(a,c)=>o.stringVariation(a,c),stringVariationDetail:(a,c)=>o.stringVariationDetail(a,c),jsonVariation:(a,c)=>o.jsonVariation(a,c),jsonVariationDetail:(a,c)=>o.jsonVariationDetail(a,c),track:(a,c,l)=>o.track(a,c,l),on:(a,c)=>o.on(a,c),off:(a,c)=>o.off(a,c),flush:()=>o.flush(),setStreaming:a=>o.setStreaming(a),identify:(a,c)=>o.identifyResult(a,c),getContext:()=>o.getContext(),close:()=>o.close(),allFlags:()=>o.allFlags(),addHook:a=>o.addHook(a),waitForInitialization:a=>o.waitForInitialization(a),logger:o.logger,start:a=>o.start(a)};return o.registerPlugins(s),s}function qI(t){return new Fa(t)}function rd(t,e,n){return $I(t,e,Ji.Disabled,n)}var tT=Object.defineProperty,eT=(t,e,n)=>e in t?tT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Te=(t,e,n)=>eT(t,typeof e!="symbol"?e+"":e,n),nT=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{a(n.next(c))}catch(l){i(l)}},s=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,s);a((n=n.apply(t,e)).next())}),ke=(t,e,...n)=>{let r=`[@launchdarkly plugins]: (${t}): `;console[e].apply(console,[r,...n]),rT(r,...n)},rT=(t,...e)=>nT(void 0,null,function*(){try{let{LDObserve:n}=yield Promise.resolve().then(()=>lR);n.recordLog(`${t}${e}`,"warn")}catch(n){}}),iT=class{constructor(t,e){Te(this,"debug"),Te(this,"name"),this.debug=t,this.name=e}log(...t){if(this.debug){let e=`[${Date.now()}]`;this.name&&(e+=` - ${this.name}`),console.log.apply(console,[e,...t])}}warn(...t){let e=`[${Date.now()}]`;this.name&&(e+=` - ${this.name}`),console.warn.apply(console,[e,...t])}},So=class{constructor(){Te(this,"_sdk"),Te(this,"_isLoaded",!1),Te(this,"_callBuffer",[]),Te(this,"_capacity",1e5),Te(this,"_droppedEvents",0),Te(this,"_exceededCapacity",!1),Te(this,"_logger",new iT)}h(e,n){if(this.Nn)try{return this.jn[e](...n)}catch(r){ke(`Error executing buffered call to ${e}:`,"error",r)}else{this.Pr({method:e,args:n});return}}Pr(e){this.wn.length<this.Is?(this.wn.push(e),this.Qn=!1):(this.Qn||(this.Qn=!0,ke("Exceeded event queue capacity. Increase capacity to avoid dropping events.","warn")),this.Ts+=1)}load(e){this.jn=e,this.Nn=!0;for(let{method:n,args:r}of this.wn)try{this.jn[n](...r)}catch(i){ke(`Error executing buffered call to ${n}:`,"error",i)}this.wn=[]}},oT=Object.defineProperty,sT=Object.defineProperties,aT=Object.getOwnPropertyDescriptors,wo=Object.getOwnPropertySymbols,Af=Object.prototype.hasOwnProperty,Jf=Object.prototype.propertyIsEnumerable,kl=(t,e,n)=>e in t?oT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,j=(t,e)=>{for(var n in e||(e={}))Af.call(e,n)&&kl(t,n,e[n]);if(wo)for(var n of wo(e))Jf.call(e,n)&&kl(t,n,e[n]);return t},An=(t,e)=>sT(t,aT(e)),xr=(t,e)=>{var n={};for(var r in t)Af.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&wo)for(var r of wo(t))e.indexOf(r)<0&&Jf.call(t,r)&&(n[r]=t[r]);return n},Wr=(t,e,n)=>kl(t,typeof e!="symbol"?e+"":e,n),Dn=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{a(n.next(c))}catch(l){i(l)}},s=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,s);a((n=n.apply(t,e)).next())});function lT(t,e){for(var n=0;n<e.length;n++){let r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(let i in r)if(i!=="default"&&!(i in t)){let o=Object.getOwnPropertyDescriptor(r,i);o&&Object.defineProperty(t,i,o.get?o:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}function co(t,e){throw new Error(e)}function cT(t){return typeof t=="object"&&t!==null}function uT(t,e){throw new Error("Unexpected invariant triggered.")}var hT=/\r\n|[\n\r]/g;function Vl(t,e){let n=0,r=1;for(let i of t.body.matchAll(hT)){if(typeof i.index=="number"||uT(),i.index>=e)break;n=i.index+i[0].length,r+=1}return{line:r,column:e+1-n}}function pT(t){return Df(t.source,Vl(t.source,t.start))}function Df(t,e){let n=t.locationOffset.column-1,r="".padStart(n)+t.body,i=e.line-1,o=t.locationOffset.line-1,s=e.line+o,a=e.line===1?n:0,c=e.column+a,l=`${t.name}:${s}:${c}
348
+ SessionSecureID: ${this.sessionData.sessionSecureID}`);let s=FF();n?yield n({session_secure_id:this.sessionData.sessionSecureID,payload_id:(this.sessionData.payloadID++).toString(),events:{events:r},messages:QL({messages:[]}),resources:JSON.stringify({resources:[]}),web_socket_events:JSON.stringify({webSocketEvents:[]}),errors:[],is_beacon:!1,has_session_unloaded:this.hasSessionUnloaded,highlight_logs:s||void 0}):this.zn.postMessage({message:{type:Ne.AsyncEvents,id:this.sessionData.payloadID++,events:r,messages:[],errors:[],resourcesString:JSON.stringify({resources:[]}),webSocketEventsString:JSON.stringify({webSocketEvents:[]}),hasSessionUnloaded:this.hasSessionUnloaded,highlightLogs:s}}),In(this.sessionData),this.events=this.events.slice(r.length),AF(s)})}takeFullSnapshot(){if(!this.Sn){this.logger.log("skipping full snapshot as rrweb is not running");return}this.logger.log("taking full snapshot",{bytesSinceSnapshot:this.br,lastSnapshotTime:this.mo}),Ge.takeFullSnapshot(),this.br=0,this.mo=new Date().getTime()}register(e,n){this.xn.push(new pu(e,n))}getHooks(e){return this.xn.flatMap(n=>{var r,i;return(i=(r=n.getHooks)==null?void 0:r.call(n,e))!=null?i:[]})}getRecordingState(){var e;return(e=this==null?void 0:this.state)!=null?e:"NotRecording"}getSession(){let e=this.sessionData.sessionSecureID,n=ks(e);if(!n)return null;let r=`${this.getFrontendUrl()}/sessions/${e}`;if(!r||!(n!=null&&n.sessionStartTime))return null;let i=new Date().getTime(),o=new URL(r),s=new URL(r),a=(i-this.Bn)/1e3;return s.searchParams.set("ts",a.toString()),{url:o.toString(),urlWithTimestamp:s.toString(),sessionSecureID:e}}getFrontendUrl(){var e,n;let r=this.pn.match(EX);if(r&&(e=r==null?void 0:r.groups)!=null&&e.domain){let i=(n=r.groups.domain)!=null?n:"";return`https://${IX[i]}${TX}`}return wX}},Ci=class extends BX{constructor(e,n){var r=(...f)=>(super(...f),Y(this,"record"),this),i,o,s,a,c,l,u,h,p;try{if(r(n),typeof window>"u"||typeof document>"u"){console.warn("@launchdarkly/session-replay is not initializing because it is not supported in this environment.");return}if(typeof Worker>"u"){console.warn("@launchdarkly/session-replay is not initializing because Worker is not supported.");return}if(!e){console.warn("@launchdarkly/session-replay is not initializing because projectID was passed undefined.");return}let f=Kt(z({},n),{organizationID:e,firstloadVersion:HF,environment:(n==null?void 0:n.environment)||"production",appVersion:n==null?void 0:n.version,sessionSecureID:this.sessionSecureID,privacySetting:(i=n==null?void 0:n.privacySetting)!=null?i:"strict"});this.record=new oh(f),n!=null&&n.manualStart||this.record.start(),Be.load(this.record),!((s=(o=n==null?void 0:n.integrations)==null?void 0:o.mixpanel)!=null&&s.disabled)&&(c=(a=n==null?void 0:n.integrations)==null?void 0:a.mixpanel)!=null&&c.projectToken&&KF(n.integrations.mixpanel),!((u=(l=n==null?void 0:n.integrations)==null?void 0:l.amplitude)!=null&&u.disabled)&&(p=(h=n==null?void 0:n.integrations)==null?void 0:h.amplitude)!=null&&p.apiKey&&YF(n.integrations.amplitude)}catch(f){Ht("Error initializing @launchdarkly/session-replay SDK","error",f)}}getMetadata(){return{name:"@launchdarkly/session-replay"}}register(e,n){var r;(r=this.record)==null||r.register(e,n)}getHooks(e){return[{getMetadata:()=>({name:"@launchdarkly/session-replay/hooks"}),afterIdentify:(n,r,i)=>{var o,s,a,c,l,u,h;for(let p of(a=(s=(o=this.record)==null?void 0:o.getHooks)==null?void 0:s.call(o,e))!=null?a:[])(c=p.afterIdentify)==null||c.call(p,n,r,i);if(i.status==="completed"){let p=DX(n.context),f=YX(n.context);(h=this.record)==null||h.identify(typeof f=="string"?f:(u=(l=f.user)==null?void 0:l.toString())!=null?u:p,Kt(z({key:p},typeof f=="object"?f:{}),{timeout:n.timeout}),"LaunchDarkly")}return r},afterEvaluation:(n,r,i)=>{var o,s,a,c;for(let l of(a=(s=(o=this.record)==null?void 0:o.getHooks)==null?void 0:s.call(o,e))!=null?a:[])(c=l.afterEvaluation)==null||c.call(l,n,r,i);return r},afterTrack:n=>{var r,i,o,s,a;for(let c of(o=(i=(r=this.record)==null?void 0:r.getHooks)==null?void 0:i.call(r,e))!=null?o:[])(s=c.afterTrack)==null||s.call(c,n);(a=this.record)==null||a.track(n.key,{data:n.data,value:n.metricValue})}}]}}});var BF={};Yh(BF,{LDObserve:()=>De,LDRecord:()=>Be,basicLogger:()=>qI,createClient:()=>zF});module.exports=nS(BF);var rS=Object.defineProperty,iS=Object.defineProperties,oS=Object.getOwnPropertyDescriptors,Mi=Object.getOwnPropertySymbols,fp=Object.prototype.hasOwnProperty,mp=Object.prototype.propertyIsEnumerable,Kh=(t,e,n)=>e in t?rS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,st=(t,e)=>{for(var n in e||(e={}))fp.call(e,n)&&Kh(t,n,e[n]);if(Mi)for(var n of Mi(e))mp.call(e,n)&&Kh(t,n,e[n]);return t},me=(t,e)=>iS(t,oS(e)),yp=(t,e)=>{var n={};for(var r in t)fp.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&Mi)for(var r of Mi(t))e.indexOf(r)<0&&mp.call(t,r)&&(n[r]=t[r]);return n};function sS(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function gp(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function aS(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>gp(e))}function lS(t){return!t.startsWith("/")}function cS(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var Nn=class{constructor(t,e=!1){if(e){let n=t;this.m=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?sS(n):n}else{if(this.redactionName=t,t===""||t==="/"||!cS(t)){this.isValid=!1,this.m=[];return}lS(t)?this.m=[t]:t.indexOf("/",1)<0?this.m=[gp(t.slice(1))]:this.m=aS(t),this.m[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{m:e,isValid:n}=this;if(!n)return;let r=t;for(let i=0;i<e.length;i+=1){let o=e[i];if(r!=null&&Object.prototype.hasOwnProperty.call(r,o)&&typeof r=="object"&&!Array.isArray(r))r=r[o];else return}return r}getComponent(t){return this.m[t]}get depth(){return this.m.length}get isKind(){return this.m.length===1&&this.m[0]==="kind"}compare(t){return this.depth===t.depth&&this.m.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.m]}};Nn.InvalidReference=new Nn("");var uS=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},Ln=class{constructor(t,e){this.ft=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.ft}},bp=class{constructor(t,e){this.ft=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.ft}},vp=class extends Ln{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},Sp=class extends Ln{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},hS=class{is(t){return typeof t=="function"}getType(){return"function"}},pS=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},dS=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,fS=class{is(t){return typeof t=="number"||typeof t=="string"&&dS.test(t)}getType(){return"date"}},mS=class extends Sp{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},G=class{static createTypeArray(t,e){return new bp(t,e)}static numberWithMin(t){return new vp(t)}static stringMatchingRegex(t){return new Sp(t)}};G.String=new Ln("string","");G.Number=new Ln("number",0);G.ObjectOrFactory=new uS;G.Object=new Ln("object",{});G.StringArray=new bp("string[]","");G.Boolean=new Ln("boolean",!0);G.Function=new hS;G.Date=new fS;G.Kind=new mS;G.NullableBoolean=new pS;function wp(t){return"kind"in t?G.String.is(t.kind)&&t.kind!=="multi":!1}function Ip(t){return"kind"in t?G.String.is(t.kind)&&t.kind==="multi":!1}function Tp(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function Fi(t,e=[]){if(t===null||typeof t!="object")return JSON.stringify(t);if(e.includes(t))throw new Error("Cycle detected");return Array.isArray(t)?`[${t.map(n=>Fi(n,[...e,t])).map(n=>n===void 0?"null":n).join(",")}]`:`{${Object.keys(t).sort().map(n=>{let r=Fi(t[n],[...e,t]);if(r!==void 0)return`${JSON.stringify(n)}:${r}`}).filter(n=>n!==void 0).join(",")}}`}var Xa="user";function _h(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function yS(t){return t&&G.Object.is(t)}function Hh(t){return G.Kind.is(t)}function zh(t){return G.String.is(t)&&t!==""}function Ca(t,e=!1){return t?t.map(n=>new Nn(n,e)):[]}function gS(t){return t!=null}function bS(t){let e=me(st({},t.custom||[]),{kind:"user",key:String(t.key)});if(gS(t.anonymous)){let n=!!t.anonymous;delete e.anonymous,e.anonymous=n}return t.name!==null&&t.name!==void 0&&(e.name=t.name),t.ip!==null&&t.ip!==void 0&&(e.ip=t.ip),t.firstName!==null&&t.firstName!==void 0&&(e.firstName=t.firstName),t.lastName!==null&&t.lastName!==void 0&&(e.lastName=t.lastName),t.email!==null&&t.email!==void 0&&(e.email=t.email),t.avatar!==null&&t.avatar!==void 0&&(e.avatar=t.avatar),t.country!==null&&t.country!==void 0&&(e.country=t.country),t.privateAttributeNames!==null&&t.privateAttributeNames!==void 0&&(e._meta={privateAttributes:t.privateAttributeNames}),e}var xn=class wt{constructor(e,n,r){this.C=!1,this.Q=!1,this.qt=!1,this.N={},this.kind=n,this.valid=e,this.message=r}static b(e,n){return new wt(!1,e,n)}static Ae(e,n){if(!(!n||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(n!=null&&n.anonymous):e.get(n)}Jt(e){if(this.C)return this.N[e];if(this.kind===e)return this.y}static Pe(e){let n=Object.keys(e).filter(c=>c!=="kind"),r=n.every(Hh);if(!n.length)return wt.b("multi","A multi-kind context must contain at least one kind");if(!r)return wt.b("multi","Context contains invalid kinds");let i={},o=!0,s=n.reduce((c,l)=>{var u;let h=e[l];return yS(h)?(c[l]=h,i[l]=Ca((u=h._meta)==null?void 0:u.privateAttributes)):o=!1,c},{});if(!o)return wt.b("multi","Context contained contexts that were not objects");if(!Object.values(s).every(c=>zh(c.key)))return wt.b("multi","Context contained invalid keys");if(n.length===1){let c=n[0],l=new wt(!0,c);return l.y=me(st({},s[c]),{kind:c}),l.tt=i,l.Q=c==="user",l}let a=new wt(!0,e.kind);return a.N=s,a.tt=i,a.C=!0,a}static Te(e){var n;let{key:r,kind:i}=e,o=Hh(i),s=zh(r);if(!o)return wt.b(i!=null?i:"unknown","The kind was not valid for the context");if(!s)return wt.b(i,"The key for the context was not valid");let a=Ca((n=e._meta)==null?void 0:n.privateAttributes),c=new wt(!0,i);return c.Q=i==="user",c.y=e,c.tt={[i]:a},c}static Ne(e){if(!(e.key!==void 0&&e.key!==null))return wt.b("user","The key for the context was not valid");let n=new wt(!0,"user");return n.Q=!0,n.qt=!0,n.y=bS(e),n.tt={user:Ca(e.privateAttributeNames,!0)},n}static fromLDContext(e){return e?wp(e)?wt.Te(e):Ip(e)?wt.Pe(e):Tp(e)?wt.Ne(e):wt.b("unknown","Context was not of a valid kind"):wt.b("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;let n=e.getContexts();if(!e.C)return n[0][1];let r={kind:"multi"};return n.forEach(i=>{let o=i[0],s=i[1];r[o]=s}),r}valueForKind(e,n=Xa){return e.isKind?this.kinds:wt.Ae(e,this.Jt(n))}key(e=Xa){var n;return(n=this.Jt(e))==null?void 0:n.key}get isMultiKind(){return this.C}get canonicalKey(){return this.Q?this.y.key:this.C?Object.keys(this.N).sort().map(e=>`${e}:${_h(this.N[e].key)}`).join(":"):`${this.kind}:${_h(this.y.key)}`}get kinds(){return this.C?Object.keys(this.N):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.N).reduce((e,[n,r])=>(e[n]=r.key,e),{}):{[this.kind]:this.y.key}}privateAttributes(e){var n;return((n=this.tt)==null?void 0:n[e])||[]}getContexts(){return this.C?Object.entries(this.N):[[this.kind,this.y]]}get legacy(){return this.qt}canonicalUnfilteredJson(){if(this.valid){if(this.pt)return this.pt;try{this.pt=Fi(wt.toLDContext(this))}catch(e){}return this.pt}}};xn.UserKind=Xa;var vS=["key","kind","_meta","anonymous"].map(t=>new Nn(t,!0)),SS=["name","ip","firstName","lastName","email","avatar","country"];function wS(t,e){return t.depth===e.length&&e.every((n,r)=>n===t.getComponent(r))}function IS(t,e){let n=[],r={},i=[];for(n.push(...Object.keys(t).map(o=>({key:o,ptr:[o],source:t,parent:r,visited:[t]})));n.length;){let o=n.pop(),s=e.find(a=>wS(a,o.ptr));if(s)i.push(s.redactionName);else{let a=o.source[o.key];a===null?o.parent[o.key]=a:Array.isArray(a)?o.parent[o.key]=[...a]:typeof a=="object"?o.visited.includes(a)||(o.parent[o.key]={},n.push(...Object.keys(a).map(c=>({key:c,ptr:[...o.ptr,c],source:a,parent:o.parent[o.key],visited:[...o.visited,a]})))):o.parent[o.key]=a}}return{cloned:r,excluded:i.sort()}}var TS=class{constructor(t,e){this.$e=t,this.Re=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.Yt(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([i,o])=>{r[i]=this.Yt(t,o,i,e)}),r}Me(t,e,n,r){return(r?Object.keys(e).map(i=>new Nn(i,!0)):[...this.Re,...t.privateAttributes(n)]).filter(i=>!vS.some(o=>o.compare(i)))}Yt(t,e,n,r){let i=this.$e||r&&e.anonymous===!0,{cloned:o,excluded:s}=IS(e,this.Me(t,e,n,i));return t.legacy&&SS.forEach(a=>{a in o&&(o[a]=String(o[a]))}),s.length&&(o._meta||(o._meta={}),o._meta.redactedAttributes=s),o._meta&&(delete o._meta.privateAttributes,Object.keys(o._meta).length===0&&delete o._meta),o}},Bh=30*1e3,ES=.5,RS=class{constructor(t,e,n=Math.random){this.Fe=e,this.Ue=n,this.gt=0,this.Zt=Math.max(1,t),this.Ve=Math.ceil(Math.log2(Bh/this.Zt))}I(){let t=Math.min(this.gt,this.Ve),e=this.Zt*2**t;return Math.min(e,Bh)}je(t){return t-Math.trunc(this.Ue()*ES*t)}success(t=Date.now()){this.mt=t}fail(t=Date.now()){this.mt!==void 0&&t-this.mt>this.Fe&&(this.gt=0),this.mt=void 0;let e=this.je(this.I());return this.gt+=1,e}},jh;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(jh||(jh={}));var Ai=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},Wa=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},QF=120*1e3,$F=300*1e3,At;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(At||(At={}));var Ji;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(Ji||(Ji={}));var On;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(On||(On={}));var en;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(en||(en={}));function Vn(t){if(typeof t=="string")return t;if(t===void 0)return"undefined";if(t===null)return"null";if(Object.prototype.hasOwnProperty.call(t,"toString"))try{return t.toString()}catch(e){}if(typeof t=="bigint")return`${t}n`;try{return JSON.stringify(t)}catch(e){return e instanceof TypeError&&e.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function CS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function ZS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function kS(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var Za={s:t=>Vn(t),d:t=>CS(t),i:t=>ZS(t),f:t=>kS(t),j:t=>Vn(t),o:t=>Vn(t),O:t=>Vn(t),c:()=>""};function Ua(...t){var e;let n=t.shift();if(G.String.is(n)){let r="",i=0;for(;i<n.length;){let o=n.charAt(i);if(o==="%"){if(i+1<n.length){let s=n.charAt(i+1);if(s in Za&&t.length){let a=t.shift();r+=(e=Za[s])==null?void 0:e.call(Za,a)}else s==="%"?r+="%":r+=`%${s}`;i+=2}}else r+=o,i+=1}return t.length&&(r.length&&(r+=" "),r+=t.map(Vn).join(" ")),r}return t.map(Vn).join(" ")}var Vt;(function(t){t[t.debug=0]="debug",t[t.info=1]="info",t[t.warn=2]="warn",t[t.error=3]="error",t[t.none=4]="none"})(Vt||(Vt={}));var VS=["debug","info","warn","error","none"],Fa=class Ep{static get(){return new Ep({})}constructor(e){var n,r,i;if(this.qe=(r=Vt[(n=e.level)!=null?n:"info"])!=null?r:Vt.info,this.Je=(i=e.name)!=null?i:"LaunchDarkly",this.ie=e.formatter,typeof e.destination=="object")this.ne={[Vt.debug]:e.destination.debug,[Vt.info]:e.destination.info,[Vt.warn]:e.destination.warn,[Vt.error]:e.destination.error};else if(typeof e.destination=="function"){let{destination:o}=e;this.ne={[Vt.debug]:o,[Vt.info]:o,[Vt.warn]:o,[Vt.error]:o}}}Ye(...e){var n;try{return this.ie?(n=this.ie)==null?void 0:n.call(this,...e):Ua(...e)}catch(r){return Ua(...e)}}Ze(e,n){try{e(n)}catch(r){console.error(n)}}k(e,n){var r;if(e>=this.qe){let i=`${VS[e]}: [${this.Je}]`;try{let o=(r=this.ne)==null?void 0:r[e];o?this.Ze(o,`${i} ${this.Ye(...n)}`):console.error(...n)}catch(o){console.error(...n)}}}error(...e){this.k(Vt.error,e)}warn(...e){this.k(Vt.warn,e)}info(...e){this.k(Vt.info,e)}debug(...e){this.k(Vt.debug,e)}},xS={error:G.Function,warn:G.Function,info:G.Function,debug:G.Function},Rp=class{constructor(t,e){Object.entries(xS).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.Xe=e}k(t,e){try{this.t[t](...e)}catch(n){this.Xe[t](...e)}}error(...t){this.k("error",t)}warn(...t){this.k("warn",t)}info(...t){this.k("info",t)}debug(...t){this.k("debug",t)}},Cp=t=>{let e=new Fa({level:"info",destination:console.error,formatter:Ua});return t?new Rp(t,e):e},Ue=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,n){return`Config option "${t}" had invalid value of ${e}, using minimum of ${n} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,n){return`Config option "${t}" should be of type ${e}, got ${n}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},NS=/^(\w|\.|-)+$/,OS=G.stringMatchingRegex(NS),GS={is:(t,e)=>OS.is(t)?t.length>64?{valid:!1,message:Ue.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:Ue.invalidTagValue(e)}},LS=class{constructor(t){let e={},n=t==null?void 0:t.application,r=t==null?void 0:t.logger;n&&Object.entries(n).forEach(([o,s])=>{if(s!=null){let{valid:a,message:c}=GS.is(s,`application.${o}`);a?o==="versionName"?e["application-version-name"]=[s]:e[`application-${o}`]=[s]:r==null||r.warn(c)}});let i=Object.keys(e);i.length&&(this.value=i.sort().flatMap(o=>e[o].sort().map(s=>`${o}/${s}`)).join(" "))}},XS=class{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function ka(t){return t.replace(/\/+$/,"")}function Aa(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var Di=class Zp{constructor(e,n,r=Zp.DEFAULT_EVENTS,i="/bulk",o="/diagnostic",s=!0,a){this.streaming=ka(e),this.polling=ka(n),this.events=ka(r),this.analyticsEventPath=i,this.diagnosticEventPath=o,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}};Di.DEFAULT_EVENTS="https://events.launchdarkly.com";function Ja(t,e=[]){if(e.length===0)return t;let n=e.map(({key:r,value:i})=>`${r}=${i}`);return`${t}?${n.join("&")}`}function WS(t,e,n){let r=Aa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Ja(`${t.streaming}/${r}`,i)}function US(t,e,n=[]){let r=Aa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Ja(`${t.polling}/${r}`,i)}function Qh(t,e,n=[]){let r=Aa(e);return Ja(`${t.events}/${r}`,n)}var kp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},PS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Vp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function _i(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function MS(t){return t===413?!0:_i(t)}function FS(t,e){let n,r;return{promise:new Promise((i,o)=>{r=i,n=setTimeout(()=>{let s=`${e} timed out after ${t} seconds.`;o(new Vp(s))},t*1e3)}),cancel:()=>{r(),clearTimeout(n)}}}function xp(t){return t==null?t:JSON.parse(JSON.stringify(t))}function Va(t){return Math.trunc(t*1e3)}var AS=t=>JSON.stringify(t)==="{}",Da=(t,e)=>t&&Object.entries(t).reduce((n,[r,i])=>(i&&!AS(i)&&!(e!=null&&e.includes(r))&&(n[r]=typeof i=="object"?Da(i,e):i),n),{});function Ui(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;var n,r,i;if(Array.isArray(t)){if(n=t.length,n!=e.length)return!1;for(r=n;r--!==0;)if(!Ui(t[r],e[r]))return!1;return!0}if(t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(r of t.entries())if(!e.has(r[0]))return!1;for(r of t.entries())if(!Ui(r[1],e.get(r[0])))return!1;return!0}if(t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(r of t.entries())if(!e.has(r[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(n=t.length,n!=e.length)return!1;for(r=n;r--!==0;)if(t[r]!==e[r])return!1;return!0}if(t.constructor===RegExp)return t.source===e.source&&t.flags===e.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===e.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===e.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(e,i[r]))return!1;for(r=n;r--!==0;){var o=i[r];if(!Ui(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function JS(t,e,n,r=!0,i="user-agent"){let{userAgentBase:o,version:s,wrapperName:a,wrapperVersion:c}=e.sdkData(),l={[i]:`${o!=null?o:"NodeJSClient"}/${s}`};return r&&(l.authorization=t),a&&(l["x-launchdarkly-wrapper"]=c?`${a}/${c}`:a),n!=null&&n.value&&(l["x-launchdarkly-tags"]=n.value),l}function Gn(t,e,n){let r;t.status?r=`error ${t.status}${t.status===401?" (invalid SDK key)":""}`:r=`I/O error (${t.message||"unknown error"})`;let i=n!=null?n:"giving up permanently";return`Received ${r} for ${e} - ${i}`}function Np({status:t}){return t?_i(t):!0}var $h=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Op=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),DS=class{constructor(t,e,n){this.p=e,this.Qe=n,this.wt=[],this.re=Date.now(),this.se=this.re,this.ae={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var t,e,n;let r=this.p.info.sdkData(),i=this.p.info.platformData();return{kind:"diagnostic-init",id:this.ae,creationDate:this.re,sdk:r,configuration:this.Qe,platform:st({name:i.name,osArch:(t=i.os)==null?void 0:t.arch,osName:(e=i.os)==null?void 0:e.name,osVersion:(n=i.os)==null?void 0:n.version},i.additional||{})}}recordStreamInit(t,e,n){let r={timestamp:t,failed:e,durationMillis:n};this.wt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),i={kind:"diagnostic",id:this.ae,creationDate:r,dataSinceDate:this.se,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.wt};return this.wt=[],this.se=r,i}},Pa;(function(t){t.MalformedFlag="MALFORMED_FLAG",t.UserNotSpecified="USER_NOT_SPECIFIED",t.FlagNotFound="FLAG_NOT_FOUND",t.ClientNotReady="CLIENT_NOT_READY",t.WrongType="WRONG_TYPE"})(Pa||(Pa={}));var YS=Pa,Gp=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};Gp.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var KS=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:o}}=n,{crypto:s,requests:a}=r;this.ti=st({},e),this.oe=Qh(n.serviceEndpoints,i,[]),this.ei=Qh(n.serviceEndpoints,o,[]),this.V=a,this.ii=s}async et(t,e,n,r){let i={status:en.Succeeded},o=me(st({},this.ti),{"content-type":"application/json"});n&&(o["x-launchdarkly-payload-id"]=n,o["x-launchDarkly-event-schema"]="4");let s;try{let{status:a,headers:c}=await this.V.fetch(e,{headers:o,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),l=Date.parse(c.get("date")||"");if(l&&(i.serverTime=l),a<=204)return i;if(s=new kp(Gn({status:a,message:"some events were dropped"},"event posting")),!_i(a))return MS(a)?i.status=en.Failed:i.status=en.FailedAndMustShutDown,i.error=s,i}catch(a){s=a}return s&&!r?(i.status=en.Failed,i.error=s,i):(await Op(),this.et(t,this.oe,n,!1))}async sendEventData(t,e){let n=t===On.AnalyticsEvents?this.ii.randomUUID():void 0,r=t===On.AnalyticsEvents?this.oe:this.ei;return this.et(e,r,n,!0)}};function Yi(t){return t.kind==="feature"}function _S(t){return t.kind==="identify"}function HS(t){return t.kind==="migration_op"}var zS=class{constructor(t,e,n,r,i,o){this.count=t,this.key=e,this.value=n,this.version=i,this.variation=o,this.default=r}increment(){this.count+=1}};function BS(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Lp=class{constructor(t=!1,e){this.ni=t,this.x=e,this.W=0,this.it=0,this.nt={},this.rt={}}summarizeEvent(t){if(Yi(t)&&!t.excludeFromSummaries){this.y||(this.y=t.context);let e=BS(t),n=this.nt[e],r=this.rt[t.key];r||(r=new Set,this.rt[t.key]=r),t.context.kinds.forEach(i=>r.add(i)),n?n.increment():this.nt[e]=new zS(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.it&&(this.it=t.creationDate)}}getSummary(){var t;let e=Object.values(this.nt).reduce((r,i)=>{let o=r[i.key];o||(o={default:i.default,counters:[],contextKinds:[...this.rt[i.key]]},r[i.key]=o);let s={value:i.value,count:i.count};return i.variation!==void 0&&i.variation!==null&&(s.variation=i.variation),i.version!==void 0&&i.version!==null?s.version=i.version:s.unknown=!0,o.counters.push(s),r},{}),n={startDate:this.W,endDate:this.it,features:e,kind:"summary",context:this.y!==void 0&&this.ni?(t=this.x)==null?void 0:t.filter(this.y):void 0};return this.ri(),n}ri(){this.W=0,this.it=0,this.nt={},this.rt={}}},jS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},QS=class{constructor(t,e){this.x=t,this.t=e,this.q={}}summarizeEvent(t){var e;if(Yi(t)){let n=t.context.canonicalUnfilteredJson();if(!n){t.context.valid&&((e=this.t)==null||e.error("Unable to serialize context, likely the context contains a cycle."));return}let r=this.q[n];r||(this.q[n]=new Lp(!0,this.x),r=this.q[n]),r.summarizeEvent(t)}}getSummaries(){let t=this.q;return this.q={},Object.values(t).map(e=>e.getSummary())}};function Pi(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function $S(t){return t.getSummaries!==void 0}var qS=class{constructor(t,e,n,r,i,o=!0,s=!1){this.e=t,this.st=r,this.S=i,this.at=[],this.ce=0,this.Et=0,this.Dt=0,this.bt=!1,this.le=0,this.kt=!1,this.xt=null,this.si=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.ue=new KS(e,n),this.x=new TS(t.allAttributesPrivate,t.privateAttributes.map(a=>new Nn(a))),s?this.J=new QS(this.x,this.t):this.J=new Lp,o&&this.start()}start(){var t,e;if(((t=this.st)==null?void 0:t.flushInterval)!==void 0&&(this.xt=setInterval(()=>{var n;(n=this.st)==null||n.flush()},this.st.flushInterval*1e3)),this.ai=setInterval(async()=>{var n;try{await this.flush()}catch(r){(n=this.t)==null||n.debug(`Flush failed: ${r}`)}},this.e.flushInterval*1e3),this.S){let n=this.S.createInitEvent();this.he(n),this.de=setInterval(()=>{let r=this.S.createStatsEventAndReset(this.Et,this.Dt,this.le);this.Et=0,this.Dt=0,this.he(r)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}he(t){this.ue.sendEventData(On.DiagnosticEvent,t)}close(){clearInterval(this.ai),this.xt&&clearInterval(this.xt),this.de&&clearInterval(this.de)}async flush(){var t;if(this.kt)throw new jS("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 e=this.at;if(this.at=[],$S(this.J))this.J.getSummaries().forEach(n=>{Object.keys(n.features).length&&e.push(n)});else{let n=this.J.getSummary();Object.keys(n.features).length&&e.push(n)}e.length&&(this.le=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.et(e))}sendEvent(t){var e;if(this.kt)return;if(HS(t)){if(Pi(t.samplingRatio)){let a=me(st({},t),{context:t.context?this.x.filter(t.context):void 0});a.samplingRatio===1&&delete a.samplingRatio,this.ot(a)}return}this.J.summarizeEvent(t);let n=Yi(t),r=n&&t.trackEvents||!n,i=this.oi(t),o=_S(t),s=(e=this.st)==null?void 0:e.processContext(t.context);s||o||(this.Dt+=1),s&&!o&&this.ot(this.St({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),r&&Pi(t.samplingRatio)&&this.ot(this.St(t,!1)),i&&Pi(t.samplingRatio)&&this.ot(this.St(t,!0))}St(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.x.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}ot(t){var e;this.at.length<this.si?(this.at.push(t),this.bt=!1):(this.bt||(this.bt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.Et+=1)}oi(t){return Yi(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.ce&&t.debugEventsUntilDate>Date.now()}async et(t){let e=await this.ue.sendEventData(On.AnalyticsEvents,t);if(e.status===en.FailedAndMustShutDown&&(this.kt=!0),e.serverTime&&(this.ce=e.serverTime),e.error)throw e.error}},Xp=class{constructor(t,e,n,r,i=1,o){this.context=t,this.key=e,this.data=n,this.metricValue=r,this.samplingRatio=i,this.url=o,this.kind="custom",this.creationDate=Date.now(),this.context=t}},Ma=class{constructor(t,e,n,r,i,o,s,a,c,l,u,h,p=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=p,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=i,o!==void 0&&(this.version=o),s!==void 0&&(this.variation=s),a!==void 0&&(this.trackEvents=a),c!==void 0&&(this.prereqOf=c),l!==void 0&&(this.reason=l),u!==void 0&&(this.debugEventsUntilDate=u),h!==void 0&&(this.excludeFromSummaries=h)}},Wp=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},tw=class{close(){}async flush(){}sendEvent(){}},ew=class{constructor(t){this.Lt=t}evalEvent(t){var e;return new Ma(this.Lt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.Lt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new Ma(this.Lt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Wp(t,1)}customEvent(t,e,n,r,i=1){return new Xp(e,t,n!=null?n:void 0,r!=null?r:void 0,i)}},qh="FDv1Fallback";function nw(t){return{ci:t,fe:"",useSelector(e){return this.fe=e,this},processFullTransfer(e){let n=[{event:"server-intent",data:{payloads:[{id:qh,target:1,intentCode:"xfer-full",reason:"payload-missing"}]}}];Object.entries((e==null?void 0:e.flags)||[]).forEach(([r,i])=>{n.push({event:"put-object",data:{kind:"flag",key:r,version:i.version||1,object:i}})}),Object.entries((e==null?void 0:e.segments)||[]).forEach(([r,i])=>{n.push({event:"put-object",data:{kind:"segment",key:r,version:i.version||1,object:i}})}),n.push({event:"payload-transferred",data:{state:this.fe,version:1,id:qh}}),this.ci.processEvents(n)}}}var pe={type:"none"};function Up(t,e){let n="inactive",r,i="partial",o=[];function s(g,S){var T;return(T=t[g])==null?void 0:T.call(t,S)}function a(){n="inactive",r=void 0,i="partial",o=[]}function c(){n="changes",i="partial",o=[]}function l(){o=[]}function u(g){return!g.id||!g.target?pe:{type:"payload",payload:{id:g.id,version:g.target,type:"none",updates:[]}}}function h(g){var S;if(!((S=g.payloads)!=null&&S.length))return{type:"error",kind:"MISSING_PAYLOAD",message:"No payload present in server-intent"};let T=g.payloads[0];switch(T==null?void 0:T.intentCode){case"xfer-full":return n="full",o=[],i="full",r=T.id,pe;case"xfer-changes":return n="changes",o=[],i="partial",r=T.id,pe;case"none":return n="changes",o=[],i="partial",r=T.id,u(T);default:return e==null||e.warn(`Unable to process intent code '${T==null?void 0:T.intentCode}'.`),pe}}function p(g){if(n==="inactive"||!r||!g.kind||!g.key||!g.version||!g.object)return pe;let S=s(g.kind,g.object);return S?(o.push({kind:g.kind,key:g.key,version:g.version,object:S}),pe):(e==null||e.warn(`Unable to process object for kind: '${g.kind}'`),pe)}function f(g){return n==="inactive"||!r||!g.kind||!g.key||!g.version||o.push({kind:g.kind,key:g.key,version:g.version,deleted:!0}),pe}function m(g){if(n==="inactive")return{type:"error",kind:"PROTOCOL_ERROR",message:"A payload transferred has been received without an intent having been established."};if(!r||g.state===null||g.state===void 0||!g.version)return a(),pe;let S={type:"payload",payload:{id:r,version:g.version,state:g.state,type:i,updates:o}};return c(),S}function d(g){return e==null||e.info(`Goodbye was received from the LaunchDarkly connection with reason: ${g.reason}.`),a(),{type:"goodbye",reason:g.reason}}function v(g){return e==null||e.info(`An issue was encountered receiving updates for payload ${r} with reason: ${g.reason}.`),l(),{type:"serverError",id:g.payload_id,reason:g.reason}}return{get state(){return n},processEvent(g){switch(g.event){case"server-intent":return h(g.data);case"put-object":return p(g.data);case"delete-object":return f(g.data);case"payload-transferred":return m(g.data);case"goodbye":return d(g.data);case"error":return v(g.data);case"heart-beat":return pe;default:return{type:"error",kind:"UNKNOWN_EVENT",message:`Received an unknown event of type '${g.event}'`}}},reset(){a()}}}function rw(t){return t==="MISSING_PAYLOAD"||t==="PROTOCOL_ERROR"}var Pp=class{constructor(t,e,n){this.g=e,this.t=n,this.n=[],this.li=Up(t,n)}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=>{var n,r;let i=this.li.processEvent(e);switch(i.type){case"payload":this.n.forEach(o=>o(i.payload));break;case"error":rw(i.kind)?(n=this.g)==null||n.call(this,At.InvalidData,i.message):(r=this.t)==null||r.warn(i.message);break}})}},iw=class{constructor(t,e,n,r){this.g=n,this.t=r,this.H(t,"server-intent"),this.H(t,"put-object"),this.H(t,"delete-object"),this.H(t,"payload-transferred"),this.H(t,"goodbye"),this.H(t,"error"),this.Ct=new Pp(e,n,r)}addPayloadListener(t){this.Ct.addPayloadListener(t)}removePayloadListener(t){this.Ct.removePayloadListener(t)}H(t,e){t.addEventListener(e,async n=>{var r,i,o,s,a;if(n!=null&&n.data){(r=this.t)==null||r.debug(`Received ${e} event. Data is ${n.data}`);try{this.Ct.processEvents([{event:e,data:JSON.parse(n.data)}])}catch(c){(i=this.t)==null||i.error(`Stream received data that was unable to be processed in "${e}" message`),(o=this.t)==null||o.debug(`Data follows: ${n.data}`),(s=this.g)==null||s.call(this,At.InvalidData,"Malformed data in EventStream.")}}else(a=this.g)==null||a.call(this,At.Unknown,"Event from EventStream missing data.")})}};function ow(t){if(t){let e=Object.keys(t).find(n=>n.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var tp="unknown plugin";function Ki(t,e){try{return e.getMetadata().name||tp}catch(n){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),tp}}function sw(t,e,n){let r=[];return n.forEach(i=>{var o;try{let s=(o=i.getHooks)==null?void 0:o.call(i,e);s===void 0?t.error(`Plugin ${Ki(t,i)} returned undefined from getHooks.`):s&&s.length>0&&r.push(...s)}catch(s){t.error(`Exception thrown getting hooks for plugin ${Ki(t,i)}. Unable to get hooks.`)}}),r}function aw(t,e,n,r){r.forEach(i=>{try{i.register(n,e)}catch(o){t.error(`Exception thrown registering plugin ${Ki(t,i)}.`)}})}var de=Object.freeze({__proto__:null,ClientMessages:Gp,DiagnosticsManager:DS,ErrorKinds:YS,EventFactoryBase:ew,EventProcessor:qS,FDv1PayloadAdaptor:nw,InputCustomEvent:Xp,InputEvalEvent:Ma,InputIdentifyEvent:Wp,NullEventProcessor:tw,PayloadProcessor:Pp,PayloadStreamReader:iw,canonicalize:Fi,createProtocolHandler:Up,initMetadataFromHeaders:ow,isLegacyUser:Tp,isMultiKind:Ip,isSingleKind:wp,safeGetHooks:sw,safeGetName:Ki,safeRegisterPlugins:aw,shouldSample:Pi}),lw={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function cw(t){return t>=200&&t<=299}var ep=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function np(t,e,n,r,i,o,s,a,c,l){let u,h="GET",p=st({},o);c&&(h="REPORT",p["content-type"]="application/json",u=t);let f=c?n.pathReport(i,t):n.pathGet(i,t),m=[...s!=null?s:[]];a&&m.push({key:"withReasons",value:"true"}),l&&m.push({key:"h",value:l});let d=US(e,f,m);return{async requestPayload(){let v;try{let g=await r.fetch(d,{method:h,headers:p,body:u});if(cw(g.status))return await g.text();v=g.status}catch(g){throw new ep(g==null?void 0:g.message)}throw new ep(`Unexpected status code: ${v}`,v)}}}var rp=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function uw(t,e,n=!1){let r,i=new Promise(a=>{r=(c,l)=>{var u;try{(u=t.after)==null||u.call(t,c,l)}catch(h){e==null||e.error(`Error in after callback: ${h}`)}a(c)}}),o=t.before?t.before():Promise.resolve(void 0),s=!1;return{execute:()=>{s&&(e==null||e.error(rp)),s=!0,o.then(a=>{t.execute(a).then(c=>r({status:"complete",result:c},a)).catch(c=>r({status:"error",error:c},a))}).catch(a=>{e==null||e.error(a),r({status:"error",error:a},void 0)})},shed:()=>{s&&(e==null||e.error(rp)),s=!0,o.then(a=>{r({status:"shed"},a)})},promise:i,sheddable:n}}function hw(t){let e,n=[];function r(){if(!e&&n.length>0){let i=n.shift();e=i.promise.finally(()=>{e=void 0,r()}),i.execute()}}return{execute(i,o=!1){var s,a;let c=uw(i,t,o);return e?((s=n[n.length-1])!=null&&s.sheddable&&((a=n.pop())==null||a.shed()),n.push(c)):(e=c.promise.finally(()=>{e=void 0,r()}),c.execute()),c.promise},pendingCount(){return n.length}}}var pw={logger:G.Object,maxCachedContexts:G.numberWithMin(0),baseUri:G.String,streamUri:G.String,eventsUri:G.String,capacity:G.numberWithMin(1),diagnosticRecordingInterval:G.numberWithMin(2),flushInterval:G.numberWithMin(2),streamInitialReconnectDelay:G.numberWithMin(0),allAttributesPrivate:G.Boolean,debug:G.Boolean,diagnosticOptOut:G.Boolean,withReasons:G.Boolean,sendEvents:G.Boolean,pollInterval:G.numberWithMin(30),useReport:G.Boolean,privateAttributes:G.StringArray,applicationInfo:G.Object,wrapperName:G.String,wrapperVersion:G.String,payloadFilterKey:G.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:G.createTypeArray("Hook[]",{}),inspectors:G.createTypeArray("LDInspection",{}),cleanOldPersistentData:G.Boolean},dw=300,Mp="https://clientsdk.launchdarkly.com",Fp="https://clientstream.launchdarkly.com";function fw(t){return t instanceof Rp?t:Cp(t)}var mw=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var n,r,i;this.logger=Cp(),this.baseUri=Mp,this.eventsUri=Di.DEFAULT_EVENTS,this.streamUri=Fp,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=dw,this.hooks=[],this.inspectors=[],this.logger=fw(t.logger),this.ui(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new Di(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 LS({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(i=e.trackEventModifier)!=null?i:(o=>o),this.credentialType=e.credentialType,this.getImplementationHooks=e.getImplementationHooks}ui(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let i=pw[n];if(i)if(i.is(r))n==="logger"||(this[n]=r!=null?r:void 0);else{let o=i.getType();if(o==="boolean")e.push(Ue.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(o==="boolean | undefined | null")e.push(Ue.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(i instanceof vp&&G.Number.is(r)){let{min:s}=i;e.push(Ue.optionBelowMinimum(n,r,s)),this[n]=s}else e.push(Ue.wrongOptionType(n,i.getType(),typeof r))}else e.push(Ue.unknownOption(n))}),e}};async function Ap(t,e){if(t.digest)return t.digest(e);if(t.asyncDigest)return t.asyncDigest(e);throw new Error("Platform must implement digest or asyncDigest")}var Jp=async(t,{crypto:e,storage:n})=>{let r=await(n==null?void 0:n.get(t));return r||(r=e.randomUUID(),await(n==null?void 0:n.set(t,r))),r};function Dp(t){return async e=>Ap(t.createHash("sha256").update(e),"base64")}var fe=async t=>t;async function gr(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function yw(t,e){return gr([{value:"LaunchDarkly",transform:fe},{value:e,transform:Dp(t)}])}async function gw(t){return gr([{value:"LaunchDarkly",transform:fe},{value:"AnonymousKeys",transform:fe},{value:t,transform:fe}])}async function bw(t){return gr([{value:"LaunchDarkly",transform:fe},{value:"ContextKeys",transform:fe},{value:t,transform:fe}])}async function vw(t){return gr([{value:t,transform:fe},{value:"ContextIndex",transform:fe}])}async function ip(t,e,n){return gr([{value:e,transform:fe},{value:n.canonicalKey,transform:Dp(t)}])}var{isLegacyUser:Sw,isSingleKind:xa,isMultiKind:op}=de,Yp="1.0",ww=t=>{let e=t,{kind:n}=e,r=yp(e,["kind"]);return{kind:"multi",[n]:r}},Iw=async({crypto:t,info:e},{applicationInfo:n})=>{var r;let{ld_application:i}=e.platformData(),o=(r=Da(i))!=null?r:{},s=(n==null?void 0:n.id)||(o==null?void 0:o.id);if(s){let a=(n==null?void 0:n.version)||(o==null?void 0:o.version),c=(n==null?void 0:n.name)||(o==null?void 0:o.name),l=(n==null?void 0:n.versionName)||(o==null?void 0:o.versionName);return o=st(st(st(me(st({},o),{id:s}),a?{version:a}:{}),c?{name:c}:{}),l?{versionName:l}:{}),o.key=await Ap(t.createHash("sha256").update(s),"base64"),o.envAttributesVersion=o.envAttributesVersion||Yp,o}},Tw=async t=>{var e,n,r,i;let{ld_device:o,os:s}=t.info.platformData(),a=(e=Da(o))!=null?e:{},c=(s==null?void 0:s.name)||((n=a.os)==null?void 0:n.name),l=(s==null?void 0:s.version)||((r=a.os)==null?void 0:r.version),u=(i=a.os)==null?void 0:i.family;if((c||l||u)&&(a.os=st(st(st({},c?{name:c}:{}),l?{version:l}:{}),u?{family:u}:{})),Object.keys(a).filter(h=>h!=="key"&&h!=="envAttributesVersion").length){let h=await bw("ld_device");return a.key=await Jp(h,t),a.envAttributesVersion=a.envAttributesVersion||Yp,a}},Ew=async(t,e,n)=>{if(Sw(t))return t;let r,i;if(xa(t)&&t.kind!=="ld_application"||op(t)&&!t.ld_application?r=await Iw(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),xa(t)&&t.kind!=="ld_device"||op(t)&&!t.ld_device?i=await Tw(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),r||i){let o=xa(t)?ww(t):t;return st(st(st({},o),r?{ld_application:r}:{}),i?{ld_device:i}:{})}return t};function Rw(){let t,e;return{set(n,r){t=n,e=r},getContext(){return e},getUnwrappedContext(){return t},newIdentificationPromise(){let n,r;return{identifyPromise:new Promise((i,o)=>{n=i,r=o}),identifyResolve:n,identifyReject:r}},hasContext(){return e!==void 0},hasValidContext(){return this.hasContext()&&e.valid}}}var{isLegacyUser:Cw,isMultiKind:Zw,isSingleKind:kw}=de,Ya=async(t,e,n)=>{let{anonymous:r,key:i}=e;if(r&&!i){let o=await gw(t);e.key=await Jp(o,n)}},Vw=async(t,e)=>{await Ya(t.kind,t,e)},xw=async(t,e)=>{let n=t,{kind:r}=n,i=yp(n,["kind"]);return Promise.all(Object.entries(i).map(([o,s])=>Ya(o,s,e)))},Nw=async(t,e)=>{await Ya("user",t,e)},Ow=async(t,e)=>{let n=xp(t);return kw(n)&&await Vw(n,e),Zw(n)&&await xw(n,e),Cw(n)&&await Nw(n,e),n},Gw=t=>({customBaseURI:t.serviceEndpoints.polling!==Mp,customStreamURI:t.serviceEndpoints.streaming!==Fp,customEventsURI:t.serviceEndpoints.events!==Di.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:Va(t.flushInterval),reconnectTimeMillis:Va(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Va(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Lw=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new de.DiagnosticsManager(t,n,Gw(e))};function sp(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function ap(t,e,n){return st({value:t,variationIndex:e!=null?e:null},n!==void 0&&{reason:n})}var Xw=(t,e,n,r,i)=>{if(e.sendEvents)return new de.EventProcessor(me(st({},e),{eventsCapacity:e.capacity}),new XS(t,e,n),r,void 0,i,!1,!0)},lp=class extends de.EventFactoryBase{evalEventClient(t,e,n,r,i,o){let{trackEvents:s,debugEventsUntilDate:a,trackReason:c,flagVersion:l,version:u,variation:h}=r;return super.evalEvent({addExperimentData:c,context:i,debugEventsUntilDate:a,defaultVal:n,flagKey:t,reason:o,trackEvents:!!s,value:e,variation:h,version:l!=null?l:u})}},Na=class Kp{constructor(){this.container={index:new Array}}static fromJson(e){let n=new Kp;try{n.container=JSON.parse(e)}catch(r){}return n}toJson(){return JSON.stringify(this.container)}notice(e,n){let r=this.container.index.find(i=>i.id===e);r===void 0?this.container.index.push({id:e,timestamp:n}):r.timestamp=n}prune(e){let n=Math.max(e,0);return this.container.index.length>n?(this.container.index.sort((r,i)=>r.timestamp-i.timestamp),this.container.index.splice(0,this.container.index.length-n)):[]}},Ww=class{constructor(t,e,n,r,i,o,s=()=>Date.now()){this.p=t,this.It=e,this.hi=n,this.P=r,this.w=i,this.t=o,this.di=s,this.pe=vw(this.It)}async init(t,e){this.w.init(t,e),await this.ge(t)}async upsert(t,e,n){return this.w.upsert(t,e,n)?(await this.ge(t),!0):!1}async loadCached(t){var e,n,r,i;let o=await ip(this.p.crypto,this.It,t),s=await((e=this.p.storage)==null?void 0:e.get(o));if(s==null){if(s=await((n=this.p.storage)==null?void 0:n.get(t.canonicalKey)),s==null)return!1;await((r=this.p.storage)==null?void 0:r.set(o,s)),await((i=this.p.storage)==null?void 0:i.clear(t.canonicalKey))}try{let a=JSON.parse(s),c=Object.entries(a).reduce((l,[u,h])=>(l[u]={version:h.version,flag:h},l),{});return this.w.initCached(t,c),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(a){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${a.message}`),!1}}async fi(){var t;if(this.B!==void 0)return this.B;let e=await((t=this.p.storage)==null?void 0:t.get(await this.pe));if(!e)return this.B=new Na,this.B;try{this.B=Na.fromJson(e),this.t.debug("Loaded context index from persistent storage")}catch(n){this.t.warn(`Could not load index from persistent storage: ${n.message}`),this.B=new Na}return this.B}async ge(t){var e,n;let r=await this.fi(),i=await ip(this.p.crypto,this.It,t);r.notice(i,this.di());let o=r.prune(this.hi);await Promise.all(o.map(async l=>{var u;return(u=this.p.storage)==null?void 0:u.clear(l.id)})),await((e=this.p.storage)==null?void 0:e.set(await this.pe,r.toJson()));let s=this.P.getAll(),a=Object.entries(s).reduce((l,[u,h])=>(h.flag!==null&&h.flag!==void 0&&(l[u]=h.flag),l),{}),c=JSON.stringify(a);await((n=this.p.storage)==null?void 0:n.set(i,c))}};function Uw(){let t={};return{init(e){t=Object.entries(e).reduce((n,[r,i])=>(n[r]=i,n),{})},insertOrUpdate(e,n){t[e]=n},get(e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},getAll(){return t}}}function Pw(t,e){let n=[];return Object.entries(t).forEach(([r,i])=>{let o=e[r];(!o||!Ui(i,o))&&n.push(r)}),Object.keys(e).forEach(r=>{t[r]||n.push(r)}),n}function Mw(t,e){let n=t,r=e,i,o=new Array;return{handleFlagChanges(s,a){i?o.forEach(c=>{try{c(i,s,a)}catch(l){}}):r.warn("Received a change event without an active context. Changes will not be propagated.")},init(s,a){i=s;let c=n.getAll();n.init(a);let l=Pw(c,a);l.length>0&&this.handleFlagChanges(l,"init")},initCached(s,a){(i==null?void 0:i.canonicalKey)!==s.canonicalKey&&this.init(s,a)},upsert(s,a,c){if((i==null?void 0:i.canonicalKey)!==s.canonicalKey)return r.warn("Received an update for an inactive context."),!1;let l=n.get(a);return l!==void 0&&l.version>=c.version?!1:(n.insertOrUpdate(a,c),this.handleFlagChanges([a],"patch"),!0)},on(s){o.push(s)},off(s){let a=o.indexOf(s);a>-1&&o.splice(a,1)}}}var Fw=class{constructor(t,e,n,r,i=()=>Date.now()){this.P=Uw(),this.w=Mw(this.P,r),this.Ot=this.pi(t,e,n,r,i)}async pi(t,e,n,r,i=()=>Date.now()){let o=await yw(t.crypto,e);return new Ww(t,o,n,this.P,this.w,r,i)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.At(this.r[t]):this.P.get(t)}getAll(){return this.r?st(st({},this.P.getAll()),Object.entries(this.r).reduce((t,[e,n])=>(t[e]=this.At(n),t),{})):this.P.getAll()}presetFlags(t){this.P.init(t)}setBootstrap(t,e){this.w.init(t,e)}async init(t,e){return(await this.Ot).init(t,e)}async upsert(t,e,n){return(await this.Ot).upsert(t,e,n)}async loadCached(t){return(await this.Ot).loadCached(t)}on(t){this.w.on(t)}off(t){this.w.off(t)}At(t){return{flag:{value:t,version:0},version:0}}setOverride(t,e){this.r||(this.r={}),this.r[t]=e,this.w.handleFlagChanges([t],"override")}removeOverride(t){!this.r||!Object.prototype.hasOwnProperty.call(this.r,t)||(delete this.r[t],Object.keys(this.r).length===0&&(this.r=void 0),this.w.handleFlagChanges([t],"override"))}clearAllOverrides(){if(this.r){let t=st({},this.r);this.r=void 0,this.w.handleFlagChanges(Object.keys(t),"override")}}getAllOverrides(){if(!this.r)return{};let t={};return Object.entries(this.r).forEach(([e,n])=>{t[e]=this.At(n)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},cp="unknown hook",_p="beforeEvaluation",Hp="afterEvaluation",Aw="afterTrack";function br(t,e,n,r,i){try{return r()}catch(o){return t==null||t.error(`An error was encountered in "${e}" of the "${n}" hook: ${o}`),i}}function vr(t,e){try{return e.getMetadata().name||cp}catch(n){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),cp}}function Jw(t,e,n){return e.map(r=>br(t,_p,vr(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeEvaluation)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Dw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];br(t,Hp,vr(t,s),()=>{var c,l;return(l=(c=s==null?void 0:s.afterEvaluation)==null?void 0:c.call(s,n,a,i))!=null?l:{}},{})}}function Yw(t,e,n){return e.map(r=>br(t,_p,vr(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeIdentify)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Kw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];br(t,Hp,vr(t,s),()=>{var c,l;return(l=(c=s==null?void 0:s.afterIdentify)==null?void 0:c.call(s,n,a,i))!=null?l:{}},{})}}function _w(t,e,n){for(let r=e.length-1;r>=0;r-=1){let i=e[r];br(t,Aw,vr(t,i),()=>{var o;return(o=i==null?void 0:i.afterTrack)==null?void 0:o.call(i,n)},void 0)}}var Hw=class{constructor(t,e){this.t=t,this.$=[],this.$.push(...e)}withEvaluation(t,e,n,r){if(this.$.length===0)return r();let i=[...this.$],o={flagKey:t,context:e,defaultValue:n},s=Jw(this.t,i,o),a=r();return Dw(this.t,i,o,s,a),a}identify(t,e){let n=[...this.$],r={context:t,timeout:e},i=Yw(this.t,n,r);return o=>{Kw(this.t,n,r,i,o)}}addHook(t){this.$.push(t)}afterTrack(t){if(this.$.length===0)return;let e=[...this.$];_w(this.t,e,t)}};function zw(t){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(e,n,r)=>(t.onFlagUsed(e.flagKey,r,e.context),n),afterIdentify(e,n,r){return t.onIdentityChanged(e.context),n}}}function Bw(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function jw(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function Qw(t,e){let n=!1,r={method:(...i)=>{try{t.method(...i)}catch(o){n||(n=!0,e.warn(jw(r.type,r.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return r}var zp="flag-used",Bp="flag-details-changed",jp="flag-detail-changed",Qp="client-identity-changed",$w=[zp,Bp,jp,Qp];function qw(t,e){let n=$w.includes(t.type)&&t.method&&typeof t.method=="function";return n||e.warn(Bw(t.type,t.name)),n}var tI=class{constructor(t,e){this.z=[];let n=t.filter(r=>qw(r,e));this.z=n.map(r=>Qw(r,e))}hasInspectors(){return this.z.length!==0}onFlagUsed(t,e,n){this.z.forEach(r=>{r.type===zp&&r.method(t,e,n)})}onFlagsChanged(t){this.z.forEach(e=>{e.type===Bp&&e.method(t)})}onFlagChanged(t,e){this.z.forEach(n=>{n.type===jp&&n.method(t,e)})}onIdentityChanged(t){this.z.forEach(e=>{e.type===Qp&&e.method(t)})}},eI=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var n,r;if(typeof t!="string"){(n=this.t)==null||n.warn("Only string event names are supported.");return}this.n.has(t)?(r=this.n.get(t))==null||r.push(e):this.n.set(t,[e])}off(t,e){let n=this.n.get(t);if(n){if(e){let r=n.filter(i=>i!==e);r.length===0?this.n.delete(t):this.n.set(t,r);return}this.n.delete(t)}}gi(t,e,...n){var r;try{t(...n)}catch(i){(r=this.t)==null||r.error(`Encountered error invoking handler for "${e}", detail: "${i}"`)}}emit(t,...e){let n=this.n.get(t);n==null||n.forEach(r=>this.gi(r,t,...e))}eventNames(){return[...this.n.keys()]}listenerCount(t){var e,n;return(n=(e=this.n.get(t))==null?void 0:e.length)!=null?n:0}};function nI(t,e,n){let r=e.info.sdkData(),i;n.applicationInfo&&(n.applicationInfo.id&&(i=i!=null?i:{},i.id=n.applicationInfo.id),n.applicationInfo.version&&(i=i!=null?i:{},i.version=n.applicationInfo.version),n.applicationInfo.name&&(i=i!=null?i:{},i.name=n.applicationInfo.name),n.applicationInfo.versionName&&(i=i!=null?i:{},i.versionName=n.applicationInfo.versionName));let o={name:r.userAgentBase,version:r.version};r.wrapperName&&(o.wrapperName=r.wrapperName),r.wrapperVersion&&(o.wrapperVersion=r.wrapperVersion);let s={sdk:o,[n.credentialType]:t};return i&&(s.application=i),s}var{ClientMessages:up,ErrorKinds:hp}=de,rI=5,iI=class{constructor(t,e,n,r,i,o){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.a=Rw(),this.Pt=15,this.T=new lp(!1),this.ct=new lp(!0),this.Tt=!1,this.mi=hw(),!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.e=new mw(r,o),this.logger=this.e.logger,this.me=JS(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.R=new Fw(this.platform,t,this.e.maxCachedContexts,this.e.logger),this.S=Lw(t,this.e,n),this.E=Xw(t,this.e,n,this.me,this.S),this.emitter=new eI,this.emitter.on("error",(a,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(a)}`)}),this.R.on((a,c,l)=>{this.yi(c,l);let u=xn.toLDContext(a);this.emitter.emit("change",u,c),c.forEach(h=>{this.emitter.emit(`change:${h}`,u)})}),this.dataManager=i(this.R,this.e,this.me,this.emitter,this.S);let s=[...this.e.hooks];if(this.environmentMetadata=nI(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(a=>{s.push(a)}),this.M=new Hw(this.logger,s),this.Y=new tI(this.e.inspectors,this.logger),this.Y.hasInspectors()&&this.M.addHook(zw(this.Y)),r.cleanOldPersistentData&&o!=null&&o.getLegacyStorageKeys&&this.platform.storage)try{this.logger.debug("Cleaning old persistent data."),Promise.all(o.getLegacyStorageKeys().map(a=>{var c;return(c=this.platform.storage)==null?void 0:c.clear(a)})).catch(a=>{this.logger.error(`Error cleaning old persistent data: ${a}`)}).finally(()=>{this.logger.debug("Cleaned old persistent data.")})}catch(a){this.logger.error(`Error cleaning old persistent data: ${a}`)}}allFlags(){return Object.entries(this.R.getAll()).reduce((t,[e,n])=>(n.flag!==null&&n.flag!==void 0&&!n.flag.deleted&&(t[e]=n.flag.value),t),{})}async close(){var t;await this.flush(),(t=this.E)==null||t.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.E)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.a.hasContext()?xp(this.a.getUnwrappedContext()):void 0}getInternalContext(){return this.a.getContext()}presetFlags(t){this.R.presetFlags(t)}async identify(t,e){let n=await this.identifyResult(t,e);if(n.status==="error")throw n.error;if(n.status==="timeout"){let r=new Vp(`identify timed out after ${n.timeout} seconds.`);throw this.logger.error(r.message),r}}async identifyResult(t,e){var n,r;let i=(n=e==null?void 0:e.timeout)!=null?n:rI,o=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Pt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Pt} seconds. We recommend a timeout of less than ${this.Pt} seconds.`);let s=this.mi.execute({before:async()=>{let c=await Ow(t,this.platform);this.autoEnvAttributes===Ji.Enabled&&(c=await Ew(c,this.platform,this.e));let l=xn.fromLDContext(c);if(l.valid){let u=this.M.identify(c,e==null?void 0:e.timeout);return{context:c,checkedContext:l,afterIdentify:u}}return{context:c,checkedContext:l}},execute:async c=>{var l;let{context:u,checkedContext:h}=c;if(!h.valid){let d=new Error("Context was unspecified or had no key");return this.emitter.emit("error",u,d),Promise.reject(d)}this.a.set(u,h),(l=this.E)==null||l.sendEvent(this.T.identifyEvent(h));let{identifyPromise:p,identifyResolve:f,identifyReject:m}=this.a.newIdentificationPromise();return this.logger.debug(`Identifying ${JSON.stringify(h)}`),await this.dataManager.identify(f,m,h,e),p},after:async(c,l)=>{var u,h,p;c.status==="complete"?(u=l==null?void 0:l.afterIdentify)==null||u.call(l,{status:"completed"}):c.status==="shed"?(h=l==null?void 0:l.afterIdentify)==null||h.call(l,{status:"shed"}):c.status==="error"&&((p=l==null?void 0:l.afterIdentify)==null||p.call(l,{status:"error"}))}},(r=e==null?void 0:e.sheddable)!=null?r:!1).then(c=>{if(c.status==="error"){let u={status:"error",error:c.error};return this.maybeSetInitializationResult({status:"failed",error:c.error}),u}if(c.status==="shed")return{status:"shed"};let l={status:"completed"};return this.maybeSetInitializationResult({status:"complete"}),l});if(o)return s;let a=new Promise(c=>{setTimeout(()=>{c({status:"timeout",timeout:i})},i*1e3)});return Promise.race([s,a])}maybeSetInitializationResult(t){this.initializeResult===void 0&&(this.initializeResult=t,this.emitter.emit("ready"),t.status==="complete"&&this.emitter.emit("initialized"),this.initResolve&&(this.initResolve(t),this.initResolve=void 0))}waitForInitialization(t){var e;let n=(e=t==null?void 0:t.timeout)!=null?e:5;return this.initializeResult?Promise.resolve(this.initializeResult):this.initializedPromise?this.promiseWithTimeout(this.initializedPromise,n):(this.initializedPromise||(this.initializedPromise=new Promise(r=>{this.initResolve=r})),this.promiseWithTimeout(this.initializedPromise,n))}promiseWithTimeout(t,e){let n=FS(e,"waitForInitialization");return Promise.race([t.then(r=>(n.cancel(),r)),n.promise.then(()=>({status:"complete"})).catch(()=>({status:"timeout"}))]).catch(r=>{var i;return(i=this.logger)==null||i.error(r.message),{status:"failed",error:r}})}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){var r,i;if(!this.a.hasValidContext()){this.logger.warn(up.MissingContextKeyNoEvent);return}n!==void 0&&!G.Number.is(n)&&((r=this.logger)==null||r.warn(up.invalidMetricValue(typeof n))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.a.getContext(),e,n))),this.M.afterTrack({key:t,context:this.a.getUnwrappedContext(),data:e,metricValue:n})}lt(t,e,n,r){var i,o,s,a,c;let l=this.a.hasContext();l||(i=this.logger)==null||i.warn("Flag evaluation called before client is fully initialized, data from this evaulation could be stale.");let u=this.a.getContext(),h=this.R.get(t);if(h===void 0||h.flag.deleted){let g=e!=null?e:null;return(o=this.logger)==null||o.warn(`Unknown feature flag "${t}"; returning default value ${g}.`),l&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(t,g,u))),sp(hp.FlagNotFound,e)}let{reason:p,value:f,variation:m,prerequisites:d}=h.flag;if(r){let[g,S]=r(f);if(!g){l&&((a=this.E)==null||a.sendEvent(n.evalEventClient(t,e,e,h.flag,u,p)));let T=new PS(`Wrong type "${S}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.a.getUnwrappedContext(),T),sp(hp.WrongType,e)}}let v=ap(f,m,p);return f==null&&(this.logger.debug("Result value is null. Providing default value."),v.value=e),d==null||d.forEach(g=>{this.lt(g,void 0,this.T)}),l&&((c=this.E)==null||c.sendEvent(n.evalEventClient(t,f,e,h.flag,u,p))),v}variation(t,e){let{value:n}=this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,this.T));return n}variationDetail(t,e){return this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,this.ct))}G(t,e,n,r){return this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,n,r))}boolVariation(t,e){return this.G(t,e,this.T,n=>[G.Boolean.is(n),G.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.G(t,e,this.T,n=>[G.Number.is(n),G.Number.getType()]).value}stringVariation(t,e){return this.G(t,e,this.T,n=>[G.String.is(n),G.String.getType()]).value}boolVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.Boolean.is(n),G.Boolean.getType()])}numberVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.Number.is(n),G.Number.getType()])}stringVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.String.is(n),G.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.M.addHook(t)}setEventSendingEnabled(t,e){var n,r,i,o;this.Tt!==t&&(this.Tt=t,t?(this.logger.debug("Starting event processor"),(n=this.E)==null||n.start()):e?((r=this.logger)==null||r.debug("Flushing event processor before disabling."),this.flush().then(()=>{var s,a;this.Tt||((s=this.logger)==null||s.debug("Stopping event processor."),(a=this.E)==null||a.close())})):((i=this.logger)==null||i.debug("Stopping event processor."),(o=this.E)==null||o.close()))}sendEvent(t){var e;(e=this.E)==null||e.sendEvent(t)}getDebugOverrides(){var t,e;return(e=(t=this.R).getDebugOverride)==null?void 0:e.call(t)}yi(t,e){if(!this.Y.hasInspectors())return;let n={};t.forEach(r=>{let i=this.R.get(r);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:o,value:s,variation:a}=i.flag;n[r]=ap(s,a,o)}else n[r]={value:void 0,variationIndex:null}}),e==="init"?this.Y.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,i])=>{this.Y.onFlagChanged(r,i)})}};function oI(t,e,n){n.forEach(r=>{var i;try{(i=r.registerDebug)==null||i.call(r,e)}catch(o){t.error(`Exception thrown registering plugin ${de.safeGetName(t,r)}.`)}})}function $p(t,e){let n=Object.keys(e),r="$flagsState",i="$valid",o=e[r];!o&&n.length&&t.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),e[i]===!1&&t.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let s={};return n.forEach(a=>{if(a!==r&&a!==i){let c;o&&o[a]?c=st({value:e[a]},o[a]):c={value:e[a],version:0},s[a]={version:c.version,flag:c}}}),s}function sI(t,e,n){return{async handlePut(r,i){n.debug(`Got PUT: ${Object.keys(i)}`);let o=Object.entries(i).reduce((s,[a,c])=>(s[a]={version:c.version,flag:c},s),{});await t.init(r,o),e.requestStateUpdate("VALID")},async handlePatch(r,i){n.debug(`Got PATCH ${JSON.stringify(i,null,2)}`),t.upsert(r,i.key,{version:i.version,flag:i})},async handleDelete(r,i){n.debug(`Got DELETE ${JSON.stringify(i,null,2)}`),t.upsert(r,i.key,{version:i.version,flag:me(st({},i),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})},handleStreamingError(r){e.reportError(r.kind,r.message,r.code,r.recoverable)},handlePollingError(r){e.reportError(r.kind,r.message,r.status,r.recoverable)}}}function aI(t,e=()=>Date.now()){let n="CLOSED",r=e(),i;function o(){return{state:n,stateSince:r,lastError:i}}function s(a,c=!1){let l=a==="INTERRUPTED"&&n==="INITIALIZING"?"INITIALIZING":a,u=n!==l;u&&(n=l,r=e()),(u||c)&&t.emit("dataSourceStatus",o())}return{get status(){return o()},requestStateUpdate(a){s(a)},reportError(a,c,l,u=!1){i={kind:a,message:c,statusCode:l,time:e()},s(u?"INTERRUPTED":"CLOSED",!0)}}}function pp(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var lI=class{constructor(t,e,n,r,i){this.vi=t,this.wi=e,this.Ei=n,this.g=r,this.t=i,this.u=!1}async ye(){var t,e,n,r,i,o,s;if(this.u)return;let a=h=>{var p,f,m;(p=this.t)==null||p.error("Polling received invalid data"),(f=this.t)==null||f.debug(`Invalid JSON follows: ${h}`),(m=this.g)==null||m.call(this,new Ai(At.InvalidData,"Malformed JSON data in polling response"))};(t=this.t)==null||t.debug("Polling LaunchDarkly for feature flag updates");let c=Date.now();try{let h=await this.vi.requestPayload();try{if(this.u){pp(this.t);return}let p=JSON.parse(h);try{(e=this.Ei)==null||e.call(this,p)}catch(f){(n=this.t)==null||n.error(`Exception from data handler: ${f}`)}}catch(p){a(h)}}catch(h){if(this.u){pp(this.t);return}let p=h;if(p.status!==void 0&&!_i(p.status)){(r=this.t)==null||r.error(Gn(h,"polling request")),(i=this.g)==null||i.call(this,new Ai(At.ErrorResponse,p.message,p.status));return}(o=this.t)==null||o.error(Gn(h,"polling request","will retry"))}let l=Date.now()-c,u=Math.max(this.wi*1e3-l,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",l,u),this.Nt=setTimeout(()=>{this.ye()},u)}start(){this.ye()}stop(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0),this.u=!0}close(){this.stop()}},cI=(t,e,n,r)=>{n==null||n.error(`Stream received invalid data in "${t}" message`),n==null||n.debug(`Invalid JSON follows: ${e}`),r==null||r(new Wa(At.InvalidData,"Malformed JSON data in event stream"))};function uI(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function dp(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var hI=class{constructor(t,e,n,r,i,o,s,a,c){var l;this.Di=t,this.$t=e,this.n=n,this.V=r,this.bi=o,this.S=s,this.g=a,this.t=c,this.u=!1;let u;e.useReport&&!r.getEventSourceCapabilities().customMethod?u=e.paths.pathPing(i,t):u=e.useReport?e.paths.pathReport(i,t):e.paths.pathGet(i,t);let h=[...(l=e.queryParameters)!=null?l:[]];this.$t.withReasons&&h.push({key:"withReasons",value:"true"}),this.V=r,this.ve=st({},e.baseHeaders),this.t=c,this.ki=WS(e.serviceEndpoints,u,h)}we(){this.ut=Date.now()}Rt(t){this.ut&&this.S&&this.S.recordStreamInit(this.ut,!t,Date.now()-this.ut),this.ut=void 0}xi(t){var e,n,r;return Np(t)?((r=this.t)==null||r.warn(Gn(t,"streaming request","will retry")),this.Rt(!1),this.we(),!0):(this.Rt(!1),(e=this.g)==null||e.call(this,new Wa(At.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(Gn(t,"streaming request")),!1)}start(){this.we();let t;this.$t.useReport?(this.ve["content-type"]="application/json",t={method:"REPORT",body:this.Di}):t={};let e=this.V.createEventSource(this.ki,me(st({headers:this.ve},t),{errorFilter:n=>this.xi(n),initialRetryDelayMillis:this.$t.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.Ee=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var r;(r=this.t)==null||r.info(`Will retry stream connection in ${n.delayMillis} milliseconds`)},this.n.forEach(({deserializeData:n,processJson:r},i)=>{e.addEventListener(i,o=>{var s,a;if(this.u){uI(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),o!=null&&o.data){this.Rt(!0);let{data:c}=o,l=n(c);if(!l){cI(i,c,this.t,this.g);return}r(l)}else(a=this.g)==null||a.call(this,new Wa(At.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,r,i,o,s,a,c;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let l=await this.bi.requestPayload();try{if(this.u){dp(this.t);return}let u=JSON.parse(l);try{(r=this.n.get("put"))==null||r.processJson(u)}catch(h){(i=this.t)==null||i.error(`Exception from data handler: ${h}`)}}catch(u){(o=this.t)==null||o.error("Polling after ping received invalid data"),(s=this.t)==null||s.debug(`Invalid JSON follows: ${l}`),(a=this.g)==null||a.call(this,new Ai(At.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){dp(this.t);return}let u=l;(c=this.g)==null||c.call(this,new Ai(At.ErrorResponse,u.message,u.status))}})}stop(){var t;(t=this.Ee)==null||t.close(),this.Ee=void 0,this.u=!0}close(){this.stop()}},pI=class{constructor(t,e,n,r,i,o,s,a,c){this.platform=t,this.flagManager=e,this.credential=n,this.config=r,this.getPollingPaths=i,this.getStreamingPaths=o,this.baseHeaders=s,this.emitter=a,this.diagnosticsManager=c,this.closed=!1,this.logger=r.logger,this.dataSourceStatusManager=aI(a),this.K=sI(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Si=t}createPollingProcessor(t,e,n,r,i){let o=new lI(n,this.config.pollInterval,async s=>{await this.K.handlePut(e,s),r==null||r()},s=>{this.emitter.emit("error",t,s),this.K.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.De(o,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,i){var o;let s=new hI(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.Si)==null?void 0:o.queryParameters},this.createStreamListeners(e,r),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,a=>{this.emitter.emit("error",t,a),this.K.handleStreamingError(a),i==null||i(a)},this.logger);this.updateProcessor=this.De(s,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.K.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.K.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.K.handleDelete(t,r)}}),n}De(t,e){return{start:()=>{e.requestStateUpdate("INITIALIZING"),t.start()},stop:()=>{t.stop(),e.requestStateUpdate("CLOSED")},close:()=>{t.close(),e.requestStateUpdate("CLOSED")}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function Hi(){return typeof document!==void 0}function Ka(){return typeof window!==void 0}function qp(t,e,n){return Hi()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function td(t,e,n){return Hi()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function yr(){return Ka()?window.location.href:""}function dI(){return Ka()?window.location.search:""}function fI(){return Ka()?window.location.hash:""}function mI(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function yI(){return Hi()?document.visibilityState:"visibile"}function gI(t){if(Hi())return document.querySelectorAll(t)}var bI="[BrowserDataManager]",vI=class extends pI{constructor(t,e,n,r,i,o,s,a,c,l){super(t,e,n,r,o,s,a,c,l),this.Ui=i,this.Z=void 0,this.Mt=!1,this.Z=i.streaming}L(t,...e){this.logger.debug(`${bI} ${t}`,...e)}async identify(t,e,n,r){if(this.closed){this.L("Identify called after data manager was closed.");return}this.context=n;let i=r;i!=null&&i.hash?this.setConnectionParams({queryParameters:[{key:"h",value:i.hash}]}):this.setConnectionParams(),this.Ft=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.Li(n,i,t):(await this.flagManager.loadCached(n)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Ci(n,t,e)),this.Ut()}async Ii(t){let e=JSON.stringify(xn.toLDContext(t)),n=np(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ft),r=3,i;for(let o=0;o<=r;o+=1)try{return await n.requestPayload()}catch(s){if(!Np(s))throw s;i=s,o<r&&(this.L(Gn(s,"initial poll request","will retry")),await Op(1e3))}throw i}async Ci(t,e,n){var r,i;try{this.dataSourceStatusManager.requestStateUpdate(lw.Initializing);let o=await this.Ii(t);try{let s=this.createStreamListeners(t,e).get("put");s.processJson(s.deserializeData(o))}catch(s){this.dataSourceStatusManager.reportError(At.InvalidData,(r=s.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(At.NetworkError,(i=o.message)!=null?i:"unexpected network error",o.status),n(o)}}Li(t,e,n){let{bootstrapParsed:r}=e;r||(r=$p(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,r),this.L("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.Z=t,this.Ut()}setAutomaticStreamingState(t){this.Mt=t,this.Ut()}Ut(){let t=this.Z||this.Mt&&this.Z===void 0;this.L(`Updating streaming state. forced(${this.Z}) automatic(${this.Mt})`),t?this.Oi():this.Ai()}Ai(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}Oi(){if(this.updateProcessor){this.L("Update processor already active. Not changing state.");return}if(!this.context){this.L("Context not set, not starting update processor.");return}this.L("Starting update processor."),this.Pi(this.context)}Pi(t,e,n){var r;let i=xn.toLDContext(t);(r=this.updateProcessor)==null||r.close();let o=JSON.stringify(xn.toLDContext(t)),s=np(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ft);this.createStreamingProcessor(i,t,s,e,n),this.updateProcessor.start()}};function SI(t){let e=qp("visibilitychange",()=>{yI()==="hidden"&&t()}),n=td("pagehide",t);return()=>{e(),n()}}function Oa(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function wI(t,e,n,r){let i=((t.kind==="substring"||t.kind==="regex")&&r.includes("/")?e:e.replace(r,"")).replace(n,"");switch(t.kind){case"exact":return new RegExp(`^${Oa(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${Oa(t.url)}/?$`).test(i);case"substring":return new RegExp(`.*${Oa(t.substring)}.*$`).test(i);case"regex":return new RegExp(t.pattern).test(i);default:return!1}}function II(t,e){let n=[];return e.forEach(r=>{let i=t.target,{selector:o}=r,s=gI(o);for(;i&&s!=null&&s.length;){for(let a=0;a<s.length;a+=1)if(i===s[a]){n.push(r);break}i=i.parentNode}}),n}var TI=class{constructor(t,e){let n=t.filter(o=>{var s;return(s=o.urls)==null?void 0:s.some(a=>wI(a,yr(),dI(),fI()))}),r=n.filter(o=>o.kind==="pageview"),i=n.filter(o=>o.kind==="click");if(r.forEach(o=>e(o)),i.length){let o=s=>{II(s,i).forEach(a=>{e(a)})};this.be=qp("click",o)}}close(){var t;(t=this.be)==null||t.call(this)}},EI=300,RI=class{constructor(t){this.Vt=yr();let e=()=>{let r=yr();r!==this.Vt&&(this.Vt=r,t())};this.jt=setInterval(e,EI);let n=td("popstate",e);this.ke=()=>{n()}}close(){var t;this.jt&&clearInterval(this.jt),(t=this.ke)==null||t.call(this)}},CI=class{constructor(t,e,n,r,i,o=s=>new RI(s)){this.V=e,this.$i=r,this.Ni=i,this.ht=[],this.Se=!1,this.dt=`${n}/sdk/goals/${t}`,this.xe=o(()=>{this.Bt()})}async initialize(){await this.Ti(),this.Bt()}startTracking(){this.Se=!0,this.Bt()}Bt(){var t;this.Se&&((t=this.Ht)==null||t.close(),this.ht&&this.ht.length&&(this.Ht=new TI(this.ht,e=>{this.Ni(yr(),e)})))}async Ti(){try{let t=await this.V.fetch(this.dt);this.ht=await t.json()}catch(t){this.$i(new kp(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.xe)==null||t.close(),(e=this.Ht)==null||e.close()}};function ZI(t){return t.kind==="click"}var kI=2,ed={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},VI={fetchGoals:G.Boolean,eventUrlTransformer:G.Function,streaming:G.Boolean,plugins:G.createTypeArray("LDPlugin",{})};function xI(t){var e;let n=st({},t);return(e=n.flushInterval)!=null||(n.flushInterval=kI),n}function NI(t){let e=xI(t);return Object.keys(ed).forEach(n=>{delete e[n]}),e}function OI(t,e){let n=st({},ed);return Object.entries(VI).forEach(r=>{let[i,o]=r,s=t[i];s!==void 0&&(o.is(s)?n[i]=s:e.warn(Ue.wrongOptionType(i,o.getType(),typeof s)))}),n}var GI=class{constructor(t,e){switch(this.Ri=t,this.Le=[],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.Le.join(""),n=new TextEncoder().encode(e),r=await this.Ri.subtle.digest(this.zt,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(r)));case"hex":return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Le.push(t),this}},LI={start:0,end:3},XI={start:4,end:5},Ga={start:6,end:7},La={start:8,end:8},WI={start:9,end:9},UI={start:10,end:15};function PI(){if(crypto&&crypto.getRandomValues){let e=new Uint8Array(16);return crypto.getRandomValues(e),[...e.values()]}let t=[];for(let e=0;e<16;e+=1)t.push(Math.floor(Math.random()*256));return t}function kn(t,e){let n="";for(let r=e.start;r<=e.end;r+=1)n+=t[r].toString(16).padStart(2,"0");return n}function MI(t){return t[La.start]=(t[La.start]|128)&191,t[Ga.start]=t[Ga.start]&15|64,`${kn(t,LI)}-${kn(t,XI)}-${kn(t,Ga)}-${kn(t,La)}${kn(t,WI)}-${kn(t,UI)}`}function FI(){let t=PI();return MI(t)}function AI(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():FI()}var JI=class{createHash(t){return new GI(mI(),t)}randomUUID(){return AI()}};function DI(t){let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e)}var YI=class{btoa(t){return DI(new TextEncoder().encode(t))}},KI=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"4.2.1",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},_I=class{constructor(t,e){this.dt=t,this.n={},this.I=new RS(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Ce=e.errorFilter,this.Ie()}Ie(){this._=new EventSource(this.dt),this._.onopen=()=>{var t;this.I.success(),(t=this.onopen)==null||t.call(this)},this._.onerror=t=>{var e;this.Mi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this._)==null||r.addEventListener(t,n)})})}addEventListener(t,e){var n,r,i;(r=(n=this.n)[t])!=null||(n[t]=[]),this.n[t].push(e),(i=this._)==null||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Gt),this.Gt=void 0,(t=this._)==null||t.close(),(e=this.onclose)==null||e.call(this)}Fi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Gt=setTimeout(()=>{this.Ie()},t)}Mi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Ce(t))&&this.Fi(this.I.fail())}},HI=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new _I(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function nd(){return typeof localStorage!="undefined"}function zI(){if(!nd())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);n&&t.push(n)}return t}var BI=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{let n=localStorage.getItem(t);return n!=null?n:null}catch(n){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(r){(n=this.t)==null||n.error(`Error setting key in localStorage: ${t}, reason: ${r}`)}}},jI=class{constructor(t,e){this.encoding=new YI,this.crypto=new JI,this.requests=new HI,nd()&&(this.storage=new BI(t)),this.info=new KI(e)}},QI=class extends iI{constructor(t,e,n={},r){var i;let{logger:o,debug:s}=n,a=o!=null?o:new Fa({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:s?"debug":"info"}),c=(i=n.baseUri)!=null?i:"https://clientsdk.launchdarkly.com",l=r!=null?r:new jI(a,n),u=OI(n,a),h=NI(me(st({},n),{logger:a})),{eventUrlTransformer:p}=u;super(t,e,l,h,(f,m,d,v,g)=>new vI(l,f,t,m,u,()=>({pathGet(S,T){return`/sdk/evalx/${t}/contexts/${$h(T,S)}`},pathReport(S,T){return`/sdk/evalx/${t}/context`},pathPing(S,T){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(S,T){return`/eval/${t}/${$h(T,S)}`},pathReport(S,T){return`/eval/${t}`},pathPing(S,T){return`/ping/${t}`}}),d,v,g),{getLegacyStorageKeys:()=>zI().filter(f=>f.startsWith(`ld:${t}:`)),analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:f=>new de.InputCustomEvent(f.context,f.key,f.data,f.metricValue,f.samplingRatio,p(yr())),getImplementationHooks:f=>de.safeGetHooks(a,f,u.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.yo=u.plugins,u.fetchGoals&&(this.Kt=new CI(t,l.requests,c,f=>{a.error(f.message)},(f,m)=>{let d=this.getInternalContext();if(!d)return;let v=p(f);ZI(m)?this.sendEvent({kind:"click",url:v,samplingRatio:1,key:m.key,creationDate:Date.now(),context:d,selector:m.selector}):this.sendEvent({kind:"pageview",url:v,samplingRatio:1,key:m.key,creationDate:Date.now(),context:d})}),this.Kt.initialize(),u.automaticBackgroundHandling&&SI(()=>this.flush()))}registerPlugins(t){de.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.yo||[]);let e=this.getDebugOverrides();e&&oI(this.logger,e,this.yo||[])}setInitialContext(t){this.Wt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var n;if(!this.X)return this.logger.error("Client must be started before it can identify a context, did you forget to call start()?"),{status:"error",error:new Error("Identify called before start")};let r=st({},e);(e==null?void 0:e.sheddable)===void 0&&(r.sheddable=!0);let i=await super.identifyResult(t,r);return(n=this.Kt)==null||n.startTracking(),i}start(t){var e,n;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.X)return this.X;if(!this.Wt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let r=me(st({},(e=t==null?void 0:t.identifyOptions)!=null?e:{}),{sheddable:!1});if(t!=null&&t.bootstrap&&!r.bootstrap&&(r.bootstrap=t.bootstrap),r!=null&&r.bootstrap)try{r.bootstrapParsed||(r.bootstrapParsed=$p(this.logger,r.bootstrap)),this.presetFlags(r.bootstrapParsed)}catch(i){this.logger.error("Failed to bootstrap data",i)}return this.initializedPromise||(this.initializedPromise=new Promise(i=>{this.initResolve=i})),this.X=this.promiseWithTimeout(this.initializedPromise,(n=t==null?void 0:t.timeout)!=null?n:5),this.identifyResult(this.Wt,r),this.X}setStreaming(t){this.dataManager.setForcedStreaming(t)}Oe(){let t=this.dataManager,e=this.emitter.eventNames().some(n=>n.startsWith("change:")||n==="change");t.setAutomaticStreamingState(e)}on(t,e){super.on(t,e),this.Oe()}off(t,e){super.off(t,e),this.Oe()}};function $I(t,e,n,r={},i){let o=new QI(t,n,r,i);o.setInitialContext(e);let s={variation:(a,c)=>o.variation(a,c),variationDetail:(a,c)=>o.variationDetail(a,c),boolVariation:(a,c)=>o.boolVariation(a,c),boolVariationDetail:(a,c)=>o.boolVariationDetail(a,c),numberVariation:(a,c)=>o.numberVariation(a,c),numberVariationDetail:(a,c)=>o.numberVariationDetail(a,c),stringVariation:(a,c)=>o.stringVariation(a,c),stringVariationDetail:(a,c)=>o.stringVariationDetail(a,c),jsonVariation:(a,c)=>o.jsonVariation(a,c),jsonVariationDetail:(a,c)=>o.jsonVariationDetail(a,c),track:(a,c,l)=>o.track(a,c,l),on:(a,c)=>o.on(a,c),off:(a,c)=>o.off(a,c),flush:()=>o.flush(),setStreaming:a=>o.setStreaming(a),identify:(a,c)=>o.identifyResult(a,c),getContext:()=>o.getContext(),close:()=>o.close(),allFlags:()=>o.allFlags(),addHook:a=>o.addHook(a),waitForInitialization:a=>o.waitForInitialization(a),logger:o.logger,start:a=>o.start(a)};return o.registerPlugins(s),s}function qI(t){return new Fa(t)}function rd(t,e,n){return $I(t,e,Ji.Disabled,n)}var tT=Object.defineProperty,eT=(t,e,n)=>e in t?tT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Te=(t,e,n)=>eT(t,typeof e!="symbol"?e+"":e,n),nT=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{a(n.next(c))}catch(l){i(l)}},s=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,s);a((n=n.apply(t,e)).next())}),ke=(t,e,...n)=>{let r=`[@launchdarkly plugins]: (${t}): `;console[e].apply(console,[r,...n]),rT(r,...n)},rT=(t,...e)=>nT(void 0,null,function*(){try{let{LDObserve:n}=yield Promise.resolve().then(()=>lR);n.recordLog(`${t}${e}`,"warn")}catch(n){}}),iT=class{constructor(t,e){Te(this,"debug"),Te(this,"name"),this.debug=t,this.name=e}log(...t){if(this.debug){let e=`[${Date.now()}]`;this.name&&(e+=` - ${this.name}`),console.log.apply(console,[e,...t])}}warn(...t){let e=`[${Date.now()}]`;this.name&&(e+=` - ${this.name}`),console.warn.apply(console,[e,...t])}},So=class{constructor(){Te(this,"_sdk"),Te(this,"_isLoaded",!1),Te(this,"_callBuffer",[]),Te(this,"_capacity",1e5),Te(this,"_droppedEvents",0),Te(this,"_exceededCapacity",!1),Te(this,"_logger",new iT)}h(e,n){if(this.Nn)try{return this.jn[e](...n)}catch(r){ke(`Error executing buffered call to ${e}:`,"error",r)}else{this.Pr({method:e,args:n});return}}Pr(e){this.wn.length<this.Is?(this.wn.push(e),this.Qn=!1):(this.Qn||(this.Qn=!0,ke("Exceeded event queue capacity. Increase capacity to avoid dropping events.","warn")),this.Ts+=1)}load(e){this.jn=e,this.Nn=!0;for(let{method:n,args:r}of this.wn)try{this.jn[n](...r)}catch(i){ke(`Error executing buffered call to ${n}:`,"error",i)}this.wn=[]}},oT=Object.defineProperty,sT=Object.defineProperties,aT=Object.getOwnPropertyDescriptors,wo=Object.getOwnPropertySymbols,Af=Object.prototype.hasOwnProperty,Jf=Object.prototype.propertyIsEnumerable,kl=(t,e,n)=>e in t?oT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,j=(t,e)=>{for(var n in e||(e={}))Af.call(e,n)&&kl(t,n,e[n]);if(wo)for(var n of wo(e))Jf.call(e,n)&&kl(t,n,e[n]);return t},An=(t,e)=>sT(t,aT(e)),xr=(t,e)=>{var n={};for(var r in t)Af.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&wo)for(var r of wo(t))e.indexOf(r)<0&&Jf.call(t,r)&&(n[r]=t[r]);return n},Wr=(t,e,n)=>kl(t,typeof e!="symbol"?e+"":e,n),Dn=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{a(n.next(c))}catch(l){i(l)}},s=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,s);a((n=n.apply(t,e)).next())});function lT(t,e){for(var n=0;n<e.length;n++){let r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(let i in r)if(i!=="default"&&!(i in t)){let o=Object.getOwnPropertyDescriptor(r,i);o&&Object.defineProperty(t,i,o.get?o:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}function co(t,e){throw new Error(e)}function cT(t){return typeof t=="object"&&t!==null}function uT(t,e){throw new Error("Unexpected invariant triggered.")}var hT=/\r\n|[\n\r]/g;function Vl(t,e){let n=0,r=1;for(let i of t.body.matchAll(hT)){if(typeof i.index=="number"||uT(),i.index>=e)break;n=i.index+i[0].length,r+=1}return{line:r,column:e+1-n}}function pT(t){return Df(t.source,Vl(t.source,t.start))}function Df(t,e){let n=t.locationOffset.column-1,r="".padStart(n)+t.body,i=e.line-1,o=t.locationOffset.line-1,s=e.line+o,a=e.line===1?n:0,c=e.column+a,l=`${t.name}:${s}:${c}
349
349
  `,u=r.split(/\r\n|[\n\r]/g),h=u[i];if(h.length>120){let p=Math.floor(c/80),f=c%80,m=[];for(let d=0;d<h.length;d+=80)m.push(h.slice(d,d+80));return l+id([[`${s} |`,m[0]],...m.slice(1,p+1).map(d=>["|",d]),["|","^".padStart(f)],["|",m[p+1]]])}return l+id([[`${s-1} |`,u[i-1]],[`${s} |`,h],["|","^".padStart(c)],[`${s+1} |`,u[i+1]]])}function id(t){let e=t.filter(([r,i])=>i!==void 0),n=Math.max(...e.map(([r])=>r.length));return e.map(([r,i])=>r.padStart(n)+(i?" "+i:"")).join(`
350
350
  `)}function dT(t){let e=t[0];return e==null||"kind"in e||"length"in e?{nodes:e,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:e}var fT=class Yf extends Error{constructor(e,...n){var r,i,o;let{nodes:s,source:a,positions:c,path:l,originalError:u,extensions:h}=dT(n);super(e),this.name="GraphQLError",this.path=l!=null?l:void 0,this.originalError=u!=null?u:void 0,this.nodes=od(Array.isArray(s)?s:s?[s]:void 0);let p=od((r=this.nodes)===null||r===void 0?void 0:r.map(m=>m.loc).filter(m=>m!=null));this.source=a!=null?a:p==null||(i=p[0])===null||i===void 0?void 0:i.source,this.positions=c!=null?c:p==null?void 0:p.map(m=>m.start),this.locations=c&&a?c.map(m=>Vl(a,m)):p==null?void 0:p.map(m=>Vl(m.source,m.start));let f=cT(u==null?void 0:u.extensions)?u==null?void 0:u.extensions:void 0;this.extensions=(o=h!=null?h:f)!==null&&o!==void 0?o:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),u!=null&&u.stack?Object.defineProperty(this,"stack",{value:u.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,Yf):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(let n of this.nodes)n.loc&&(e+=`
351
351