@launchdarkly/browser 0.1.3 → 0.1.4
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 +9 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.1.4](https://github.com/launchdarkly/js-core/compare/browser-v0.1.3...browser-v0.1.4) (2026-02-04)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Dependencies
|
|
7
|
+
|
|
8
|
+
* The following workspace dependencies were updated
|
|
9
|
+
* dependencies
|
|
10
|
+
* @launchdarkly/js-client-sdk bumped from 0.13.1 to 4.0.0
|
|
11
|
+
|
|
3
12
|
## [0.1.3](https://github.com/launchdarkly/js-core/compare/browser-v0.1.2...browser-v0.1.3) (2026-02-03)
|
|
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:xe.Initialize,sessionSecureID:this.sessionData.sessionSecureID,backend:this.pn,debug:!!this.debugOptions.clientInteractions,recordingStartTime:this.Bn}});for(let b of this.xn)b.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.ko||(this.pushPayloadTimerId=setTimeout(()=>{this.Ls()},ig)),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=(b,I)=>{I&&this.logger.log("received isCheckout emit",{event:b}),this.events.push(b)};f.bind(this);let m=!!this.Sn;this.Sn&&(this.Sn(),this.Sn=void 0);let[d,v]=IF(this.privacySetting);this.Sn=Oe({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:b=>!this.options.recordCrossOriginIframe,inlineImages:this.inlineImages,inlineVideos:this.inlineVideos,collectFonts:this.inlineImages,inlineStylesheet:this.inlineStylesheet,plugins:[qX()],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.ml(),document.referrer&&(window&&document.referrer.includes(window.location.origin)||(this.addCustomEvent("Referrer",document.referrer),this.addProperties({referrer:document.referrer},{type:"session"}))),this.yl(),this.ready=!0,this.state="Recording",this.manualStopped=!1}catch(u){Ht("initializeSession _setupWindowListeners","warn",u)}})}Xs(e){return Dt(this,null,function*(){if(this.manualStopped){this.logger.log("Ignoring visibility event due to manual stop.");return}new Date().getTime()-this.Gs<gX||(this.Gs=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)))})}fl(){return Dt(this,null,function*(){this.logger.log("highlight in cross-origin iframe is waiting "),yield new Promise(e=>{let n=r=>{if(r.data.highlight===fb){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:mb},"*"),window.removeEventListener("message",n),e()}};window.addEventListener("message",n)})})}ml(){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:fb,projectID:this.sessionData.projectID,sessionSecureID:this.sessionData.sessionSecureID},"*")})},ig),window.addEventListener("message",e=>{e.data.highlight===mb&&this.logger.log("highlight got response from initialized iframe")})}yl(){var e;try{let r=this;this.enableSegmentIntegration&&this.listeners.push(CF(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(wF(o=>{this.reloaded?(this.addCustomEvent("Reload",o),this.reloaded=!1,r.addProperties({reload:!0},{type:"session"})):this.addCustomEvent("Navigate",o)})),this.listeners.push(KX(o=>{this.addCustomEvent("Viewport",o)})),this.listeners.push(TF((o,s)=>{let a=null,c=null;if(s&&s.target){let l=s.target;a=DX(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(EF(o=>{o&&this.addCustomEvent("Focus",o)})),this.sessionShortcut&&kF(this.sessionShortcut,()=>{window.open(this.getCurrentSessionURLWithTimestamp(),"_blank")}),this.Ns||((e=window.electron)!=null&&e.ipcRenderer?(window.electron.ipcRenderer.on("highlight.run",({visible:o})=>{this.Xs(!o)}),this.logger.log("Set up Electron highlight.run events.")):(RF(o=>this.Xs(o)),this.logger.log("Set up document visibility listener.")),this.Ns=!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",""),ai(this.sessionData.sessionSecureID),wn(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",""),ai(this.sessionData.sessionSecureID),wn(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://${sg}/${n}/sessions/${r}?ts=${i}`}getCurrentSessionURL(){let e=this.sessionData.projectID,n=this.sessionData.sessionSecureID;return e&&n?`https://${sg}/${e}/sessions/${n}`:null}snapshot(e){return Dt(this,null,function*(){yield Oe.snapshotCanvas(e)})}addSessionFeedback({timestamp:e,verbatim:n,user_email:r,user_name:i}){var o;this.zn.postMessage({message:{type:xe.Feedback,verbatim:n,timestamp:e,userName:i||this.sessionData.userIdentifier,userEmail:r||((o=this.sessionData.userObject)==null?void 0:o.name)}})}Ls(){return Dt(this,null,function*(){var e;try{this.state==="Recording"&&this.listeners&&this.sessionData.sessionStartTime&&Date.now()-this.sessionData.sessionStartTime>yX&&(this.logger.log("Resetting session",{start:this.sessionData.sessionStartTime}),yield this.Os({}));let n;((e=this.options)==null?void 0:e.sendMode)==="local"&&(n=r=>Dt(this,null,function*(){let i=new Blob([JSON.stringify({query:Nb(Ub),variables:r})],{type:"application/json"});return yield window.fetch(`${this.pn}`,{method:"POST",body:i}),0})),yield this.gl({sendFn:n}),this.hasPushedData=!0,this.sessionData.lastPushTime=Date.now(),wn(this.sessionData)}catch(n){Ht("_save","warn",n)}this.state==="Recording"&&(this.pushPayloadTimerId&&(clearTimeout(this.pushPayloadTimerId),this.pushPayloadTimerId=void 0),this.pushPayloadTimerId=setTimeout(()=>{this.Ls()},mX))})}addCustomEvent(e,n){if(this.state==="NotRecording"){let r,i=()=>{clearInterval(r),this.state==="Recording"&&this.events.length>0?hb(e,n):r=setTimeout(i,500)};r=setTimeout(i,500)}else this.state==="Recording"&&(this.events.length>0||this.hasPushedData)&&hb(e,n)}gl(e){return Dt(this,arguments,function*({sendFn:n}){let r=[...this.events],{bytes:i,time:o}=this.enableCanvasRecording?og.canvas:og.normal;this.br>=i&&new Date().getTime()-this.xo>=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=UF();n?yield n({session_secure_id:this.sessionData.sessionSecureID,payload_id:(this.sessionData.payloadID++).toString(),events:{events:r},messages:zL({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:xe.AsyncEvents,id:this.sessionData.payloadID++,events:r,messages:[],errors:[],resourcesString:JSON.stringify({resources:[]}),webSocketEventsString:JSON.stringify({webSocketEvents:[]}),hasSessionUnloaded:this.hasSessionUnloaded,highlightLogs:s}}),wn(this.sessionData),this.events=this.events.slice(r.length),PF(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.xo}),Oe.takeFullSnapshot(),this.br=0,this.xo=new Date().getTime()}register(e,n){this.xn.push(new hu(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=Zs(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(wX);if(r&&(e=r==null?void 0:r.groups)!=null&&e.domain){let i=(n=r.groups.domain)!=null?n:"";return`https://${vX[i]}${SX}`}return bX}},Ri=class extends _X{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=Yt(z({},n),{organizationID:e,firstloadVersion:YF,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 ih(f),n!=null&&n.manualStart||this.record.start(),ze.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&&JF(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&&AF(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=FX(n.context),f=AX(n.context);(h=this.record)==null||h.identify(typeof f=="string"?f:(u=(l=f.user)==null?void 0:l.toString())!=null?u:p,Yt(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 _F={};Dh(_F,{LDObserve:()=>Je,LDRecord:()=>ze,basicLogger:()=>jI,createClient:()=>KF});module.exports=tS(_F);var eS=Object.defineProperty,nS=Object.defineProperties,rS=Object.getOwnPropertyDescriptors,Pi=Object.getOwnPropertySymbols,dp=Object.prototype.hasOwnProperty,fp=Object.prototype.propertyIsEnumerable,Yh=(t,e,n)=>e in t?eS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,st=(t,e)=>{for(var n in e||(e={}))dp.call(e,n)&&Yh(t,n,e[n]);if(Pi)for(var n of Pi(e))fp.call(e,n)&&Yh(t,n,e[n]);return t},fe=(t,e)=>nS(t,rS(e)),mp=(t,e)=>{var n={};for(var r in t)dp.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&Pi)for(var r of Pi(t))e.indexOf(r)<0&&fp.call(t,r)&&(n[r]=t[r]);return n};function iS(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function yp(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function oS(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>yp(e))}function sS(t){return!t.startsWith("/")}function aS(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var xn=class{constructor(t,e=!1){if(e){let n=t;this.g=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?iS(n):n}else{if(this.redactionName=t,t===""||t==="/"||!aS(t)){this.isValid=!1,this.g=[];return}sS(t)?this.g=[t]:t.indexOf("/",1)<0?this.g=[yp(t.slice(1))]:this.g=oS(t),this.g[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{g: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.g[t]}get depth(){return this.g.length}get isKind(){return this.g.length===1&&this.g[0]==="kind"}compare(t){return this.depth===t.depth&&this.g.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.g]}};xn.InvalidReference=new xn("");var lS=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},Gn=class{constructor(t,e){this.mt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.mt}},gp=class{constructor(t,e){this.mt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.mt}},bp=class extends Gn{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},vp=class extends Gn{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},cS=class{is(t){return typeof t=="function"}getType(){return"function"}},uS=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},hS=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,pS=class{is(t){return typeof t=="number"||typeof t=="string"&&hS.test(t)}getType(){return"date"}},dS=class extends vp{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},G=class{static createTypeArray(t,e){return new gp(t,e)}static numberWithMin(t){return new bp(t)}static stringMatchingRegex(t){return new vp(t)}};G.String=new Gn("string","");G.Number=new Gn("number",0);G.ObjectOrFactory=new lS;G.Object=new Gn("object",{});G.StringArray=new gp("string[]","");G.Boolean=new Gn("boolean",!0);G.Function=new cS;G.Date=new pS;G.Kind=new dS;G.NullableBoolean=new uS;function Sp(t){return"kind"in t?G.String.is(t.kind)&&t.kind!=="multi":!1}function wp(t){return"kind"in t?G.String.is(t.kind)&&t.kind==="multi":!1}function Ip(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function Mi(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=>Mi(n,[...e,t])).map(n=>n===void 0?"null":n).join(",")}]`:`{${Object.keys(t).sort().map(n=>{let r=Mi(t[n],[...e,t]);if(r!==void 0)return`${JSON.stringify(n)}:${r}`}).filter(n=>n!==void 0).join(",")}}`}var La="user";function Kh(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function fS(t){return t&&G.Object.is(t)}function _h(t){return G.Kind.is(t)}function Hh(t){return G.String.is(t)&&t!==""}function Ra(t,e=!1){return t?t.map(n=>new xn(n,e)):[]}function mS(t){return t!=null}function yS(t){let e=fe(st({},t.custom||[]),{kind:"user",key:String(t.key)});if(mS(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 Vn=class wt{constructor(e,n,r){this.C=!1,this.it=!1,this.Xt=!1,this.$={},this.kind=n,this.valid=e,this.message=r}static b(e,n){return new wt(!1,e,n)}static Re(e,n){if(!(!n||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(n!=null&&n.anonymous):e.get(n)}Qt(e){if(this.C)return this.$[e];if(this.kind===e)return this.y}static Me(e){let n=Object.keys(e).filter(c=>c!=="kind"),r=n.every(_h);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 fS(h)?(c[l]=h,i[l]=Ra((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=>Hh(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=fe(st({},s[c]),{kind:c}),l.nt=i,l.it=c==="user",l}let a=new wt(!0,e.kind);return a.$=s,a.nt=i,a.C=!0,a}static Fe(e){var n;let{key:r,kind:i}=e,o=_h(i),s=Hh(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=Ra((n=e._meta)==null?void 0:n.privateAttributes),c=new wt(!0,i);return c.it=i==="user",c.y=e,c.nt={[i]:a},c}static Ue(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.it=!0,n.Xt=!0,n.y=yS(e),n.nt={user:Ra(e.privateAttributeNames,!0)},n}static fromLDContext(e){return e?Sp(e)?wt.Fe(e):wp(e)?wt.Me(e):Ip(e)?wt.Ue(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=La){return e.isKind?this.kinds:wt.Re(e,this.Qt(n))}key(e=La){var n;return(n=this.Qt(e))==null?void 0:n.key}get isMultiKind(){return this.C}get canonicalKey(){return this.it?this.y.key:this.C?Object.keys(this.$).sort().map(e=>`${e}:${Kh(this.$[e].key)}`).join(":"):`${this.kind}:${Kh(this.y.key)}`}get kinds(){return this.C?Object.keys(this.$):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.$).reduce((e,[n,r])=>(e[n]=r.key,e),{}):{[this.kind]:this.y.key}}privateAttributes(e){var n;return((n=this.nt)==null?void 0:n[e])||[]}getContexts(){return this.C?Object.entries(this.$):[[this.kind,this.y]]}get legacy(){return this.Xt}canonicalUnfilteredJson(){if(this.valid){if(this.yt)return this.yt;try{this.yt=Mi(wt.toLDContext(this))}catch(e){}return this.yt}}};Vn.UserKind=La;var gS=["key","kind","_meta","anonymous"].map(t=>new xn(t,!0)),bS=["name","ip","firstName","lastName","email","avatar","country"];function vS(t,e){return t.depth===e.length&&e.every((n,r)=>n===t.getComponent(r))}function SS(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=>vS(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 wS=class{constructor(t,e){this.Ve=t,this.je=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.te(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([i,o])=>{r[i]=this.te(t,o,i,e)}),r}He(t,e,n,r){return(r?Object.keys(e).map(i=>new xn(i,!0)):[...this.je,...t.privateAttributes(n)]).filter(i=>!gS.some(o=>o.compare(i)))}te(t,e,n,r){let i=this.Ve||r&&e.anonymous===!0,{cloned:o,excluded:s}=SS(e,this.He(t,e,n,i));return t.legacy&&bS.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}},zh=30*1e3,IS=.5,TS=class{constructor(t,e,n=Math.random){this.Be=e,this.ze=n,this.vt=0,this.ee=Math.max(1,t),this.Ge=Math.ceil(Math.log2(zh/this.ee))}I(){let t=Math.min(this.vt,this.Ge),e=this.ee*2**t;return Math.min(e,zh)}Ke(t){return t-Math.trunc(this.ze()*IS*t)}success(t=Date.now()){this.wt=t}fail(t=Date.now()){this.wt!==void 0&&t-this.wt>this.Be&&(this.vt=0),this.wt=void 0;let e=this.Ke(this.I());return this.vt+=1,e}},Bh;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(Bh||(Bh={}));var Fi=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},Xa=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},zF=120*1e3,BF=300*1e3,Kt;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(Kt||(Kt={}));var Ai;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(Ai||(Ai={}));var Nn;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(Nn||(Nn={}));var tn;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(tn||(tn={}));function kn(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 ES(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function RS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function CS(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var Ca={s:t=>kn(t),d:t=>ES(t),i:t=>RS(t),f:t=>CS(t),j:t=>kn(t),o:t=>kn(t),O:t=>kn(t),c:()=>""};function Wa(...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 Ca&&t.length){let a=t.shift();r+=(e=Ca[s])==null?void 0:e.call(Ca,a)}else s==="%"?r+="%":r+=`%${s}`;i+=2}}else r+=o,i+=1}return t.length&&(r.length&&(r+=" "),r+=t.map(kn).join(" ")),r}return t.map(kn).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 ZS=["debug","info","warn","error","none"],Ma=class Tp{static get(){return new Tp({})}constructor(e){var n,r,i;if(this.Qe=(r=Vt[(n=e.level)!=null?n:"info"])!=null?r:Vt.info,this.ti=(i=e.name)!=null?i:"LaunchDarkly",this.ae=e.formatter,typeof e.destination=="object")this.oe={[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.oe={[Vt.debug]:o,[Vt.info]:o,[Vt.warn]:o,[Vt.error]:o}}}ei(...e){var n;try{return this.ae?(n=this.ae)==null?void 0:n.call(this,...e):Wa(...e)}catch(r){return Wa(...e)}}ii(e,n){try{e(n)}catch(r){console.error(n)}}k(e,n){var r;if(e>=this.Qe){let i=`${ZS[e]}: [${this.ti}]`;try{let o=(r=this.oe)==null?void 0:r[e];o?this.ii(o,`${i} ${this.ei(...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)}},kS={error:G.Function,warn:G.Function,info:G.Function,debug:G.Function},Ep=class{constructor(t,e){Object.entries(kS).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.ni=e}k(t,e){try{this.t[t](...e)}catch(n){this.ni[t](...e)}}error(...t){this.k("error",t)}warn(...t){this.k("warn",t)}info(...t){this.k("info",t)}debug(...t){this.k("debug",t)}},Rp=t=>{let e=new Ma({level:"info",destination:console.error,formatter:Wa});return t?new Ep(t,e):e},We=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`}},VS=/^(\w|\.|-)+$/,xS=G.stringMatchingRegex(VS),NS={is:(t,e)=>xS.is(t)?t.length>64?{valid:!1,message:We.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:We.invalidTagValue(e)}},OS=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}=NS.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(" "))}},GS=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 Za(t){return t.replace(/\/+$/,"")}function Fa(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var Ji=class Cp{constructor(e,n,r=Cp.DEFAULT_EVENTS,i="/bulk",o="/diagnostic",s=!0,a){this.streaming=Za(e),this.polling=Za(n),this.events=Za(r),this.analyticsEventPath=i,this.diagnosticEventPath=o,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}};Ji.DEFAULT_EVENTS="https://events.launchdarkly.com";function Aa(t,e=[]){if(e.length===0)return t;let n=e.map(({key:r,value:i})=>`${r}=${i}`);return`${t}?${n.join("&")}`}function LS(t,e,n){let r=Fa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Aa(`${t.streaming}/${r}`,i)}function XS(t,e,n=[]){let r=Fa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Aa(`${t.polling}/${r}`,i)}function jh(t,e,n=[]){let r=Fa(e);return Aa(`${t.events}/${r}`,n)}var Zp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},WS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},kp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Ki(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function US(t){return t===413?!0:Ki(t)}function PS(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 kp(s))},t*1e3)}),cancel:()=>{r(),clearTimeout(n)}}}function Vp(t){return t==null?t:JSON.parse(JSON.stringify(t))}function ka(t){return Math.trunc(t*1e3)}var MS=t=>JSON.stringify(t)==="{}",Ja=(t,e)=>t&&Object.entries(t).reduce((n,[r,i])=>(i&&!MS(i)&&!(e!=null&&e.includes(r))&&(n[r]=typeof i=="object"?Ja(i,e):i),n),{});function Wi(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(!Wi(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(!Wi(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(!Wi(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function FS(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 On(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 xp({status:t}){return t?Ki(t):!0}var Qh=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Np=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),AS=class{constructor(t,e,n){this.p=e,this.si=n,this.bt=[],this.ce=Date.now(),this.le=this.ce,this.ue={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var t,e,n;let r=this.p.info.sdkData(),i=this.p.info.platformData();return{kind:"diagnostic-init",id:this.ue,creationDate:this.ce,sdk:r,configuration:this.si,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.bt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),i={kind:"diagnostic",id:this.ue,creationDate:r,dataSinceDate:this.le,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.bt};return this.bt=[],this.le=r,i}},Ua;(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"})(Ua||(Ua={}));var JS=Ua,Op=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};Op.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var DS=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:o}}=n,{crypto:s,requests:a}=r;this.ri=st({},e),this.he=jh(n.serviceEndpoints,i,[]),this.ai=jh(n.serviceEndpoints,o,[]),this.H=a,this.oi=s}async st(t,e,n,r){let i={status:tn.Succeeded},o=fe(st({},this.ri),{"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.H.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 Zp(On({status:a,message:"some events were dropped"},"event posting")),!Ki(a))return US(a)?i.status=tn.Failed:i.status=tn.FailedAndMustShutDown,i.error=s,i}catch(a){s=a}return s&&!r?(i.status=tn.Failed,i.error=s,i):(await Np(),this.st(t,this.he,n,!1))}async sendEventData(t,e){let n=t===Nn.AnalyticsEvents?this.oi.randomUUID():void 0,r=t===Nn.AnalyticsEvents?this.he:this.ai;return this.st(e,r,n,!0)}};function Di(t){return t.kind==="feature"}function YS(t){return t.kind==="identify"}function KS(t){return t.kind==="migration_op"}var _S=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 HS(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Gp=class{constructor(t=!1,e){this.ci=t,this.x=e,this.Y=0,this.rt=0,this.at={},this.ot={}}summarizeEvent(t){if(Di(t)&&!t.excludeFromSummaries){this.y||(this.y=t.context);let e=HS(t),n=this.at[e],r=this.ot[t.key];r||(r=new Set,this.ot[t.key]=r),t.context.kinds.forEach(i=>r.add(i)),n?n.increment():this.at[e]=new _S(1,t.key,t.value,t.default,t.version,t.variation),(this.Y===0||t.creationDate<this.Y)&&(this.Y=t.creationDate),t.creationDate>this.rt&&(this.rt=t.creationDate)}}getSummary(){var t;let e=Object.values(this.at).reduce((r,i)=>{let o=r[i.key];o||(o={default:i.default,counters:[],contextKinds:[...this.ot[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.Y,endDate:this.rt,features:e,kind:"summary",context:this.y!==void 0&&this.ci?(t=this.x)==null?void 0:t.filter(this.y):void 0};return this.li(),n}li(){this.Y=0,this.rt=0,this.at={},this.ot={}}},zS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},BS=class{constructor(t,e){this.x=t,this.t=e,this.Z={}}summarizeEvent(t){var e;if(Di(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.Z[n];r||(this.Z[n]=new Gp(!0,this.x),r=this.Z[n]),r.summarizeEvent(t)}}getSummaries(){let t=this.Z;return this.Z={},Object.values(t).map(e=>e.getSummary())}};function Ui(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function jS(t){return t.getSummaries!==void 0}var QS=class{constructor(t,e,n,r,i,o=!0,s=!1){this.e=t,this.ct=r,this.S=i,this.lt=[],this.de=0,this.kt=0,this.xt=0,this.St=!1,this.fe=0,this.Lt=!1,this.Ct=null,this.ui=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.pe=new DS(e,n),this.x=new wS(t.allAttributesPrivate,t.privateAttributes.map(a=>new xn(a))),s?this.X=new BS(this.x,this.t):this.X=new Gp,o&&this.start()}start(){var t,e;if(((t=this.ct)==null?void 0:t.flushInterval)!==void 0&&(this.Ct=setInterval(()=>{var n;(n=this.ct)==null||n.flush()},this.ct.flushInterval*1e3)),this.hi=setInterval(async()=>{var n;try{await this.flush()}catch(r){(n=this.t)==null||n.debug(`Flush failed: ${r}`)}},this.e.flushInterval*1e3),this.S){let n=this.S.createInitEvent();this.ge(n),this.me=setInterval(()=>{let r=this.S.createStatsEventAndReset(this.kt,this.xt,this.fe);this.kt=0,this.xt=0,this.ge(r)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}ge(t){this.pe.sendEventData(Nn.DiagnosticEvent,t)}close(){clearInterval(this.hi),this.Ct&&clearInterval(this.Ct),this.me&&clearInterval(this.me)}async flush(){var t;if(this.Lt)throw new zS("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.lt;if(this.lt=[],jS(this.X))this.X.getSummaries().forEach(n=>{Object.keys(n.features).length&&e.push(n)});else{let n=this.X.getSummary();Object.keys(n.features).length&&e.push(n)}e.length&&(this.fe=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.st(e))}sendEvent(t){var e;if(this.Lt)return;if(KS(t)){if(Ui(t.samplingRatio)){let a=fe(st({},t),{context:t.context?this.x.filter(t.context):void 0});a.samplingRatio===1&&delete a.samplingRatio,this.ut(a)}return}this.X.summarizeEvent(t);let n=Di(t),r=n&&t.trackEvents||!n,i=this.di(t),o=YS(t),s=(e=this.ct)==null?void 0:e.processContext(t.context);s||o||(this.xt+=1),s&&!o&&this.ut(this.It({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),r&&Ui(t.samplingRatio)&&this.ut(this.It(t,!1)),i&&Ui(t.samplingRatio)&&this.ut(this.It(t,!0))}It(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.x.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}ut(t){var e;this.lt.length<this.ui?(this.lt.push(t),this.St=!1):(this.St||(this.St=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.kt+=1)}di(t){return Di(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.de&&t.debugEventsUntilDate>Date.now()}async st(t){let e=await this.pe.sendEventData(Nn.AnalyticsEvents,t);if(e.status===tn.FailedAndMustShutDown&&(this.Lt=!0),e.serverTime&&(this.de=e.serverTime),e.error)throw e.error}},Lp=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}},Pa=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)}},Xp=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},$S=class{close(){}async flush(){}sendEvent(){}},qS=class{constructor(t){this.At=t}evalEvent(t){var e;return new Pa(this.At,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.At||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new Pa(this.At,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Xp(t,1)}customEvent(t,e,n,r,i=1){return new Lp(e,t,n!=null?n:void 0,r!=null?r:void 0,i)}},$h="FDv1Fallback";function tw(t){return{fi:t,ye:"",useSelector(e){return this.ye=e,this},processFullTransfer(e){let n=[{event:"server-intent",data:{payloads:[{id:$h,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.ye,version:1,id:$h}}),this.fi.processEvents(n)}}}var Wp=class{constructor(t,e,n){this.pi=t,this.m=e,this.t=n,this.n=[],this.N=void 0,this.B=!1,this.z=[],this.gi=r=>{var i;if(this.Pt(),!r.payloads.length)return;let o=r.payloads[0];switch(o==null?void 0:o.intentCode){case"xfer-full":this.B=!0;break;case"xfer-changes":this.B=!1;break;case"none":this.B=!1,this.mi(o);break;default:(i=this.t)==null||i.warn(`Unable to process intent code '${o==null?void 0:o.intentCode}'.`);return}this.N=o==null?void 0:o.id},this.yi=r=>{var i;if(!this.N||!r.kind||!r.key||!r.version||!r.object)return;let o=this.vi(r.kind,r.object);if(!o){(i=this.t)==null||i.warn(`Unable to process object for kind: '${r.kind}'`);return}this.z.push({kind:r.kind,key:r.key,version:r.version,object:o})},this.wi=r=>{!this.N||!r.kind||!r.key||!r.version||this.z.push({kind:r.kind,key:r.key,version:r.version,deleted:!0})},this.mi=r=>{if(!r.id||!r.target)return;let i={id:r.id,version:r.target,basis:!1,updates:[]};this.n.forEach(o=>o(i)),this.ve()},this.Ei=r=>{if(!this.N||r.state===null||r.state===void 0||!r.version){this.Pt();return}let i={id:this.N,version:r.version,state:r.state,basis:this.B,updates:this.z};this.n.forEach(o=>o(i)),this.ve()},this.Di=r=>{var i;(i=this.t)==null||i.info(`Goodbye was received from the LaunchDarkly connection with reason: ${r.reason}.`),this.Pt()},this.bi=r=>{var i;(i=this.t)==null||i.info(`An issue was encountered receiving updates for payload ${this.N} with reason: ${r.reason}.`),this.ki()}}addPayloadListener(t){this.n.push(t)}removePayloadListener(t){let e=this.n.indexOf(t,0);e>-1&&this.n.splice(e,1)}processEvents(t){t.forEach(e=>{switch(e.event){case"server-intent":{this.gi(e.data);break}case"put-object":{this.yi(e.data);break}case"delete-object":{this.wi(e.data);break}case"payload-transferred":{this.Ei(e.data);break}case"goodbye":{this.Di(e.data);break}case"error":{this.bi(e.data);break}}})}vi(t,e){var n,r;return(r=(n=this.pi)[t])==null?void 0:r.call(n,e)}ve(){this.B=!1,this.z=[]}ki(){this.z=[]}Pt(){this.N=void 0,this.B=!1,this.z=[]}},ew=class{constructor(t,e,n,r){this.m=n,this.t=r,this.G(t,"server-intent"),this.G(t,"put-object"),this.G(t,"delete-object"),this.G(t,"payload-transferred"),this.G(t,"goodbye"),this.G(t,"error"),this.Ot=new Wp(e,n,r)}addPayloadListener(t){this.Ot.addPayloadListener(t)}removePayloadListener(t){this.Ot.removePayloadListener(t)}G(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.Ot.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.m)==null||s.call(this,Kt.InvalidData,"Malformed data in EventStream.")}}else(a=this.m)==null||a.call(this,Kt.Unknown,"Event from EventStream missing data.")})}};function nw(t){if(t){let e=Object.keys(t).find(n=>n.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var qh="unknown plugin";function Yi(t,e){try{return e.getMetadata().name||qh}catch(n){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),qh}}function rw(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 ${Yi(t,i)} returned undefined from getHooks.`):s&&s.length>0&&r.push(...s)}catch(s){t.error(`Exception thrown getting hooks for plugin ${Yi(t,i)}. Unable to get hooks.`)}}),r}function iw(t,e,n,r){r.forEach(i=>{try{i.register(n,e)}catch(o){t.error(`Exception thrown registering plugin ${Yi(t,i)}.`)}})}var pe=Object.freeze({__proto__:null,ClientMessages:Op,DiagnosticsManager:AS,ErrorKinds:JS,EventFactoryBase:qS,EventProcessor:QS,FDv1PayloadAdaptor:tw,InputCustomEvent:Lp,InputEvalEvent:Pa,InputIdentifyEvent:Xp,NullEventProcessor:$S,PayloadProcessor:Wp,PayloadStreamReader:ew,canonicalize:Mi,initMetadataFromHeaders:nw,isLegacyUser:Ip,isMultiKind:wp,isSingleKind:Sp,safeGetHooks:rw,safeGetName:Yi,safeRegisterPlugins:iw,shouldSample:Ui}),ow={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function sw(t){return t>=200&&t<=299}var tp=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function ep(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=XS(e,f,m);return{async requestPayload(){let v;try{let b=await r.fetch(d,{method:h,headers:p,body:u});if(sw(b.status))return await b.text();v=b.status}catch(b){throw new tp(b==null?void 0:b.message)}throw new tp(`Unexpected status code: ${v}`,v)}}}var np=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function aw(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(np)),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(np)),s=!0,o.then(a=>{r({status:"shed"},a)})},promise:i,sheddable:n}}function lw(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=aw(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 cw={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},uw=300,Up="https://clientsdk.launchdarkly.com",Pp="https://clientstream.launchdarkly.com";function hw(t){return t instanceof Ep?t:Rp(t)}var pw=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var n,r,i;this.logger=Rp(),this.baseUri=Up,this.eventsUri=Ji.DEFAULT_EVENTS,this.streamUri=Pp,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=uw,this.hooks=[],this.inspectors=[],this.logger=hw(t.logger),this.xi(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new Ji(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 OS({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}xi(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let i=cw[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(We.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(o==="boolean | undefined | null")e.push(We.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(i instanceof bp&&G.Number.is(r)){let{min:s}=i;e.push(We.optionBelowMinimum(n,r,s)),this[n]=s}else e.push(We.wrongOptionType(n,i.getType(),typeof r))}else e.push(We.unknownOption(n))}),e}};async function Mp(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 Fp=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 Ap(t){return async e=>Mp(t.createHash("sha256").update(e),"base64")}var de=async t=>t;async function yr(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function dw(t,e){return yr([{value:"LaunchDarkly",transform:de},{value:e,transform:Ap(t)}])}async function fw(t){return yr([{value:"LaunchDarkly",transform:de},{value:"AnonymousKeys",transform:de},{value:t,transform:de}])}async function mw(t){return yr([{value:"LaunchDarkly",transform:de},{value:"ContextKeys",transform:de},{value:t,transform:de}])}async function yw(t){return yr([{value:t,transform:de},{value:"ContextIndex",transform:de}])}async function rp(t,e,n){return yr([{value:e,transform:de},{value:n.canonicalKey,transform:Ap(t)}])}var{isLegacyUser:gw,isSingleKind:Va,isMultiKind:ip}=pe,Jp="1.0",bw=t=>{let e=t,{kind:n}=e,r=mp(e,["kind"]);return{kind:"multi",[n]:r}},vw=async({crypto:t,info:e},{applicationInfo:n})=>{var r;let{ld_application:i}=e.platformData(),o=(r=Ja(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(fe(st({},o),{id:s}),a?{version:a}:{}),c?{name:c}:{}),l?{versionName:l}:{}),o.key=await Mp(t.createHash("sha256").update(s),"base64"),o.envAttributesVersion=o.envAttributesVersion||Jp,o}},Sw=async t=>{var e,n,r,i;let{ld_device:o,os:s}=t.info.platformData(),a=(e=Ja(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 mw("ld_device");return a.key=await Fp(h,t),a.envAttributesVersion=a.envAttributesVersion||Jp,a}},ww=async(t,e,n)=>{if(gw(t))return t;let r,i;if(Va(t)&&t.kind!=="ld_application"||ip(t)&&!t.ld_application?r=await vw(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),Va(t)&&t.kind!=="ld_device"||ip(t)&&!t.ld_device?i=await Sw(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),r||i){let o=Va(t)?bw(t):t;return st(st(st({},o),r?{ld_application:r}:{}),i?{ld_device:i}:{})}return t};function Iw(){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:Tw,isMultiKind:Ew,isSingleKind:Rw}=pe,Da=async(t,e,n)=>{let{anonymous:r,key:i}=e;if(r&&!i){let o=await fw(t);e.key=await Fp(o,n)}},Cw=async(t,e)=>{await Da(t.kind,t,e)},Zw=async(t,e)=>{let n=t,{kind:r}=n,i=mp(n,["kind"]);return Promise.all(Object.entries(i).map(([o,s])=>Da(o,s,e)))},kw=async(t,e)=>{await Da("user",t,e)},Vw=async(t,e)=>{let n=Vp(t);return Rw(n)&&await Cw(n,e),Ew(n)&&await Zw(n,e),Tw(n)&&await kw(n,e),n},xw=t=>({customBaseURI:t.serviceEndpoints.polling!==Up,customStreamURI:t.serviceEndpoints.streaming!==Pp,customEventsURI:t.serviceEndpoints.events!==Ji.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:ka(t.flushInterval),reconnectTimeMillis:ka(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:ka(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Nw=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new pe.DiagnosticsManager(t,n,xw(e))};function op(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function sp(t,e,n){return st({value:t,variationIndex:e!=null?e:null},n!==void 0&&{reason:n})}var Ow=(t,e,n,r,i)=>{if(e.sendEvents)return new pe.EventProcessor(fe(st({},e),{eventsCapacity:e.capacity}),new GS(t,e,n),r,void 0,i,!1,!0)},ap=class extends pe.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})}},xa=class Dp{constructor(){this.container={index:new Array}}static fromJson(e){let n=new Dp;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)):[]}},Gw=class{constructor(t,e,n,r,i,o,s=()=>Date.now()){this.p=t,this.Tt=e,this.Si=n,this.P=r,this.w=i,this.t=o,this.Li=s,this.we=yw(this.Tt)}async init(t,e){this.w.init(t,e),await this.Ee(t)}async upsert(t,e,n){return this.w.upsert(t,e,n)?(await this.Ee(t),!0):!1}async loadCached(t){var e,n,r,i;let o=await rp(this.p.crypto,this.Tt,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 Ci(){var t;if(this.K!==void 0)return this.K;let e=await((t=this.p.storage)==null?void 0:t.get(await this.we));if(!e)return this.K=new xa,this.K;try{this.K=xa.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.K=new xa}return this.K}async Ee(t){var e,n;let r=await this.Ci(),i=await rp(this.p.crypto,this.Tt,t);r.notice(i,this.Li());let o=r.prune(this.Si);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.we,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 Lw(){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 Xw(t,e){let n=[];return Object.entries(t).forEach(([r,i])=>{let o=e[r];(!o||!Wi(i,o))&&n.push(r)}),Object.keys(e).forEach(r=>{t[r]||n.push(r)}),n}function Ww(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=Xw(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 Uw=class{constructor(t,e,n,r,i=()=>Date.now()){this.P=Lw(),this.w=Ww(this.P,r),this.$t=this.Ii(t,e,n,r,i)}async Ii(t,e,n,r,i=()=>Date.now()){let o=await dw(t.crypto,e);return new Gw(t,o,n,this.P,this.w,r,i)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.Nt(this.r[t]):this.P.get(t)}getAll(){return this.r?st(st({},this.P.getAll()),Object.entries(this.r).reduce((t,[e,n])=>(t[e]=this.Nt(n),t),{})):this.P.getAll()}presetFlags(t){this.P.init(t)}setBootstrap(t,e){this.w.init(t,e)}async init(t,e){return(await this.$t).init(t,e)}async upsert(t,e,n){return(await this.$t).upsert(t,e,n)}async loadCached(t){return(await this.$t).loadCached(t)}on(t){this.w.on(t)}off(t){this.w.off(t)}Nt(t){return{flag:{value:t,version:0},version:0}}setOverride(t,e){this.r||(this.r={}),this.r[t]=e,this.w.handleFlagChanges([t],"override")}removeOverride(t){!this.r||!Object.prototype.hasOwnProperty.call(this.r,t)||(delete this.r[t],Object.keys(this.r).length===0&&(this.r=void 0),this.w.handleFlagChanges([t],"override"))}clearAllOverrides(){if(this.r){let t=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.Nt(n)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},lp="unknown hook",Yp="beforeEvaluation",Kp="afterEvaluation",Pw="afterTrack";function gr(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 br(t,e){try{return e.getMetadata().name||lp}catch(n){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),lp}}function Mw(t,e,n){return e.map(r=>gr(t,Yp,br(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeEvaluation)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Fw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];gr(t,Kp,br(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 Aw(t,e,n){return e.map(r=>gr(t,Yp,br(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeIdentify)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Jw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];gr(t,Kp,br(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 Dw(t,e,n){for(let r=e.length-1;r>=0;r-=1){let i=e[r];gr(t,Pw,br(t,i),()=>{var o;return(o=i==null?void 0:i.afterTrack)==null?void 0:o.call(i,n)},void 0)}}var Yw=class{constructor(t,e){this.t=t,this.R=[],this.R.push(...e)}withEvaluation(t,e,n,r){if(this.R.length===0)return r();let i=[...this.R],o={flagKey:t,context:e,defaultValue:n},s=Mw(this.t,i,o),a=r();return Fw(this.t,i,o,s,a),a}identify(t,e){let n=[...this.R],r={context:t,timeout:e},i=Aw(this.t,n,r);return o=>{Jw(this.t,n,r,i,o)}}addHook(t){this.R.push(t)}afterTrack(t){if(this.R.length===0)return;let e=[...this.R];Dw(this.t,e,t)}};function Kw(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 _w(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function Hw(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function zw(t,e){let n=!1,r={method:(...i)=>{try{t.method(...i)}catch(o){n||(n=!0,e.warn(Hw(r.type,r.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return r}var _p="flag-used",Hp="flag-details-changed",zp="flag-detail-changed",Bp="client-identity-changed",Bw=[_p,Hp,zp,Bp];function jw(t,e){let n=Bw.includes(t.type)&&t.method&&typeof t.method=="function";return n||e.warn(_w(t.type,t.name)),n}var Qw=class{constructor(t,e){this.W=[];let n=t.filter(r=>jw(r,e));this.W=n.map(r=>zw(r,e))}hasInspectors(){return this.W.length!==0}onFlagUsed(t,e,n){this.W.forEach(r=>{r.type===_p&&r.method(t,e,n)})}onFlagsChanged(t){this.W.forEach(e=>{e.type===Hp&&e.method(t)})}onFlagChanged(t,e){this.W.forEach(n=>{n.type===zp&&n.method(t,e)})}onIdentityChanged(t){this.W.forEach(e=>{e.type===Bp&&e.method(t)})}},$w=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var n;this.n.has(t)?(n=this.n.get(t))==null||n.push(e):this.n.set(t,[e])}off(t,e){let n=this.n.get(t);if(n){if(e){let r=n.filter(i=>i!==e);r.length===0?this.n.delete(t):this.n.set(t,r);return}this.n.delete(t)}}Ai(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.Ai(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 qw(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:cp,ErrorKinds:up}=pe,tI=5,eI=class{constructor(t,e,n,r,i,o){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.a=Iw(),this.Rt=15,this.T=new ap(!1),this.ht=new ap(!0),this.Mt=!1,this.Pi=lw(),!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 pw(r,o),this.logger=this.e.logger,this.De=FS(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.M=new Uw(this.platform,t,this.e.maxCachedContexts,this.e.logger),this.S=Nw(t,this.e,n),this.E=Ow(t,this.e,n,this.De,this.S),this.emitter=new $w,this.emitter.on("error",(a,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(a)}`)}),this.M.on((a,c,l)=>{this.Oi(c,l);let u=Vn.toLDContext(a);this.emitter.emit("change",u,c),c.forEach(h=>{this.emitter.emit(`change:${h}`,u)})}),this.dataManager=i(this.M,this.e,this.De,this.emitter,this.S);let s=[...this.e.hooks];if(this.environmentMetadata=qw(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(a=>{s.push(a)}),this.F=new Yw(this.logger,s),this.Q=new Qw(this.e.inspectors,this.logger),this.Q.hasInspectors()&&this.F.addHook(Kw(this.Q)),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.M.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()?Vp(this.a.getUnwrappedContext()):void 0}getInternalContext(){return this.a.getContext()}presetFlags(t){this.M.presetFlags(t)}async identify(t,e){let n=await this.identifyResult(t,e);if(n.status==="error")throw n.error;if(n.status==="timeout"){let r=new kp(`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:tI,o=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Rt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Rt} seconds. We recommend a timeout of less than ${this.Rt} seconds.`);let s=this.Pi.execute({before:async()=>{let c=await Vw(t,this.platform);this.autoEnvAttributes===Ai.Enabled&&(c=await ww(c,this.platform,this.e));let l=Vn.fromLDContext(c);if(l.valid){let u=this.F.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=PS(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(cp.MissingContextKeyNoEvent);return}n!==void 0&&!G.Number.is(n)&&((r=this.logger)==null||r.warn(cp.invalidMetricValue(typeof n))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.a.getContext(),e,n))),this.F.afterTrack({key:t,context:this.a.getUnwrappedContext(),data:e,metricValue:n})}dt(t,e,n,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.M.get(t);if(h===void 0||h.flag.deleted){let b=e!=null?e:null;return(o=this.logger)==null||o.warn(`Unknown feature flag "${t}"; returning default value ${b}.`),l&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(t,b,u))),op(up.FlagNotFound,e)}let{reason:p,value:f,variation:m,prerequisites:d}=h.flag;if(r){let[b,I]=r(f);if(!b){l&&((a=this.E)==null||a.sendEvent(n.evalEventClient(t,e,e,h.flag,u,p)));let R=new WS(`Wrong type "${I}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.a.getUnwrappedContext(),R),op(up.WrongType,e)}}let v=sp(f,m,p);return f==null&&(this.logger.debug("Result value is null. Providing default value."),v.value=e),d==null||d.forEach(b=>{this.dt(b,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.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,this.T));return n}variationDetail(t,e){return this.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,this.ht))}_(t,e,n,r){return this.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,n,r))}boolVariation(t,e){return this._(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._(t,e,this.T,n=>[G.Number.is(n),G.Number.getType()]).value}stringVariation(t,e){return this._(t,e,this.T,n=>[G.String.is(n),G.String.getType()]).value}boolVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.Boolean.is(n),G.Boolean.getType()])}numberVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.Number.is(n),G.Number.getType()])}stringVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.String.is(n),G.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.F.addHook(t)}setEventSendingEnabled(t,e){var n,r,i,o;this.Mt!==t&&(this.Mt=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.Mt||((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.M).getDebugOverride)==null?void 0:e.call(t)}Oi(t,e){if(!this.Q.hasInspectors())return;let n={};t.forEach(r=>{let i=this.M.get(r);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:o,value:s,variation:a}=i.flag;n[r]=sp(s,a,o)}else n[r]={value:void 0,variationIndex:null}}),e==="init"?this.Q.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,i])=>{this.Q.onFlagChanged(r,i)})}};function nI(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 ${pe.safeGetName(t,r)}.`)}})}function rI(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:fe(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 iI(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 hp(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var oI=class{constructor(t,e,n,r,i){this.Ti=t,this.$i=e,this.Ni=n,this.m=r,this.t=i,this.u=!1}async be(){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.m)==null||m.call(this,new Fi(Kt.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.Ti.requestPayload();try{if(this.u){hp(this.t);return}let p=JSON.parse(h);try{(e=this.Ni)==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){hp(this.t);return}let p=h;if(p.status!==void 0&&!Ki(p.status)){(r=this.t)==null||r.error(On(h,"polling request")),(i=this.m)==null||i.call(this,new Fi(Kt.ErrorResponse,p.message,p.status));return}(o=this.t)==null||o.error(On(h,"polling request","will retry"))}let l=Date.now()-c,u=Math.max(this.$i*1e3-l,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",l,u),this.Ft=setTimeout(()=>{this.be()},u)}start(){this.be()}stop(){this.Ft&&(clearTimeout(this.Ft),this.Ft=void 0),this.u=!0}close(){this.stop()}},sI=(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 Xa(Kt.InvalidData,"Malformed JSON data in event stream"))};function aI(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function pp(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var lI=class{constructor(t,e,n,r,i,o,s,a,c){var l;this.Ri=t,this.Ut=e,this.n=n,this.H=r,this.Mi=o,this.S=s,this.m=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.Ut.withReasons&&h.push({key:"withReasons",value:"true"}),this.H=r,this.ke=st({},e.baseHeaders),this.t=c,this.Fi=LS(e.serviceEndpoints,u,h)}xe(){this.ft=Date.now()}Vt(t){this.ft&&this.S&&this.S.recordStreamInit(this.ft,!t,Date.now()-this.ft),this.ft=void 0}Ui(t){var e,n,r;return xp(t)?((r=this.t)==null||r.warn(On(t,"streaming request","will retry")),this.Vt(!1),this.xe(),!0):(this.Vt(!1),(e=this.m)==null||e.call(this,new Xa(Kt.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(On(t,"streaming request")),!1)}start(){this.xe();let t;this.Ut.useReport?(this.ke["content-type"]="application/json",t={method:"REPORT",body:this.Ri}):t={};let e=this.H.createEventSource(this.Fi,fe(st({headers:this.ke},t),{errorFilter:n=>this.Ui(n),initialRetryDelayMillis:this.Ut.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.Se=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var 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){aI(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),o!=null&&o.data){this.Vt(!0);let{data:c}=o,l=n(c);if(!l){sI(i,c,this.t,this.m);return}r(l)}else(a=this.m)==null||a.call(this,new Xa(Kt.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.Mi.requestPayload();try{if(this.u){pp(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.m)==null||a.call(this,new Fi(Kt.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){pp(this.t);return}let u=l;(c=this.m)==null||c.call(this,new Fi(Kt.ErrorResponse,u.message,u.status))}})}stop(){var t;(t=this.Se)==null||t.close(),this.Se=void 0,this.u=!0}close(){this.stop()}},cI=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=iI(a),this.q=rI(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Vi=t}createPollingProcessor(t,e,n,r,i){let o=new oI(n,this.config.pollInterval,async s=>{await this.q.handlePut(e,s),r==null||r()},s=>{this.emitter.emit("error",t,s),this.q.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.Le(o,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,i){var o;let s=new lI(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.Vi)==null?void 0:o.queryParameters},this.createStreamListeners(e,r),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,a=>{this.emitter.emit("error",t,a),this.q.handleStreamingError(a),i==null||i(a)},this.logger);this.updateProcessor=this.Le(s,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.q.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.q.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.q.handleDelete(t,r)}}),n}Le(t,e){return{start:()=>{e.requestStateUpdate("INITIALIZING"),t.start()},stop:()=>{t.stop(),e.requestStateUpdate("CLOSED")},close:()=>{t.close(),e.requestStateUpdate("CLOSED")}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function jp(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 _i(){return typeof document!==void 0}function Ya(){return typeof window!==void 0}function Qp(t,e,n){return _i()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function $p(t,e,n){return _i()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function mr(){return Ya()?window.location.href:""}function uI(){return Ya()?window.location.search:""}function hI(){return Ya()?window.location.hash:""}function pI(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function dI(){return _i()?document.visibilityState:"visibile"}function fI(t){if(_i())return document.querySelectorAll(t)}var mI="[BrowserDataManager]",yI=class extends cI{constructor(t,e,n,r,i,o,s,a,c,l){super(t,e,n,r,o,s,a,c,l),this.Xi=i,this.tt=void 0,this.jt=!1,this.tt=i.streaming}L(t,...e){this.logger.debug(`${mI} ${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.Ht=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.ji(n,i,t):(await this.flagManager.loadCached(n)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Hi(n,t,e)),this.Bt()}async Bi(t){let e=JSON.stringify(Vn.toLDContext(t)),n=ep(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ht),r=3,i;for(let o=0;o<=r;o+=1)try{return await n.requestPayload()}catch(s){if(!xp(s))throw s;i=s,o<r&&(this.L(On(s,"initial poll request","will retry")),await Np(1e3))}throw i}async Hi(t,e,n){var r,i;try{this.dataSourceStatusManager.requestStateUpdate(ow.Initializing);let o=await this.Bi(t);try{let s=this.createStreamListeners(t,e).get("put");s.processJson(s.deserializeData(o))}catch(s){this.dataSourceStatusManager.reportError(Kt.InvalidData,(r=s.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(Kt.NetworkError,(i=o.message)!=null?i:"unexpected network error",o.status),n(o)}}ji(t,e,n){let{bootstrapParsed:r}=e;r||(r=jp(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,r),this.L("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.tt=t,this.Bt()}setAutomaticStreamingState(t){this.jt=t,this.Bt()}Bt(){let t=this.tt||this.jt&&this.tt===void 0;this.L(`Updating streaming state. forced(${this.tt}) automatic(${this.jt})`),t?this.zi():this.Gi()}Gi(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}zi(){if(this.updateProcessor){this.L("Update processor already active. Not changing state.");return}if(!this.context){this.L("Context not set, not starting update processor.");return}this.L("Starting update processor."),this.Ki(this.context)}Ki(t,e,n){var r;let i=Vn.toLDContext(t);(r=this.updateProcessor)==null||r.close();let o=JSON.stringify(Vn.toLDContext(t)),s=ep(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ht);this.createStreamingProcessor(i,t,s,e,n),this.updateProcessor.start()}};function gI(t){let e=Qp("visibilitychange",()=>{dI()==="hidden"&&t()}),n=$p("pagehide",t);return()=>{e(),n()}}function Na(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function bI(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(`^${Na(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${Na(t.url)}/?$`).test(i);case"substring":return new RegExp(`.*${Na(t.substring)}.*$`).test(i);case"regex":return new RegExp(t.pattern).test(i);default:return!1}}function vI(t,e){let n=[];return e.forEach(r=>{let i=t.target,{selector:o}=r,s=fI(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 SI=class{constructor(t,e){let n=t.filter(o=>{var s;return(s=o.urls)==null?void 0:s.some(a=>bI(a,mr(),uI(),hI()))}),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=>{vI(s,i).forEach(a=>{e(a)})};this.Ce=Qp("click",o)}}close(){var t;(t=this.Ce)==null||t.call(this)}},wI=300,II=class{constructor(t){this.zt=mr();let e=()=>{let r=mr();r!==this.zt&&(this.zt=r,t())};this.Gt=setInterval(e,wI);let n=$p("popstate",e);this.Ie=()=>{n()}}close(){var t;this.Gt&&clearInterval(this.Gt),(t=this.Ie)==null||t.call(this)}},TI=class{constructor(t,e,n,r,i,o=s=>new II(s)){this.H=e,this.qi=r,this.Pr=i,this.pt=[],this.Pe=!1,this.gt=`${n}/sdk/goals/${t}`,this.Ae=o(()=>{this.Wt()})}async initialize(){await this.Wi(),this.Wt()}startTracking(){this.Pe=!0,this.Wt()}Wt(){var t;this.Pe&&((t=this.Kt)==null||t.close(),this.pt&&this.pt.length&&(this.Kt=new SI(this.pt,e=>{this.Pr(mr(),e)})))}async Wi(){try{let t=await this.H.fetch(this.gt);this.pt=await t.json()}catch(t){this.qi(new Zp(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.Ae)==null||t.close(),(e=this.Kt)==null||e.close()}};function EI(t){return t.kind==="click"}var RI=2,qp={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},CI={fetchGoals:G.Boolean,eventUrlTransformer:G.Function,streaming:G.Boolean,plugins:G.createTypeArray("LDPlugin",{})};function ZI(t){var e;let n=st({},t);return(e=n.flushInterval)!=null||(n.flushInterval=RI),n}function kI(t){let e=ZI(t);return Object.keys(qp).forEach(n=>{delete e[n]}),e}function VI(t,e){let n=st({},qp);return Object.entries(CI).forEach(r=>{let[i,o]=r,s=t[i];s!==void 0&&(o.is(s)?n[i]=s:e.warn(We.wrongOptionType(i,o.getType(),typeof s)))}),n}var xI=class{constructor(t,e){switch(this.Ji=t,this.Oe=[],e){case"sha1":this.No="SHA-1";break;case"sha256":this.No="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Oe.join(""),n=new TextEncoder().encode(e),r=await this.Ji.subtle.digest(this.No,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.Oe.push(t),this}},NI={start:0,end:3},OI={start:4,end:5},Oa={start:6,end:7},Ga={start:8,end:8},GI={start:9,end:9},LI={start:10,end:15};function XI(){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 Zn(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 WI(t){return t[Ga.start]=(t[Ga.start]|128)&191,t[Oa.start]=t[Oa.start]&15|64,`${Zn(t,NI)}-${Zn(t,OI)}-${Zn(t,Oa)}-${Zn(t,Ga)}${Zn(t,GI)}-${Zn(t,LI)}`}function UI(){let t=XI();return WI(t)}function PI(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():UI()}var MI=class{createHash(t){return new xI(pI(),t)}randomUUID(){return PI()}};function FI(t){let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e)}var AI=class{btoa(t){return FI(new TextEncoder().encode(t))}},JI=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"0.13.1",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},DI=class{constructor(t,e){this.gt=t,this.n={},this.I=new TS(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Te=e.errorFilter,this.$e()}$e(){this.J=new EventSource(this.gt),this.J.onopen=()=>{var t;this.I.success(),(t=this.onopen)==null||t.call(this)},this.J.onerror=t=>{var e;this.Yi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this.J)==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.J)==null||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.qt),this.qt=void 0,(t=this.J)==null||t.close(),(e=this.onclose)==null||e.call(this)}Zi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.qt=setTimeout(()=>{this.$e()},t)}Yi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Te(t))&&this.Zi(this.I.fail())}},YI=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new DI(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function td(){return typeof localStorage!="undefined"}function KI(){if(!td())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);n&&t.push(n)}return t}var _I=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}`)}}},HI=class{constructor(t,e){this.encoding=new AI,this.crypto=new MI,this.requests=new YI,td()&&(this.storage=new _I(t)),this.info=new JI(e)}},zI=class extends eI{constructor(t,e,n={},r){var i;let{logger:o,debug:s}=n,a=o!=null?o:new Ma({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 HI(a,n),u=VI(n,a),h=kI(fe(st({},n),{logger:a})),{eventUrlTransformer:p}=u;super(t,e,l,h,(f,m,d,v,b)=>new yI(l,f,t,m,u,()=>({pathGet(I,R){return`/sdk/evalx/${t}/contexts/${Qh(R,I)}`},pathReport(I,R){return`/sdk/evalx/${t}/context`},pathPing(I,R){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(I,R){return`/eval/${t}/${Qh(R,I)}`},pathReport(I,R){return`/eval/${t}`},pathPing(I,R){return`/ping/${t}`}}),d,v,b),{getLegacyStorageKeys:()=>KI().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 pe.InputCustomEvent(f.context,f.key,f.data,f.metricValue,f.samplingRatio,p(mr())),getImplementationHooks:f=>pe.safeGetHooks(a,f,u.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.Yt=u.plugins,u.fetchGoals&&(this.Jt=new TI(t,l.requests,c,f=>{a.error(f.message)},(f,m)=>{let d=this.getInternalContext();if(!d)return;let v=p(f);EI(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.Jt.initialize(),u.automaticBackgroundHandling&&gI(()=>this.flush()))}registerPlugins(t){pe.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.Yt||[]);let e=this.getDebugOverrides();e&&nI(this.logger,e,this.Yt||[])}setInitialContext(t){this.Zt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var n;if(!this.et)return this.logger.error("Client must be started before it can identify a context, did you forget to call start()?"),{status:"error",error:new Error("Identify called before start")};let r=st({},e);(e==null?void 0:e.sheddable)===void 0&&(r.sheddable=!0);let i=await super.identifyResult(t,r);return(n=this.Jt)==null||n.startTracking(),i}start(t){var e,n;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.et)return this.et;if(!this.Zt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let r=fe(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=jp(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.et=this.promiseWithTimeout(this.initializedPromise,(n=t==null?void 0:t.timeout)!=null?n:5),this.identifyResult(this.Zt,r),this.et}setStreaming(t){this.dataManager.setForcedStreaming(t)}Ne(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.Ne()}off(t,e){super.off(t,e),this.Ne()}};function BI(t,e,n,r={},i){let o=new zI(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 jI(t){return new Ma(t)}function ed(t,e,n){return BI(t,e,Ai.Disabled,n)}var QI=Object.defineProperty,$I=(t,e,n)=>e in t?QI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ie=(t,e,n)=>$I(t,typeof e!="symbol"?e+"":e,n),qI=(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())}),Ze=(t,e,...n)=>{let r=`[@launchdarkly plugins]: (${t}): `;console[e].apply(console,[r,...n]),tT(r,...n)},tT=(t,...e)=>qI(void 0,null,function*(){try{let{LDObserve:n}=yield Promise.resolve().then(()=>oR);n.recordLog(`${t}${e}`,"warn")}catch(n){}}),eT=class{constructor(t,e){Ie(this,"debug"),Ie(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])}},vo=class{constructor(){Ie(this,"_sdk"),Ie(this,"_isLoaded",!1),Ie(this,"_callBuffer",[]),Ie(this,"_capacity",1e5),Ie(this,"_droppedEvents",0),Ie(this,"_exceededCapacity",!1),Ie(this,"_logger",new eT)}h(e,n){if(this.Nn)try{return this.jn[e](...n)}catch(r){Ze(`Error executing buffered call to ${e}:`,"error",r)}else{this.Mr({method:e,args:n});return}}Mr(e){this.wn.length<this.Ws?(this.wn.push(e),this.Qn=!1):(this.Qn||(this.Qn=!0,Ze("Exceeded event queue capacity. Increase capacity to avoid dropping events.","warn")),this.Us+=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){Ze(`Error executing buffered call to ${n}:`,"error",i)}this.wn=[]}},nT=Object.defineProperty,rT=Object.defineProperties,iT=Object.getOwnPropertyDescriptors,So=Object.getOwnPropertySymbols,Mf=Object.prototype.hasOwnProperty,Ff=Object.prototype.propertyIsEnumerable,Zl=(t,e,n)=>e in t?nT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,j=(t,e)=>{for(var n in e||(e={}))Mf.call(e,n)&&Zl(t,n,e[n]);if(So)for(var n of So(e))Ff.call(e,n)&&Zl(t,n,e[n]);return t},Fn=(t,e)=>rT(t,iT(e)),Vr=(t,e)=>{var n={};for(var r in t)Mf.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&So)for(var r of So(t))e.indexOf(r)<0&&Ff.call(t,r)&&(n[r]=t[r]);return n},Xr=(t,e,n)=>Zl(t,typeof e!="symbol"?e+"":e,n),Jn=(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 oT(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 lo(t,e){throw new Error(e)}function sT(t){return typeof t=="object"&&t!==null}function aT(t,e){throw new Error("Unexpected invariant triggered.")}var lT=/\r\n|[\n\r]/g;function kl(t,e){let n=0,r=1;for(let i of t.body.matchAll(lT)){if(typeof i.index=="number"||aT(),i.index>=e)break;n=i.index+i[0].length,r+=1}return{line:r,column:e+1-n}}function cT(t){return Af(t.source,kl(t.source,t.start))}function Af(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=UF();n?yield n({session_secure_id:this.sessionData.sessionSecureID,payload_id:(this.sessionData.payloadID++).toString(),events:{events:r},messages:zL({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:xe.AsyncEvents,id:this.sessionData.payloadID++,events:r,messages:[],errors:[],resourcesString:JSON.stringify({resources:[]}),webSocketEventsString:JSON.stringify({webSocketEvents:[]}),hasSessionUnloaded:this.hasSessionUnloaded,highlightLogs:s}}),wn(this.sessionData),this.events=this.events.slice(r.length),PF(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.xo}),Oe.takeFullSnapshot(),this.br=0,this.xo=new Date().getTime()}register(e,n){this.xn.push(new hu(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=Zs(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(wX);if(r&&(e=r==null?void 0:r.groups)!=null&&e.domain){let i=(n=r.groups.domain)!=null?n:"";return`https://${vX[i]}${SX}`}return bX}},Ri=class extends _X{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=Yt(z({},n),{organizationID:e,firstloadVersion:YF,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 ih(f),n!=null&&n.manualStart||this.record.start(),ze.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&&JF(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&&AF(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=FX(n.context),f=AX(n.context);(h=this.record)==null||h.identify(typeof f=="string"?f:(u=(l=f.user)==null?void 0:l.toString())!=null?u:p,Yt(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 _F={};Dh(_F,{LDObserve:()=>Je,LDRecord:()=>ze,basicLogger:()=>jI,createClient:()=>KF});module.exports=tS(_F);var eS=Object.defineProperty,nS=Object.defineProperties,rS=Object.getOwnPropertyDescriptors,Pi=Object.getOwnPropertySymbols,dp=Object.prototype.hasOwnProperty,fp=Object.prototype.propertyIsEnumerable,Yh=(t,e,n)=>e in t?eS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,st=(t,e)=>{for(var n in e||(e={}))dp.call(e,n)&&Yh(t,n,e[n]);if(Pi)for(var n of Pi(e))fp.call(e,n)&&Yh(t,n,e[n]);return t},fe=(t,e)=>nS(t,rS(e)),mp=(t,e)=>{var n={};for(var r in t)dp.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&Pi)for(var r of Pi(t))e.indexOf(r)<0&&fp.call(t,r)&&(n[r]=t[r]);return n};function iS(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function yp(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function oS(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>yp(e))}function sS(t){return!t.startsWith("/")}function aS(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var xn=class{constructor(t,e=!1){if(e){let n=t;this.g=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?iS(n):n}else{if(this.redactionName=t,t===""||t==="/"||!aS(t)){this.isValid=!1,this.g=[];return}sS(t)?this.g=[t]:t.indexOf("/",1)<0?this.g=[yp(t.slice(1))]:this.g=oS(t),this.g[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{g: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.g[t]}get depth(){return this.g.length}get isKind(){return this.g.length===1&&this.g[0]==="kind"}compare(t){return this.depth===t.depth&&this.g.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.g]}};xn.InvalidReference=new xn("");var lS=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},Gn=class{constructor(t,e){this.mt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.mt}},gp=class{constructor(t,e){this.mt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.mt}},bp=class extends Gn{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},vp=class extends Gn{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},cS=class{is(t){return typeof t=="function"}getType(){return"function"}},uS=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},hS=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,pS=class{is(t){return typeof t=="number"||typeof t=="string"&&hS.test(t)}getType(){return"date"}},dS=class extends vp{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},G=class{static createTypeArray(t,e){return new gp(t,e)}static numberWithMin(t){return new bp(t)}static stringMatchingRegex(t){return new vp(t)}};G.String=new Gn("string","");G.Number=new Gn("number",0);G.ObjectOrFactory=new lS;G.Object=new Gn("object",{});G.StringArray=new gp("string[]","");G.Boolean=new Gn("boolean",!0);G.Function=new cS;G.Date=new pS;G.Kind=new dS;G.NullableBoolean=new uS;function Sp(t){return"kind"in t?G.String.is(t.kind)&&t.kind!=="multi":!1}function wp(t){return"kind"in t?G.String.is(t.kind)&&t.kind==="multi":!1}function Ip(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function Mi(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=>Mi(n,[...e,t])).map(n=>n===void 0?"null":n).join(",")}]`:`{${Object.keys(t).sort().map(n=>{let r=Mi(t[n],[...e,t]);if(r!==void 0)return`${JSON.stringify(n)}:${r}`}).filter(n=>n!==void 0).join(",")}}`}var La="user";function Kh(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function fS(t){return t&&G.Object.is(t)}function _h(t){return G.Kind.is(t)}function Hh(t){return G.String.is(t)&&t!==""}function Ra(t,e=!1){return t?t.map(n=>new xn(n,e)):[]}function mS(t){return t!=null}function yS(t){let e=fe(st({},t.custom||[]),{kind:"user",key:String(t.key)});if(mS(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 Vn=class wt{constructor(e,n,r){this.C=!1,this.it=!1,this.Xt=!1,this.$={},this.kind=n,this.valid=e,this.message=r}static b(e,n){return new wt(!1,e,n)}static Re(e,n){if(!(!n||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(n!=null&&n.anonymous):e.get(n)}Qt(e){if(this.C)return this.$[e];if(this.kind===e)return this.y}static Me(e){let n=Object.keys(e).filter(c=>c!=="kind"),r=n.every(_h);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 fS(h)?(c[l]=h,i[l]=Ra((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=>Hh(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=fe(st({},s[c]),{kind:c}),l.nt=i,l.it=c==="user",l}let a=new wt(!0,e.kind);return a.$=s,a.nt=i,a.C=!0,a}static Fe(e){var n;let{key:r,kind:i}=e,o=_h(i),s=Hh(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=Ra((n=e._meta)==null?void 0:n.privateAttributes),c=new wt(!0,i);return c.it=i==="user",c.y=e,c.nt={[i]:a},c}static Ue(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.it=!0,n.Xt=!0,n.y=yS(e),n.nt={user:Ra(e.privateAttributeNames,!0)},n}static fromLDContext(e){return e?Sp(e)?wt.Fe(e):wp(e)?wt.Me(e):Ip(e)?wt.Ue(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=La){return e.isKind?this.kinds:wt.Re(e,this.Qt(n))}key(e=La){var n;return(n=this.Qt(e))==null?void 0:n.key}get isMultiKind(){return this.C}get canonicalKey(){return this.it?this.y.key:this.C?Object.keys(this.$).sort().map(e=>`${e}:${Kh(this.$[e].key)}`).join(":"):`${this.kind}:${Kh(this.y.key)}`}get kinds(){return this.C?Object.keys(this.$):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.$).reduce((e,[n,r])=>(e[n]=r.key,e),{}):{[this.kind]:this.y.key}}privateAttributes(e){var n;return((n=this.nt)==null?void 0:n[e])||[]}getContexts(){return this.C?Object.entries(this.$):[[this.kind,this.y]]}get legacy(){return this.Xt}canonicalUnfilteredJson(){if(this.valid){if(this.yt)return this.yt;try{this.yt=Mi(wt.toLDContext(this))}catch(e){}return this.yt}}};Vn.UserKind=La;var gS=["key","kind","_meta","anonymous"].map(t=>new xn(t,!0)),bS=["name","ip","firstName","lastName","email","avatar","country"];function vS(t,e){return t.depth===e.length&&e.every((n,r)=>n===t.getComponent(r))}function SS(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=>vS(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 wS=class{constructor(t,e){this.Ve=t,this.je=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.te(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([i,o])=>{r[i]=this.te(t,o,i,e)}),r}He(t,e,n,r){return(r?Object.keys(e).map(i=>new xn(i,!0)):[...this.je,...t.privateAttributes(n)]).filter(i=>!gS.some(o=>o.compare(i)))}te(t,e,n,r){let i=this.Ve||r&&e.anonymous===!0,{cloned:o,excluded:s}=SS(e,this.He(t,e,n,i));return t.legacy&&bS.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}},zh=30*1e3,IS=.5,TS=class{constructor(t,e,n=Math.random){this.Be=e,this.ze=n,this.vt=0,this.ee=Math.max(1,t),this.Ge=Math.ceil(Math.log2(zh/this.ee))}I(){let t=Math.min(this.vt,this.Ge),e=this.ee*2**t;return Math.min(e,zh)}Ke(t){return t-Math.trunc(this.ze()*IS*t)}success(t=Date.now()){this.wt=t}fail(t=Date.now()){this.wt!==void 0&&t-this.wt>this.Be&&(this.vt=0),this.wt=void 0;let e=this.Ke(this.I());return this.vt+=1,e}},Bh;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(Bh||(Bh={}));var Fi=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},Xa=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},zF=120*1e3,BF=300*1e3,Kt;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(Kt||(Kt={}));var Ai;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(Ai||(Ai={}));var Nn;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(Nn||(Nn={}));var tn;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(tn||(tn={}));function kn(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 ES(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function RS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function CS(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var Ca={s:t=>kn(t),d:t=>ES(t),i:t=>RS(t),f:t=>CS(t),j:t=>kn(t),o:t=>kn(t),O:t=>kn(t),c:()=>""};function Wa(...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 Ca&&t.length){let a=t.shift();r+=(e=Ca[s])==null?void 0:e.call(Ca,a)}else s==="%"?r+="%":r+=`%${s}`;i+=2}}else r+=o,i+=1}return t.length&&(r.length&&(r+=" "),r+=t.map(kn).join(" ")),r}return t.map(kn).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 ZS=["debug","info","warn","error","none"],Ma=class Tp{static get(){return new Tp({})}constructor(e){var n,r,i;if(this.Qe=(r=Vt[(n=e.level)!=null?n:"info"])!=null?r:Vt.info,this.ti=(i=e.name)!=null?i:"LaunchDarkly",this.ae=e.formatter,typeof e.destination=="object")this.oe={[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.oe={[Vt.debug]:o,[Vt.info]:o,[Vt.warn]:o,[Vt.error]:o}}}ei(...e){var n;try{return this.ae?(n=this.ae)==null?void 0:n.call(this,...e):Wa(...e)}catch(r){return Wa(...e)}}ii(e,n){try{e(n)}catch(r){console.error(n)}}k(e,n){var r;if(e>=this.Qe){let i=`${ZS[e]}: [${this.ti}]`;try{let o=(r=this.oe)==null?void 0:r[e];o?this.ii(o,`${i} ${this.ei(...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)}},kS={error:G.Function,warn:G.Function,info:G.Function,debug:G.Function},Ep=class{constructor(t,e){Object.entries(kS).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.ni=e}k(t,e){try{this.t[t](...e)}catch(n){this.ni[t](...e)}}error(...t){this.k("error",t)}warn(...t){this.k("warn",t)}info(...t){this.k("info",t)}debug(...t){this.k("debug",t)}},Rp=t=>{let e=new Ma({level:"info",destination:console.error,formatter:Wa});return t?new Ep(t,e):e},We=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`}},VS=/^(\w|\.|-)+$/,xS=G.stringMatchingRegex(VS),NS={is:(t,e)=>xS.is(t)?t.length>64?{valid:!1,message:We.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:We.invalidTagValue(e)}},OS=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}=NS.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(" "))}},GS=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 Za(t){return t.replace(/\/+$/,"")}function Fa(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var Ji=class Cp{constructor(e,n,r=Cp.DEFAULT_EVENTS,i="/bulk",o="/diagnostic",s=!0,a){this.streaming=Za(e),this.polling=Za(n),this.events=Za(r),this.analyticsEventPath=i,this.diagnosticEventPath=o,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}};Ji.DEFAULT_EVENTS="https://events.launchdarkly.com";function Aa(t,e=[]){if(e.length===0)return t;let n=e.map(({key:r,value:i})=>`${r}=${i}`);return`${t}?${n.join("&")}`}function LS(t,e,n){let r=Fa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Aa(`${t.streaming}/${r}`,i)}function XS(t,e,n=[]){let r=Fa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Aa(`${t.polling}/${r}`,i)}function jh(t,e,n=[]){let r=Fa(e);return Aa(`${t.events}/${r}`,n)}var Zp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},WS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},kp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Ki(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function US(t){return t===413?!0:Ki(t)}function PS(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 kp(s))},t*1e3)}),cancel:()=>{r(),clearTimeout(n)}}}function Vp(t){return t==null?t:JSON.parse(JSON.stringify(t))}function ka(t){return Math.trunc(t*1e3)}var MS=t=>JSON.stringify(t)==="{}",Ja=(t,e)=>t&&Object.entries(t).reduce((n,[r,i])=>(i&&!MS(i)&&!(e!=null&&e.includes(r))&&(n[r]=typeof i=="object"?Ja(i,e):i),n),{});function Wi(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(!Wi(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(!Wi(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(!Wi(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function FS(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 On(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 xp({status:t}){return t?Ki(t):!0}var Qh=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Np=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),AS=class{constructor(t,e,n){this.p=e,this.si=n,this.bt=[],this.ce=Date.now(),this.le=this.ce,this.ue={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var t,e,n;let r=this.p.info.sdkData(),i=this.p.info.platformData();return{kind:"diagnostic-init",id:this.ue,creationDate:this.ce,sdk:r,configuration:this.si,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.bt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),i={kind:"diagnostic",id:this.ue,creationDate:r,dataSinceDate:this.le,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.bt};return this.bt=[],this.le=r,i}},Ua;(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"})(Ua||(Ua={}));var JS=Ua,Op=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};Op.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var DS=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:o}}=n,{crypto:s,requests:a}=r;this.ri=st({},e),this.he=jh(n.serviceEndpoints,i,[]),this.ai=jh(n.serviceEndpoints,o,[]),this.H=a,this.oi=s}async st(t,e,n,r){let i={status:tn.Succeeded},o=fe(st({},this.ri),{"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.H.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 Zp(On({status:a,message:"some events were dropped"},"event posting")),!Ki(a))return US(a)?i.status=tn.Failed:i.status=tn.FailedAndMustShutDown,i.error=s,i}catch(a){s=a}return s&&!r?(i.status=tn.Failed,i.error=s,i):(await Np(),this.st(t,this.he,n,!1))}async sendEventData(t,e){let n=t===Nn.AnalyticsEvents?this.oi.randomUUID():void 0,r=t===Nn.AnalyticsEvents?this.he:this.ai;return this.st(e,r,n,!0)}};function Di(t){return t.kind==="feature"}function YS(t){return t.kind==="identify"}function KS(t){return t.kind==="migration_op"}var _S=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 HS(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Gp=class{constructor(t=!1,e){this.ci=t,this.x=e,this.Y=0,this.rt=0,this.at={},this.ot={}}summarizeEvent(t){if(Di(t)&&!t.excludeFromSummaries){this.y||(this.y=t.context);let e=HS(t),n=this.at[e],r=this.ot[t.key];r||(r=new Set,this.ot[t.key]=r),t.context.kinds.forEach(i=>r.add(i)),n?n.increment():this.at[e]=new _S(1,t.key,t.value,t.default,t.version,t.variation),(this.Y===0||t.creationDate<this.Y)&&(this.Y=t.creationDate),t.creationDate>this.rt&&(this.rt=t.creationDate)}}getSummary(){var t;let e=Object.values(this.at).reduce((r,i)=>{let o=r[i.key];o||(o={default:i.default,counters:[],contextKinds:[...this.ot[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.Y,endDate:this.rt,features:e,kind:"summary",context:this.y!==void 0&&this.ci?(t=this.x)==null?void 0:t.filter(this.y):void 0};return this.li(),n}li(){this.Y=0,this.rt=0,this.at={},this.ot={}}},zS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},BS=class{constructor(t,e){this.x=t,this.t=e,this.Z={}}summarizeEvent(t){var e;if(Di(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.Z[n];r||(this.Z[n]=new Gp(!0,this.x),r=this.Z[n]),r.summarizeEvent(t)}}getSummaries(){let t=this.Z;return this.Z={},Object.values(t).map(e=>e.getSummary())}};function Ui(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function jS(t){return t.getSummaries!==void 0}var QS=class{constructor(t,e,n,r,i,o=!0,s=!1){this.e=t,this.ct=r,this.S=i,this.lt=[],this.de=0,this.kt=0,this.xt=0,this.St=!1,this.fe=0,this.Lt=!1,this.Ct=null,this.ui=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.pe=new DS(e,n),this.x=new wS(t.allAttributesPrivate,t.privateAttributes.map(a=>new xn(a))),s?this.X=new BS(this.x,this.t):this.X=new Gp,o&&this.start()}start(){var t,e;if(((t=this.ct)==null?void 0:t.flushInterval)!==void 0&&(this.Ct=setInterval(()=>{var n;(n=this.ct)==null||n.flush()},this.ct.flushInterval*1e3)),this.hi=setInterval(async()=>{var n;try{await this.flush()}catch(r){(n=this.t)==null||n.debug(`Flush failed: ${r}`)}},this.e.flushInterval*1e3),this.S){let n=this.S.createInitEvent();this.ge(n),this.me=setInterval(()=>{let r=this.S.createStatsEventAndReset(this.kt,this.xt,this.fe);this.kt=0,this.xt=0,this.ge(r)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}ge(t){this.pe.sendEventData(Nn.DiagnosticEvent,t)}close(){clearInterval(this.hi),this.Ct&&clearInterval(this.Ct),this.me&&clearInterval(this.me)}async flush(){var t;if(this.Lt)throw new zS("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.lt;if(this.lt=[],jS(this.X))this.X.getSummaries().forEach(n=>{Object.keys(n.features).length&&e.push(n)});else{let n=this.X.getSummary();Object.keys(n.features).length&&e.push(n)}e.length&&(this.fe=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.st(e))}sendEvent(t){var e;if(this.Lt)return;if(KS(t)){if(Ui(t.samplingRatio)){let a=fe(st({},t),{context:t.context?this.x.filter(t.context):void 0});a.samplingRatio===1&&delete a.samplingRatio,this.ut(a)}return}this.X.summarizeEvent(t);let n=Di(t),r=n&&t.trackEvents||!n,i=this.di(t),o=YS(t),s=(e=this.ct)==null?void 0:e.processContext(t.context);s||o||(this.xt+=1),s&&!o&&this.ut(this.It({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),r&&Ui(t.samplingRatio)&&this.ut(this.It(t,!1)),i&&Ui(t.samplingRatio)&&this.ut(this.It(t,!0))}It(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.x.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}ut(t){var e;this.lt.length<this.ui?(this.lt.push(t),this.St=!1):(this.St||(this.St=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.kt+=1)}di(t){return Di(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.de&&t.debugEventsUntilDate>Date.now()}async st(t){let e=await this.pe.sendEventData(Nn.AnalyticsEvents,t);if(e.status===tn.FailedAndMustShutDown&&(this.Lt=!0),e.serverTime&&(this.de=e.serverTime),e.error)throw e.error}},Lp=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}},Pa=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)}},Xp=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},$S=class{close(){}async flush(){}sendEvent(){}},qS=class{constructor(t){this.At=t}evalEvent(t){var e;return new Pa(this.At,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.At||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new Pa(this.At,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Xp(t,1)}customEvent(t,e,n,r,i=1){return new Lp(e,t,n!=null?n:void 0,r!=null?r:void 0,i)}},$h="FDv1Fallback";function tw(t){return{fi:t,ye:"",useSelector(e){return this.ye=e,this},processFullTransfer(e){let n=[{event:"server-intent",data:{payloads:[{id:$h,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.ye,version:1,id:$h}}),this.fi.processEvents(n)}}}var Wp=class{constructor(t,e,n){this.pi=t,this.m=e,this.t=n,this.n=[],this.N=void 0,this.B=!1,this.z=[],this.gi=r=>{var i;if(this.Pt(),!r.payloads.length)return;let o=r.payloads[0];switch(o==null?void 0:o.intentCode){case"xfer-full":this.B=!0;break;case"xfer-changes":this.B=!1;break;case"none":this.B=!1,this.mi(o);break;default:(i=this.t)==null||i.warn(`Unable to process intent code '${o==null?void 0:o.intentCode}'.`);return}this.N=o==null?void 0:o.id},this.yi=r=>{var i;if(!this.N||!r.kind||!r.key||!r.version||!r.object)return;let o=this.vi(r.kind,r.object);if(!o){(i=this.t)==null||i.warn(`Unable to process object for kind: '${r.kind}'`);return}this.z.push({kind:r.kind,key:r.key,version:r.version,object:o})},this.wi=r=>{!this.N||!r.kind||!r.key||!r.version||this.z.push({kind:r.kind,key:r.key,version:r.version,deleted:!0})},this.mi=r=>{if(!r.id||!r.target)return;let i={id:r.id,version:r.target,basis:!1,updates:[]};this.n.forEach(o=>o(i)),this.ve()},this.Ei=r=>{if(!this.N||r.state===null||r.state===void 0||!r.version){this.Pt();return}let i={id:this.N,version:r.version,state:r.state,basis:this.B,updates:this.z};this.n.forEach(o=>o(i)),this.ve()},this.Di=r=>{var i;(i=this.t)==null||i.info(`Goodbye was received from the LaunchDarkly connection with reason: ${r.reason}.`),this.Pt()},this.bi=r=>{var i;(i=this.t)==null||i.info(`An issue was encountered receiving updates for payload ${this.N} with reason: ${r.reason}.`),this.ki()}}addPayloadListener(t){this.n.push(t)}removePayloadListener(t){let e=this.n.indexOf(t,0);e>-1&&this.n.splice(e,1)}processEvents(t){t.forEach(e=>{switch(e.event){case"server-intent":{this.gi(e.data);break}case"put-object":{this.yi(e.data);break}case"delete-object":{this.wi(e.data);break}case"payload-transferred":{this.Ei(e.data);break}case"goodbye":{this.Di(e.data);break}case"error":{this.bi(e.data);break}}})}vi(t,e){var n,r;return(r=(n=this.pi)[t])==null?void 0:r.call(n,e)}ve(){this.B=!1,this.z=[]}ki(){this.z=[]}Pt(){this.N=void 0,this.B=!1,this.z=[]}},ew=class{constructor(t,e,n,r){this.m=n,this.t=r,this.G(t,"server-intent"),this.G(t,"put-object"),this.G(t,"delete-object"),this.G(t,"payload-transferred"),this.G(t,"goodbye"),this.G(t,"error"),this.Ot=new Wp(e,n,r)}addPayloadListener(t){this.Ot.addPayloadListener(t)}removePayloadListener(t){this.Ot.removePayloadListener(t)}G(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.Ot.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.m)==null||s.call(this,Kt.InvalidData,"Malformed data in EventStream.")}}else(a=this.m)==null||a.call(this,Kt.Unknown,"Event from EventStream missing data.")})}};function nw(t){if(t){let e=Object.keys(t).find(n=>n.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var qh="unknown plugin";function Yi(t,e){try{return e.getMetadata().name||qh}catch(n){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),qh}}function rw(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 ${Yi(t,i)} returned undefined from getHooks.`):s&&s.length>0&&r.push(...s)}catch(s){t.error(`Exception thrown getting hooks for plugin ${Yi(t,i)}. Unable to get hooks.`)}}),r}function iw(t,e,n,r){r.forEach(i=>{try{i.register(n,e)}catch(o){t.error(`Exception thrown registering plugin ${Yi(t,i)}.`)}})}var pe=Object.freeze({__proto__:null,ClientMessages:Op,DiagnosticsManager:AS,ErrorKinds:JS,EventFactoryBase:qS,EventProcessor:QS,FDv1PayloadAdaptor:tw,InputCustomEvent:Lp,InputEvalEvent:Pa,InputIdentifyEvent:Xp,NullEventProcessor:$S,PayloadProcessor:Wp,PayloadStreamReader:ew,canonicalize:Mi,initMetadataFromHeaders:nw,isLegacyUser:Ip,isMultiKind:wp,isSingleKind:Sp,safeGetHooks:rw,safeGetName:Yi,safeRegisterPlugins:iw,shouldSample:Ui}),ow={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function sw(t){return t>=200&&t<=299}var tp=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function ep(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=XS(e,f,m);return{async requestPayload(){let v;try{let b=await r.fetch(d,{method:h,headers:p,body:u});if(sw(b.status))return await b.text();v=b.status}catch(b){throw new tp(b==null?void 0:b.message)}throw new tp(`Unexpected status code: ${v}`,v)}}}var np=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function aw(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(np)),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(np)),s=!0,o.then(a=>{r({status:"shed"},a)})},promise:i,sheddable:n}}function lw(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=aw(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 cw={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},uw=300,Up="https://clientsdk.launchdarkly.com",Pp="https://clientstream.launchdarkly.com";function hw(t){return t instanceof Ep?t:Rp(t)}var pw=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var n,r,i;this.logger=Rp(),this.baseUri=Up,this.eventsUri=Ji.DEFAULT_EVENTS,this.streamUri=Pp,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=uw,this.hooks=[],this.inspectors=[],this.logger=hw(t.logger),this.xi(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new Ji(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 OS({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}xi(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let i=cw[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(We.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(o==="boolean | undefined | null")e.push(We.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(i instanceof bp&&G.Number.is(r)){let{min:s}=i;e.push(We.optionBelowMinimum(n,r,s)),this[n]=s}else e.push(We.wrongOptionType(n,i.getType(),typeof r))}else e.push(We.unknownOption(n))}),e}};async function Mp(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 Fp=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 Ap(t){return async e=>Mp(t.createHash("sha256").update(e),"base64")}var de=async t=>t;async function yr(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function dw(t,e){return yr([{value:"LaunchDarkly",transform:de},{value:e,transform:Ap(t)}])}async function fw(t){return yr([{value:"LaunchDarkly",transform:de},{value:"AnonymousKeys",transform:de},{value:t,transform:de}])}async function mw(t){return yr([{value:"LaunchDarkly",transform:de},{value:"ContextKeys",transform:de},{value:t,transform:de}])}async function yw(t){return yr([{value:t,transform:de},{value:"ContextIndex",transform:de}])}async function rp(t,e,n){return yr([{value:e,transform:de},{value:n.canonicalKey,transform:Ap(t)}])}var{isLegacyUser:gw,isSingleKind:Va,isMultiKind:ip}=pe,Jp="1.0",bw=t=>{let e=t,{kind:n}=e,r=mp(e,["kind"]);return{kind:"multi",[n]:r}},vw=async({crypto:t,info:e},{applicationInfo:n})=>{var r;let{ld_application:i}=e.platformData(),o=(r=Ja(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(fe(st({},o),{id:s}),a?{version:a}:{}),c?{name:c}:{}),l?{versionName:l}:{}),o.key=await Mp(t.createHash("sha256").update(s),"base64"),o.envAttributesVersion=o.envAttributesVersion||Jp,o}},Sw=async t=>{var e,n,r,i;let{ld_device:o,os:s}=t.info.platformData(),a=(e=Ja(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 mw("ld_device");return a.key=await Fp(h,t),a.envAttributesVersion=a.envAttributesVersion||Jp,a}},ww=async(t,e,n)=>{if(gw(t))return t;let r,i;if(Va(t)&&t.kind!=="ld_application"||ip(t)&&!t.ld_application?r=await vw(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),Va(t)&&t.kind!=="ld_device"||ip(t)&&!t.ld_device?i=await Sw(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),r||i){let o=Va(t)?bw(t):t;return st(st(st({},o),r?{ld_application:r}:{}),i?{ld_device:i}:{})}return t};function Iw(){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:Tw,isMultiKind:Ew,isSingleKind:Rw}=pe,Da=async(t,e,n)=>{let{anonymous:r,key:i}=e;if(r&&!i){let o=await fw(t);e.key=await Fp(o,n)}},Cw=async(t,e)=>{await Da(t.kind,t,e)},Zw=async(t,e)=>{let n=t,{kind:r}=n,i=mp(n,["kind"]);return Promise.all(Object.entries(i).map(([o,s])=>Da(o,s,e)))},kw=async(t,e)=>{await Da("user",t,e)},Vw=async(t,e)=>{let n=Vp(t);return Rw(n)&&await Cw(n,e),Ew(n)&&await Zw(n,e),Tw(n)&&await kw(n,e),n},xw=t=>({customBaseURI:t.serviceEndpoints.polling!==Up,customStreamURI:t.serviceEndpoints.streaming!==Pp,customEventsURI:t.serviceEndpoints.events!==Ji.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:ka(t.flushInterval),reconnectTimeMillis:ka(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:ka(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Nw=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new pe.DiagnosticsManager(t,n,xw(e))};function op(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function sp(t,e,n){return st({value:t,variationIndex:e!=null?e:null},n!==void 0&&{reason:n})}var Ow=(t,e,n,r,i)=>{if(e.sendEvents)return new pe.EventProcessor(fe(st({},e),{eventsCapacity:e.capacity}),new GS(t,e,n),r,void 0,i,!1,!0)},ap=class extends pe.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})}},xa=class Dp{constructor(){this.container={index:new Array}}static fromJson(e){let n=new Dp;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)):[]}},Gw=class{constructor(t,e,n,r,i,o,s=()=>Date.now()){this.p=t,this.Tt=e,this.Si=n,this.P=r,this.w=i,this.t=o,this.Li=s,this.we=yw(this.Tt)}async init(t,e){this.w.init(t,e),await this.Ee(t)}async upsert(t,e,n){return this.w.upsert(t,e,n)?(await this.Ee(t),!0):!1}async loadCached(t){var e,n,r,i;let o=await rp(this.p.crypto,this.Tt,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 Ci(){var t;if(this.K!==void 0)return this.K;let e=await((t=this.p.storage)==null?void 0:t.get(await this.we));if(!e)return this.K=new xa,this.K;try{this.K=xa.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.K=new xa}return this.K}async Ee(t){var e,n;let r=await this.Ci(),i=await rp(this.p.crypto,this.Tt,t);r.notice(i,this.Li());let o=r.prune(this.Si);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.we,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 Lw(){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 Xw(t,e){let n=[];return Object.entries(t).forEach(([r,i])=>{let o=e[r];(!o||!Wi(i,o))&&n.push(r)}),Object.keys(e).forEach(r=>{t[r]||n.push(r)}),n}function Ww(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=Xw(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 Uw=class{constructor(t,e,n,r,i=()=>Date.now()){this.P=Lw(),this.w=Ww(this.P,r),this.$t=this.Ii(t,e,n,r,i)}async Ii(t,e,n,r,i=()=>Date.now()){let o=await dw(t.crypto,e);return new Gw(t,o,n,this.P,this.w,r,i)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.Nt(this.r[t]):this.P.get(t)}getAll(){return this.r?st(st({},this.P.getAll()),Object.entries(this.r).reduce((t,[e,n])=>(t[e]=this.Nt(n),t),{})):this.P.getAll()}presetFlags(t){this.P.init(t)}setBootstrap(t,e){this.w.init(t,e)}async init(t,e){return(await this.$t).init(t,e)}async upsert(t,e,n){return(await this.$t).upsert(t,e,n)}async loadCached(t){return(await this.$t).loadCached(t)}on(t){this.w.on(t)}off(t){this.w.off(t)}Nt(t){return{flag:{value:t,version:0},version:0}}setOverride(t,e){this.r||(this.r={}),this.r[t]=e,this.w.handleFlagChanges([t],"override")}removeOverride(t){!this.r||!Object.prototype.hasOwnProperty.call(this.r,t)||(delete this.r[t],Object.keys(this.r).length===0&&(this.r=void 0),this.w.handleFlagChanges([t],"override"))}clearAllOverrides(){if(this.r){let t=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.Nt(n)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},lp="unknown hook",Yp="beforeEvaluation",Kp="afterEvaluation",Pw="afterTrack";function gr(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 br(t,e){try{return e.getMetadata().name||lp}catch(n){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),lp}}function Mw(t,e,n){return e.map(r=>gr(t,Yp,br(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeEvaluation)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Fw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];gr(t,Kp,br(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 Aw(t,e,n){return e.map(r=>gr(t,Yp,br(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeIdentify)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Jw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];gr(t,Kp,br(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 Dw(t,e,n){for(let r=e.length-1;r>=0;r-=1){let i=e[r];gr(t,Pw,br(t,i),()=>{var o;return(o=i==null?void 0:i.afterTrack)==null?void 0:o.call(i,n)},void 0)}}var Yw=class{constructor(t,e){this.t=t,this.R=[],this.R.push(...e)}withEvaluation(t,e,n,r){if(this.R.length===0)return r();let i=[...this.R],o={flagKey:t,context:e,defaultValue:n},s=Mw(this.t,i,o),a=r();return Fw(this.t,i,o,s,a),a}identify(t,e){let n=[...this.R],r={context:t,timeout:e},i=Aw(this.t,n,r);return o=>{Jw(this.t,n,r,i,o)}}addHook(t){this.R.push(t)}afterTrack(t){if(this.R.length===0)return;let e=[...this.R];Dw(this.t,e,t)}};function Kw(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 _w(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function Hw(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function zw(t,e){let n=!1,r={method:(...i)=>{try{t.method(...i)}catch(o){n||(n=!0,e.warn(Hw(r.type,r.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return r}var _p="flag-used",Hp="flag-details-changed",zp="flag-detail-changed",Bp="client-identity-changed",Bw=[_p,Hp,zp,Bp];function jw(t,e){let n=Bw.includes(t.type)&&t.method&&typeof t.method=="function";return n||e.warn(_w(t.type,t.name)),n}var Qw=class{constructor(t,e){this.W=[];let n=t.filter(r=>jw(r,e));this.W=n.map(r=>zw(r,e))}hasInspectors(){return this.W.length!==0}onFlagUsed(t,e,n){this.W.forEach(r=>{r.type===_p&&r.method(t,e,n)})}onFlagsChanged(t){this.W.forEach(e=>{e.type===Hp&&e.method(t)})}onFlagChanged(t,e){this.W.forEach(n=>{n.type===zp&&n.method(t,e)})}onIdentityChanged(t){this.W.forEach(e=>{e.type===Bp&&e.method(t)})}},$w=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var n;this.n.has(t)?(n=this.n.get(t))==null||n.push(e):this.n.set(t,[e])}off(t,e){let n=this.n.get(t);if(n){if(e){let r=n.filter(i=>i!==e);r.length===0?this.n.delete(t):this.n.set(t,r);return}this.n.delete(t)}}Ai(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.Ai(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 qw(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:cp,ErrorKinds:up}=pe,tI=5,eI=class{constructor(t,e,n,r,i,o){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.a=Iw(),this.Rt=15,this.T=new ap(!1),this.ht=new ap(!0),this.Mt=!1,this.Pi=lw(),!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 pw(r,o),this.logger=this.e.logger,this.De=FS(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.M=new Uw(this.platform,t,this.e.maxCachedContexts,this.e.logger),this.S=Nw(t,this.e,n),this.E=Ow(t,this.e,n,this.De,this.S),this.emitter=new $w,this.emitter.on("error",(a,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(a)}`)}),this.M.on((a,c,l)=>{this.Oi(c,l);let u=Vn.toLDContext(a);this.emitter.emit("change",u,c),c.forEach(h=>{this.emitter.emit(`change:${h}`,u)})}),this.dataManager=i(this.M,this.e,this.De,this.emitter,this.S);let s=[...this.e.hooks];if(this.environmentMetadata=qw(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(a=>{s.push(a)}),this.F=new Yw(this.logger,s),this.Q=new Qw(this.e.inspectors,this.logger),this.Q.hasInspectors()&&this.F.addHook(Kw(this.Q)),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.M.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()?Vp(this.a.getUnwrappedContext()):void 0}getInternalContext(){return this.a.getContext()}presetFlags(t){this.M.presetFlags(t)}async identify(t,e){let n=await this.identifyResult(t,e);if(n.status==="error")throw n.error;if(n.status==="timeout"){let r=new kp(`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:tI,o=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Rt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Rt} seconds. We recommend a timeout of less than ${this.Rt} seconds.`);let s=this.Pi.execute({before:async()=>{let c=await Vw(t,this.platform);this.autoEnvAttributes===Ai.Enabled&&(c=await ww(c,this.platform,this.e));let l=Vn.fromLDContext(c);if(l.valid){let u=this.F.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=PS(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(cp.MissingContextKeyNoEvent);return}n!==void 0&&!G.Number.is(n)&&((r=this.logger)==null||r.warn(cp.invalidMetricValue(typeof n))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.a.getContext(),e,n))),this.F.afterTrack({key:t,context:this.a.getUnwrappedContext(),data:e,metricValue:n})}dt(t,e,n,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.M.get(t);if(h===void 0||h.flag.deleted){let b=e!=null?e:null;return(o=this.logger)==null||o.warn(`Unknown feature flag "${t}"; returning default value ${b}.`),l&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(t,b,u))),op(up.FlagNotFound,e)}let{reason:p,value:f,variation:m,prerequisites:d}=h.flag;if(r){let[b,I]=r(f);if(!b){l&&((a=this.E)==null||a.sendEvent(n.evalEventClient(t,e,e,h.flag,u,p)));let R=new WS(`Wrong type "${I}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.a.getUnwrappedContext(),R),op(up.WrongType,e)}}let v=sp(f,m,p);return f==null&&(this.logger.debug("Result value is null. Providing default value."),v.value=e),d==null||d.forEach(b=>{this.dt(b,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.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,this.T));return n}variationDetail(t,e){return this.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,this.ht))}_(t,e,n,r){return this.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,n,r))}boolVariation(t,e){return this._(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._(t,e,this.T,n=>[G.Number.is(n),G.Number.getType()]).value}stringVariation(t,e){return this._(t,e,this.T,n=>[G.String.is(n),G.String.getType()]).value}boolVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.Boolean.is(n),G.Boolean.getType()])}numberVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.Number.is(n),G.Number.getType()])}stringVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.String.is(n),G.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.F.addHook(t)}setEventSendingEnabled(t,e){var n,r,i,o;this.Mt!==t&&(this.Mt=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.Mt||((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.M).getDebugOverride)==null?void 0:e.call(t)}Oi(t,e){if(!this.Q.hasInspectors())return;let n={};t.forEach(r=>{let i=this.M.get(r);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:o,value:s,variation:a}=i.flag;n[r]=sp(s,a,o)}else n[r]={value:void 0,variationIndex:null}}),e==="init"?this.Q.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,i])=>{this.Q.onFlagChanged(r,i)})}};function nI(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 ${pe.safeGetName(t,r)}.`)}})}function rI(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:fe(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 iI(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 hp(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var oI=class{constructor(t,e,n,r,i){this.Ti=t,this.$i=e,this.Ni=n,this.m=r,this.t=i,this.u=!1}async be(){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.m)==null||m.call(this,new Fi(Kt.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.Ti.requestPayload();try{if(this.u){hp(this.t);return}let p=JSON.parse(h);try{(e=this.Ni)==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){hp(this.t);return}let p=h;if(p.status!==void 0&&!Ki(p.status)){(r=this.t)==null||r.error(On(h,"polling request")),(i=this.m)==null||i.call(this,new Fi(Kt.ErrorResponse,p.message,p.status));return}(o=this.t)==null||o.error(On(h,"polling request","will retry"))}let l=Date.now()-c,u=Math.max(this.$i*1e3-l,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",l,u),this.Ft=setTimeout(()=>{this.be()},u)}start(){this.be()}stop(){this.Ft&&(clearTimeout(this.Ft),this.Ft=void 0),this.u=!0}close(){this.stop()}},sI=(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 Xa(Kt.InvalidData,"Malformed JSON data in event stream"))};function aI(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function pp(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var lI=class{constructor(t,e,n,r,i,o,s,a,c){var l;this.Ri=t,this.Ut=e,this.n=n,this.H=r,this.Mi=o,this.S=s,this.m=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.Ut.withReasons&&h.push({key:"withReasons",value:"true"}),this.H=r,this.ke=st({},e.baseHeaders),this.t=c,this.Fi=LS(e.serviceEndpoints,u,h)}xe(){this.ft=Date.now()}Vt(t){this.ft&&this.S&&this.S.recordStreamInit(this.ft,!t,Date.now()-this.ft),this.ft=void 0}Ui(t){var e,n,r;return xp(t)?((r=this.t)==null||r.warn(On(t,"streaming request","will retry")),this.Vt(!1),this.xe(),!0):(this.Vt(!1),(e=this.m)==null||e.call(this,new Xa(Kt.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(On(t,"streaming request")),!1)}start(){this.xe();let t;this.Ut.useReport?(this.ke["content-type"]="application/json",t={method:"REPORT",body:this.Ri}):t={};let e=this.H.createEventSource(this.Fi,fe(st({headers:this.ke},t),{errorFilter:n=>this.Ui(n),initialRetryDelayMillis:this.Ut.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.Se=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var 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){aI(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),o!=null&&o.data){this.Vt(!0);let{data:c}=o,l=n(c);if(!l){sI(i,c,this.t,this.m);return}r(l)}else(a=this.m)==null||a.call(this,new Xa(Kt.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.Mi.requestPayload();try{if(this.u){pp(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.m)==null||a.call(this,new Fi(Kt.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){pp(this.t);return}let u=l;(c=this.m)==null||c.call(this,new Fi(Kt.ErrorResponse,u.message,u.status))}})}stop(){var t;(t=this.Se)==null||t.close(),this.Se=void 0,this.u=!0}close(){this.stop()}},cI=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=iI(a),this.q=rI(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Vi=t}createPollingProcessor(t,e,n,r,i){let o=new oI(n,this.config.pollInterval,async s=>{await this.q.handlePut(e,s),r==null||r()},s=>{this.emitter.emit("error",t,s),this.q.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.Le(o,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,i){var o;let s=new lI(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.Vi)==null?void 0:o.queryParameters},this.createStreamListeners(e,r),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,a=>{this.emitter.emit("error",t,a),this.q.handleStreamingError(a),i==null||i(a)},this.logger);this.updateProcessor=this.Le(s,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.q.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.q.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.q.handleDelete(t,r)}}),n}Le(t,e){return{start:()=>{e.requestStateUpdate("INITIALIZING"),t.start()},stop:()=>{t.stop(),e.requestStateUpdate("CLOSED")},close:()=>{t.close(),e.requestStateUpdate("CLOSED")}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function jp(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 _i(){return typeof document!==void 0}function Ya(){return typeof window!==void 0}function Qp(t,e,n){return _i()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function $p(t,e,n){return _i()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function mr(){return Ya()?window.location.href:""}function uI(){return Ya()?window.location.search:""}function hI(){return Ya()?window.location.hash:""}function pI(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function dI(){return _i()?document.visibilityState:"visibile"}function fI(t){if(_i())return document.querySelectorAll(t)}var mI="[BrowserDataManager]",yI=class extends cI{constructor(t,e,n,r,i,o,s,a,c,l){super(t,e,n,r,o,s,a,c,l),this.Xi=i,this.tt=void 0,this.jt=!1,this.tt=i.streaming}L(t,...e){this.logger.debug(`${mI} ${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.Ht=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.ji(n,i,t):(await this.flagManager.loadCached(n)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Hi(n,t,e)),this.Bt()}async Bi(t){let e=JSON.stringify(Vn.toLDContext(t)),n=ep(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ht),r=3,i;for(let o=0;o<=r;o+=1)try{return await n.requestPayload()}catch(s){if(!xp(s))throw s;i=s,o<r&&(this.L(On(s,"initial poll request","will retry")),await Np(1e3))}throw i}async Hi(t,e,n){var r,i;try{this.dataSourceStatusManager.requestStateUpdate(ow.Initializing);let o=await this.Bi(t);try{let s=this.createStreamListeners(t,e).get("put");s.processJson(s.deserializeData(o))}catch(s){this.dataSourceStatusManager.reportError(Kt.InvalidData,(r=s.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(Kt.NetworkError,(i=o.message)!=null?i:"unexpected network error",o.status),n(o)}}ji(t,e,n){let{bootstrapParsed:r}=e;r||(r=jp(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,r),this.L("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.tt=t,this.Bt()}setAutomaticStreamingState(t){this.jt=t,this.Bt()}Bt(){let t=this.tt||this.jt&&this.tt===void 0;this.L(`Updating streaming state. forced(${this.tt}) automatic(${this.jt})`),t?this.zi():this.Gi()}Gi(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}zi(){if(this.updateProcessor){this.L("Update processor already active. Not changing state.");return}if(!this.context){this.L("Context not set, not starting update processor.");return}this.L("Starting update processor."),this.Ki(this.context)}Ki(t,e,n){var r;let i=Vn.toLDContext(t);(r=this.updateProcessor)==null||r.close();let o=JSON.stringify(Vn.toLDContext(t)),s=ep(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ht);this.createStreamingProcessor(i,t,s,e,n),this.updateProcessor.start()}};function gI(t){let e=Qp("visibilitychange",()=>{dI()==="hidden"&&t()}),n=$p("pagehide",t);return()=>{e(),n()}}function Na(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function bI(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(`^${Na(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${Na(t.url)}/?$`).test(i);case"substring":return new RegExp(`.*${Na(t.substring)}.*$`).test(i);case"regex":return new RegExp(t.pattern).test(i);default:return!1}}function vI(t,e){let n=[];return e.forEach(r=>{let i=t.target,{selector:o}=r,s=fI(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 SI=class{constructor(t,e){let n=t.filter(o=>{var s;return(s=o.urls)==null?void 0:s.some(a=>bI(a,mr(),uI(),hI()))}),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=>{vI(s,i).forEach(a=>{e(a)})};this.Ce=Qp("click",o)}}close(){var t;(t=this.Ce)==null||t.call(this)}},wI=300,II=class{constructor(t){this.zt=mr();let e=()=>{let r=mr();r!==this.zt&&(this.zt=r,t())};this.Gt=setInterval(e,wI);let n=$p("popstate",e);this.Ie=()=>{n()}}close(){var t;this.Gt&&clearInterval(this.Gt),(t=this.Ie)==null||t.call(this)}},TI=class{constructor(t,e,n,r,i,o=s=>new II(s)){this.H=e,this.qi=r,this.Pr=i,this.pt=[],this.Pe=!1,this.gt=`${n}/sdk/goals/${t}`,this.Ae=o(()=>{this.Wt()})}async initialize(){await this.Wi(),this.Wt()}startTracking(){this.Pe=!0,this.Wt()}Wt(){var t;this.Pe&&((t=this.Kt)==null||t.close(),this.pt&&this.pt.length&&(this.Kt=new SI(this.pt,e=>{this.Pr(mr(),e)})))}async Wi(){try{let t=await this.H.fetch(this.gt);this.pt=await t.json()}catch(t){this.qi(new Zp(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.Ae)==null||t.close(),(e=this.Kt)==null||e.close()}};function EI(t){return t.kind==="click"}var RI=2,qp={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},CI={fetchGoals:G.Boolean,eventUrlTransformer:G.Function,streaming:G.Boolean,plugins:G.createTypeArray("LDPlugin",{})};function ZI(t){var e;let n=st({},t);return(e=n.flushInterval)!=null||(n.flushInterval=RI),n}function kI(t){let e=ZI(t);return Object.keys(qp).forEach(n=>{delete e[n]}),e}function VI(t,e){let n=st({},qp);return Object.entries(CI).forEach(r=>{let[i,o]=r,s=t[i];s!==void 0&&(o.is(s)?n[i]=s:e.warn(We.wrongOptionType(i,o.getType(),typeof s)))}),n}var xI=class{constructor(t,e){switch(this.Ji=t,this.Oe=[],e){case"sha1":this.No="SHA-1";break;case"sha256":this.No="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Oe.join(""),n=new TextEncoder().encode(e),r=await this.Ji.subtle.digest(this.No,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.Oe.push(t),this}},NI={start:0,end:3},OI={start:4,end:5},Oa={start:6,end:7},Ga={start:8,end:8},GI={start:9,end:9},LI={start:10,end:15};function XI(){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 Zn(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 WI(t){return t[Ga.start]=(t[Ga.start]|128)&191,t[Oa.start]=t[Oa.start]&15|64,`${Zn(t,NI)}-${Zn(t,OI)}-${Zn(t,Oa)}-${Zn(t,Ga)}${Zn(t,GI)}-${Zn(t,LI)}`}function UI(){let t=XI();return WI(t)}function PI(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():UI()}var MI=class{createHash(t){return new xI(pI(),t)}randomUUID(){return PI()}};function FI(t){let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e)}var AI=class{btoa(t){return FI(new TextEncoder().encode(t))}},JI=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"4.0.0",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},DI=class{constructor(t,e){this.gt=t,this.n={},this.I=new TS(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Te=e.errorFilter,this.$e()}$e(){this.J=new EventSource(this.gt),this.J.onopen=()=>{var t;this.I.success(),(t=this.onopen)==null||t.call(this)},this.J.onerror=t=>{var e;this.Yi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this.J)==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.J)==null||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.qt),this.qt=void 0,(t=this.J)==null||t.close(),(e=this.onclose)==null||e.call(this)}Zi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.qt=setTimeout(()=>{this.$e()},t)}Yi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Te(t))&&this.Zi(this.I.fail())}},YI=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new DI(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function td(){return typeof localStorage!="undefined"}function KI(){if(!td())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);n&&t.push(n)}return t}var _I=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}`)}}},HI=class{constructor(t,e){this.encoding=new AI,this.crypto=new MI,this.requests=new YI,td()&&(this.storage=new _I(t)),this.info=new JI(e)}},zI=class extends eI{constructor(t,e,n={},r){var i;let{logger:o,debug:s}=n,a=o!=null?o:new Ma({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 HI(a,n),u=VI(n,a),h=kI(fe(st({},n),{logger:a})),{eventUrlTransformer:p}=u;super(t,e,l,h,(f,m,d,v,b)=>new yI(l,f,t,m,u,()=>({pathGet(I,R){return`/sdk/evalx/${t}/contexts/${Qh(R,I)}`},pathReport(I,R){return`/sdk/evalx/${t}/context`},pathPing(I,R){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(I,R){return`/eval/${t}/${Qh(R,I)}`},pathReport(I,R){return`/eval/${t}`},pathPing(I,R){return`/ping/${t}`}}),d,v,b),{getLegacyStorageKeys:()=>KI().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 pe.InputCustomEvent(f.context,f.key,f.data,f.metricValue,f.samplingRatio,p(mr())),getImplementationHooks:f=>pe.safeGetHooks(a,f,u.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.Yt=u.plugins,u.fetchGoals&&(this.Jt=new TI(t,l.requests,c,f=>{a.error(f.message)},(f,m)=>{let d=this.getInternalContext();if(!d)return;let v=p(f);EI(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.Jt.initialize(),u.automaticBackgroundHandling&&gI(()=>this.flush()))}registerPlugins(t){pe.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.Yt||[]);let e=this.getDebugOverrides();e&&nI(this.logger,e,this.Yt||[])}setInitialContext(t){this.Zt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var n;if(!this.et)return this.logger.error("Client must be started before it can identify a context, did you forget to call start()?"),{status:"error",error:new Error("Identify called before start")};let r=st({},e);(e==null?void 0:e.sheddable)===void 0&&(r.sheddable=!0);let i=await super.identifyResult(t,r);return(n=this.Jt)==null||n.startTracking(),i}start(t){var e,n;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.et)return this.et;if(!this.Zt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let r=fe(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=jp(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.et=this.promiseWithTimeout(this.initializedPromise,(n=t==null?void 0:t.timeout)!=null?n:5),this.identifyResult(this.Zt,r),this.et}setStreaming(t){this.dataManager.setForcedStreaming(t)}Ne(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.Ne()}off(t,e){super.off(t,e),this.Ne()}};function BI(t,e,n,r={},i){let o=new zI(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 jI(t){return new Ma(t)}function ed(t,e,n){return BI(t,e,Ai.Disabled,n)}var QI=Object.defineProperty,$I=(t,e,n)=>e in t?QI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ie=(t,e,n)=>$I(t,typeof e!="symbol"?e+"":e,n),qI=(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())}),Ze=(t,e,...n)=>{let r=`[@launchdarkly plugins]: (${t}): `;console[e].apply(console,[r,...n]),tT(r,...n)},tT=(t,...e)=>qI(void 0,null,function*(){try{let{LDObserve:n}=yield Promise.resolve().then(()=>oR);n.recordLog(`${t}${e}`,"warn")}catch(n){}}),eT=class{constructor(t,e){Ie(this,"debug"),Ie(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])}},vo=class{constructor(){Ie(this,"_sdk"),Ie(this,"_isLoaded",!1),Ie(this,"_callBuffer",[]),Ie(this,"_capacity",1e5),Ie(this,"_droppedEvents",0),Ie(this,"_exceededCapacity",!1),Ie(this,"_logger",new eT)}h(e,n){if(this.Nn)try{return this.jn[e](...n)}catch(r){Ze(`Error executing buffered call to ${e}:`,"error",r)}else{this.Mr({method:e,args:n});return}}Mr(e){this.wn.length<this.Ws?(this.wn.push(e),this.Qn=!1):(this.Qn||(this.Qn=!0,Ze("Exceeded event queue capacity. Increase capacity to avoid dropping events.","warn")),this.Us+=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){Ze(`Error executing buffered call to ${n}:`,"error",i)}this.wn=[]}},nT=Object.defineProperty,rT=Object.defineProperties,iT=Object.getOwnPropertyDescriptors,So=Object.getOwnPropertySymbols,Mf=Object.prototype.hasOwnProperty,Ff=Object.prototype.propertyIsEnumerable,Zl=(t,e,n)=>e in t?nT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,j=(t,e)=>{for(var n in e||(e={}))Mf.call(e,n)&&Zl(t,n,e[n]);if(So)for(var n of So(e))Ff.call(e,n)&&Zl(t,n,e[n]);return t},Fn=(t,e)=>rT(t,iT(e)),Vr=(t,e)=>{var n={};for(var r in t)Mf.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&So)for(var r of So(t))e.indexOf(r)<0&&Ff.call(t,r)&&(n[r]=t[r]);return n},Xr=(t,e,n)=>Zl(t,typeof e!="symbol"?e+"":e,n),Jn=(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 oT(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 lo(t,e){throw new Error(e)}function sT(t){return typeof t=="object"&&t!==null}function aT(t,e){throw new Error("Unexpected invariant triggered.")}var lT=/\r\n|[\n\r]/g;function kl(t,e){let n=0,r=1;for(let i of t.body.matchAll(lT)){if(typeof i.index=="number"||aT(),i.index>=e)break;n=i.index+i[0].length,r+=1}return{line:r,column:e+1-n}}function cT(t){return Af(t.source,kl(t.source,t.start))}function Af(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+nd([[`${s} |`,m[0]],...m.slice(1,p+1).map(d=>["|",d]),["|","^".padStart(f)],["|",m[p+1]]])}return l+nd([[`${s-1} |`,u[i-1]],[`${s} |`,h],["|","^".padStart(c)],[`${s+1} |`,u[i+1]]])}function nd(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 uT(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 hT=class Jf extends Error{constructor(e,...n){var r,i,o;let{nodes:s,source:a,positions:c,path:l,originalError:u,extensions:h}=uT(n);super(e),this.name="GraphQLError",this.path=l!=null?l:void 0,this.originalError=u!=null?u:void 0,this.nodes=rd(Array.isArray(s)?s:s?[s]:void 0);let p=rd((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=>kl(a,m)):p==null?void 0:p.map(m=>kl(m.source,m.start));let f=sT(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,Jf):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
|
|