@launchdarkly/js-client-sdk 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +1 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.es.js.map +1 -1
- package/dist/src/BrowserClient.d.ts +2 -3
- package/dist/src/BrowserClient.d.ts.map +1 -1
- package/dist/src/BrowserDataManager.d.ts +12 -13
- package/dist/src/BrowserDataManager.d.ts.map +1 -1
- package/dist/src/goals/GoalManager.d.ts +11 -11
- package/dist/src/goals/GoalManager.d.ts.map +1 -1
- package/dist/src/goals/GoalTracker.d.ts +1 -1
- package/dist/src/goals/GoalTracker.d.ts.map +1 -1
- package/dist/src/platform/Backoff.d.ts +9 -9
- package/dist/src/platform/Backoff.d.ts.map +1 -1
- package/dist/src/platform/BrowserHasher.d.ts +4 -4
- package/dist/src/platform/BrowserHasher.d.ts.map +1 -1
- package/dist/src/platform/DefaultBrowserEventSource.d.ts +10 -10
- package/dist/src/platform/DefaultBrowserEventSource.d.ts.map +1 -1
- package/dist/src/platform/LocalStorage.d.ts +2 -2
- package/dist/src/platform/LocalStorage.d.ts.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.1.0](https://github.com/launchdarkly/js-core/compare/js-client-sdk-v0.0.1...js-client-sdk-v0.1.0) (2024-10-17)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* Add prerequisite information to server-side allFlagsState. ([8c84e01](https://github.com/launchdarkly/js-core/commit/8c84e0149a5621c6fcb95f2cfdbd6112f3540191))
|
|
9
|
+
* Add support for client-side prerequisite events. ([8c84e01](https://github.com/launchdarkly/js-core/commit/8c84e0149a5621c6fcb95f2cfdbd6112f3540191))
|
|
10
|
+
* Add support for inspectors. ([#625](https://github.com/launchdarkly/js-core/issues/625)) ([a986478](https://github.com/launchdarkly/js-core/commit/a986478ed8e39d0f529ca6adec0a09b484421390))
|
|
11
|
+
* Add support for prerequisite details to evaluation detail. ([8c84e01](https://github.com/launchdarkly/js-core/commit/8c84e0149a5621c6fcb95f2cfdbd6112f3540191))
|
|
12
|
+
* adds ping stream support ([#624](https://github.com/launchdarkly/js-core/issues/624)) ([dee53af](https://github.com/launchdarkly/js-core/commit/dee53af9312b74a70b748d49b2d2911d65333cf3))
|
|
13
|
+
* Apply private property naming standard. Mangle browser private properties. ([#620](https://github.com/launchdarkly/js-core/issues/620)) ([3e6d404](https://github.com/launchdarkly/js-core/commit/3e6d404ae665c5cc7e5a1394a59c8f2c9d5d682a))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
### Bug Fixes
|
|
17
|
+
|
|
18
|
+
* Do not mangle _meta. ([#622](https://github.com/launchdarkly/js-core/issues/622)) ([f6fc40b](https://github.com/launchdarkly/js-core/commit/f6fc40bc518d175d18d556b8c22e3c924ed25bbd))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
### Dependencies
|
|
22
|
+
|
|
23
|
+
* The following workspace dependencies were updated
|
|
24
|
+
* dependencies
|
|
25
|
+
* @launchdarkly/js-client-sdk-common bumped from 1.9.0 to 1.10.0
|
|
26
|
+
|
|
3
27
|
## 0.0.1 (2024-10-10)
|
|
4
28
|
|
|
5
29
|
|
package/README.md
CHANGED
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function t(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}class e{constructor(e,n=!1){if(n){const t=e;this.components=[t],this.isValid=""!==t,this.redactionName=t.startsWith("/")?`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`:t}else{if(this.redactionName=e,""===e||"/"===e||e.match(/\/\/|(^\/.*~[^0|^1])|~$/))return this.isValid=!1,void(this.components=[]);!function(t){return!t.startsWith("/")}(e)?e.indexOf("/",1)<0?this.components=[t(e.slice(1))]:this.components=function(e){return(e.startsWith("/")?e.substring(1):e).split("/").map((e=>t(e)))}(e):this.components=[e],"_meta"===this.components[0]?this.isValid=!1:this.isValid=!0}}get(t){const{components:e,isValid:n}=this;if(!n)return;let i=t;for(let t=0;t<e.length;t+=1){const n=e[t];if(null==i||!Object.prototype.hasOwnProperty.call(i,n)||"object"!=typeof i||Array.isArray(i))return;i=i[n]}return i}getComponent(t){return this.components[t]}get depth(){return this.components.length}get isKind(){return 1===this.components.length&&"kind"===this.components[0]}compare(t){return this.depth===t.depth&&this.components.every(((e,n)=>e===t.getComponent(n)))}}e.invalidReference=new e("");class n{constructor(t,e){this.typeName=t,this.typeOf=typeof e}is(t){return!Array.isArray(t)&&typeof t===this.typeOf}getType(){return this.typeName}}class i{constructor(t,e){this.typeName=t,this.typeOf=typeof e}is(t){return!!Array.isArray(t)&&(!(t.length>0)||t.every((t=>typeof t===this.typeOf)))}getType(){return this.typeName}}class s extends n{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}}class r extends n{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return"string"==typeof t&&!!t.match(this.expression)}}const a=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/;class o{static createTypeArray(t,e){return new i(t,e)}static numberWithMin(t){return new s(t)}static stringMatchingRegex(t){return new r(t)}}function c(t){return"kind"in t&&(o.String.is(t.kind)&&"multi"!==t.kind)}function l(t){return"kind"in t&&(o.String.is(t.kind)&&"multi"===t.kind)}function h(t){return!("kind"in t)||null===t.kind||void 0===t.kind}o.String=new n("string",""),o.Number=new n("number",0),o.ObjectOrFactory=new class{is(t){if(Array.isArray(t))return!1;const e=typeof t;return"function"===e||"object"===e}getType(){return"factory method or object"}},o.Object=new n("object",{}),o.StringArray=new i("string[]",""),o.Boolean=new n("boolean",!0),o.Function=new class{is(t){return"function"==typeof t}getType(){return"function"}},o.Date=new class{is(t){return"number"==typeof t||"string"==typeof t&&a.test(t)}getType(){return"date"}},o.Kind=new class extends r{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&"kind"!==t}},o.NullableBoolean=new class{is(t){return"boolean"==typeof t||null==t}getType(){return"boolean | undefined | null"}};const u="user";function d(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function g(t){return o.Kind.is(t)}function f(t){return o.String.is(t)&&""!==t}function p(t,n=!1){return t?t.map((t=>new e(t,n))):[]}class m{constructor(t,e,n){this.isMulti=!1,this.isUser=!1,this.wasLegacy=!1,this.contexts={},this.kind=e,this.valid=t,this.message=n}static contextForError(t,e){return new m(!1,t,e)}static getValueFromContext(t,e){if(e&&t.isValid)return 1===t.depth&&"anonymous"===t.getComponent(0)?!!e?.anonymous:t.get(e)}contextForKind(t){return this.isMulti?this.contexts[t]:this.kind===t?this.context:void 0}static fromMultiKindContext(t){const e=Object.keys(t).filter((t=>"kind"!==t)),n=e.every(g);if(!e.length)return m.contextForError("multi","A multi-kind context must contain at least one kind");if(!n)return m.contextForError("multi","Context contains invalid kinds");const i={};let s=!0;const r=e.reduce(((e,n)=>{const r=t[n];var a;return(a=r)&&o.Object.is(a)?(e[n]=r,i[n]=p(r._meta?.privateAttributes)):s=!1,e}),{});if(!s)return m.contextForError("multi","Context contained contexts that were not objects");if(!Object.values(r).every((t=>f(t.key))))return m.contextForError("multi","Context contained invalid keys");if(1===e.length){const t=e[0],n=new m(!0,t);return n.context={...r[t],kind:t},n.privateAttributeReferences=i,n.isUser="user"===t,n}const a=new m(!0,t.kind);return a.contexts=r,a.privateAttributeReferences=i,a.isMulti=!0,a}static fromSingleKindContext(t){const{key:e,kind:n}=t,i=g(n),s=f(e);if(!i)return m.contextForError(n??"unknown","The kind was not valid for the context");if(!s)return m.contextForError(n,"The key for the context was not valid");const r=p(t._meta?.privateAttributes),a=new m(!0,n);return a.isUser="user"===n,a.context=t,a.privateAttributeReferences={[n]:r},a}static fromLegacyUser(t){if(!(void 0!==t.key&&null!==t.key))return m.contextForError("user","The key for the context was not valid");const e=new m(!0,"user");return e.isUser=!0,e.wasLegacy=!0,e.context=function(t){const e={...t.custom||[],kind:"user",key:String(t.key)};if(null!=t.anonymous){const n=!!t.anonymous;delete e.anonymous,e.anonymous=n}return null!==t.name&&void 0!==t.name&&(e.name=t.name),null!==t.ip&&void 0!==t.ip&&(e.ip=t.ip),null!==t.firstName&&void 0!==t.firstName&&(e.firstName=t.firstName),null!==t.lastName&&void 0!==t.lastName&&(e.lastName=t.lastName),null!==t.email&&void 0!==t.email&&(e.email=t.email),null!==t.avatar&&void 0!==t.avatar&&(e.avatar=t.avatar),null!==t.country&&void 0!==t.country&&(e.country=t.country),null!==t.privateAttributeNames&&void 0!==t.privateAttributeNames&&(e._meta={privateAttributes:t.privateAttributeNames}),e}(t),e.privateAttributeReferences={user:p(t.privateAttributeNames,!0)},e}static fromLDContext(t){return t?c(t)?m.fromSingleKindContext(t):l(t)?m.fromMultiKindContext(t):h(t)?m.fromLegacyUser(t):m.contextForError("unknown","Context was not of a valid kind"):m.contextForError("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;const e=t.getContexts();if(!t.isMulti)return e[0][1];const n={kind:"multi"};return e.forEach((t=>{const e=t[0],i=t[1];n[e]=i})),n}valueForKind(t,e=u){return t.isKind?this.kinds:m.getValueFromContext(t,this.contextForKind(e))}key(t=u){return this.contextForKind(t)?.key}get isMultiKind(){return this.isMulti}get canonicalKey(){return this.isUser?this.context.key:this.isMulti?Object.keys(this.contexts).sort().map((t=>`${t}:${d(this.contexts[t].key)}`)).join(":"):`${this.kind}:${d(this.context.key)}`}get kinds(){return this.isMulti?Object.keys(this.contexts):[this.kind]}get kindsAndKeys(){return this.isMulti?Object.entries(this.contexts).reduce(((t,[e,n])=>(t[e]=n.key,t)),{}):{[this.kind]:this.context.key}}privateAttributes(t){return this.privateAttributeReferences?.[t]||[]}getContexts(){return this.isMulti?Object.entries(this.contexts):[[this.kind,this.context]]}get legacy(){return this.wasLegacy}}m.userKind=u;const v=["key","kind","_meta","anonymous"].map((t=>new e(t,!0))),y=["name","ip","firstName","lastName","email","avatar","country"];class w{constructor(t,e){this.allAttributesPrivate=t,this.privateAttributes=e}filter(t,e=!1){const n=t.getContexts();if(1===n.length)return this.filterSingleKind(t,n[0][1],n[0][0],e);const i={kind:"multi"};return n.forEach((([n,s])=>{i[n]=this.filterSingleKind(t,s,n,e)})),i}getAttributesToFilter(t,n,i,s){return(s?Object.keys(n).map((t=>new e(t,!0))):[...this.privateAttributes,...t.privateAttributes(i)]).filter((t=>!v.some((e=>e.compare(t)))))}filterSingleKind(t,e,n,i){const s=this.allAttributesPrivate||i&&!0===e.anonymous,{cloned:r,excluded:a}=function(t,e){const n=[],i={},s=[];for(n.push(...Object.keys(t).map((e=>({key:e,ptr:[e],source:t,parent:i,visited:[t]}))));n.length;){const t=n.pop(),i=e.find((e=>{return n=e,i=t.ptr,n.depth===i.length&&i.every(((t,e)=>t===n.getComponent(e)));var n,i}));if(i)s.push(i.redactionName);else{const e=t.source[t.key];null===e?t.parent[t.key]=e:Array.isArray(e)?t.parent[t.key]=[...e]:"object"==typeof e?t.visited.includes(e)||(t.parent[t.key]={},n.push(...Object.keys(e).map((n=>({key:n,ptr:[...t.ptr,n],source:e,parent:t.parent[t.key],visited:[...t.visited,e]}))))):t.parent[t.key]=e}}return{cloned:i,excluded:s.sort()}}(e,this.getAttributesToFilter(t,e,n,s));return t.legacy&&y.forEach((t=>{t in r&&(r[t]=String(r[t]))})),a.length&&(r._meta||(r._meta={}),r._meta.redactedAttributes=a),r._meta&&(delete r._meta.privateAttributes,0===Object.keys(r._meta).length&&delete r._meta),r}}var k,E,b,S;!function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"}(k||(k={}));class x extends Error{constructor(t,e,n,i=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=i}}class D extends Error{constructor(t,e,n,i=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=i}}function C(t){if("string"==typeof t)return t;if(void 0===t)return"undefined";if(null===t)return"null";if(Object.prototype.hasOwnProperty.call(t,"toString"))try{return t.toString()}catch{}if("bigint"==typeof t)return`${t}n`;try{return JSON.stringify(t)}catch(t){return t instanceof TypeError&&t.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}!function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"}(E||(E={})),function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"}(b||(b={})),function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"}(S||(S={}));const R={s:t=>C(t),d:t=>function(t){return"symbol"==typeof t?"NaN":"bigint"==typeof t?`${t}n`:String(Number(t))}(t),i:t=>function(t){return"symbol"==typeof t?"NaN":"bigint"==typeof t?`${t}n`:String(parseInt(t,10))}(t),f:t=>function(t){return"symbol"==typeof t?"NaN":String(parseFloat(t))}(t),j:t=>C(t),o:t=>C(t),O:t=>C(t),c:()=>""};function I(...t){const e=t.shift();if(o.String.is(e)){let n="",i=0;for(;i<e.length;){const s=e.charAt(i);if("%"===s){if(i+1<e.length){const s=e.charAt(i+1);if(s in R&&t.length){const e=t.shift();n+=R[s]?.(e)}else n+="%"===s?"%":`%${s}`;i+=2}}else n+=s,i+=1}return t.length&&(n.length&&(n+=" "),n+=t.map(C).join(" ")),n}return t.map(C).join(" ")}const M={debug:0,info:1,warn:2,error:3,none:4},O=["debug","info","warn","error","none"];class T{static get(){return new T({})}constructor(t){this.logLevel=M[t.level??"info"]??M.info,this.name=t.name??"LaunchDarkly",this.destination=t.destination,this.formatter=t.formatter}tryFormat(...t){try{return this.formatter?this.formatter?.(...t):I(...t)}catch{return I(...t)}}tryWrite(t){try{this.destination(t)}catch{console.error(t)}}log(t,e){if(t>=this.logLevel){const n=`${O[t]}: [${this.name}]`;try{this.destination?this.tryWrite(`${n} ${this.tryFormat(...e)}`):console.error(...e)}catch{console.error(...e)}}}error(...t){this.log(M.error,t)}warn(...t){this.log(M.warn,t)}info(...t){this.log(M.info,t)}debug(...t){this.log(M.debug,t)}}const A={error:o.Function,warn:o.Function,info:o.Function,debug:o.Function};class ${constructor(t,e){Object.entries(A).forEach((([e,n])=>{if(!n.is(t[e]))throw new Error(`Provided logger instance must support logger.${e}(...) method`)})),this.logger=t,this.fallback=e}log(t,e){try{this.logger[t](...e)}catch{this.fallback[t](...e)}}error(...t){this.log("error",t)}warn(...t){this.log("warn",t)}info(...t){this.log("info",t)}debug(...t){this.log("debug",t)}}const P=t=>{const e=new T({level:"info",destination:console.error,formatter:I});return t?new $(t,e):e};class N{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`}}const U=o.stringMatchingRegex(/^(\w|\.|-)+$/),F=(t,e)=>U.is(t)?t.length>64?{valid:!1,message:N.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:N.invalidTagValue(e)};class L{constructor(t){const e={},n=t?.application,i=t?.logger;n&&Object.entries(n).forEach((([t,n])=>{if(null!=n){const{valid:s,message:r}=F(n,`application.${t}`);s?"versionName"===t?e["application-version-name"]=[n]:e[`application-${t}`]=[n]:i?.warn(r)}}));const s=Object.keys(e);s.length&&(this.value=s.sort().flatMap((t=>e[t].sort().map((e=>`${t}/${e}`)))).join(" "))}}class j{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}}function K(t){return t.replace(/\/+$/,"")}function H(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}class q{constructor(t,e,n=q.DEFAULT_EVENTS,i="/bulk",s="/diagnostic",r=!0,a){this.streaming=K(t),this.polling=K(e),this.events=K(n),this.analyticsEventPath=i,this.diagnosticEventPath=s,this.includeAuthorizationHeader=r,this.payloadFilterKey=a}}function V(t,e){if(0===e.length)return t;return`${t}?${e.map((({key:t,value:e})=>`${t}=${e}`)).join("&")}`}function _(t,e,n){const i=H(e),s=[...n];return t.payloadFilterKey&&s.push({key:"filter",value:t.payloadFilterKey}),V(`${t.streaming}/${i}`,s)}function J(t,e,n){const i=H(e),s=[...n];return t.payloadFilterKey&&s.push({key:"filter",value:t.payloadFilterKey}),V(`${t.polling}/${i}`,s)}function B(t,e,n){const i=H(e);return V(`${t.events}/${i}`,n)}q.DEFAULT_EVENTS="https://events.launchdarkly.com";class z extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}}class W extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}}class G extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}}function Y(t){return!(t>=400&&t<500)||(400===t||408===t||429===t)}function Z(t){return null==t?t:JSON.parse(JSON.stringify(t))}function Q(t){return Math.trunc(1e3*t)}const X=(t,e)=>t?Object.entries(t).reduce(((t,[n,i])=>(!Boolean(i)||(t=>"{}"===JSON.stringify(t))(i)||e?.includes(n)||(t[n]="object"==typeof i?X(i,e):i),t)),{}):t;function tt(t,e){if(t===e)return!0;if(t&&e&&"object"==typeof t&&"object"==typeof e){if(t.constructor!==e.constructor)return!1;var n,i,s;if(Array.isArray(t)){if((n=t.length)!=e.length)return!1;for(i=n;0!=i--;)if(!tt(t[i],e[i]))return!1;return!0}if(t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(i of t.entries())if(!e.has(i[0]))return!1;for(i of t.entries())if(!tt(i[1],e.get(i[0])))return!1;return!0}if(t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(i of t.entries())if(!e.has(i[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if((n=t.length)!=e.length)return!1;for(i=n;0!=i--;)if(t[i]!==e[i])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((n=(s=Object.keys(t)).length)!==Object.keys(e).length)return!1;for(i=n;0!=i--;)if(!Object.prototype.hasOwnProperty.call(e,s[i]))return!1;for(i=n;0!=i--;){var r=s[i];if(!tt(t[r],e[r]))return!1}return!0}return t!=t&&e!=e}function et(t,e,n){let i;i=t.status?`error ${t.status}${401===t.status?" (invalid SDK key)":""}`:`I/O error (${t.message||"unknown error"})`;return`Received ${i} for ${e} - ${n??"giving up permanently"}`}function nt({status:t}){return!t||Y(t)}const it=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var st;!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"}(st||(st={}));var rt=st;let at=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};at.missingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";class ot{constructor(t,e){const{basicConfiguration:n,platform:i}=t,{serviceEndpoints:{analyticsEventPath:s,diagnosticEventPath:r}}=n,{crypto:a,requests:o}=i;this.defaultHeaders={...e},this.eventsUri=B(n.serviceEndpoints,s,[]),this.diagnosticEventsUri=B(n.serviceEndpoints,r,[]),this.requests=o,this.crypto=a}async tryPostingEvents(t,e,n,i){const s={status:S.Succeeded},r={...this.defaultHeaders,"content-type":"application/json"};let a;n&&(r["x-launchdarkly-payload-id"]=n,r["x-launchDarkly-event-schema"]="4");try{const{status:n,headers:i}=await this.requests.fetch(e,{headers:r,body:JSON.stringify(t),method:"POST",keepalive:!0}),o=Date.parse(i.get("date")||"");if(o&&(s.serverTime=o),n<=204)return s;if(a=new z(et({status:n,message:"some events were dropped"},"event posting")),!Y(n))return!function(t){return 413===t||Y(t)}(n)?s.status=S.FailedAndMustShutDown:s.status=S.Failed,s.error=a,s}catch(t){a=t}return a&&!i?(s.status=S.Failed,s.error=a,s):(await(async(t=1e3)=>new Promise((e=>{setTimeout(e,t)})))(),this.tryPostingEvents(t,this.eventsUri,n,!1))}async sendEventData(t,e){const n=t===b.AnalyticsEvents?this.crypto.randomUUID():void 0,i=t===b.AnalyticsEvents?this.eventsUri:this.diagnosticEventsUri;return this.tryPostingEvents(e,i,n,!0)}}function ct(t){return"feature"===t.kind}class lt{constructor(t,e,n,i,s,r){this.count=t,this.key=e,this.value=n,this.version=s,this.variation=r,this.default=i}increment(){this.count+=1}}class ht{constructor(){this.startDate=0,this.endDate=0,this.counters={},this.contextKinds={}}summarizeEvent(t){if(ct(t)&&!t.excludeFromSummaries){const e=function(t){return`${t.key}:${null!==t.variation&&void 0!==t.variation?t.variation:""}:${null!==t.version&&void 0!==t.version?t.version:""}`}(t),n=this.counters[e];let i=this.contextKinds[t.key];i||(i=new Set,this.contextKinds[t.key]=i),t.context.kinds.forEach((t=>i.add(t))),n?n.increment():this.counters[e]=new lt(1,t.key,t.value,t.default,t.version,t.variation),(0===this.startDate||t.creationDate<this.startDate)&&(this.startDate=t.creationDate),t.creationDate>this.endDate&&(this.endDate=t.creationDate)}}getSummary(){const t=Object.values(this.counters).reduce(((t,e)=>{let n=t[e.key];n||(n={default:e.default,counters:[],contextKinds:[...this.contextKinds[e.key]]},t[e.key]=n);const i={value:e.value,count:e.count};return void 0!==e.variation&&null!==e.variation&&(i.variation=e.variation),void 0!==e.version&&null!==e.version?i.version=e.version:i.unknown=!0,n.counters.push(i),t}),{});return{startDate:this.startDate,endDate:this.endDate,features:t,kind:"summary"}}clearSummary(){this.startDate=0,this.endDate=0,this.counters={},this.contextKinds={}}}class ut extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}}function dt(t){const e=Math.trunc(t);return 1===e||0!==e&&0===Math.floor(Math.random()*e)}class gt{constructor(t,e,n,i,s=1,r){this.context=t,this.key=e,this.data=n,this.metricValue=i,this.samplingRatio=s,this.url=r,this.kind="custom",this.creationDate=Date.now(),this.context=t}}class ft{constructor(t,e,n,i,s,r,a,o,c,l,h,u,d=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=d,this.kind="feature",this.creationDate=Date.now(),this.value=i,this.default=s,void 0!==r&&(this.version=r),void 0!==a&&(this.variation=a),void 0!==o&&(this.trackEvents=o),void 0!==c&&(this.prereqOf=c),void 0!==l&&(this.reason=l),void 0!==h&&(this.debugEventsUntilDate=h),void 0!==u&&(this.excludeFromSummaries=u)}}class pt{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}}var mt,vt=Object.freeze({__proto__:null,ClientMessages:at,DiagnosticsManager:class{constructor(t,e,n){this.platform=e,this.diagnosticInitConfig=n,this.streamInits=[],this.startTime=Date.now(),this.dataSinceDate=this.startTime,this.id={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){const t=this.platform.info.sdkData(),e=this.platform.info.platformData();return{kind:"diagnostic-init",id:this.id,creationDate:this.startTime,sdk:t,configuration:this.diagnosticInitConfig,platform:{name:e.name,osArch:e.os?.arch,osName:e.os?.name,osVersion:e.os?.version,...e.additional||{}}}}recordStreamInit(t,e,n){const i={timestamp:t,failed:e,durationMillis:n};this.streamInits.push(i)}createStatsEventAndReset(t,e,n){const i=Date.now(),s={kind:"diagnostic",id:this.id,creationDate:i,dataSinceDate:this.dataSinceDate,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.streamInits};return this.streamInits=[],this.dataSinceDate=i,s}},ErrorKinds:rt,EventFactoryBase:class{constructor(t){this.withReasons=t}evalEvent(t){return new ft(this.withReasons,t.context,t.flagKey,t.value,t.defaultVal,t.version,t.variation??void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.withReasons||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new ft(this.withReasons,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new pt(t,1)}customEvent(t,e,n,i,s=1){return new gt(e,t,n??void 0,i??void 0,s)}},EventProcessor:class{constructor(t,n,i,s,r,a=!0){this.config=t,this.contextDeduplicator=s,this.diagnosticsManager=r,this.summarizer=new ht,this.queue=[],this.lastKnownPastTime=0,this.droppedEvents=0,this.deduplicatedUsers=0,this.exceededCapacity=!1,this.eventsInLastBatch=0,this.shutdown=!1,this.flushUsersTimer=null,this.capacity=t.eventsCapacity,this.logger=n.basicConfiguration.logger,this.eventSender=new ot(n,i),this.contextFilter=new w(t.allAttributesPrivate,t.privateAttributes.map((t=>new e(t)))),a&&this.start()}start(){if(void 0!==this.contextDeduplicator?.flushInterval&&(this.flushUsersTimer=setInterval((()=>{this.contextDeduplicator?.flush()}),1e3*this.contextDeduplicator.flushInterval)),this.flushTimer=setInterval((async()=>{try{await this.flush()}catch(t){this.logger?.debug(`Flush failed: ${t}`)}}),1e3*this.config.flushInterval),this.diagnosticsManager){const t=this.diagnosticsManager.createInitEvent();this.postDiagnosticEvent(t),this.diagnosticsTimer=setInterval((()=>{const t=this.diagnosticsManager.createStatsEventAndReset(this.droppedEvents,this.deduplicatedUsers,this.eventsInLastBatch);this.droppedEvents=0,this.deduplicatedUsers=0,this.postDiagnosticEvent(t)}),1e3*this.config.diagnosticRecordingInterval)}this.logger?.debug("Started EventProcessor.")}postDiagnosticEvent(t){this.eventSender.sendEventData(b.DiagnosticEvent,t)}close(){clearInterval(this.flushTimer),this.flushUsersTimer&&clearInterval(this.flushUsersTimer),this.diagnosticsTimer&&clearInterval(this.diagnosticsTimer)}async flush(){if(this.shutdown)throw new ut("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.");const t=this.queue;this.queue=[];const e=this.summarizer.getSummary();this.summarizer.clearSummary(),Object.keys(e.features).length&&t.push(e),t.length&&(this.eventsInLastBatch=t.length,this.logger?.debug("Flushing %d events",t.length),await this.tryPostingEvents(t))}sendEvent(t){if(this.shutdown)return;if("migration_op"===t.kind){if(dt(t.samplingRatio)){const e={...t};1===e.samplingRatio&&delete e.samplingRatio,this.enqueue(e)}return}this.summarizer.summarizeEvent(t);const e=ct(t),n=e&&t.trackEvents||!e,i=this.shouldDebugEvent(t),s=function(t){return"identify"===t.kind}(t),r=this.contextDeduplicator?.processContext(t.context);r||s||(this.deduplicatedUsers+=1);r&&!s&&this.enqueue(this.makeOutputEvent({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),n&&dt(t.samplingRatio)&&this.enqueue(this.makeOutputEvent(t,!1)),i&&dt(t.samplingRatio)&&this.enqueue(this.makeOutputEvent(t,!0))}makeOutputEvent(t,e){switch(t.kind){case"feature":{const n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.contextFilter.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return 1!==t.samplingRatio&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),void 0!==t.variation&&(n.variation=t.variation),void 0!==t.version&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{const e={kind:t.kind,creationDate:t.creationDate,context:this.contextFilter.filter(t.context)};return 1!==t.samplingRatio&&(e.samplingRatio=t.samplingRatio),e}case"custom":{const e={kind:"custom",creationDate:t.creationDate,key:t.key,contextKeys:t.context.kindsAndKeys};return 1!==t.samplingRatio&&(e.samplingRatio=t.samplingRatio),void 0!==t.data&&(e.data=t.data),void 0!==t.metricValue&&(e.metricValue=t.metricValue),void 0!==t.url&&(e.url=t.url),e}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}}enqueue(t){this.queue.length<this.capacity?(this.queue.push(t),this.exceededCapacity=!1):(this.exceededCapacity||(this.exceededCapacity=!0,this.logger?.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.droppedEvents+=1)}shouldDebugEvent(t){return ct(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.lastKnownPastTime&&t.debugEventsUntilDate>Date.now()}async tryPostingEvents(t){const e=await this.eventSender.sendEventData(b.AnalyticsEvents,t);if(e.status===S.FailedAndMustShutDown&&(this.shutdown=!0),e.serverTime&&(this.lastKnownPastTime=e.serverTime),e.error)throw e.error}},InputCustomEvent:gt,InputEvalEvent:ft,InputIdentifyEvent:pt,NullEventProcessor:class{close(){}async flush(){}sendEvent(){}},StreamingProcessor:class{constructor(t,e,n,i,s,r,a,o=1){this.listeners=i,this.diagnosticsManager=r,this.errorHandler=a,this.streamInitialReconnectDelay=o;const{basicConfiguration:c,platform:l}=t,{logger:h}=c,{requests:u}=l;this.headers={...s},this.logger=h,this.requests=u,this.streamUri=_(c.serviceEndpoints,e,n)}logConnectionStarted(){this.connectionAttemptStartTime=Date.now()}logConnectionResult(t){this.connectionAttemptStartTime&&this.diagnosticsManager&&this.diagnosticsManager.recordStreamInit(this.connectionAttemptStartTime,!t,Date.now()-this.connectionAttemptStartTime),this.connectionAttemptStartTime=void 0}retryAndHandleError(t){return nt(t)?(this.logger?.warn(et(t,"streaming request","will retry")),this.logConnectionResult(!1),this.logConnectionStarted(),!0):(this.logConnectionResult(!1),this.errorHandler?.(new D(k.ErrorResponse,t.message,t.status)),this.logger?.error(et(t,"streaming request")),!1)}start(){this.logConnectionStarted();const t=this.requests.createEventSource(this.streamUri,{headers:this.headers,errorFilter:t=>this.retryAndHandleError(t),initialRetryDelayMillis:1e3*this.streamInitialReconnectDelay,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this.eventSource=t,t.onclose=()=>{this.logger?.info("Closed LaunchDarkly stream connection")},t.onerror=()=>{},t.onopen=()=>{this.logger?.info("Opened LaunchDarkly stream connection")},t.onretrying=t=>{this.logger?.info(`Will retry stream connection in ${t.delayMillis} milliseconds`)},this.listeners.forEach((({deserializeData:e,processJson:n},i)=>{t.addEventListener(i,(t=>{if(this.logger?.debug(`Received ${i} event`),t?.data){this.logConnectionResult(!0);const{data:s}=t,r=e(s);if(!r)return void((t,e,n,i)=>{n?.error(`Stream received invalid data in "${t}" message`),n?.debug(`Invalid JSON follows: ${e}`),i?.(new D(k.InvalidData,"Malformed JSON data in event stream"))})(i,s,this.logger,this.errorHandler);n(r)}else this.errorHandler?.(new D(k.Unknown,"Unexpected payload from event stream"))}))}))}stop(){this.eventSource?.close(),this.eventSource=void 0}close(){this.stop()}},isLegacyUser:h,isMultiKind:l,isSingleKind:c,shouldSample:dt});!function(t){t.Initializing="INITIALIZING",t.Valid="VALID",t.Interrupted="INTERRUPTED",t.SetOffline="SET_OFFLINE",t.Closed="CLOSED"}(mt||(mt={}));const yt={logger:o.Object,maxCachedContexts:o.numberWithMin(0),baseUri:o.String,streamUri:o.String,eventsUri:o.String,capacity:o.numberWithMin(1),diagnosticRecordingInterval:o.numberWithMin(2),flushInterval:o.numberWithMin(2),streamInitialReconnectDelay:o.numberWithMin(0),allAttributesPrivate:o.Boolean,debug:o.Boolean,diagnosticOptOut:o.Boolean,withReasons:o.Boolean,sendEvents:o.Boolean,pollInterval:o.numberWithMin(30),useReport:o.Boolean,privateAttributes:o.StringArray,applicationInfo:o.Object,wrapperName:o.String,wrapperVersion:o.String,payloadFilterKey:o.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:o.createTypeArray("Hook[]",{})},wt="https://clientsdk.launchdarkly.com",kt="https://clientstream.launchdarkly.com";class Et{constructor(t={},e={}){var n;this.logger=P(),this.baseUri=wt,this.eventsUri=q.DEFAULT_EVENTS,this.streamUri=kt,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=300,this.hooks=[],this.logger=(n=t.logger)instanceof $?n:P(n);this.validateTypesAndNames(t).forEach((t=>this.logger.warn(t))),this.serviceEndpoints=new q(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=t.useReport??!1,this.tags=new L({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=e.userAgentHeaderName??"user-agent",this.trackEventModifier=e.trackEventModifier??(t=>t)}validateTypesAndNames(t){const e=[];return Object.entries(t).forEach((([t,n])=>{const i=yt[t];if(i)if(i.is(n))"logger"===t||(this[t]=n??void 0);else{const r=i.getType();if("boolean"===r)e.push(N.wrongOptionTypeBoolean(t,typeof n)),this[t]=!!n;else if("boolean | undefined | null"===r)e.push(N.wrongOptionTypeBoolean(t,typeof n)),"boolean"!=typeof n&&null!=n&&(this[t]=!!n);else if(i instanceof s&&o.Number.is(n)){const{min:s}=i;e.push(N.optionBelowMinimum(t,n,s)),this[t]=s}else e.push(N.wrongOptionType(t,i.getType(),typeof n))}else e.push(N.unknownOption(t))})),e}}async function bt(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")}const St=async(t,{crypto:e,storage:n})=>{let i=await(n?.get(t));return i||(i=e.randomUUID(),await(n?.set(t,i))),i};function xt(t){return async e=>bt(t.createHash("sha256").update(e),"base64")}const Dt=async t=>t;async function Ct(t){return(await Promise.all(t.map((t=>t.transform(t.value))))).join("_")}async function Rt(t,e,n){return Ct([{value:e,transform:Dt},{value:n.canonicalKey,transform:xt(t)}])}const{isLegacyUser:It,isSingleKind:Mt,isMultiKind:Ot}=vt,Tt=async t=>{const{ld_device:e,os:n}=t.info.platformData(),i=X(e)??{},s=n?.name||i.os?.name,r=n?.version||i.os?.version,a=i.os?.family;if((s||r||a)&&(i.os={...s?{name:s}:{},...r?{version:r}:{},...a?{family:a}:{}}),Object.keys(i).filter((t=>"key"!==t&&"envAttributesVersion"!==t)).length){const e=await async function(t){return Ct([{value:"LaunchDarkly",transform:Dt},{value:"ContextKeys",transform:Dt},{value:t,transform:Dt}])}("ld_device");return i.key=await St(e,t),i.envAttributesVersion=i.envAttributesVersion||"1.0",i}},At=async(t,e,n)=>{if(It(t))return t;let i,s;if(Mt(t)&&"ld_application"!==t.kind||Ot(t)&&!t.ld_application?i=await(async({crypto:t,info:e},{applicationInfo:n})=>{const{ld_application:i}=e.platformData();let s=X(i)??{};const r=n?.id||s?.id;if(r){const e=n?.version||s?.version,i=n?.name||s?.name,a=n?.versionName||s?.versionName;return s={...s,id:r,...e?{version:e}:{},...i?{name:i}:{},...a?{versionName:a}:{}},s.key=await bt(t.createHash("sha256").update(r),"base64"),s.envAttributesVersion=s.envAttributesVersion||"1.0",s}})(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),Mt(t)&&"ld_device"!==t.kind||Ot(t)&&!t.ld_device?s=await Tt(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),i||s){return{...Mt(t)?(t=>{const{kind:e,...n}=t;return{kind:"multi",[e]:n}})(t):t,...i?{ld_application:i}:{},...s?{ld_device:s}:{}}}return t},{isLegacyUser:$t,isMultiKind:Pt,isSingleKind:Nt}=vt,Ut=async(t,e,n)=>{const{anonymous:i,key:s}=e;if(i&&!s){const i=await async function(t){return Ct([{value:"LaunchDarkly",transform:Dt},{value:"AnonymousKeys",transform:Dt},{value:t,transform:Dt}])}(t);e.key=await St(i,n)}},Ft=async(t,e)=>{const n=Z(t);return Nt(n)&&await(async(t,e)=>{await Ut(t.kind,t,e)})(n,e),Pt(n)&&await(async(t,e)=>{const{kind:n,...i}=t;return Promise.all(Object.entries(i).map((([t,n])=>Ut(t,n,e))))})(n,e),$t(n)&&await(async(t,e)=>{await Ut("user",t,e)})(n,e),n},Lt=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new vt.DiagnosticsManager(t,n,(t=>({customBaseURI:t.serviceEndpoints.polling!==wt,customStreamURI:t.serviceEndpoints.streaming!==kt,customEventsURI:t.serviceEndpoints.events!==q.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:Q(t.flushInterval),reconnectTimeMillis:Q(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Q(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}))(e))};function jt(t,e){return{value:e??null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}class Kt extends vt.EventFactoryBase{evalEventClient(t,e,n,i,s,r){const{trackEvents:a,debugEventsUntilDate:o,trackReason:c,flagVersion:l,version:h,variation:u}=i;return super.evalEvent({addExperimentData:c,context:s,debugEventsUntilDate:o,defaultVal:n,flagKey:t,reason:r,trackEvents:!!a,value:e,variation:u,version:l??h})}}class Ht{constructor(){this.container={index:new Array}}static fromJson(t){const e=new Ht;try{e.container=JSON.parse(t)}catch(t){}return e}toJson(){return JSON.stringify(this.container)}notice(t,e){const n=this.container.index.find((e=>e.id===t));void 0===n?this.container.index.push({id:t,timestamp:e}):n.timestamp=e}prune(t){const e=Math.max(t,0);return this.container.index.length>e?(this.container.index.sort(((t,e)=>t.timestamp-e.timestamp)),this.container.index.splice(0,this.container.index.length-e)):[]}}class qt{constructor(t,e,n,i,s,r,a=()=>Date.now()){this.platform=t,this.environmentNamespace=e,this.maxCachedContexts=n,this.flagStore=i,this.flagUpdater=s,this.logger=r,this.timeStamper=a,this.indexKeyPromise=async function(t){return Ct([{value:t,transform:Dt},{value:"ContextIndex",transform:Dt}])}(this.environmentNamespace)}async init(t,e){this.flagUpdater.init(t,e),await this.storeCache(t)}async upsert(t,e,n){return!!this.flagUpdater.upsert(t,e,n)&&(await this.storeCache(t),!0)}async loadCached(t){const e=await Rt(this.platform.crypto,this.environmentNamespace,t);let n=await(this.platform.storage?.get(e));if(null==n){if(n=await(this.platform.storage?.get(t.canonicalKey)),null==n)return!1;await(this.platform.storage?.set(e,n)),await(this.platform.storage?.clear(t.canonicalKey))}try{const e=JSON.parse(n),i=Object.entries(e).reduce(((t,[e,n])=>(t[e]={version:n.version,flag:n},t)),{});return this.flagUpdater.initCached(t,i),this.logger.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(t){return this.logger.warn(`Could not load cached flag evaluations from persistent storage: ${t.message}`),!1}}async loadIndex(){if(void 0!==this.contextIndex)return this.contextIndex;const t=await(this.platform.storage?.get(await this.indexKeyPromise));if(!t)return this.contextIndex=new Ht,this.contextIndex;try{this.contextIndex=Ht.fromJson(t),this.logger.debug("Loaded context index from persistent storage")}catch(t){this.logger.warn(`Could not load index from persistent storage: ${t.message}`),this.contextIndex=new Ht}return this.contextIndex}async storeCache(t){const e=await this.loadIndex(),n=await Rt(this.platform.crypto,this.environmentNamespace,t);e.notice(n,this.timeStamper());const i=e.prune(this.maxCachedContexts);await Promise.all(i.map((async t=>this.platform.storage?.clear(t.id)))),await(this.platform.storage?.set(await this.indexKeyPromise,e.toJson()));const s=this.flagStore.getAll(),r=Object.entries(s).reduce(((t,[e,n])=>(null!==n.flag&&void 0!==n.flag&&(t[e]=n.flag),t)),{}),a=JSON.stringify(r);await(this.platform.storage?.set(n,a))}}class Vt{constructor(){this.flags={}}init(t){this.flags=Object.entries(t).reduce(((t,[e,n])=>(t[e]=n,t)),{})}insertOrUpdate(t,e){this.flags[t]=e}get(t){if(Object.prototype.hasOwnProperty.call(this.flags,t))return this.flags[t]}getAll(){return this.flags}}function _t(t,e){const n=[];return Object.entries(t).forEach((([t,i])=>{const s=e[t];s&&tt(i,s)||n.push(t)})),Object.keys(e).forEach((e=>{t[e]||n.push(e)})),n}class Jt{constructor(t,e){this.changeCallbacks=new Array,this.flagStore=t,this.logger=e}init(t,e){this.activeContextKey=t.canonicalKey;const n=this.flagStore.getAll();this.flagStore.init(e);const i=_t(n,e);i.length>0&&this.changeCallbacks.forEach((e=>{try{e(t,i)}catch(t){}}))}initCached(t,e){this.activeContextKey!==t.canonicalKey&&this.init(t,e)}upsert(t,e,n){if(this.activeContextKey!==t.canonicalKey)return this.logger.warn("Received an update for an inactive context."),!1;const i=this.flagStore.get(e);return!(void 0!==i&&i.version>=n.version)&&(this.flagStore.insertOrUpdate(e,n),this.changeCallbacks.forEach((n=>{try{n(t,[e])}catch(t){}})),!0)}on(t){this.changeCallbacks.push(t)}off(t){const e=this.changeCallbacks.indexOf(t);e>-1&&this.changeCallbacks.splice(e,1)}}class Bt{constructor(t,e,n,i,s=()=>Date.now()){this.timeStamper=s,this.flagStore=new Vt,this.flagUpdater=new Jt(this.flagStore,i),this.flagPersistencePromise=this.initPersistence(t,e,n,i,s)}async initPersistence(t,e,n,i,s=()=>Date.now()){const r=await async function(t,e){return Ct([{value:"LaunchDarkly",transform:Dt},{value:e,transform:xt(t)}])}(t.crypto,e);return new qt(t,r,n,this.flagStore,this.flagUpdater,i,s)}get(t){return this.flagStore.get(t)}getAll(){return this.flagStore.getAll()}setBootstrap(t,e){this.flagUpdater.init(t,e)}async init(t,e){return(await this.flagPersistencePromise).init(t,e)}async upsert(t,e,n){return(await this.flagPersistencePromise).upsert(t,e,n)}async loadCached(t){return(await this.flagPersistencePromise).loadCached(t)}on(t){this.flagUpdater.on(t)}off(t){this.flagUpdater.off(t)}}const zt="unknown hook",Wt="beforeEvaluation",Gt="afterEvaluation";function Yt(t,e,n,i,s){try{return i()}catch(i){return t?.error(`An error was encountered in "${e}" of the "${n}" hook: ${i}`),s}}function Zt(t,e){try{return e.getMetadata().name||zt}catch{return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),zt}}class Qt{constructor(t,e){this.logger=t,this.hooks=[],this.hooks.push(...e)}withEvaluation(t,e,n,i){if(0===this.hooks.length)return i();const s=[...this.hooks],r={flagKey:t,context:e,defaultValue:n},a=function(t,e,n){return e.map((e=>Yt(t,Wt,Zt(t,e),(()=>e?.beforeEvaluation?.(n,{})??{}),{})))}(this.logger,s,r),o=i();return function(t,e,n,i,s){for(let r=e.length-1;r>=0;r-=1){const a=e[r],o=i[r];Yt(t,Gt,Zt(t,a),(()=>a?.afterEvaluation?.(n,o,s)??{}),{})}}(this.logger,s,r,a,o),o}identify(t,e){const n=[...this.hooks],i={context:t,timeout:e},s=function(t,e,n){return e.map((e=>Yt(t,Wt,Zt(t,e),(()=>e?.beforeIdentify?.(n,{})??{}),{})))}(this.logger,n,i);return t=>{!function(t,e,n,i,s){for(let r=e.length-1;r>=0;r-=1){const a=e[r],o=i[r];Yt(t,Gt,Zt(t,a),(()=>a?.afterIdentify?.(n,o,s)??{}),{})}}(this.logger,n,i,s,t)}}addHook(t){this.hooks.push(t)}}class Xt{constructor(t){this.logger=t,this.listeners=new Map}on(t,e){this.listeners.has(t)?this.listeners.get(t)?.push(e):this.listeners.set(t,[e])}off(t,e){const n=this.listeners.get(t);if(n)if(e){const i=n.filter((t=>t!==e));0===i.length?this.listeners.delete(t):this.listeners.set(t,i)}else this.listeners.delete(t)}invokeListener(t,e,...n){try{t(...n)}catch(t){this.logger?.error(`Encountered error invoking handler for "${e}", detail: "${t}"`)}}emit(t,...e){const n=this.listeners.get(t);n?.forEach((n=>this.invokeListener(n,t,...e)))}eventNames(){return[...this.listeners.keys()]}listenerCount(t){return this.listeners.get(t)?.length??0}}const{ClientMessages:te,ErrorKinds:ee}=vt;class ne{constructor(t,e,n,i,s,r){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.identifyTimeout=5,this.highTimeoutThreshold=15,this.eventFactoryDefault=new Kt(!1),this.eventFactoryWithReasons=new Kt(!0),this.eventSendingEnabled=!1,!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.config=new Et(i,r),this.logger=this.config.logger,this.baseHeaders=function(t,e,n,i=!0,s="user-agent"){const{userAgentBase:r,version:a,wrapperName:o,wrapperVersion:c}=e.sdkData(),l={[s]:`${r??"NodeJSClient"}/${a}`};return i&&(l.authorization=t),o&&(l["x-launchdarkly-wrapper"]=c?`${o}/${c}`:o),n?.value&&(l["x-launchdarkly-tags"]=n.value),l}(this.sdkKey,this.platform.info,this.config.tags,this.config.serviceEndpoints.includeAuthorizationHeader,this.config.userAgentHeaderName),this.flagManager=new Bt(this.platform,t,this.config.maxCachedContexts,this.config.logger),this.diagnosticsManager=Lt(t,this.config,n),this.eventProcessor=((t,e,n,i,s)=>{if(e.sendEvents)return new vt.EventProcessor({...e,eventsCapacity:e.capacity},new j(t,e,n),i,void 0,s,!1)})(t,this.config,n,this.baseHeaders,this.diagnosticsManager),this.emitter=new Xt,this.emitter.on("error",((t,e)=>{this.logger.error(`error: ${e}, context: ${JSON.stringify(t)}`)})),this.flagManager.on(((t,e)=>{const n=m.toLDContext(t);this.emitter.emit("change",n,e),e.forEach((t=>{this.emitter.emit(`change:${t}`,n)}))})),this.dataManager=s(this.flagManager,this.config,this.baseHeaders,this.emitter,this.diagnosticsManager),this.hookRunner=new Qt(this.logger,this.config.hooks)}allFlags(){return Object.entries(this.flagManager.getAll()).reduce(((t,[e,n])=>(null===n.flag||void 0===n.flag||n.flag.deleted||(t[e]=n.flag.value),t)),{})}async close(){await this.flush(),this.eventProcessor?.close(),this.updateProcessor?.close(),this.logger.debug("Closed event processor and data source.")}async flush(){try{await(this.eventProcessor?.flush()),this.logger.debug("Successfully flushed event processor.")}catch(t){return this.logger.error(`Error flushing event processor: ${t}.`),{error:t,result:!1}}return{result:!0}}getContext(){return this.uncheckedContext?Z(this.uncheckedContext):void 0}getInternalContext(){return this.checkedContext}createIdentifyPromise(t){let e,n;const i=new Promise(((t,i)=>{e=t,n=i})),s=(r=t,a="identify",new Promise(((t,e)=>{setTimeout((()=>{e(new G(`${a} timed out after ${r} seconds.`))}),1e3*r)})));var r,a;return{identifyPromise:Promise.race([s,i]).catch((t=>{throw t.message.includes("timed out")&&this.logger.error(`identify error: ${t}`),t})),identifyResolve:e,identifyReject:n}}async identify(t,e){e?.timeout&&(this.identifyTimeout=e.timeout),this.identifyTimeout>this.highTimeoutThreshold&&this.logger.warn(`The identify function was called with a timeout greater than ${this.highTimeoutThreshold} seconds. We recommend a timeout of less than ${this.highTimeoutThreshold} seconds.`);let n=await Ft(t,this.platform);this.autoEnvAttributes===E.Enabled&&(n=await At(n,this.platform,this.config));const i=m.fromLDContext(n);if(!i.valid){const t=new Error("Context was unspecified or had no key");return this.emitter.emit("error",n,t),Promise.reject(t)}this.uncheckedContext=n,this.checkedContext=i,this.eventProcessor?.sendEvent(this.eventFactoryDefault.identifyEvent(this.checkedContext));const{identifyPromise:s,identifyResolve:r,identifyReject:a}=this.createIdentifyPromise(this.identifyTimeout);this.logger.debug(`Identifying ${JSON.stringify(this.checkedContext)}`);const o=this.hookRunner.identify(n,e?.timeout);return await this.dataManager.identify(r,a,i,e),s.then((t=>(o({status:"completed"}),t)),(t=>{throw o({status:"error"}),t}))}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){this.checkedContext&&this.checkedContext.valid?(void 0===n||o.Number.is(n)||this.logger?.warn(te.invalidMetricValue(typeof n)),this.eventProcessor?.sendEvent(this.config.trackEventModifier(this.eventFactoryDefault.customEvent(t,this.checkedContext,e,n)))):this.logger.warn(te.missingContextKeyNoEvent)}variationInternal(t,e,n,i){if(!this.uncheckedContext)return this.logger.debug(te.missingContextKeyNoEvent),jt(ee.UserNotSpecified,e);const s=m.fromLDContext(this.uncheckedContext),r=this.flagManager.get(t);if(void 0===r||r.flag.deleted){const n=e??null,i=new W(`Unknown feature flag "${t}"; returning default value ${n}.`);return this.emitter.emit("error",this.uncheckedContext,i),this.eventProcessor?.sendEvent(this.eventFactoryDefault.unknownFlagEvent(t,n,s)),jt(ee.FlagNotFound,e)}const{reason:a,value:o,variation:c}=r.flag;if(i){const[c,l]=i(o);if(!c){this.eventProcessor?.sendEvent(n.evalEventClient(t,e,e,r.flag,s,a));const i=new W(`Wrong type "${l}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.uncheckedContext,i),jt(ee.WrongType,e)}}const l=function(t,e,n){return{value:t,variationIndex:e??null,reason:n??null}}(o,c,a);return null==o&&(this.logger.debug("Result value is null. Providing default value."),l.value=e),this.eventProcessor?.sendEvent(n.evalEventClient(t,o,e,r.flag,s,a)),l}variation(t,e){const{value:n}=this.hookRunner.withEvaluation(t,this.uncheckedContext,e,(()=>this.variationInternal(t,e,this.eventFactoryDefault)));return n}variationDetail(t,e){return this.hookRunner.withEvaluation(t,this.uncheckedContext,e,(()=>this.variationInternal(t,e,this.eventFactoryWithReasons)))}typedEval(t,e,n,i){return this.hookRunner.withEvaluation(t,this.uncheckedContext,e,(()=>this.variationInternal(t,e,n,i)))}boolVariation(t,e){return this.typedEval(t,e,this.eventFactoryDefault,(t=>[o.Boolean.is(t),o.Boolean.getType()])).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.typedEval(t,e,this.eventFactoryDefault,(t=>[o.Number.is(t),o.Number.getType()])).value}stringVariation(t,e){return this.typedEval(t,e,this.eventFactoryDefault,(t=>[o.String.is(t),o.String.getType()])).value}boolVariationDetail(t,e){return this.typedEval(t,e,this.eventFactoryWithReasons,(t=>[o.Boolean.is(t),o.Boolean.getType()]))}numberVariationDetail(t,e){return this.typedEval(t,e,this.eventFactoryWithReasons,(t=>[o.Number.is(t),o.Number.getType()]))}stringVariationDetail(t,e){return this.typedEval(t,e,this.eventFactoryWithReasons,(t=>[o.String.is(t),o.String.getType()]))}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.hookRunner.addHook(t)}setEventSendingEnabled(t,e){this.eventSendingEnabled!==t&&(this.eventSendingEnabled=t,t?(this.logger.debug("Starting event processor"),this.eventProcessor?.start()):e?(this.logger?.debug("Flushing event processor before disabling."),this.flush().then((()=>{this.eventSendingEnabled||(this.logger?.debug("Stopping event processor."),this.eventProcessor?.close())}))):(this.logger?.debug("Stopping event processor."),this.eventProcessor?.close()))}sendEvent(t){this.eventProcessor?.sendEvent(t)}}class ie extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}}class se{constructor(t,e,n,i,s){this.requests=t,this.uri=e,this.headers=n,this.method=i,this.body=s}async requestPayload(){let t;try{const e=await this.requests.fetch(this.uri,{method:this.method,headers:this.headers,body:this.body});if(function(t){return t>=200&&t<=299}(e.status))return await e.text();t=e.status}catch(t){throw new ie(t?.message)}throw new ie(`Unexpected status code: ${t}`,t)}}class re{constructor(t,e,n){this.flagManager=t,this.statusManager=e,this.logger=n}async handlePut(t,e){this.logger.debug(`Got PUT: ${Object.keys(e)}`);const n=Object.entries(e).reduce(((t,[e,n])=>(t[e]={version:n.version,flag:n},t)),{});await this.flagManager.init(t,n),this.statusManager.requestStateUpdate(mt.Valid)}async handlePatch(t,e){this.logger.debug(`Got PATCH ${JSON.stringify(e,null,2)}`),this.flagManager.upsert(t,e.key,{version:e.version,flag:e})}async handleDelete(t,e){this.logger.debug(`Got DELETE ${JSON.stringify(e,null,2)}`),this.flagManager.upsert(t,e.key,{version:e.version,flag:{...e,deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1}})}handleStreamingError(t){this.statusManager.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.statusManager.reportError(t.kind,t.message,t.status,t.recoverable)}}class ae{constructor(t,e=()=>Date.now()){this.emitter=t,this.state=mt.Closed,this.stateSinceMillis=e(),this.timeStamper=e}get status(){return{state:this.state,stateSince:this.stateSinceMillis,lastError:this.errorInfo}}updateState(t,e=!1){const n=t===mt.Interrupted&&this.state===mt.Initializing?mt.Initializing:t,i=this.state!==n;i&&(this.state=n,this.stateSinceMillis=this.timeStamper()),(i||e)&&this.emitter.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.updateState(t)}reportError(t,e,n,i=!1){const s={kind:t,message:e,statusCode:n,time:this.timeStamper()};this.errorInfo=s,this.updateState(i?mt.Interrupted:mt.Closed,!0)}}class oe{constructor(t,e,n,i,s,r,a){this.plainContextString=t,this.dataSourceConfig=e,this.dataHandler=s,this.errorHandler=r,this.logger=a,this.stopped=!1;const o=e.useReport?e.paths.pathReport(i,t):e.paths.pathGet(i,t),c=[...e.queryParameters??[]];this.dataSourceConfig.withReasons&&c.push({key:"withReasons",value:"true"});const l=J(e.serviceEndpoints,o,c);this.pollInterval=e.pollInterval;let h="GET";const u={...e.baseHeaders};let d;e.useReport&&(h="REPORT",u["content-type"]="application/json",d=t),this.requestor=new se(n,l,u,h,d)}async poll(){if(this.stopped)return;const t=t=>{this.logger?.error("Polling received invalid data"),this.logger?.debug(`Invalid JSON follows: ${t}`),this.errorHandler?.(new x(k.InvalidData,"Malformed JSON data in polling response"))};this.logger?.debug("Polling LaunchDarkly for feature flag updates");const e=Date.now();try{const e=await this.requestor.requestPayload();try{const t=JSON.parse(e);try{this.dataHandler?.(t)}catch(t){this.logger?.error(`Exception from data handler: ${t}`)}}catch{t(e)}}catch(t){const e=t;if(void 0!==e.status&&!Y(e.status))return this.logger?.error(et(t,"polling request")),void this.errorHandler?.(new x(k.ErrorResponse,e.message,e.status));this.logger?.error(et(t,"polling request","will retry"))}const n=Date.now()-e,i=Math.max(1e3*this.pollInterval-n,0);this.logger?.debug("Elapsed: %d ms, sleeping for %d ms",n,i),this.timeoutHandle=setTimeout((()=>{this.poll()}),i)}start(){this.poll()}stop(){this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=void 0),this.stopped=!0}close(){this.stop()}}class ce{constructor(t,e,n,i,s,r,a,o){this.plainContextString=t,this.dataSourceConfig=e,this.listeners=n,this.requests=i,this.diagnosticsManager=r,this.errorHandler=a,this.logger=o,e.useReport&&!i.getEventSourceCapabilities().customMethod&&o?.error("Configuration option useReport is true, but platform's EventSource does not support custom HTTP methods. Streaming may not work.");const c=e.useReport?e.paths.pathReport(s,t):e.paths.pathGet(s,t),l=[...e.queryParameters??[]];this.dataSourceConfig.withReasons&&l.push({key:"withReasons",value:"true"}),this.requests=i,this.headers={...e.baseHeaders},this.logger=o,this.streamUri=_(e.serviceEndpoints,c,l)}logConnectionStarted(){this.connectionAttemptStartTime=Date.now()}logConnectionResult(t){this.connectionAttemptStartTime&&this.diagnosticsManager&&this.diagnosticsManager.recordStreamInit(this.connectionAttemptStartTime,!t,Date.now()-this.connectionAttemptStartTime),this.connectionAttemptStartTime=void 0}retryAndHandleError(t){return nt(t)?(this.logger?.warn(et(t,"streaming request","will retry")),this.logConnectionResult(!1),this.logConnectionStarted(),!0):(this.logConnectionResult(!1),this.errorHandler?.(new D(k.ErrorResponse,t.message,t.status,!1)),this.logger?.error(et(t,"streaming request")),!1)}start(){let t;this.logConnectionStarted(),this.dataSourceConfig.useReport?(this.headers["content-type"]="application/json",t={method:"REPORT",body:this.plainContextString}):t={};const e=this.requests.createEventSource(this.streamUri,{headers:this.headers,...t,errorFilter:t=>this.retryAndHandleError(t),initialRetryDelayMillis:this.dataSourceConfig.initialRetryDelayMillis,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this.eventSource=e,e.onclose=()=>{this.logger?.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{this.logger?.info("Opened LaunchDarkly stream connection")},e.onretrying=t=>{this.logger?.info(`Will retry stream connection in ${t.delayMillis} milliseconds`)},this.listeners.forEach((({deserializeData:t,processJson:n},i)=>{e.addEventListener(i,(e=>{if(this.logger?.debug(`Received ${i} event`),e?.data){this.logConnectionResult(!0);const{data:s}=e,r=t(s);if(!r)return void((t,e,n,i)=>{n?.error(`Stream received invalid data in "${t}" message`),n?.debug(`Invalid JSON follows: ${e}`),i?.(new D(k.InvalidData,"Malformed JSON data in event stream"))})(i,s,this.logger,this.errorHandler);n(r)}else this.errorHandler?.(new D(k.InvalidData,"Unexpected payload from event stream"))}))}))}stop(){this.eventSource?.close(),this.eventSource=void 0}close(){this.stop()}}class le{constructor(t,e,n,i,s,r,a,o,c){this.platform=t,this.flagManager=e,this.credential=n,this.config=i,this.getPollingPaths=s,this.getStreamingPaths=r,this.baseHeaders=a,this.emitter=o,this.diagnosticsManager=c,this.logger=i.logger,this.dataSourceStatusManager=new ae(o),this.dataSourceEventHandler=new re(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.connectionParams=t}createPollingProcessor(t,e,n,i){const s=new oe(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getPollingPaths(),baseHeaders:this.baseHeaders,pollInterval:this.config.pollInterval,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:this.connectionParams?.queryParameters},this.platform.requests,this.platform.encoding,(async t=>{await this.dataSourceEventHandler.handlePut(e,t),n?.()}),(e=>{this.emitter.emit("error",t,e),this.dataSourceEventHandler.handlePollingError(e),i?.(e)}));this.updateProcessor=this.decorateProcessorWithStatusReporting(s,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,i){const s=new ce(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:1e3*this.config.streamInitialReconnectDelay,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:this.connectionParams?.queryParameters},this.createStreamListeners(e,n),this.platform.requests,this.platform.encoding,this.diagnosticsManager,(e=>{this.emitter.emit("error",t,e),this.dataSourceEventHandler.handleStreamingError(e),i?.(e)}));this.updateProcessor=this.decorateProcessorWithStatusReporting(s,this.dataSourceStatusManager)}createStreamListeners(t,e){const n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async n=>{await this.dataSourceEventHandler.handlePut(t,n),e?.()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async e=>{this.dataSourceEventHandler.handlePatch(t,e)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async e=>{this.dataSourceEventHandler.handleDelete(t,e)}}),n}decorateProcessorWithStatusReporting(t,e){return{start:()=>{e.requestStateUpdate(mt.Initializing),t.start()},stop:()=>{t.stop(),e.requestStateUpdate(mt.Closed)},close:()=>{t.close(),e.requestStateUpdate(mt.Closed)}}}}function he(){return void 0!==typeof document}function ue(){return void 0!==typeof window}function de(t,e,n){return he()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function ge(t,e,n){return he()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function fe(){return ue()?window.location.href:""}class pe extends le{constructor(t,e,n,i,s,r,a,o,c,l){super(t,e,n,i,r,a,o,c,l),this.browserConfig=s,this.forcedStreaming=void 0,this.automaticStreamingState=!1,this.forcedStreaming=s.streaming}debugLog(t,...e){this.logger.debug(`[BrowserDataManager] ${t}`,...e)}async identify(t,e,n,i){this.context=n;const s=i;if((null==s?void 0:s.hash)?this.setConnectionParams({queryParameters:[{key:"h",value:s.hash}]}):this.setConnectionParams(),this.secureModeHash=null==s?void 0:s.hash,null==s?void 0:s.bootstrap)this.finishIdentifyFromBootstrap(n,s.bootstrap,t);else{await this.flagManager.loadCached(n)&&this.debugLog("Identify - Flags loaded from cache. Continuing to initialize via a poll.");const i=JSON.stringify(m.toLDContext(n)),s=this.getRequestor(i);await this.finishIdentifyFromPoll(s,n,t,e)}this.updateStreamingState()}async finishIdentifyFromPoll(t,e,n,i){var s,r;try{this.dataSourceStatusManager.requestStateUpdate(mt.Initializing);const i=await t.requestPayload();try{const t=this.createStreamListeners(e,n).get("put");t.processJson(t.deserializeData(i))}catch(t){this.dataSourceStatusManager.reportError(k.InvalidData,null!==(s=t.message)&&void 0!==s?s:"Could not parse poll response")}}catch(t){this.dataSourceStatusManager.reportError(k.NetworkError,null!==(r=t.message)&&void 0!==r?r:"unexpected network error",t.status),i(t)}}finishIdentifyFromBootstrap(t,e,n){this.flagManager.setBootstrap(t,function(t,e){const n=Object.keys(e),i="$flagsState",s="$valid",r=e[i];!r&&n.length&&t.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),!1===e[s]&&t.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");const a={};return n.forEach((t=>{if(t!==i&&t!==s){let n;n=r&&r[t]?Object.assign({value:e[t]},r[t]):{value:e[t],version:0},a[t]={version:n.version,flag:n}}})),a}(this.logger,e)),this.debugLog("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.forcedStreaming=t,this.updateStreamingState()}setAutomaticStreamingState(t){this.automaticStreamingState=t,this.updateStreamingState()}updateStreamingState(){const t=this.forcedStreaming||this.automaticStreamingState&&void 0===this.forcedStreaming;this.debugLog(`Updating streaming state. forced(${this.forcedStreaming}) automatic(${this.automaticStreamingState})`),t?this.startDataSource():this.stopDataSource()}stopDataSource(){var t;this.updateProcessor&&this.debugLog("Stopping update processor."),null===(t=this.updateProcessor)||void 0===t||t.close(),this.updateProcessor=void 0}startDataSource(){this.updateProcessor?this.debugLog("Update processor already active. Not changing state."):this.context?(this.debugLog("Starting update processor."),this.setupConnection(this.context)):this.debugLog("Context not set, not starting update processor.")}setupConnection(t,e,n){var i;const s=m.toLDContext(t);null===(i=this.updateProcessor)||void 0===i||i.close(),this.createStreamingProcessor(s,t,e,n),this.updateProcessor.start()}getRequestor(t){const e=this.getPollingPaths(),n=this.config.useReport?e.pathReport(this.platform.encoding,t):e.pathGet(this.platform.encoding,t),i=[];this.config.withReasons&&i.push({key:"withReasons",value:"true"}),this.secureModeHash&&i.push({key:"h",value:this.secureModeHash});const s=Object.assign({},this.baseHeaders);let r,a="GET";this.config.useReport&&(a="REPORT",s["content-type"]="application/json",r=t);const o=J(this.config.serviceEndpoints,n,i);return new se(this.platform.requests,o,s,a,r)}}function me(t){const e=de("visibilitychange",(()=>{"hidden"===(he()?document.visibilityState:"visibile")&&t()})),n=ge("pagehide",t);return()=>{e(),n()}}function ve(t){if("string"!=typeof t)throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function ye(t,e){const n=[];return e.forEach((e=>{let i=t.target;const{selector:s}=e,r=function(t){if(he())return document.querySelectorAll(t)}(s);for(;i&&(null==r?void 0:r.length);){for(let t=0;t<r.length;t+=1)if(i===r[t]){n.push(e);break}i=i.parentNode}})),n}class we{constructor(t,e){const n=t.filter((t=>{var e;return null===(e=t.urls)||void 0===e?void 0:e.some((t=>function(t,e,n,i){const s=("substring"!==t.kind&&"regex"!==t.kind||!i.includes("/")?e.replace(i,""):e).replace(n,"");switch(t.kind){case"exact":return new RegExp(`^${ve(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${ve(t.url)}/?$`).test(s);case"substring":return new RegExp(`.*${ve(t.substring)}.*$`).test(s);case"regex":return new RegExp(t.pattern).test(s);default:return!1}}(t,fe(),ue()?window.location.search:"",ue()?window.location.hash:"")))})),i=n.filter((t=>"pageview"===t.kind)),s=n.filter((t=>"click"===t.kind));if(i.forEach((t=>e(t))),s.length){const t=t=>{ye(t,s).forEach((t=>{e(t)}))};this.cleanup=de("click",t)}}close(){var t;null===(t=this.cleanup)||void 0===t||t.call(this)}}class ke{constructor(t){this.previousLocation=fe();const e=()=>{const e=fe();e!==this.previousLocation&&(this.previousLocation=e,t())};this.watcherHandle=setInterval(e,300);const n=ge("popstate",e);this.cleanupListeners=()=>{n()}}close(){var t;this.watcherHandle&&clearInterval(this.watcherHandle),null===(t=this.cleanupListeners)||void 0===t||t.call(this)}}class Ee{constructor(t,e,n,i,s,r=t=>new ke(t)){this.requests=e,this.reportError=i,this.reportGoal=s,this.goals=[],this.isTracking=!1,this.url=`${n}/sdk/goals/${t}`,this.watcher=r((()=>{this.createTracker()}))}async initialize(){await this.fetchGoals(),this.createTracker()}startTracking(){this.isTracking=!0,this.createTracker()}createTracker(){var t;this.isTracking&&(null===(t=this.tracker)||void 0===t||t.close(),this.goals&&this.goals.length&&(this.tracker=new we(this.goals,(t=>{this.reportGoal(fe(),t)}))))}async fetchGoals(){try{const t=await this.requests.fetch(this.url);this.goals=await t.json()}catch(t){this.reportError(new z(`Encountered error fetching goals: ${t}`))}}close(){var t,e;null===(t=this.watcher)||void 0===t||t.close(),null===(e=this.tracker)||void 0===e||e.close()}}const be={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0},Se={fetchGoals:o.Boolean,eventUrlTransformer:o.Function,streaming:o.Boolean};class xe{constructor(t,e){switch(this.webcrypto=t,this.data=[],e){case"sha1":this.algorithm="SHA-1";break;case"sha256":this.algorithm="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){const e=this.data.join(""),n=(new TextEncoder).encode(e),i=await this.webcrypto.subtle.digest(this.algorithm,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(i)));case"hex":return[...new Uint8Array(i)].map((t=>t.toString(16).padStart(2,"0"))).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.data.push(t),this}}const De={start:0,end:3},Ce={start:4,end:5},Re={start:6,end:7},Ie={start:8,end:8},Me={start:9,end:9},Oe={start:10,end:15};function Te(t,e){let n="";for(let i=e.start;i<=e.end;i+=1)n+=t[i].toString(16).padStart(2,"0");return n}function Ae(){const t=function(){if(crypto&&crypto.getRandomValues){const t=new Uint8Array(16);return crypto.getRandomValues(t),[...t.values()]}const t=[];for(let e=0;e<16;e+=1)t.push(Math.floor(256*Math.random()));return t}();return function(t){return t[Ie.start]=191&t[Ie.start]|128,t[Re.start]=15&t[Re.start]|64,`${Te(t,De)}-${Te(t,Ce)}-${Te(t,Re)}-${Te(t,Ie)}${Te(t,Me)}-${Te(t,Oe)}`}(t)}class $e{createHash(t){return new xe(function(){if(void 0!==typeof crypto)return crypto;throw Error("Access to a web crypto API is required")}(),t)}randomUUID(){return void 0!==typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():Ae()}}class Pe{btoa(t){return function(t){const e=Array.from(t,(t=>String.fromCodePoint(t))).join("");return btoa(e)}((new TextEncoder).encode(t))}}class Ne{platformData(){return{name:"JS"}}sdkData(){return{name:"@launchdarkly/js-client-sdk",version:"0.0.0",userAgentBase:"JSClient"}}}class Ue{constructor(t,e,n=Math.random){this.retryResetIntervalMillis=e,this.random=n,this.retryCount=0,this.initialRetryDelayMillis=Math.max(1,t),this.maxExponent=Math.ceil(Math.log2(3e4/this.initialRetryDelayMillis))}backoff(){const t=Math.min(this.retryCount,this.maxExponent),e=this.initialRetryDelayMillis*2**t;return Math.min(e,3e4)}jitter(t){return t-Math.trunc(.5*this.random()*t)}success(t=Date.now()){this.activeSince=t}fail(t=Date.now()){void 0!==this.activeSince&&t-this.activeSince>this.retryResetIntervalMillis&&(this.retryCount=0),this.activeSince=void 0;const e=this.jitter(this.backoff());return this.retryCount+=1,e}}class Fe{constructor(t,e){this.url=t,this.listeners={},this.backoff=new Ue(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.errorFilter=e.errorFilter,this.openConnection()}openConnection(){this.es=new EventSource(this.url),this.es.onopen=()=>{var t;this.backoff.success(),null===(t=this.onopen)||void 0===t||t.call(this)},this.es.onerror=t=>{var e;this.handleError(t),null===(e=this.onerror)||void 0===e||e.call(this,t)},Object.entries(this.listeners).forEach((([t,e])=>{e.forEach((e=>{var n;null===(n=this.es)||void 0===n||n.addEventListener(t,e)}))}))}addEventListener(t,e){var n,i,s;null!==(n=(s=this.listeners)[t])&&void 0!==n||(s[t]=[]),this.listeners[t].push(e),null===(i=this.es)||void 0===i||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0,null===(t=this.es)||void 0===t||t.close(),null===(e=this.onclose)||void 0===e||e.call(this)}tryConnect(t){var e;null===(e=this.onretrying)||void 0===e||e.call(this,{delayMillis:t}),this.reconnectTimeoutHandle=setTimeout((()=>{this.openConnection()}),t)}handleError(t){this.close(),t.status&&"number"==typeof t.status&&!this.errorFilter(t)||this.tryConnect(this.backoff.fail())}}class Le{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new Fe(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}}class je{constructor(t){this.logger=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){null===(e=this.logger)||void 0===e||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{const e=localStorage.getItem(t);return null!=e?e:null}catch(n){return null===(e=this.logger)||void 0===e||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(e){null===(n=this.logger)||void 0===n||n.error(`Error setting key in localStorage: ${t}, reason: ${e}`)}}}class Ke{constructor(t){this.encoding=new Pe,this.info=new Ne,this.crypto=new $e,this.requests=new Le,"undefined"!=typeof localStorage&&(this.storage=new je(t))}}class He extends ne{constructor(t,e,n={},i){var s;const{logger:r,debug:a}=n,o=null!=r?r:P({debug:a?console.debug:()=>{},info:console.info,warn:console.warn,error:console.error}),c=null!==(s=n.baseUri)&&void 0!==s?s:"https://clientsdk.launchdarkly.com",l=null!=i?i:new Ke(o),h=function(t,e){const n=Object.assign({},be);return function(t){var e;null!==(e=t.flushInterval)&&void 0!==e||(t.flushInterval=2)}(n),Object.entries(Se).forEach((i=>{const[s,r]=i,a=t[s];void 0!==a&&(r.is(a)?n[s]=a:e.warn(N.wrongOptionType(s,r.getType(),typeof a)))})),n}(n,o),{eventUrlTransformer:u}=h;super(t,e,l,function(t){const e=Object.assign({},t);return Object.keys(be).forEach((t=>{delete e[t]})),e}(Object.assign(Object.assign({},n),{logger:o})),((e,n,i,s,r)=>new pe(l,e,t,n,h,(()=>({pathGet:(e,n)=>`/sdk/evalx/${t}/contexts/${it(n,e)}`,pathReport:(e,n)=>`/sdk/evalx/${t}/context`})),(()=>({pathGet:(e,n)=>`/eval/${t}/${it(n,e)}`,pathReport:(e,n)=>`/eval/${t}`})),i,s,r)),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:t=>new vt.InputCustomEvent(t.context,t.key,t.data,t.metricValue,t.samplingRatio,u(fe()))}),this.clientSideId=t,this.setEventSendingEnabled(!0,!1),h.fetchGoals&&(this.goalManager=new Ee(t,l.requests,c,(t=>{o.error(t.message)}),((t,e)=>{const n=this.getInternalContext();if(!n)return;const i=u(t);!function(t){return"click"===t.kind}(e)?this.sendEvent({kind:"pageview",url:i,samplingRatio:1,key:e.key,creationDate:Date.now(),context:n}):this.sendEvent({kind:"click",url:i,samplingRatio:1,key:e.key,creationDate:Date.now(),context:n,selector:e.selector})})),this.goalManager.initialize(),h.automaticBackgroundHandling&&me((()=>this.flush())))}async identify(t,e){var n;await super.identify(t,e),null===(n=this.goalManager)||void 0===n||n.startTracking()}setStreaming(t){this.dataManager.setForcedStreaming(t)}updateAutomaticStreamingState(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.updateAutomaticStreamingState()}off(t,e){super.off(t,e),this.updateAutomaticStreamingState()}}exports.initialize=function(t,e){return new He(t,E.Disabled,e)};
|
|
1
|
+
"use strict";function t(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}class i{constructor(i,s=!1){if(s){const t=i;this.t=[t],this.isValid=""!==t,this.redactionName=t.startsWith("/")?`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`:t}else{if(this.redactionName=i,""===i||"/"===i||i.match(/\/\/|(^\/.*~[^0|^1])|~$/))return this.isValid=!1,void(this.t=[]);!function(t){return!t.startsWith("/")}(i)?i.indexOf("/",1)<0?this.t=[t(i.slice(1))]:this.t=function(i){return(i.startsWith("/")?i.substring(1):i).split("/").map((i=>t(i)))}(i):this.t=[i],"_meta"===this.t[0]?this.isValid=!1:this.isValid=!0}}get(t){const{t:i,isValid:s}=this;if(!s)return;let e=t;for(let t=0;t<i.length;t+=1){const s=i[t];if(null==e||!Object.prototype.hasOwnProperty.call(e,s)||"object"!=typeof e||Array.isArray(e))return;e=e[s]}return e}getComponent(t){return this.t[t]}get depth(){return this.t.length}get isKind(){return 1===this.t.length&&"kind"===this.t[0]}compare(t){return this.depth===t.depth&&this.t.every(((i,s)=>i===t.getComponent(s)))}}i.InvalidReference=new i("");class s{constructor(t,i){this.h=t,this.typeOf=typeof i}is(t){return!Array.isArray(t)&&typeof t===this.typeOf}getType(){return this.h}}class e{constructor(t,i){this.h=t,this.typeOf=typeof i}is(t){return!!Array.isArray(t)&&(!(t.length>0)||t.every((t=>typeof t===this.typeOf)))}getType(){return this.h}}class n extends s{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}}class r extends s{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return"string"==typeof t&&!!t.match(this.expression)}}const o=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/;class a{static createTypeArray(t,i){return new e(t,i)}static numberWithMin(t){return new n(t)}static stringMatchingRegex(t){return new r(t)}}function h(t){return"kind"in t&&(a.String.is(t.kind)&&"multi"!==t.kind)}function c(t){return"kind"in t&&(a.String.is(t.kind)&&"multi"===t.kind)}function u(t){return!("kind"in t)||null===t.kind||void 0===t.kind}a.String=new s("string",""),a.Number=new s("number",0),a.ObjectOrFactory=new class{is(t){if(Array.isArray(t))return!1;const i=typeof t;return"function"===i||"object"===i}getType(){return"factory method or object"}},a.Object=new s("object",{}),a.StringArray=new e("string[]",""),a.Boolean=new s("boolean",!0),a.Function=new class{is(t){return"function"==typeof t}getType(){return"function"}},a.Date=new class{is(t){return"number"==typeof t||"string"==typeof t&&o.test(t)}getType(){return"date"}},a.Kind=new class extends r{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&"kind"!==t}},a.NullableBoolean=new class{is(t){return"boolean"==typeof t||null==t}getType(){return"boolean | undefined | null"}};const l="user";function d(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function f(t){return a.Kind.is(t)}function v(t){return a.String.is(t)&&""!==t}function p(t,s=!1){return t?t.map((t=>new i(t,s))):[]}class y{constructor(t,i,s){this.u=!1,this.l=!1,this.v=!1,this.p={},this.kind=i,this.valid=t,this.message=s}static m(t,i){return new y(!1,t,i)}static k(t,i){if(i&&t.isValid)return 1===t.depth&&"anonymous"===t.getComponent(0)?!!i?.anonymous:t.get(i)}$(t){return this.u?this.p[t]:this.kind===t?this.S:void 0}static D(t){const i=Object.keys(t).filter((t=>"kind"!==t)),s=i.every(f);if(!i.length)return y.m("multi","A multi-kind context must contain at least one kind");if(!s)return y.m("multi","Context contains invalid kinds");const e={};let n=!0;const r=i.reduce(((i,s)=>{const r=t[s];var o;return(o=r)&&a.Object.is(o)?(i[s]=r,e[s]=p(r._meta?.privateAttributes)):n=!1,i}),{});if(!n)return y.m("multi","Context contained contexts that were not objects");if(!Object.values(r).every((t=>v(t.key))))return y.m("multi","Context contained invalid keys");if(1===i.length){const t=i[0],s=new y(!0,t);return s.S={...r[t],kind:t},s._=e,s.l="user"===t,s}const o=new y(!0,t.kind);return o.p=r,o._=e,o.u=!0,o}static I(t){const{key:i,kind:s}=t,e=f(s),n=v(i);if(!e)return y.m(s??"unknown","The kind was not valid for the context");if(!n)return y.m(s,"The key for the context was not valid");const r=p(t._meta?.privateAttributes),o=new y(!0,s);return o.l="user"===s,o.S=t,o._={[s]:r},o}static N(t){if(!(void 0!==t.key&&null!==t.key))return y.m("user","The key for the context was not valid");const i=new y(!0,"user");return i.l=!0,i.v=!0,i.S=function(t){const i={...t.custom||[],kind:"user",key:String(t.key)};if(null!=t.anonymous){const s=!!t.anonymous;delete i.anonymous,i.anonymous=s}return null!==t.name&&void 0!==t.name&&(i.name=t.name),null!==t.ip&&void 0!==t.ip&&(i.ip=t.ip),null!==t.firstName&&void 0!==t.firstName&&(i.firstName=t.firstName),null!==t.lastName&&void 0!==t.lastName&&(i.lastName=t.lastName),null!==t.email&&void 0!==t.email&&(i.email=t.email),null!==t.avatar&&void 0!==t.avatar&&(i.avatar=t.avatar),null!==t.country&&void 0!==t.country&&(i.country=t.country),null!==t.privateAttributeNames&&void 0!==t.privateAttributeNames&&(i._meta={privateAttributes:t.privateAttributeNames}),i}(t),i._={user:p(t.privateAttributeNames,!0)},i}static fromLDContext(t){return t?h(t)?y.I(t):c(t)?y.D(t):u(t)?y.N(t):y.m("unknown","Context was not of a valid kind"):y.m("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;const i=t.getContexts();if(!t.u)return i[0][1];const s={kind:"multi"};return i.forEach((t=>{const i=t[0],e=t[1];s[i]=e})),s}valueForKind(t,i=l){return t.isKind?this.kinds:y.k(t,this.$(i))}key(t=l){return this.$(t)?.key}get isMultiKind(){return this.u}get canonicalKey(){return this.l?this.S.key:this.u?Object.keys(this.p).sort().map((t=>`${t}:${d(this.p[t].key)}`)).join(":"):`${this.kind}:${d(this.S.key)}`}get kinds(){return this.u?Object.keys(this.p):[this.kind]}get kindsAndKeys(){return this.u?Object.entries(this.p).reduce(((t,[i,s])=>(t[i]=s.key,t)),{}):{[this.kind]:this.S.key}}privateAttributes(t){return this._?.[t]||[]}getContexts(){return this.u?Object.entries(this.p):[[this.kind,this.S]]}get legacy(){return this.v}}y.UserKind=l;const g=["key","kind","_meta","anonymous"].map((t=>new i(t,!0))),w=["name","ip","firstName","lastName","email","avatar","country"];class m{constructor(t,i){this.R=t,this.C=i}filter(t,i=!1){const s=t.getContexts();if(1===s.length)return this.T(t,s[0][1],s[0][0],i);const e={kind:"multi"};return s.forEach((([s,n])=>{e[s]=this.T(t,n,s,i)})),e}A(t,s,e,n){return(n?Object.keys(s).map((t=>new i(t,!0))):[...this.C,...t.privateAttributes(e)]).filter((t=>!g.some((i=>i.compare(t)))))}T(t,i,s,e){const n=this.R||e&&!0===i.anonymous,{cloned:r,excluded:o}=function(t,i){const s=[],e={},n=[];for(s.push(...Object.keys(t).map((i=>({key:i,ptr:[i],source:t,parent:e,visited:[t]}))));s.length;){const t=s.pop(),e=i.find((i=>{return s=i,e=t.ptr,s.depth===e.length&&e.every(((t,i)=>t===s.getComponent(i)));var s,e}));if(e)n.push(e.redactionName);else{const i=t.source[t.key];null===i?t.parent[t.key]=i:Array.isArray(i)?t.parent[t.key]=[...i]:"object"==typeof i?t.visited.includes(i)||(t.parent[t.key]={},s.push(...Object.keys(i).map((s=>({key:s,ptr:[...t.ptr,s],source:i,parent:t.parent[t.key],visited:[...t.visited,i]}))))):t.parent[t.key]=i}}return{cloned:e,excluded:n.sort()}}(i,this.A(t,i,s,n));return t.legacy&&w.forEach((t=>{t in r&&(r[t]=String(r[t]))})),o.length&&(r._meta||(r._meta={}),r._meta.redactedAttributes=o),r._meta&&(delete r._meta.privateAttributes,0===Object.keys(r._meta).length&&delete r._meta),r}}var b,k,$,E;!function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"}(b||(b={}));class S extends Error{constructor(t,i,s,e=!0){super(i),this.kind=t,this.status=s,this.name="LaunchDarklyPollingError",this.recoverable=e}}class D extends Error{constructor(t,i,s,e=!0){super(i),this.kind=t,this.code=s,this.name="LaunchDarklyStreamingError",this.recoverable=e}}function O(t){if("string"==typeof t)return t;if(void 0===t)return"undefined";if(null===t)return"null";if(Object.prototype.hasOwnProperty.call(t,"toString"))try{return t.toString()}catch{}if("bigint"==typeof t)return`${t}n`;try{return JSON.stringify(t)}catch(t){return t instanceof TypeError&&t.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}!function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"}(k||(k={})),function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"}($||($={})),function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"}(E||(E={}));const x={s:t=>O(t),d:t=>function(t){return"symbol"==typeof t?"NaN":"bigint"==typeof t?`${t}n`:String(Number(t))}(t),i:t=>function(t){return"symbol"==typeof t?"NaN":"bigint"==typeof t?`${t}n`:String(parseInt(t,10))}(t),f:t=>function(t){return"symbol"==typeof t?"NaN":String(parseFloat(t))}(t),j:t=>O(t),o:t=>O(t),O:t=>O(t),c:()=>""};function _(...t){const i=t.shift();if(a.String.is(i)){let s="",e=0;for(;e<i.length;){const n=i.charAt(e);if("%"===n){if(e+1<i.length){const n=i.charAt(e+1);if(n in x&&t.length){const i=t.shift();s+=x[n]?.(i)}else s+="%"===n?"%":`%${n}`;e+=2}}else s+=n,e+=1}return t.length&&(s.length&&(s+=" "),s+=t.map(O).join(" ")),s}return t.map(O).join(" ")}const I={debug:0,info:1,warn:2,error:3,none:4},N=["debug","info","warn","error","none"];class R{static get(){return new R({})}constructor(t){this.P=I[t.level??"info"]??I.info,this.M=t.name??"LaunchDarkly",this.L=t.destination,this.J=t.formatter}U(...t){try{return this.J?this.J?.(...t):_(...t)}catch{return _(...t)}}K(t){try{this.L(t)}catch{console.error(t)}}F(t,i){if(t>=this.P){const s=`${N[t]}: [${this.M}]`;try{this.L?this.K(`${s} ${this.U(...i)}`):console.error(...i)}catch{console.error(...i)}}}error(...t){this.F(I.error,t)}warn(...t){this.F(I.warn,t)}info(...t){this.F(I.info,t)}debug(...t){this.F(I.debug,t)}}const C={error:a.Function,warn:a.Function,info:a.Function,debug:a.Function};class j{constructor(t,i){Object.entries(C).forEach((([i,s])=>{if(!s.is(t[i]))throw new Error(`Provided logger instance must support logger.${i}(...) method`)})),this.V=t,this.q=i}F(t,i){try{this.V[t](...i)}catch{this.q[t](...i)}}error(...t){this.F("error",t)}warn(...t){this.F("warn",t)}info(...t){this.F("info",t)}debug(...t){this.F("debug",t)}}const T=t=>{const i=new R({level:"info",destination:console.error,formatter:_});return t?new j(t,i):i};class A{static deprecated(t,i){return`"${t}" is deprecated, please use "${i}"`}static optionBelowMinimum(t,i,s){return`Config option "${t}" had invalid value of ${i}, using minimum of ${s} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,i,s){return`Config option "${t}" should be of type ${i}, got ${s}, using default value`}static wrongOptionTypeBoolean(t,i){return`Config option "${t}" should be a boolean, got ${i}, 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`}}const P=a.stringMatchingRegex(/^(\w|\.|-)+$/),M=(t,i)=>P.is(t)?t.length>64?{valid:!1,message:A.tagValueTooLong(i)}:{valid:!0}:{valid:!1,message:A.invalidTagValue(i)};class L{constructor(t){const i={},s=t?.application,e=t?.logger;s&&Object.entries(s).forEach((([t,s])=>{if(null!=s){const{valid:n,message:r}=M(s,`application.${t}`);n?"versionName"===t?i["application-version-name"]=[s]:i[`application-${t}`]=[s]:e?.warn(r)}}));const n=Object.keys(i);n.length&&(this.value=n.sort().flatMap((t=>i[t].sort().map((i=>`${t}/${i}`)))).join(" "))}}class J{constructor(t,i,s){this.platform=s,this.basicConfiguration={tags:i.tags,logger:i.logger,offline:i.offline,serviceEndpoints:i.serviceEndpoints,sdkKey:t}}}function U(t){return t.replace(/\/+$/,"")}function K(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}class F{constructor(t,i,s=F.DEFAULT_EVENTS,e="/bulk",n="/diagnostic",r=!0,o){this.streaming=U(t),this.polling=U(i),this.events=U(s),this.analyticsEventPath=e,this.diagnosticEventPath=n,this.includeAuthorizationHeader=r,this.payloadFilterKey=o}}function V(t,i){if(0===i.length)return t;return`${t}?${i.map((({key:t,value:i})=>`${t}=${i}`)).join("&")}`}function q(t,i,s){const e=K(i),n=[...s];return t.payloadFilterKey&&n.push({key:"filter",value:t.payloadFilterKey}),V(`${t.streaming}/${e}`,n)}function G(t,i,s){const e=K(i);return V(`${t.events}/${e}`,s)}F.DEFAULT_EVENTS="https://events.launchdarkly.com";class B extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}}class z extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}}class H extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}}function W(t){return!(t>=400&&t<500)||(400===t||408===t||429===t)}function Y(t){return null==t?t:JSON.parse(JSON.stringify(t))}function Z(t){return Math.trunc(1e3*t)}const Q=(t,i)=>t?Object.entries(t).reduce(((t,[s,e])=>(!Boolean(e)||(t=>"{}"===JSON.stringify(t))(e)||i?.includes(s)||(t[s]="object"==typeof e?Q(e,i):e),t)),{}):t;function X(t,i){if(t===i)return!0;if(t&&i&&"object"==typeof t&&"object"==typeof i){if(t.constructor!==i.constructor)return!1;var s,e,n;if(Array.isArray(t)){if((s=t.length)!=i.length)return!1;for(e=s;0!=e--;)if(!X(t[e],i[e]))return!1;return!0}if(t instanceof Map&&i instanceof Map){if(t.size!==i.size)return!1;for(e of t.entries())if(!i.has(e[0]))return!1;for(e of t.entries())if(!X(e[1],i.get(e[0])))return!1;return!0}if(t instanceof Set&&i instanceof Set){if(t.size!==i.size)return!1;for(e of t.entries())if(!i.has(e[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(i)){if((s=t.length)!=i.length)return!1;for(e=s;0!=e--;)if(t[e]!==i[e])return!1;return!0}if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if((s=(n=Object.keys(t)).length)!==Object.keys(i).length)return!1;for(e=s;0!=e--;)if(!Object.prototype.hasOwnProperty.call(i,n[e]))return!1;for(e=s;0!=e--;){var r=n[e];if(!X(t[r],i[r]))return!1}return!0}return t!=t&&i!=i}function tt(t,i,s){let e;e=t.status?`error ${t.status}${401===t.status?" (invalid SDK key)":""}`:`I/O error (${t.message||"unknown error"})`;return`Received ${e} for ${i} - ${s??"giving up permanently"}`}function it({status:t}){return!t||W(t)}const st=(t,i)=>i.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var et;!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"}(et||(et={}));var nt=et;let rt=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};rt.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";class ot{constructor(t,i){const{basicConfiguration:s,platform:e}=t,{serviceEndpoints:{analyticsEventPath:n,diagnosticEventPath:r}}=s,{crypto:o,requests:a}=e;this.G={...i},this.B=G(s.serviceEndpoints,n,[]),this.H=G(s.serviceEndpoints,r,[]),this.W=a,this.Y=o}async Z(t,i,s,e){const n={status:E.Succeeded},r={...this.G,"content-type":"application/json"};let o;s&&(r["x-launchdarkly-payload-id"]=s,r["x-launchDarkly-event-schema"]="4");try{const{status:s,headers:e}=await this.W.fetch(i,{headers:r,body:JSON.stringify(t),method:"POST",keepalive:!0}),a=Date.parse(e.get("date")||"");if(a&&(n.serverTime=a),s<=204)return n;if(o=new B(tt({status:s,message:"some events were dropped"},"event posting")),!W(s))return!function(t){return 413===t||W(t)}(s)?n.status=E.FailedAndMustShutDown:n.status=E.Failed,n.error=o,n}catch(t){o=t}return o&&!e?(n.status=E.Failed,n.error=o,n):(await(async(t=1e3)=>new Promise((i=>{setTimeout(i,t)})))(),this.Z(t,this.B,s,!1))}async sendEventData(t,i){const s=t===$.AnalyticsEvents?this.Y.randomUUID():void 0,e=t===$.AnalyticsEvents?this.B:this.H;return this.Z(i,e,s,!0)}}function at(t){return"feature"===t.kind}class ht{constructor(t,i,s,e,n,r){this.count=t,this.key=i,this.value=s,this.version=n,this.variation=r,this.default=e}increment(){this.count+=1}}class ct{constructor(){this.X=0,this.tt=0,this.it={},this.st={}}summarizeEvent(t){if(at(t)&&!t.excludeFromSummaries){const i=function(t){return`${t.key}:${null!==t.variation&&void 0!==t.variation?t.variation:""}:${null!==t.version&&void 0!==t.version?t.version:""}`}(t),s=this.it[i];let e=this.st[t.key];e||(e=new Set,this.st[t.key]=e),t.context.kinds.forEach((t=>e.add(t))),s?s.increment():this.it[i]=new ht(1,t.key,t.value,t.default,t.version,t.variation),(0===this.X||t.creationDate<this.X)&&(this.X=t.creationDate),t.creationDate>this.tt&&(this.tt=t.creationDate)}}getSummary(){const t=Object.values(this.it).reduce(((t,i)=>{let s=t[i.key];s||(s={default:i.default,counters:[],contextKinds:[...this.st[i.key]]},t[i.key]=s);const e={value:i.value,count:i.count};return void 0!==i.variation&&null!==i.variation&&(e.variation=i.variation),void 0!==i.version&&null!==i.version?e.version=i.version:e.unknown=!0,s.counters.push(e),t}),{});return{startDate:this.X,endDate:this.tt,features:t,kind:"summary"}}clearSummary(){this.X=0,this.tt=0,this.it={},this.st={}}}class ut extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}}function lt(t){const i=Math.trunc(t);return 1===i||0!==i&&0===Math.floor(Math.random()*i)}class dt{constructor(t,i,s,e,n=1,r){this.context=t,this.key=i,this.data=s,this.metricValue=e,this.samplingRatio=n,this.url=r,this.kind="custom",this.creationDate=Date.now(),this.context=t}}class ft{constructor(t,i,s,e,n,r,o,a,h,c,u,l,d=1){this.withReasons=t,this.context=i,this.key=s,this.samplingRatio=d,this.kind="feature",this.creationDate=Date.now(),this.value=e,this.default=n,void 0!==r&&(this.version=r),void 0!==o&&(this.variation=o),void 0!==a&&(this.trackEvents=a),void 0!==h&&(this.prereqOf=h),void 0!==c&&(this.reason=c),void 0!==u&&(this.debugEventsUntilDate=u),void 0!==l&&(this.excludeFromSummaries=l)}}class vt{constructor(t,i=1){this.context=t,this.samplingRatio=i,this.kind="identify",this.creationDate=Date.now()}}var pt,yt=Object.freeze({__proto__:null,ClientMessages:rt,DiagnosticsManager:class{constructor(t,i,s){this.et=i,this.nt=s,this.rt=[],this.ot=Date.now(),this.ht=this.ot,this.ct={diagnosticId:i.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){const t=this.et.info.sdkData(),i=this.et.info.platformData();return{kind:"diagnostic-init",id:this.ct,creationDate:this.ot,sdk:t,configuration:this.nt,platform:{name:i.name,osArch:i.os?.arch,osName:i.os?.name,osVersion:i.os?.version,...i.additional||{}}}}recordStreamInit(t,i,s){const e={timestamp:t,failed:i,durationMillis:s};this.rt.push(e)}createStatsEventAndReset(t,i,s){const e=Date.now(),n={kind:"diagnostic",id:this.ct,creationDate:e,dataSinceDate:this.ht,droppedEvents:t,deduplicatedUsers:i,eventsInLastBatch:s,streamInits:this.rt};return this.rt=[],this.ht=e,n}},ErrorKinds:nt,EventFactoryBase:class{constructor(t){this.ut=t}evalEvent(t){return new ft(this.ut,t.context,t.flagKey,t.value,t.defaultVal,t.version,t.variation??void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.ut||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,i,s){return new ft(this.ut,s,t,i,i,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new vt(t,1)}customEvent(t,i,s,e,n=1){return new dt(i,t,s??void 0,e??void 0,n)}},EventProcessor:class{constructor(t,s,e,n,r,o=!0){this.lt=t,this.dt=n,this.ft=r,this.vt=new ct,this.yt=[],this.gt=0,this.wt=0,this.bt=0,this.kt=!1,this.$t=0,this.Et=!1,this.St=null,this.Dt=t.eventsCapacity,this.V=s.basicConfiguration.logger,this.Ot=new ot(s,e),this.xt=new m(t.allAttributesPrivate,t.privateAttributes.map((t=>new i(t)))),o&&this.start()}start(){if(void 0!==this.dt?.flushInterval&&(this.St=setInterval((()=>{this.dt?.flush()}),1e3*this.dt.flushInterval)),this._t=setInterval((async()=>{try{await this.flush()}catch(t){this.V?.debug(`Flush failed: ${t}`)}}),1e3*this.lt.flushInterval),this.ft){const t=this.ft.createInitEvent();this.It(t),this.Nt=setInterval((()=>{const t=this.ft.createStatsEventAndReset(this.wt,this.bt,this.$t);this.wt=0,this.bt=0,this.It(t)}),1e3*this.lt.diagnosticRecordingInterval)}this.V?.debug("Started EventProcessor.")}It(t){this.Ot.sendEventData($.DiagnosticEvent,t)}close(){clearInterval(this._t),this.St&&clearInterval(this.St),this.Nt&&clearInterval(this.Nt)}async flush(){if(this.Et)throw new ut("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.");const t=this.yt;this.yt=[];const i=this.vt.getSummary();this.vt.clearSummary(),Object.keys(i.features).length&&t.push(i),t.length&&(this.$t=t.length,this.V?.debug("Flushing %d events",t.length),await this.Z(t))}sendEvent(t){if(this.Et)return;if("migration_op"===t.kind){if(lt(t.samplingRatio)){const i={...t};1===i.samplingRatio&&delete i.samplingRatio,this.Rt(i)}return}this.vt.summarizeEvent(t);const i=at(t),s=i&&t.trackEvents||!i,e=this.Ct(t),n=function(t){return"identify"===t.kind}(t),r=this.dt?.processContext(t.context);r||n||(this.bt+=1);r&&!n&&this.Rt(this.jt({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),s&<(t.samplingRatio)&&this.Rt(this.jt(t,!1)),e&<(t.samplingRatio)&&this.Rt(this.jt(t,!0))}jt(t,i){switch(t.kind){case"feature":{const s={kind:i?"debug":"feature",creationDate:t.creationDate,context:this.xt.filter(t.context,!i),key:t.key,value:t.value,default:t.default};return 1!==t.samplingRatio&&(s.samplingRatio=t.samplingRatio),t.prereqOf&&(s.prereqOf=t.prereqOf),void 0!==t.variation&&(s.variation=t.variation),void 0!==t.version&&(s.version=t.version),t.reason&&(s.reason=t.reason),s}case"index":case"identify":{const i={kind:t.kind,creationDate:t.creationDate,context:this.xt.filter(t.context)};return 1!==t.samplingRatio&&(i.samplingRatio=t.samplingRatio),i}case"custom":{const i={kind:"custom",creationDate:t.creationDate,key:t.key,contextKeys:t.context.kindsAndKeys};return 1!==t.samplingRatio&&(i.samplingRatio=t.samplingRatio),void 0!==t.data&&(i.data=t.data),void 0!==t.metricValue&&(i.metricValue=t.metricValue),void 0!==t.url&&(i.url=t.url),i}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}}Rt(t){this.yt.length<this.Dt?(this.yt.push(t),this.kt=!1):(this.kt||(this.kt=!0,this.V?.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.wt+=1)}Ct(t){return at(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.gt&&t.debugEventsUntilDate>Date.now()}async Z(t){const i=await this.Ot.sendEventData($.AnalyticsEvents,t);if(i.status===E.FailedAndMustShutDown&&(this.Et=!0),i.serverTime&&(this.gt=i.serverTime),i.error)throw i.error}},InputCustomEvent:dt,InputEvalEvent:ft,InputIdentifyEvent:vt,NullEventProcessor:class{close(){}async flush(){}sendEvent(){}},StreamingProcessor:class{constructor(t,i,s,e,n,r,o,a=1){this.Tt=e,this.ft=r,this.At=o,this.Pt=a;const{basicConfiguration:h,platform:c}=t,{logger:u}=h,{requests:l}=c;this.Mt={...n},this.V=u,this.W=l,this.Lt=q(h.serviceEndpoints,i,s)}Jt(){this.Ut=Date.now()}Kt(t){this.Ut&&this.ft&&this.ft.recordStreamInit(this.Ut,!t,Date.now()-this.Ut),this.Ut=void 0}Ft(t){return it(t)?(this.V?.warn(tt(t,"streaming request","will retry")),this.Kt(!1),this.Jt(),!0):(this.Kt(!1),this.At?.(new D(b.ErrorResponse,t.message,t.status)),this.V?.error(tt(t,"streaming request")),!1)}start(){this.Jt();const t=this.W.createEventSource(this.Lt,{headers:this.Mt,errorFilter:t=>this.Ft(t),initialRetryDelayMillis:1e3*this.Pt,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this.Vt=t,t.onclose=()=>{this.V?.info("Closed LaunchDarkly stream connection")},t.onerror=()=>{},t.onopen=()=>{this.V?.info("Opened LaunchDarkly stream connection")},t.onretrying=t=>{this.V?.info(`Will retry stream connection in ${t.delayMillis} milliseconds`)},this.Tt.forEach((({deserializeData:i,processJson:s},e)=>{t.addEventListener(e,(t=>{if(this.V?.debug(`Received ${e} event`),t?.data){this.Kt(!0);const{data:n}=t,r=i(n);if(!r)return void((t,i,s,e)=>{s?.error(`Stream received invalid data in "${t}" message`),s?.debug(`Invalid JSON follows: ${i}`),e?.(new D(b.InvalidData,"Malformed JSON data in event stream"))})(e,n,this.V,this.At);s(r)}else this.At?.(new D(b.Unknown,"Unexpected payload from event stream"))}))}))}stop(){this.Vt?.close(),this.Vt=void 0}close(){this.stop()}},isLegacyUser:u,isMultiKind:c,isSingleKind:h,shouldSample:lt});!function(t){t.Initializing="INITIALIZING",t.Valid="VALID",t.Interrupted="INTERRUPTED",t.SetOffline="SET_OFFLINE",t.Closed="CLOSED"}(pt||(pt={}));class gt extends Error{constructor(t,i){super(t),this.status=i,this.name="LaunchDarklyRequestError"}}class wt{constructor(t,i,s,e,n){this.W=t,this.qt=i,this.Mt=s,this.Gt=e,this.Bt=n}async requestPayload(){let t;try{const i=await this.W.fetch(this.qt,{method:this.Gt,headers:this.Mt,body:this.Bt});if(function(t){return t>=200&&t<=299}(i.status))return await i.text();t=i.status}catch(t){throw new gt(t?.message)}throw new gt(`Unexpected status code: ${t}`,t)}}function mt(t,i,s,e,n,r,o,a,h,c){let u,l="GET";const d={...r};h&&(l="REPORT",d["content-type"]="application/json",u=t);const f=h?s.pathReport(n,t):s.pathGet(n,t),v=[...o??[]];a&&v.push({key:"withReasons",value:"true"}),c&&v.push({key:"h",value:c});const p=function(t,i,s){const e=K(i),n=[...s];return t.payloadFilterKey&&n.push({key:"filter",value:t.payloadFilterKey}),V(`${t.polling}/${e}`,n)}(i,f,v);return new wt(e,p,d,l,u)}const bt={logger:a.Object,maxCachedContexts:a.numberWithMin(0),baseUri:a.String,streamUri:a.String,eventsUri:a.String,capacity:a.numberWithMin(1),diagnosticRecordingInterval:a.numberWithMin(2),flushInterval:a.numberWithMin(2),streamInitialReconnectDelay:a.numberWithMin(0),allAttributesPrivate:a.Boolean,debug:a.Boolean,diagnosticOptOut:a.Boolean,withReasons:a.Boolean,sendEvents:a.Boolean,pollInterval:a.numberWithMin(30),useReport:a.Boolean,privateAttributes:a.StringArray,applicationInfo:a.Object,wrapperName:a.String,wrapperVersion:a.String,payloadFilterKey:a.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:a.createTypeArray("Hook[]",{}),inspectors:a.createTypeArray("LDInspection",{})},kt="https://clientsdk.launchdarkly.com",$t="https://clientstream.launchdarkly.com";class Et{constructor(t={},i={}){var s;this.logger=T(),this.baseUri=kt,this.eventsUri=F.DEFAULT_EVENTS,this.streamUri=$t,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=300,this.hooks=[],this.inspectors=[],this.logger=(s=t.logger)instanceof j?s:T(s);this.zt(t).forEach((t=>this.logger.warn(t))),this.serviceEndpoints=new F(this.streamUri,this.baseUri,this.eventsUri,i.analyticsEventPath,i.diagnosticEventPath,i.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=t.useReport??!1,this.tags=new L({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=i.userAgentHeaderName??"user-agent",this.trackEventModifier=i.trackEventModifier??(t=>t)}zt(t){const i=[];return Object.entries(t).forEach((([t,s])=>{const e=bt[t];if(e)if(e.is(s))"logger"===t||(this[t]=s??void 0);else{const r=e.getType();if("boolean"===r)i.push(A.wrongOptionTypeBoolean(t,typeof s)),this[t]=!!s;else if("boolean | undefined | null"===r)i.push(A.wrongOptionTypeBoolean(t,typeof s)),"boolean"!=typeof s&&null!=s&&(this[t]=!!s);else if(e instanceof n&&a.Number.is(s)){const{min:n}=e;i.push(A.optionBelowMinimum(t,s,n)),this[t]=n}else i.push(A.wrongOptionType(t,e.getType(),typeof s))}else i.push(A.unknownOption(t))})),i}}async function St(t,i){if(t.digest)return t.digest(i);if(t.asyncDigest)return t.asyncDigest(i);throw new Error("Platform must implement digest or asyncDigest")}const Dt=async(t,{crypto:i,storage:s})=>{let e=await(s?.get(t));return e||(e=i.randomUUID(),await(s?.set(t,e))),e};function Ot(t){return async i=>St(t.createHash("sha256").update(i),"base64")}const xt=async t=>t;async function _t(t){return(await Promise.all(t.map((t=>t.transform(t.value))))).join("_")}async function It(t,i,s){return _t([{value:i,transform:xt},{value:s.canonicalKey,transform:Ot(t)}])}const{isLegacyUser:Nt,isSingleKind:Rt,isMultiKind:Ct}=yt,jt=async t=>{const{ld_device:i,os:s}=t.info.platformData(),e=Q(i)??{},n=s?.name||e.os?.name,r=s?.version||e.os?.version,o=e.os?.family;if((n||r||o)&&(e.os={...n?{name:n}:{},...r?{version:r}:{},...o?{family:o}:{}}),Object.keys(e).filter((t=>"key"!==t&&"envAttributesVersion"!==t)).length){const i=await async function(t){return _t([{value:"LaunchDarkly",transform:xt},{value:"ContextKeys",transform:xt},{value:t,transform:xt}])}("ld_device");return e.key=await Dt(i,t),e.envAttributesVersion=e.envAttributesVersion||"1.0",e}},Tt=async(t,i,s)=>{if(Nt(t))return t;let e,n;if(Rt(t)&&"ld_application"!==t.kind||Ct(t)&&!t.ld_application?e=await(async({crypto:t,info:i},{applicationInfo:s})=>{const{ld_application:e}=i.platformData();let n=Q(e)??{};const r=s?.id||n?.id;if(r){const i=s?.version||n?.version,e=s?.name||n?.name,o=s?.versionName||n?.versionName;return n={...n,id:r,...i?{version:i}:{},...e?{name:e}:{},...o?{versionName:o}:{}},n.key=await St(t.createHash("sha256").update(r),"base64"),n.envAttributesVersion=n.envAttributesVersion||"1.0",n}})(i,s):s.logger.warn("Not adding ld_application environment attributes because it already exists."),Rt(t)&&"ld_device"!==t.kind||Ct(t)&&!t.ld_device?n=await jt(i):s.logger.warn("Not adding ld_device environment attributes because it already exists."),e||n){return{...Rt(t)?(t=>{const{kind:i,...s}=t;return{kind:"multi",[i]:s}})(t):t,...e?{ld_application:e}:{},...n?{ld_device:n}:{}}}return t},{isLegacyUser:At,isMultiKind:Pt,isSingleKind:Mt}=yt,Lt=async(t,i,s)=>{const{anonymous:e,key:n}=i;if(e&&!n){const e=await async function(t){return _t([{value:"LaunchDarkly",transform:xt},{value:"AnonymousKeys",transform:xt},{value:t,transform:xt}])}(t);i.key=await Dt(e,s)}},Jt=async(t,i)=>{const s=Y(t);return Mt(s)&&await(async(t,i)=>{await Lt(t.kind,t,i)})(s,i),Pt(s)&&await(async(t,i)=>{const{kind:s,...e}=t;return Promise.all(Object.entries(e).map((([t,s])=>Lt(t,s,i))))})(s,i),At(s)&&await(async(t,i)=>{await Lt("user",t,i)})(s,i),s},Ut=(t,i,s)=>{if(i.sendEvents&&!i.diagnosticOptOut)return new yt.DiagnosticsManager(t,s,(t=>({customBaseURI:t.serviceEndpoints.polling!==kt,customStreamURI:t.serviceEndpoints.streaming!==$t,customEventsURI:t.serviceEndpoints.events!==F.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:Z(t.flushInterval),reconnectTimeMillis:Z(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Z(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}))(i))};function Kt(t,i){return{value:i??null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function Ft(t,i,s){return{value:t,variationIndex:i??null,reason:s??null}}class Vt extends yt.EventFactoryBase{evalEventClient(t,i,s,e,n,r){const{trackEvents:o,debugEventsUntilDate:a,trackReason:h,flagVersion:c,version:u,variation:l}=e;return super.evalEvent({addExperimentData:h,context:n,debugEventsUntilDate:a,defaultVal:s,flagKey:t,reason:r,trackEvents:!!o,value:i,variation:l,version:c??u})}}class qt{constructor(){this.container={index:new Array}}static fromJson(t){const i=new qt;try{i.container=JSON.parse(t)}catch(t){}return i}toJson(){return JSON.stringify(this.container)}notice(t,i){const s=this.container.index.find((i=>i.id===t));void 0===s?this.container.index.push({id:t,timestamp:i}):s.timestamp=i}prune(t){const i=Math.max(t,0);return this.container.index.length>i?(this.container.index.sort(((t,i)=>t.timestamp-i.timestamp)),this.container.index.splice(0,this.container.index.length-i)):[]}}class Gt{constructor(t,i,s,e,n,r,o=()=>Date.now()){this.et=t,this.Ht=i,this.Wt=s,this.Yt=e,this.Zt=n,this.V=r,this.Qt=o,this.Xt=async function(t){return _t([{value:t,transform:xt},{value:"ContextIndex",transform:xt}])}(this.Ht)}async init(t,i){this.Zt.init(t,i),await this.ti(t)}async upsert(t,i,s){return!!this.Zt.upsert(t,i,s)&&(await this.ti(t),!0)}async loadCached(t){const i=await It(this.et.crypto,this.Ht,t);let s=await(this.et.storage?.get(i));if(null==s){if(s=await(this.et.storage?.get(t.canonicalKey)),null==s)return!1;await(this.et.storage?.set(i,s)),await(this.et.storage?.clear(t.canonicalKey))}try{const i=JSON.parse(s),e=Object.entries(i).reduce(((t,[i,s])=>(t[i]={version:s.version,flag:s},t)),{});return this.Zt.initCached(t,e),this.V.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(t){return this.V.warn(`Could not load cached flag evaluations from persistent storage: ${t.message}`),!1}}async ii(){if(void 0!==this.si)return this.si;const t=await(this.et.storage?.get(await this.Xt));if(!t)return this.si=new qt,this.si;try{this.si=qt.fromJson(t),this.V.debug("Loaded context index from persistent storage")}catch(t){this.V.warn(`Could not load index from persistent storage: ${t.message}`),this.si=new qt}return this.si}async ti(t){const i=await this.ii(),s=await It(this.et.crypto,this.Ht,t);i.notice(s,this.Qt());const e=i.prune(this.Wt);await Promise.all(e.map((async t=>this.et.storage?.clear(t.id)))),await(this.et.storage?.set(await this.Xt,i.toJson()));const n=this.Yt.getAll(),r=Object.entries(n).reduce(((t,[i,s])=>(null!==s.flag&&void 0!==s.flag&&(t[i]=s.flag),t)),{}),o=JSON.stringify(r);await(this.et.storage?.set(s,o))}}class Bt{constructor(){this.ei={}}init(t){this.ei=Object.entries(t).reduce(((t,[i,s])=>(t[i]=s,t)),{})}insertOrUpdate(t,i){this.ei[t]=i}get(t){if(Object.prototype.hasOwnProperty.call(this.ei,t))return this.ei[t]}getAll(){return this.ei}}function zt(t,i){const s=[];return Object.entries(t).forEach((([t,e])=>{const n=i[t];n&&X(e,n)||s.push(t)})),Object.keys(i).forEach((i=>{t[i]||s.push(i)})),s}class Ht{constructor(t,i){this.ni=new Array,this.Yt=t,this.V=i}init(t,i){this.ri=t.canonicalKey;const s=this.Yt.getAll();this.Yt.init(i);const e=zt(s,i);e.length>0&&this.ni.forEach((i=>{try{i(t,e,"init")}catch(t){}}))}initCached(t,i){this.ri!==t.canonicalKey&&this.init(t,i)}upsert(t,i,s){if(this.ri!==t.canonicalKey)return this.V.warn("Received an update for an inactive context."),!1;const e=this.Yt.get(i);return!(void 0!==e&&e.version>=s.version)&&(this.Yt.insertOrUpdate(i,s),this.ni.forEach((s=>{try{s(t,[i],"patch")}catch(t){}})),!0)}on(t){this.ni.push(t)}off(t){const i=this.ni.indexOf(t);i>-1&&this.ni.splice(i,1)}}class Wt{constructor(t,i,s,e,n=()=>Date.now()){this.Yt=new Bt,this.Zt=new Ht(this.Yt,e),this.oi=this.ai(t,i,s,e,n)}async ai(t,i,s,e,n=()=>Date.now()){const r=await async function(t,i){return _t([{value:"LaunchDarkly",transform:xt},{value:i,transform:Ot(t)}])}(t.crypto,i);return new Gt(t,r,s,this.Yt,this.Zt,e,n)}get(t){return this.Yt.get(t)}getAll(){return this.Yt.getAll()}setBootstrap(t,i){this.Zt.init(t,i)}async init(t,i){return(await this.oi).init(t,i)}async upsert(t,i,s){return(await this.oi).upsert(t,i,s)}async loadCached(t){return(await this.oi).loadCached(t)}on(t){this.Zt.on(t)}off(t){this.Zt.off(t)}}const Yt="unknown hook",Zt="beforeEvaluation",Qt="afterEvaluation";function Xt(t,i,s,e,n){try{return e()}catch(e){return t?.error(`An error was encountered in "${i}" of the "${s}" hook: ${e}`),n}}function ti(t,i){try{return i.getMetadata().name||Yt}catch{return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),Yt}}class ii{constructor(t,i){this.V=t,this.hi=[],this.hi.push(...i)}withEvaluation(t,i,s,e){if(0===this.hi.length)return e();const n=[...this.hi],r={flagKey:t,context:i,defaultValue:s},o=function(t,i,s){return i.map((i=>Xt(t,Zt,ti(t,i),(()=>i?.beforeEvaluation?.(s,{})??{}),{})))}(this.V,n,r),a=e();return function(t,i,s,e,n){for(let r=i.length-1;r>=0;r-=1){const o=i[r],a=e[r];Xt(t,Qt,ti(t,o),(()=>o?.afterEvaluation?.(s,a,n)??{}),{})}}(this.V,n,r,o,a),a}identify(t,i){const s=[...this.hi],e={context:t,timeout:i},n=function(t,i,s){return i.map((i=>Xt(t,Zt,ti(t,i),(()=>i?.beforeIdentify?.(s,{})??{}),{})))}(this.V,s,e);return t=>{!function(t,i,s,e,n){for(let r=i.length-1;r>=0;r-=1){const o=i[r],a=e[r];Xt(t,Qt,ti(t,o),(()=>o?.afterIdentify?.(s,a,n)??{}),{})}}(this.V,s,e,n,t)}}addHook(t){this.hi.push(t)}}const si="flag-used",ei="flag-details-changed",ni="flag-detail-changed",ri="client-identity-changed",oi=[si,ei,ni,ri];class ai{constructor(t,i){this.ci=[];const s=t.filter((t=>function(t,i){const s=oi.includes(t.type)&&t.method&&"function"==typeof t.method;var e;return s||i.warn((e=t.type,`an inspector: "${t.name}" of an invalid type (${e}) was configured`)),s}(t,i)));this.ci=s.map((t=>function(t,i){let s=!1;const e={method:(...n)=>{try{t.method(...n)}catch{s||(s=!0,i.warn((r=e.type,`an inspector: "${e.name}" of type: "${r}" generated an exception`)))}var r},type:t.type,name:t.name,synchronous:t.synchronous};return e}(t,i)))}hasInspectors(){return 0!==this.ci.length}onFlagUsed(t,i,s){this.ci.forEach((e=>{e.type===si&&e.method(t,i,s)}))}onFlagsChanged(t){this.ci.forEach((i=>{i.type===ei&&i.method(t)}))}onFlagChanged(t,i){this.ci.forEach((s=>{s.type===ni&&s.method(t,i)}))}onIdentityChanged(t){this.ci.forEach((i=>{i.type===ri&&i.method(t)}))}}class hi{constructor(t){this.V=t,this.Tt=new Map}on(t,i){this.Tt.has(t)?this.Tt.get(t)?.push(i):this.Tt.set(t,[i])}off(t,i){const s=this.Tt.get(t);if(s)if(i){const e=s.filter((t=>t!==i));0===e.length?this.Tt.delete(t):this.Tt.set(t,e)}else this.Tt.delete(t)}ui(t,i,...s){try{t(...s)}catch(t){this.V?.error(`Encountered error invoking handler for "${i}", detail: "${t}"`)}}emit(t,...i){const s=this.Tt.get(t);s?.forEach((s=>this.ui(s,t,...i)))}eventNames(){return[...this.Tt.keys()]}listenerCount(t){return this.Tt.get(t)?.length??0}}const{ClientMessages:ci,ErrorKinds:ui}=yt;class li{constructor(t,i,s,e,n,r){if(this.sdkKey=t,this.autoEnvAttributes=i,this.platform=s,this.li=5,this.di=15,this.fi=new Vt(!1),this.pi=new Vt(!0),this.yi=!1,!t)throw new Error("You must configure the client with a client-side SDK key");if(!s.encoding)throw new Error("Platform must implement Encoding because btoa is required.");var o;this.lt=new Et(e,r),this.logger=this.lt.logger,this.gi=function(t,i,s,e=!0,n="user-agent"){const{userAgentBase:r,version:o,wrapperName:a,wrapperVersion:h}=i.sdkData(),c={[n]:`${r??"NodeJSClient"}/${o}`};return e&&(c.authorization=t),a&&(c["x-launchdarkly-wrapper"]=h?`${a}/${h}`:a),s?.value&&(c["x-launchdarkly-tags"]=s.value),c}(this.sdkKey,this.platform.info,this.lt.tags,this.lt.serviceEndpoints.includeAuthorizationHeader,this.lt.userAgentHeaderName),this.wi=new Wt(this.platform,t,this.lt.maxCachedContexts,this.lt.logger),this.ft=Ut(t,this.lt,s),this.mi=((t,i,s,e,n)=>{if(i.sendEvents)return new yt.EventProcessor({...i,eventsCapacity:i.capacity},new J(t,i,s),e,void 0,n,!1)})(t,this.lt,s,this.gi,this.ft),this.emitter=new hi,this.emitter.on("error",((t,i)=>{this.logger.error(`error: ${i}, context: ${JSON.stringify(t)}`)})),this.wi.on(((t,i,s)=>{this.bi(i,s);const e=y.toLDContext(t);this.emitter.emit("change",e,i),i.forEach((t=>{this.emitter.emit(`change:${t}`,e)}))})),this.dataManager=n(this.wi,this.lt,this.gi,this.emitter,this.ft),this.ki=new ii(this.logger,this.lt.hooks),this.$i=new ai(this.lt.inspectors,this.logger),this.$i.hasInspectors()&&this.ki.addHook((o=this.$i,{getMetadata:()=>({name:"LaunchDarkly-Inspector-Adapter"}),afterEvaluation:(t,i,s)=>(o.onFlagUsed(t.flagKey,s,t.context),i),afterIdentify:(t,i,s)=>(o.onIdentityChanged(t.context),i)}))}allFlags(){return Object.entries(this.wi.getAll()).reduce(((t,[i,s])=>(null===s.flag||void 0===s.flag||s.flag.deleted||(t[i]=s.flag.value),t)),{})}async close(){await this.flush(),this.mi?.close(),this.Ei?.close(),this.logger.debug("Closed event processor and data source.")}async flush(){try{await(this.mi?.flush()),this.logger.debug("Successfully flushed event processor.")}catch(t){return this.logger.error(`Error flushing event processor: ${t}.`),{error:t,result:!1}}return{result:!0}}getContext(){return this.Si?Y(this.Si):void 0}getInternalContext(){return this.Di}Oi(t){let i,s;const e=new Promise(((t,e)=>{i=t,s=e})),n=(r=t,o="identify",new Promise(((t,i)=>{setTimeout((()=>{i(new H(`${o} timed out after ${r} seconds.`))}),1e3*r)})));var r,o;return{identifyPromise:Promise.race([n,e]).catch((t=>{throw t.message.includes("timed out")&&this.logger.error(`identify error: ${t}`),t})),identifyResolve:i,identifyReject:s}}async identify(t,i){i?.timeout&&(this.li=i.timeout),this.li>this.di&&this.logger.warn(`The identify function was called with a timeout greater than ${this.di} seconds. We recommend a timeout of less than ${this.di} seconds.`);let s=await Jt(t,this.platform);this.autoEnvAttributes===k.Enabled&&(s=await Tt(s,this.platform,this.lt));const e=y.fromLDContext(s);if(!e.valid){const t=new Error("Context was unspecified or had no key");return this.emitter.emit("error",s,t),Promise.reject(t)}this.Si=s,this.Di=e,this.mi?.sendEvent(this.fi.identifyEvent(this.Di));const{identifyPromise:n,identifyResolve:r,identifyReject:o}=this.Oi(this.li);this.logger.debug(`Identifying ${JSON.stringify(this.Di)}`);const a=this.ki.identify(s,i?.timeout);return await this.dataManager.identify(r,o,e,i),n.then((t=>(a({status:"completed"}),t)),(t=>{throw a({status:"error"}),t}))}on(t,i){this.emitter.on(t,i)}off(t,i){this.emitter.off(t,i)}track(t,i,s){this.Di&&this.Di.valid?(void 0===s||a.Number.is(s)||this.logger?.warn(ci.invalidMetricValue(typeof s)),this.mi?.sendEvent(this.lt.trackEventModifier(this.fi.customEvent(t,this.Di,i,s)))):this.logger.warn(ci.MissingContextKeyNoEvent)}xi(t,i,s,e){if(!this.Si)return this.logger.debug(ci.MissingContextKeyNoEvent),Kt(ui.UserNotSpecified,i);const n=y.fromLDContext(this.Si),r=this.wi.get(t);if(void 0===r||r.flag.deleted){const s=i??null,e=new z(`Unknown feature flag "${t}"; returning default value ${s}.`);return this.emitter.emit("error",this.Si,e),this.mi?.sendEvent(this.fi.unknownFlagEvent(t,s,n)),Kt(ui.FlagNotFound,i)}const{reason:o,value:a,variation:h,prerequisites:c}=r.flag;if(e){const[h,c]=e(a);if(!h){this.mi?.sendEvent(s.evalEventClient(t,i,i,r.flag,n,o));const e=new z(`Wrong type "${c}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.Si,e),Kt(ui.WrongType,i)}}const u=Ft(a,h,o);return null==a&&(this.logger.debug("Result value is null. Providing default value."),u.value=i),c?.forEach((t=>{this.xi(t,void 0,this.fi)})),this.mi?.sendEvent(s.evalEventClient(t,a,i,r.flag,n,o)),u}variation(t,i){const{value:s}=this.ki.withEvaluation(t,this.Si,i,(()=>this.xi(t,i,this.fi)));return s}variationDetail(t,i){return this.ki.withEvaluation(t,this.Si,i,(()=>this.xi(t,i,this.pi)))}_i(t,i,s,e){return this.ki.withEvaluation(t,this.Si,i,(()=>this.xi(t,i,s,e)))}boolVariation(t,i){return this._i(t,i,this.fi,(t=>[a.Boolean.is(t),a.Boolean.getType()])).value}jsonVariation(t,i){return this.variation(t,i)}numberVariation(t,i){return this._i(t,i,this.fi,(t=>[a.Number.is(t),a.Number.getType()])).value}stringVariation(t,i){return this._i(t,i,this.fi,(t=>[a.String.is(t),a.String.getType()])).value}boolVariationDetail(t,i){return this._i(t,i,this.pi,(t=>[a.Boolean.is(t),a.Boolean.getType()]))}numberVariationDetail(t,i){return this._i(t,i,this.pi,(t=>[a.Number.is(t),a.Number.getType()]))}stringVariationDetail(t,i){return this._i(t,i,this.pi,(t=>[a.String.is(t),a.String.getType()]))}jsonVariationDetail(t,i){return this.variationDetail(t,i)}addHook(t){this.ki.addHook(t)}setEventSendingEnabled(t,i){this.yi!==t&&(this.yi=t,t?(this.logger.debug("Starting event processor"),this.mi?.start()):i?(this.logger?.debug("Flushing event processor before disabling."),this.flush().then((()=>{this.yi||(this.logger?.debug("Stopping event processor."),this.mi?.close())}))):(this.logger?.debug("Stopping event processor."),this.mi?.close()))}sendEvent(t){this.mi?.sendEvent(t)}bi(t,i){if(!this.$i.hasInspectors())return;const s={};t.forEach((t=>{const i=this.wi.get(t);if(i?.flag&&!i.flag.deleted){const{reason:e,value:n,variation:r}=i.flag;s[t]=Ft(n,r,e)}})),"init"===i?this.$i.onFlagsChanged(s):"patch"===i&&Object.entries(s).forEach((([t,i])=>{this.$i.onFlagChanged(t,i)}))}}class di{constructor(t,i,s){this.wi=t,this.Ii=i,this.V=s}async handlePut(t,i){this.V.debug(`Got PUT: ${Object.keys(i)}`);const s=Object.entries(i).reduce(((t,[i,s])=>(t[i]={version:s.version,flag:s},t)),{});await this.wi.init(t,s),this.Ii.requestStateUpdate(pt.Valid)}async handlePatch(t,i){this.V.debug(`Got PATCH ${JSON.stringify(i,null,2)}`),this.wi.upsert(t,i.key,{version:i.version,flag:i})}async handleDelete(t,i){this.V.debug(`Got DELETE ${JSON.stringify(i,null,2)}`),this.wi.upsert(t,i.key,{version:i.version,flag:{...i,deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1}})}handleStreamingError(t){this.Ii.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.Ii.reportError(t.kind,t.message,t.status,t.recoverable)}}class fi{constructor(t,i=()=>Date.now()){this.Ni=t,this.Ri=pt.Closed,this.Ci=i(),this.Qt=i}get status(){return{state:this.Ri,stateSince:this.Ci,lastError:this.ji}}Ti(t,i=!1){const s=t===pt.Interrupted&&this.Ri===pt.Initializing?pt.Initializing:t,e=this.Ri!==s;e&&(this.Ri=s,this.Ci=this.Qt()),(e||i)&&this.Ni.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.Ti(t)}reportError(t,i,s,e=!1){const n={kind:t,message:i,statusCode:s,time:this.Qt()};this.ji=n,this.Ti(e?pt.Interrupted:pt.Closed,!0)}}class vi{constructor(t,i,s,e,n){this.Ai=t,this.Pi=i,this.Mi=s,this.At=e,this.V=n,this.Li=!1}async Ji(){if(this.Li)return;const t=t=>{this.V?.error("Polling received invalid data"),this.V?.debug(`Invalid JSON follows: ${t}`),this.At?.(new S(b.InvalidData,"Malformed JSON data in polling response"))};this.V?.debug("Polling LaunchDarkly for feature flag updates");const i=Date.now();try{const i=await this.Ai.requestPayload();try{const t=JSON.parse(i);try{this.Mi?.(t)}catch(t){this.V?.error(`Exception from data handler: ${t}`)}}catch{t(i)}}catch(t){const i=t;if(void 0!==i.status&&!W(i.status))return this.V?.error(tt(t,"polling request")),void this.At?.(new S(b.ErrorResponse,i.message,i.status));this.V?.error(tt(t,"polling request","will retry"))}const s=Date.now()-i,e=Math.max(1e3*this.Pi-s,0);this.V?.debug("Elapsed: %d ms, sleeping for %d ms",s,e),this.Ui=setTimeout((()=>{this.Ji()}),e)}start(){this.Ji()}stop(){this.Ui&&(clearTimeout(this.Ui),this.Ui=void 0),this.Li=!0}close(){this.stop()}}class pi{constructor(t,i,s,e,n,r,o,a,h){let c;this.Ki=t,this.Fi=i,this.Tt=s,this.W=e,this.Vi=r,this.ft=o,this.At=a,this.V=h,c=i.useReport&&!e.getEventSourceCapabilities().customMethod?i.paths.pathPing(n,t):i.useReport?i.paths.pathReport(n,t):i.paths.pathGet(n,t);const u=[...i.queryParameters??[]];this.Fi.withReasons&&u.push({key:"withReasons",value:"true"}),this.W=e,this.Mt={...i.baseHeaders},this.V=h,this.Lt=q(i.serviceEndpoints,c,u)}Jt(){this.Ut=Date.now()}Kt(t){this.Ut&&this.ft&&this.ft.recordStreamInit(this.Ut,!t,Date.now()-this.Ut),this.Ut=void 0}Ft(t){return it(t)?(this.V?.warn(tt(t,"streaming request","will retry")),this.Kt(!1),this.Jt(),!0):(this.Kt(!1),this.At?.(new D(b.ErrorResponse,t.message,t.status,!1)),this.V?.error(tt(t,"streaming request")),!1)}start(){let t;this.Jt(),this.Fi.useReport?(this.Mt["content-type"]="application/json",t={method:"REPORT",body:this.Ki}):t={};const i=this.W.createEventSource(this.Lt,{headers:this.Mt,...t,errorFilter:t=>this.Ft(t),initialRetryDelayMillis:this.Fi.initialRetryDelayMillis,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this.Vt=i,i.onclose=()=>{this.V?.info("Closed LaunchDarkly stream connection")},i.onerror=()=>{},i.onopen=()=>{this.V?.info("Opened LaunchDarkly stream connection")},i.onretrying=t=>{this.V?.info(`Will retry stream connection in ${t.delayMillis} milliseconds`)},this.Tt.forEach((({deserializeData:t,processJson:s},e)=>{i.addEventListener(e,(i=>{if(this.V?.debug(`Received ${e} event`),i?.data){this.Kt(!0);const{data:n}=i,r=t(n);if(!r)return void((t,i,s,e)=>{s?.error(`Stream received invalid data in "${t}" message`),s?.debug(`Invalid JSON follows: ${i}`),e?.(new D(b.InvalidData,"Malformed JSON data in event stream"))})(e,n,this.V,this.At);s(r)}else this.At?.(new D(b.InvalidData,"Unexpected payload from event stream"))}))})),i.addEventListener("ping",(async()=>{this.V?.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{const t=await this.Vi.requestPayload();try{const i=JSON.parse(t);try{this.Tt.get("put")?.processJson(i)}catch(t){this.V?.error(`Exception from data handler: ${t}`)}}catch{this.V?.error("Polling after ping received invalid data"),this.V?.debug(`Invalid JSON follows: ${t}`),this.At?.(new S(b.InvalidData,"Malformed JSON data in ping polling response"))}}catch(t){const i=t;this.At?.(new S(b.ErrorResponse,i.message,i.status))}}))}stop(){this.Vt?.close(),this.Vt=void 0}close(){this.stop()}}class yi{constructor(t,i,s,e,n,r,o,a,h){this.platform=t,this.flagManager=i,this.credential=s,this.config=e,this.getPollingPaths=n,this.getStreamingPaths=r,this.baseHeaders=o,this.emitter=a,this.diagnosticsManager=h,this.logger=e.logger,this.dataSourceStatusManager=new fi(a),this.qi=new di(i,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Gi=t}createPollingProcessor(t,i,s,e,n){const r=new vi(s,this.config.pollInterval,(async t=>{await this.qi.handlePut(i,t),e?.()}),(i=>{this.emitter.emit("error",t,i),this.qi.handlePollingError(i),n?.(i)}),this.logger);this.updateProcessor=this.Bi(r,this.dataSourceStatusManager)}createStreamingProcessor(t,i,s,e,n){const r=new pi(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:1e3*this.config.streamInitialReconnectDelay,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:this.Gi?.queryParameters},this.createStreamListeners(i,e),this.platform.requests,this.platform.encoding,s,this.diagnosticsManager,(i=>{this.emitter.emit("error",t,i),this.qi.handleStreamingError(i),n?.(i)}),this.logger);this.updateProcessor=this.Bi(r,this.dataSourceStatusManager)}createStreamListeners(t,i){const s=new Map;return s.set("put",{deserializeData:JSON.parse,processJson:async s=>{await this.qi.handlePut(t,s),i?.()}}),s.set("patch",{deserializeData:JSON.parse,processJson:async i=>{this.qi.handlePatch(t,i)}}),s.set("delete",{deserializeData:JSON.parse,processJson:async i=>{this.qi.handleDelete(t,i)}}),s}Bi(t,i){return{start:()=>{i.requestStateUpdate(pt.Initializing),t.start()},stop:()=>{t.stop(),i.requestStateUpdate(pt.Closed)},close:()=>{t.close(),i.requestStateUpdate(pt.Closed)}}}}function gi(){return void 0!==typeof document}function wi(){return void 0!==typeof window}function mi(t,i,s){return gi()?(document.addEventListener(t,i,s),()=>{document.removeEventListener(t,i,s)}):()=>{}}function bi(t,i,s){return gi()?(window.addEventListener(t,i,s),()=>{window.removeEventListener(t,i,s)}):()=>{}}function ki(){return wi()?window.location.href:""}class $i extends yi{constructor(t,i,s,e,n,r,o,a,h,c){super(t,i,s,e,r,o,a,h,c),this.zi=n,this.Hi=void 0,this.Wi=!1,this.Hi=n.streaming}Yi(t,...i){this.logger.debug(`[BrowserDataManager] ${t}`,...i)}async identify(t,i,s,e){this.context=s;const n=e;(null==n?void 0:n.hash)?this.setConnectionParams({queryParameters:[{key:"h",value:n.hash}]}):this.setConnectionParams(),this.Zi=null==n?void 0:n.hash,(null==n?void 0:n.bootstrap)?this.Qi(s,n.bootstrap,t):(await this.flagManager.loadCached(s)&&this.Yi("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Xi(s,t,i)),this.ts()}async Xi(t,i,s){var e,n;try{this.dataSourceStatusManager.requestStateUpdate(pt.Initializing);const s=mt(JSON.stringify(y.toLDContext(t)),this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Zi),n=await s.requestPayload();try{const s=this.createStreamListeners(t,i).get("put");s.processJson(s.deserializeData(n))}catch(t){this.dataSourceStatusManager.reportError(b.InvalidData,null!==(e=t.message)&&void 0!==e?e:"Could not parse poll response")}}catch(t){this.dataSourceStatusManager.reportError(b.NetworkError,null!==(n=t.message)&&void 0!==n?n:"unexpected network error",t.status),s(t)}}Qi(t,i,s){this.flagManager.setBootstrap(t,function(t,i){const s=Object.keys(i),e="$flagsState",n="$valid",r=i[e];!r&&s.length&&t.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),!1===i[n]&&t.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");const o={};return s.forEach((t=>{if(t!==e&&t!==n){let s;s=r&&r[t]?Object.assign({value:i[t]},r[t]):{value:i[t],version:0},o[t]={version:s.version,flag:s}}})),o}(this.logger,i)),this.Yi("Identify - Initialization completed from bootstrap"),s()}setForcedStreaming(t){this.Hi=t,this.ts()}setAutomaticStreamingState(t){this.Wi=t,this.ts()}ts(){const t=this.Hi||this.Wi&&void 0===this.Hi;this.Yi(`Updating streaming state. forced(${this.Hi}) automatic(${this.Wi})`),t?this.ss():this.es()}es(){var t;this.updateProcessor&&this.Yi("Stopping update processor."),null===(t=this.updateProcessor)||void 0===t||t.close(),this.updateProcessor=void 0}ss(){this.updateProcessor?this.Yi("Update processor already active. Not changing state."):this.context?(this.Yi("Starting update processor."),this.ns(this.context)):this.Yi("Context not set, not starting update processor.")}ns(t,i,s){var e;const n=y.toLDContext(t);null===(e=this.updateProcessor)||void 0===e||e.close();const r=mt(JSON.stringify(y.toLDContext(t)),this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Zi);this.createStreamingProcessor(n,t,r,i,s),this.updateProcessor.start()}}function Ei(t){const i=mi("visibilitychange",(()=>{"hidden"===(gi()?document.visibilityState:"visibile")&&t()})),s=bi("pagehide",t);return()=>{i(),s()}}function Si(t){if("string"!=typeof t)throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Di(t,i){const s=[];return i.forEach((i=>{let e=t.target;const{selector:n}=i,r=function(t){if(gi())return document.querySelectorAll(t)}(n);for(;e&&(null==r?void 0:r.length);){for(let t=0;t<r.length;t+=1)if(e===r[t]){s.push(i);break}e=e.parentNode}})),s}class Oi{constructor(t,i){const s=t.filter((t=>{var i;return null===(i=t.urls)||void 0===i?void 0:i.some((t=>function(t,i,s,e){const n=("substring"!==t.kind&&"regex"!==t.kind||!e.includes("/")?i.replace(e,""):i).replace(s,"");switch(t.kind){case"exact":return new RegExp(`^${Si(t.url)}/?$`).test(i);case"canonical":return new RegExp(`^${Si(t.url)}/?$`).test(n);case"substring":return new RegExp(`.*${Si(t.substring)}.*$`).test(n);case"regex":return new RegExp(t.pattern).test(n);default:return!1}}(t,ki(),wi()?window.location.search:"",wi()?window.location.hash:"")))})),e=s.filter((t=>"pageview"===t.kind)),n=s.filter((t=>"click"===t.kind));if(e.forEach((t=>i(t))),n.length){const t=t=>{Di(t,n).forEach((t=>{i(t)}))};this.rs=mi("click",t)}}close(){var t;null===(t=this.rs)||void 0===t||t.call(this)}}class xi{constructor(t){this.hs=ki();const i=()=>{const i=ki();i!==this.hs&&(this.hs=i,t())};this.cs=setInterval(i,300);const s=bi("popstate",i);this.us=()=>{s()}}close(){var t;this.cs&&clearInterval(this.cs),null===(t=this.us)||void 0===t||t.call(this)}}class _i{constructor(t,i,s,e,n,r=t=>new xi(t)){this.W=i,this.ls=e,this.ds=n,this.fs=[],this.vs=!1,this.ps=`${s}/sdk/goals/${t}`,this.ys=r((()=>{this.gs()}))}async initialize(){await this.ws(),this.gs()}startTracking(){this.vs=!0,this.gs()}gs(){var t;this.vs&&(null===(t=this.bs)||void 0===t||t.close(),this.fs&&this.fs.length&&(this.bs=new Oi(this.fs,(t=>{this.ds(ki(),t)}))))}async ws(){try{const t=await this.W.fetch(this.ps);this.fs=await t.json()}catch(t){this.ls(new B(`Encountered error fetching goals: ${t}`))}}close(){var t,i;null===(t=this.ys)||void 0===t||t.close(),null===(i=this.bs)||void 0===i||i.close()}}const Ii={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0},Ni={fetchGoals:a.Boolean,eventUrlTransformer:a.Function,streaming:a.Boolean};class Ri{constructor(t,i){switch(this.ks=t,this.$s=[],i){case"sha1":this.Es="SHA-1";break;case"sha256":this.Es="SHA-256";break;default:throw new Error(`Algorithm is not supported ${i}`)}}async asyncDigest(t){const i=this.$s.join(""),s=(new TextEncoder).encode(i),e=await this.ks.subtle.digest(this.Es,s);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(e)));case"hex":return[...new Uint8Array(e)].map((t=>t.toString(16).padStart(2,"0"))).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.$s.push(t),this}}const Ci={start:0,end:3},ji={start:4,end:5},Ti={start:6,end:7},Ai={start:8,end:8},Pi={start:9,end:9},Mi={start:10,end:15};function Li(t,i){let s="";for(let e=i.start;e<=i.end;e+=1)s+=t[e].toString(16).padStart(2,"0");return s}function Ji(){const t=function(){if(crypto&&crypto.getRandomValues){const t=new Uint8Array(16);return crypto.getRandomValues(t),[...t.values()]}const t=[];for(let i=0;i<16;i+=1)t.push(Math.floor(256*Math.random()));return t}();return function(t){return t[Ai.start]=191&t[Ai.start]|128,t[Ti.start]=15&t[Ti.start]|64,`${Li(t,Ci)}-${Li(t,ji)}-${Li(t,Ti)}-${Li(t,Ai)}${Li(t,Pi)}-${Li(t,Mi)}`}(t)}class Ui{createHash(t){return new Ri(function(){if(void 0!==typeof crypto)return crypto;throw Error("Access to a web crypto API is required")}(),t)}randomUUID(){return void 0!==typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():Ji()}}class Ki{btoa(t){return function(t){const i=Array.from(t,(t=>String.fromCodePoint(t))).join("");return btoa(i)}((new TextEncoder).encode(t))}}class Fi{platformData(){return{name:"JS"}}sdkData(){return{name:"@launchdarkly/js-client-sdk",version:"0.0.0",userAgentBase:"JSClient"}}}class Vi{constructor(t,i,s=Math.random){this.Ss=i,this.Ds=s,this.Os=0,this.xs=Math.max(1,t),this._s=Math.ceil(Math.log2(3e4/this.xs))}Is(){const t=Math.min(this.Os,this._s),i=this.xs*2**t;return Math.min(i,3e4)}Ns(t){return t-Math.trunc(.5*this.Ds()*t)}success(t=Date.now()){this.Rs=t}fail(t=Date.now()){void 0!==this.Rs&&t-this.Rs>this.Ss&&(this.Os=0),this.Rs=void 0;const i=this.Ns(this.Is());return this.Os+=1,i}}class qi{constructor(t,i){this.ps=t,this.Tt={},this.Is=new Vi(i.initialRetryDelayMillis,i.retryResetIntervalMillis),this.Cs=i.errorFilter,this.js()}js(){this.Ts=new EventSource(this.ps),this.Ts.onopen=()=>{var t;this.Is.success(),null===(t=this.onopen)||void 0===t||t.call(this)},this.Ts.onerror=t=>{var i;this.As(t),null===(i=this.onerror)||void 0===i||i.call(this,t)},Object.entries(this.Tt).forEach((([t,i])=>{i.forEach((i=>{var s;null===(s=this.Ts)||void 0===s||s.addEventListener(t,i)}))}))}addEventListener(t,i){var s,e,n;null!==(s=(n=this.Tt)[t])&&void 0!==s||(n[t]=[]),this.Tt[t].push(i),null===(e=this.Ts)||void 0===e||e.addEventListener(t,i)}close(){var t,i;clearTimeout(this.Ps),this.Ps=void 0,null===(t=this.Ts)||void 0===t||t.close(),null===(i=this.onclose)||void 0===i||i.call(this)}Ms(t){var i;null===(i=this.onretrying)||void 0===i||i.call(this,{delayMillis:t}),this.Ps=setTimeout((()=>{this.js()}),t)}As(t){this.close(),t.status&&"number"==typeof t.status&&!this.Cs(t)||this.Ms(this.Is.fail())}}class Gi{fetch(t,i){return fetch(t,i)}createEventSource(t,i){return new qi(t,i)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}}class Bi{constructor(t){this.V=t}async clear(t){var i;try{localStorage.removeItem(t)}catch(s){null===(i=this.V)||void 0===i||i.error(`Error clearing key from localStorage: ${t}, reason: ${s}`)}}async get(t){var i;try{const i=localStorage.getItem(t);return null!=i?i:null}catch(s){return null===(i=this.V)||void 0===i||i.error(`Error getting key from localStorage: ${t}, reason: ${s}`),null}}async set(t,i){var s;try{localStorage.setItem(t,i)}catch(i){null===(s=this.V)||void 0===s||s.error(`Error setting key in localStorage: ${t}, reason: ${i}`)}}}class zi{constructor(t){this.encoding=new Ki,this.info=new Fi,this.crypto=new Ui,this.requests=new Gi,"undefined"!=typeof localStorage&&(this.storage=new Bi(t))}}class Hi extends li{constructor(t,i,s={},e){var n;const{logger:r,debug:o}=s,a=null!=r?r:T({debug:o?console.debug:()=>{},info:console.info,warn:console.warn,error:console.error}),h=null!==(n=s.baseUri)&&void 0!==n?n:"https://clientsdk.launchdarkly.com",c=null!=e?e:new zi(a),u=function(t,i){const s=Object.assign({},Ii);return function(t){var i;null!==(i=t.flushInterval)&&void 0!==i||(t.flushInterval=2)}(s),Object.entries(Ni).forEach((e=>{const[n,r]=e,o=t[n];void 0!==o&&(r.is(o)?s[n]=o:i.warn(A.wrongOptionType(n,r.getType(),typeof o)))})),s}(s,a),{eventUrlTransformer:l}=u;super(t,i,c,function(t){const i=Object.assign({},t);return Object.keys(Ii).forEach((t=>{delete i[t]})),i}(Object.assign(Object.assign({},s),{logger:a})),((i,s,e,n,r)=>new $i(c,i,t,s,u,(()=>({pathGet:(i,s)=>`/sdk/evalx/${t}/contexts/${st(s,i)}`,pathReport:(i,s)=>`/sdk/evalx/${t}/context`,pathPing(t,i){throw new Error("Ping for polling unsupported.")}})),(()=>({pathGet:(i,s)=>`/eval/${t}/${st(s,i)}`,pathReport:(i,s)=>`/eval/${t}`,pathPing:(i,s)=>`/ping/${t}`})),e,n,r)),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:t=>new yt.InputCustomEvent(t.context,t.key,t.data,t.metricValue,t.samplingRatio,l(ki()))}),this.setEventSendingEnabled(!0,!1),u.fetchGoals&&(this.Ls=new _i(t,c.requests,h,(t=>{a.error(t.message)}),((t,i)=>{const s=this.getInternalContext();if(!s)return;const e=l(t);!function(t){return"click"===t.kind}(i)?this.sendEvent({kind:"pageview",url:e,samplingRatio:1,key:i.key,creationDate:Date.now(),context:s}):this.sendEvent({kind:"click",url:e,samplingRatio:1,key:i.key,creationDate:Date.now(),context:s,selector:i.selector})})),this.Ls.initialize(),u.automaticBackgroundHandling&&Ei((()=>this.flush())))}async identify(t,i){var s;await super.identify(t,i),null===(s=this.Ls)||void 0===s||s.startTracking()}setStreaming(t){this.dataManager.setForcedStreaming(t)}Js(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,i){super.on(t,i),this.Js()}off(t,i){super.off(t,i),this.Js()}}exports.initialize=function(t,i){return new Hi(t,k.Disabled,i)};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|