@launchdarkly/js-client-sdk 0.0.1 → 0.2.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.
Files changed (62) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +1 -0
  3. package/dist/BrowserClient-DTEj396e.d.cts +121 -0
  4. package/dist/BrowserClient-DTEj396e.d.ts +121 -0
  5. package/dist/compat.cjs +1 -0
  6. package/dist/compat.d.cts +180 -0
  7. package/dist/compat.d.ts +180 -0
  8. package/dist/compat.js +1 -0
  9. package/dist/index.cjs +1 -0
  10. package/dist/index.d.cts +36 -0
  11. package/dist/{src/index.d.ts → index.d.ts} +8 -7
  12. package/dist/index.js +1 -0
  13. package/dist/metafile-cjs.json +1 -0
  14. package/dist/metafile-esm.json +1 -0
  15. package/package.json +29 -16
  16. package/dist/index.cjs.js +0 -2
  17. package/dist/index.cjs.js.map +0 -1
  18. package/dist/index.es.js +0 -2
  19. package/dist/index.es.js.map +0 -1
  20. package/dist/src/BrowserApi.d.ts +0 -48
  21. package/dist/src/BrowserApi.d.ts.map +0 -1
  22. package/dist/src/BrowserClient.d.ts +0 -69
  23. package/dist/src/BrowserClient.d.ts.map +0 -1
  24. package/dist/src/BrowserDataManager.d.ts +0 -21
  25. package/dist/src/BrowserDataManager.d.ts.map +0 -1
  26. package/dist/src/BrowserIdentifyOptions.d.ts +0 -23
  27. package/dist/src/BrowserIdentifyOptions.d.ts.map +0 -1
  28. package/dist/src/BrowserStateDetector.d.ts +0 -2
  29. package/dist/src/BrowserStateDetector.d.ts.map +0 -1
  30. package/dist/src/bootstrap.d.ts +0 -5
  31. package/dist/src/bootstrap.d.ts.map +0 -1
  32. package/dist/src/goals/GoalManager.d.ts +0 -20
  33. package/dist/src/goals/GoalManager.d.ts.map +0 -1
  34. package/dist/src/goals/GoalTracker.d.ts +0 -16
  35. package/dist/src/goals/GoalTracker.d.ts.map +0 -1
  36. package/dist/src/goals/Goals.d.ts +0 -33
  37. package/dist/src/goals/Goals.d.ts.map +0 -1
  38. package/dist/src/goals/LocationWatcher.d.ts +0 -6
  39. package/dist/src/goals/LocationWatcher.d.ts.map +0 -1
  40. package/dist/src/index.d.ts.map +0 -1
  41. package/dist/src/options.d.ts +0 -49
  42. package/dist/src/options.d.ts.map +0 -1
  43. package/dist/src/platform/Backoff.d.ts +0 -42
  44. package/dist/src/platform/Backoff.d.ts.map +0 -1
  45. package/dist/src/platform/BrowserCrypto.d.ts +0 -7
  46. package/dist/src/platform/BrowserCrypto.d.ts.map +0 -1
  47. package/dist/src/platform/BrowserEncoding.d.ts +0 -10
  48. package/dist/src/platform/BrowserEncoding.d.ts.map +0 -1
  49. package/dist/src/platform/BrowserHasher.d.ts +0 -10
  50. package/dist/src/platform/BrowserHasher.d.ts.map +0 -1
  51. package/dist/src/platform/BrowserInfo.d.ts +0 -6
  52. package/dist/src/platform/BrowserInfo.d.ts.map +0 -1
  53. package/dist/src/platform/BrowserPlatform.d.ts +0 -10
  54. package/dist/src/platform/BrowserPlatform.d.ts.map +0 -1
  55. package/dist/src/platform/BrowserRequests.d.ts +0 -7
  56. package/dist/src/platform/BrowserRequests.d.ts.map +0 -1
  57. package/dist/src/platform/DefaultBrowserEventSource.d.ts +0 -33
  58. package/dist/src/platform/DefaultBrowserEventSource.d.ts.map +0 -1
  59. package/dist/src/platform/LocalStorage.d.ts +0 -16
  60. package/dist/src/platform/LocalStorage.d.ts.map +0 -1
  61. package/dist/src/platform/randomUuidV4.d.ts +0 -12
  62. package/dist/src/platform/randomUuidV4.d.ts.map +0 -1
@@ -0,0 +1,180 @@
1
+ import { LDContext, LDFlagSet } from '@launchdarkly/js-client-sdk-common';
2
+ import { L as LDClient$1, B as BrowserOptions } from './BrowserClient-DTEj396e.cjs';
3
+
4
+ /**
5
+ * Compatibility interface. This interface extends the base LDCLient interface with functions
6
+ * that improve backwards compatibility.
7
+ *
8
+ * If starting a new project please import the root package instead of `/compat`.
9
+ *
10
+ * In the `launchdarkly-js-client-sdk@3.x` package a number of functions had the return typings
11
+ * incorrect. Any function which optionally returned a promise based on a callback had incorrect
12
+ * typings. Those have been corrected in this implementation.
13
+ */
14
+ interface LDClient extends Omit<LDClient$1, 'close' | 'flush' | 'identify'> {
15
+ /**
16
+ * Identifies a context to LaunchDarkly.
17
+ *
18
+ * Unlike the server-side SDKs, the client-side JavaScript SDKs maintain a current context state,
19
+ * which is set at initialization time. You only need to call `identify()` if the context has changed
20
+ * since then.
21
+ *
22
+ * Changing the current context also causes all feature flag values to be reloaded. Until that has
23
+ * finished, calls to {@link variation} will still return flag values for the previous context. You can
24
+ * use a callback or a Promise to determine when the new flag values are available.
25
+ *
26
+ * @param context
27
+ * The context properties. Must contain at least the `key` property.
28
+ * @param hash
29
+ * The signed context key if you are using [Secure Mode](https://docs.launchdarkly.com/sdk/features/secure-mode#configuring-secure-mode-in-the-javascript-client-side-sdk).
30
+ * @param onDone
31
+ * A function which will be called as soon as the flag values for the new context are available,
32
+ * with two parameters: an error value (if any), and an {@link LDFlagSet} containing the new values
33
+ * (which can also be obtained by calling {@link variation}). If the callback is omitted, you will
34
+ * receive a Promise instead.
35
+ * @returns
36
+ * If you provided a callback, then nothing. Otherwise, a Promise which resolve once the flag
37
+ * values for the new context are available, providing an {@link LDFlagSet} containing the new values
38
+ * (which can also be obtained by calling {@link variation}).
39
+ */
40
+ identify(context: LDContext, hash?: string, onDone?: (err: Error | null, flags: LDFlagSet | null) => void): Promise<LDFlagSet> | undefined;
41
+ /**
42
+ * Returns a Promise that tracks the client's initialization state.
43
+ *
44
+ * The Promise will be resolved if the client successfully initializes, or rejected if client
45
+ * initialization has irrevocably failed (for instance, if it detects that the SDK key is invalid).
46
+ *
47
+ * ```
48
+ * // using async/await
49
+ * try {
50
+ * await client.waitForInitialization(5);
51
+ * doSomethingWithSuccessfullyInitializedClient();
52
+ * } catch (err) {
53
+ * doSomethingForFailedStartup(err);
54
+ * }
55
+ * ```
56
+ *
57
+ * It is important that you handle the rejection case; otherwise it will become an unhandled Promise
58
+ * rejection, which is a serious error on some platforms. The Promise is not created unless you
59
+ * request it, so if you never call `waitForInitialization()` then you do not have to worry about
60
+ * unhandled rejections.
61
+ *
62
+ * Note that you can also use event listeners ({@link on}) for the same purpose: the event `"initialized"`
63
+ * indicates success, and `"failed"` indicates failure.
64
+ *
65
+ * @param timeout
66
+ * The amount of time, in seconds, to wait for initialization before rejecting the promise.
67
+ * Using a large timeout is not recommended. If you use a large timeout and await it, then
68
+ * any network delays will cause your application to wait a long time before
69
+ * continuing execution.
70
+ *
71
+ * If no timeout is specified, then the returned promise will only be resolved when the client
72
+ * successfully initializes or initialization fails.
73
+ *
74
+ * @returns
75
+ * A Promise that will be resolved if the client initializes successfully, or rejected if it
76
+ * fails or the specified timeout elapses.
77
+ */
78
+ waitForInitialization(timeout?: number): Promise<void>;
79
+ /**
80
+ * Returns a Promise that tracks the client's initialization state.
81
+ *
82
+ * The returned Promise will be resolved once the client has either successfully initialized
83
+ * or failed to initialize (e.g. due to an invalid environment key or a server error). It will
84
+ * never be rejected.
85
+ *
86
+ * ```
87
+ * // using async/await
88
+ * await client.waitUntilReady();
89
+ * doSomethingWithClient();
90
+ * ```
91
+ *
92
+ * If you want to distinguish between these success and failure conditions, use
93
+ * {@link waitForInitialization} instead.
94
+ *
95
+ * If you prefer to use event listeners ({@link on}) rather than Promises, you can listen on the
96
+ * client for a `"ready"` event, which will be fired in either case.
97
+ *
98
+ * @returns
99
+ * A Promise that will be resolved once the client is no longer trying to initialize.
100
+ * @deprecated Please use {@link waitForInitialization} instead. This method will always
101
+ * cause a warning to be logged because it is implemented via waitForInitialization.
102
+ */
103
+ waitUntilReady(): Promise<void>;
104
+ /**
105
+ * Shuts down the client and releases its resources, after delivering any pending analytics
106
+ * events.
107
+ *
108
+ * @param onDone
109
+ * A function which will be called when the operation completes. If omitted, you
110
+ * will receive a Promise instead.
111
+ *
112
+ * @returns
113
+ * If you provided a callback, then nothing. Otherwise, a Promise which resolves once
114
+ * closing is finished. It will never be rejected.
115
+ */
116
+ close(onDone?: () => void): Promise<void> | undefined;
117
+ /**
118
+ * Flushes all pending analytics events.
119
+ *
120
+ * Normally, batches of events are delivered in the background at intervals determined by the
121
+ * `flushInterval` property of {@link LDOptions}. Calling `flush()` triggers an immediate delivery.
122
+ *
123
+ * @param onDone
124
+ * A function which will be called when the flush completes. If omitted, you
125
+ * will receive a Promise instead.
126
+ *
127
+ * @returns
128
+ * If you provided a callback, then nothing. Otherwise, a Promise which resolves once
129
+ * flushing is finished. Note that the Promise will be rejected if the HTTP request
130
+ * fails, so be sure to attach a rejection handler to it.
131
+ */
132
+ flush(onDone?: () => void): Promise<void> | undefined;
133
+ }
134
+
135
+ /**
136
+ * This module provides a compatibility layer which emulates the interface used
137
+ * in the launchdarkly-js-client 3.x package.
138
+ *
139
+ * Some code changes may still be required, for example {@link LDOptions} removes
140
+ * support for some previously available options.
141
+ */
142
+
143
+ /**
144
+ * Creates an instance of the LaunchDarkly client. This version of initialization is for
145
+ * improved backwards compatibility. In general the `initialize` function from the root packge
146
+ * should be used instead of the one in the `/compat` module.
147
+ *
148
+ * The client will begin attempting to connect to LaunchDarkly as soon as it is created. To
149
+ * determine when it is ready to use, call {@link LDClient.waitForInitialization}, or register an
150
+ * event listener for the `"ready"` event using {@link LDClient.on}.
151
+ *
152
+ * Example:
153
+ * import { initialize } from '@launchdarkly/js-client-sdk/compat';
154
+ * const client = initialize(envKey, context, options);
155
+ *
156
+ * Note: The `compat` module minimizes compatibility breaks, but not all functionality is directly
157
+ * equivalent to the previous version.
158
+ *
159
+ * LDOptions are where the primary differences are. By default the new SDK implementation will
160
+ * generally use localStorage to cache flags. This can be disabled by setting the
161
+ * `maxCachedContexts` to 0.
162
+ *
163
+ * This does allow combinations that were not possible before. For insance an initial context
164
+ * could be identified using bootstrap, and a second context without bootstrap, and the second
165
+ * context could cache flags in local storage. For more control the primary module can be used
166
+ * instead of this `compat` module (for instance bootstrap can be provided per identify call in
167
+ * the primary module).
168
+ *
169
+ * @param envKey
170
+ * The environment ID.
171
+ * @param context
172
+ * The initial context properties. These can be changed later with {@link LDClient.identify}.
173
+ * @param options
174
+ * Optional configuration settings.
175
+ * @return
176
+ * The new client instance.
177
+ */
178
+ declare function initialize(envKey: string, context: LDContext, options?: BrowserOptions): LDClient;
179
+
180
+ export { initialize };
@@ -0,0 +1,180 @@
1
+ import { LDContext, LDFlagSet } from '@launchdarkly/js-client-sdk-common';
2
+ import { L as LDClient$1, B as BrowserOptions } from './BrowserClient-DTEj396e.js';
3
+
4
+ /**
5
+ * Compatibility interface. This interface extends the base LDCLient interface with functions
6
+ * that improve backwards compatibility.
7
+ *
8
+ * If starting a new project please import the root package instead of `/compat`.
9
+ *
10
+ * In the `launchdarkly-js-client-sdk@3.x` package a number of functions had the return typings
11
+ * incorrect. Any function which optionally returned a promise based on a callback had incorrect
12
+ * typings. Those have been corrected in this implementation.
13
+ */
14
+ interface LDClient extends Omit<LDClient$1, 'close' | 'flush' | 'identify'> {
15
+ /**
16
+ * Identifies a context to LaunchDarkly.
17
+ *
18
+ * Unlike the server-side SDKs, the client-side JavaScript SDKs maintain a current context state,
19
+ * which is set at initialization time. You only need to call `identify()` if the context has changed
20
+ * since then.
21
+ *
22
+ * Changing the current context also causes all feature flag values to be reloaded. Until that has
23
+ * finished, calls to {@link variation} will still return flag values for the previous context. You can
24
+ * use a callback or a Promise to determine when the new flag values are available.
25
+ *
26
+ * @param context
27
+ * The context properties. Must contain at least the `key` property.
28
+ * @param hash
29
+ * The signed context key if you are using [Secure Mode](https://docs.launchdarkly.com/sdk/features/secure-mode#configuring-secure-mode-in-the-javascript-client-side-sdk).
30
+ * @param onDone
31
+ * A function which will be called as soon as the flag values for the new context are available,
32
+ * with two parameters: an error value (if any), and an {@link LDFlagSet} containing the new values
33
+ * (which can also be obtained by calling {@link variation}). If the callback is omitted, you will
34
+ * receive a Promise instead.
35
+ * @returns
36
+ * If you provided a callback, then nothing. Otherwise, a Promise which resolve once the flag
37
+ * values for the new context are available, providing an {@link LDFlagSet} containing the new values
38
+ * (which can also be obtained by calling {@link variation}).
39
+ */
40
+ identify(context: LDContext, hash?: string, onDone?: (err: Error | null, flags: LDFlagSet | null) => void): Promise<LDFlagSet> | undefined;
41
+ /**
42
+ * Returns a Promise that tracks the client's initialization state.
43
+ *
44
+ * The Promise will be resolved if the client successfully initializes, or rejected if client
45
+ * initialization has irrevocably failed (for instance, if it detects that the SDK key is invalid).
46
+ *
47
+ * ```
48
+ * // using async/await
49
+ * try {
50
+ * await client.waitForInitialization(5);
51
+ * doSomethingWithSuccessfullyInitializedClient();
52
+ * } catch (err) {
53
+ * doSomethingForFailedStartup(err);
54
+ * }
55
+ * ```
56
+ *
57
+ * It is important that you handle the rejection case; otherwise it will become an unhandled Promise
58
+ * rejection, which is a serious error on some platforms. The Promise is not created unless you
59
+ * request it, so if you never call `waitForInitialization()` then you do not have to worry about
60
+ * unhandled rejections.
61
+ *
62
+ * Note that you can also use event listeners ({@link on}) for the same purpose: the event `"initialized"`
63
+ * indicates success, and `"failed"` indicates failure.
64
+ *
65
+ * @param timeout
66
+ * The amount of time, in seconds, to wait for initialization before rejecting the promise.
67
+ * Using a large timeout is not recommended. If you use a large timeout and await it, then
68
+ * any network delays will cause your application to wait a long time before
69
+ * continuing execution.
70
+ *
71
+ * If no timeout is specified, then the returned promise will only be resolved when the client
72
+ * successfully initializes or initialization fails.
73
+ *
74
+ * @returns
75
+ * A Promise that will be resolved if the client initializes successfully, or rejected if it
76
+ * fails or the specified timeout elapses.
77
+ */
78
+ waitForInitialization(timeout?: number): Promise<void>;
79
+ /**
80
+ * Returns a Promise that tracks the client's initialization state.
81
+ *
82
+ * The returned Promise will be resolved once the client has either successfully initialized
83
+ * or failed to initialize (e.g. due to an invalid environment key or a server error). It will
84
+ * never be rejected.
85
+ *
86
+ * ```
87
+ * // using async/await
88
+ * await client.waitUntilReady();
89
+ * doSomethingWithClient();
90
+ * ```
91
+ *
92
+ * If you want to distinguish between these success and failure conditions, use
93
+ * {@link waitForInitialization} instead.
94
+ *
95
+ * If you prefer to use event listeners ({@link on}) rather than Promises, you can listen on the
96
+ * client for a `"ready"` event, which will be fired in either case.
97
+ *
98
+ * @returns
99
+ * A Promise that will be resolved once the client is no longer trying to initialize.
100
+ * @deprecated Please use {@link waitForInitialization} instead. This method will always
101
+ * cause a warning to be logged because it is implemented via waitForInitialization.
102
+ */
103
+ waitUntilReady(): Promise<void>;
104
+ /**
105
+ * Shuts down the client and releases its resources, after delivering any pending analytics
106
+ * events.
107
+ *
108
+ * @param onDone
109
+ * A function which will be called when the operation completes. If omitted, you
110
+ * will receive a Promise instead.
111
+ *
112
+ * @returns
113
+ * If you provided a callback, then nothing. Otherwise, a Promise which resolves once
114
+ * closing is finished. It will never be rejected.
115
+ */
116
+ close(onDone?: () => void): Promise<void> | undefined;
117
+ /**
118
+ * Flushes all pending analytics events.
119
+ *
120
+ * Normally, batches of events are delivered in the background at intervals determined by the
121
+ * `flushInterval` property of {@link LDOptions}. Calling `flush()` triggers an immediate delivery.
122
+ *
123
+ * @param onDone
124
+ * A function which will be called when the flush completes. If omitted, you
125
+ * will receive a Promise instead.
126
+ *
127
+ * @returns
128
+ * If you provided a callback, then nothing. Otherwise, a Promise which resolves once
129
+ * flushing is finished. Note that the Promise will be rejected if the HTTP request
130
+ * fails, so be sure to attach a rejection handler to it.
131
+ */
132
+ flush(onDone?: () => void): Promise<void> | undefined;
133
+ }
134
+
135
+ /**
136
+ * This module provides a compatibility layer which emulates the interface used
137
+ * in the launchdarkly-js-client 3.x package.
138
+ *
139
+ * Some code changes may still be required, for example {@link LDOptions} removes
140
+ * support for some previously available options.
141
+ */
142
+
143
+ /**
144
+ * Creates an instance of the LaunchDarkly client. This version of initialization is for
145
+ * improved backwards compatibility. In general the `initialize` function from the root packge
146
+ * should be used instead of the one in the `/compat` module.
147
+ *
148
+ * The client will begin attempting to connect to LaunchDarkly as soon as it is created. To
149
+ * determine when it is ready to use, call {@link LDClient.waitForInitialization}, or register an
150
+ * event listener for the `"ready"` event using {@link LDClient.on}.
151
+ *
152
+ * Example:
153
+ * import { initialize } from '@launchdarkly/js-client-sdk/compat';
154
+ * const client = initialize(envKey, context, options);
155
+ *
156
+ * Note: The `compat` module minimizes compatibility breaks, but not all functionality is directly
157
+ * equivalent to the previous version.
158
+ *
159
+ * LDOptions are where the primary differences are. By default the new SDK implementation will
160
+ * generally use localStorage to cache flags. This can be disabled by setting the
161
+ * `maxCachedContexts` to 0.
162
+ *
163
+ * This does allow combinations that were not possible before. For insance an initial context
164
+ * could be identified using bootstrap, and a second context without bootstrap, and the second
165
+ * context could cache flags in local storage. For more control the primary module can be used
166
+ * instead of this `compat` module (for instance bootstrap can be provided per identify call in
167
+ * the primary module).
168
+ *
169
+ * @param envKey
170
+ * The environment ID.
171
+ * @param context
172
+ * The initial context properties. These can be changed later with {@link LDClient.identify}.
173
+ * @param options
174
+ * Optional configuration settings.
175
+ * @return
176
+ * The new client instance.
177
+ */
178
+ declare function initialize(envKey: string, context: LDContext, options?: BrowserOptions): LDClient;
179
+
180
+ export { initialize };
package/dist/compat.js ADDED
@@ -0,0 +1 @@
1
+ var Li=Object.defineProperty,Ci=Object.defineProperties;var Ai=Object.getOwnPropertyDescriptors;var ft=Object.getOwnPropertySymbols;var Ue=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var Fe=(n,t,e)=>t in n?Li(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,p=(n,t)=>{for(var e in t||(t={}))Ue.call(t,e)&&Fe(n,e,t[e]);if(ft)for(var e of ft(t))Ve.call(t,e)&&Fe(n,e,t[e]);return n},D=(n,t)=>Ci(n,Ai(t));var Ut=(n,t)=>{var e={};for(var i in n)Ue.call(n,i)&&t.indexOf(i)<0&&(e[i]=n[i]);if(n!=null&&ft)for(var i of ft(n))t.indexOf(i)<0&&Ve.call(n,i)&&(e[i]=n[i]);return e};function Ti(n){return`/${n.replace(/~/g,"~0").replace(/\//g,"~1")}`}function Ke(n){return n.indexOf("~")?n.replace(/~1/g,"/").replace(/~0/g,"~"):n}function Oi(n){return(n.startsWith("/")?n.substring(1):n).split("/").map(e=>Ke(e))}function Ni(n){return!n.startsWith("/")}function $i(n){return!n.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var A=class{constructor(t,e=!1){if(e){let i=t;this.h=[i],this.isValid=i!=="",this.redactionName=i.startsWith("/")?Ti(i):i}else{if(this.redactionName=t,t===""||t==="/"||!$i(t)){this.isValid=!1,this.h=[];return}Ni(t)?this.h=[t]:t.indexOf("/",1)<0?this.h=[Ke(t.slice(1))]:this.h=Oi(t),this.h[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{h:e,isValid:i}=this;if(!i)return;let r=t;for(let s=0;s<e.length;s+=1){let a=e[s];if(r!=null&&Object.prototype.hasOwnProperty.call(r,a)&&typeof r=="object"&&!Array.isArray(r))r=r[a];else return}return r}getComponent(t){return this.h[t]}get depth(){return this.h.length}get isKind(){return this.h.length===1&&this.h[0]==="kind"}compare(t){return this.depth===t.depth&&this.h.every((e,i)=>e===t.getComponent(i))}};A.InvalidReference=new A("");var _t=class{is(t){if(Array.isArray(t))return!1;let i=typeof t;return i==="function"||i==="object"}getType(){return"factory method or object"}},T=class{constructor(t,e){this.dt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.dt}},mt=class{constructor(t,e){this.dt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.dt}},B=class extends T{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},yt=class extends T{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},Ht=class{is(t){return typeof t=="function"}getType(){return"function"}},Bt=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},Ri=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,Kt=class{is(t){return typeof t=="number"||typeof t=="string"&&Ri.test(t)}getType(){return"date"}},Gt=class extends yt{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},u=class{static createTypeArray(t,e){return new mt(t,e)}static numberWithMin(t){return new B(t)}static stringMatchingRegex(t){return new yt(t)}};u.String=new T("string","");u.Number=new T("number",0);u.ObjectOrFactory=new _t;u.Object=new T("object",{});u.StringArray=new mt("string[]","");u.Boolean=new T("boolean",!0);u.Function=new Ht;u.Date=new Kt;u.Kind=new Gt;u.NullableBoolean=new Bt;function Ge(n){return"kind"in n?u.String.is(n.kind)&&n.kind!=="multi":!1}function qe(n){return"kind"in n?u.String.is(n.kind)&&n.kind==="multi":!1}function Je(n){return!("kind"in n)||n.kind===null||n.kind===void 0}var qt="user";function je(n){return n.includes("%")||n.includes(":")?n.replace(/%/g,"%25").replace(/:/g,"%3A"):n}function Pi(n){return n&&u.Object.is(n)}function _e(n){return u.Kind.is(n)}function He(n){return u.String.is(n)&&n!==""}function Vt(n,t=!1){return n?n.map(e=>new A(e,t)):[]}function Ii(n){return n!=null}function Mi(n){let t=D(p({},n.custom||[]),{kind:"user",key:String(n.key)});if(Ii(n.anonymous)){let e=!!n.anonymous;delete t.anonymous,t.anonymous=e}return n.name!==null&&n.name!==void 0&&(t.name=n.name),n.ip!==null&&n.ip!==void 0&&(t.ip=n.ip),n.firstName!==null&&n.firstName!==void 0&&(t.firstName=n.firstName),n.lastName!==null&&n.lastName!==void 0&&(t.lastName=n.lastName),n.email!==null&&n.email!==void 0&&(t.email=n.email),n.avatar!==null&&n.avatar!==void 0&&(t.avatar=n.avatar),n.country!==null&&n.country!==void 0&&(t.country=n.country),n.privateAttributeNames!==null&&n.privateAttributeNames!==void 0&&(t._meta={privateAttributes:n.privateAttributeNames}),t}var b=class n{constructor(t,e,i){this.b=!1,this.Y=!1,this.Gt=!1,this.L={},this.kind=e,this.valid=t,this.message=i}static y(t,e){return new n(!1,t,e)}static Ae(t,e){if(!(!e||!t.isValid))return t.depth===1&&t.getComponent(0)==="anonymous"?!!(e!=null&&e.anonymous):t.get(e)}qt(t){if(this.b)return this.L[t];if(this.kind===t)return this.C}static Te(t){let e=Object.keys(t).filter(c=>c!=="kind"),i=e.every(_e);if(!e.length)return n.y("multi","A multi-kind context must contain at least one kind");if(!i)return n.y("multi","Context contains invalid kinds");let r={},s=!0,a=e.reduce((c,l)=>{var d;let h=t[l];return Pi(h)?(c[l]=h,r[l]=Vt((d=h._meta)==null?void 0:d.privateAttributes)):s=!1,c},{});if(!s)return n.y("multi","Context contained contexts that were not objects");if(!Object.values(a).every(c=>He(c.key)))return n.y("multi","Context contained invalid keys");if(e.length===1){let c=e[0],l=new n(!0,c);return l.C=D(p({},a[c]),{kind:c}),l.X=r,l.Y=c==="user",l}let o=new n(!0,t.kind);return o.L=a,o.X=r,o.b=!0,o}static Oe(t){var c;let{key:e,kind:i}=t,r=_e(i),s=He(e);if(!r)return n.y(i!=null?i:"unknown","The kind was not valid for the context");if(!s)return n.y(i,"The key for the context was not valid");let a=Vt((c=t._meta)==null?void 0:c.privateAttributes),o=new n(!0,i);return o.Y=i==="user",o.C=t,o.X={[i]:a},o}static Ne(t){if(!(t.key!==void 0&&t.key!==null))return n.y("user","The key for the context was not valid");let i=new n(!0,"user");return i.Y=!0,i.Gt=!0,i.C=Mi(t),i.X={user:Vt(t.privateAttributeNames,!0)},i}static fromLDContext(t){return t?Ge(t)?n.Oe(t):qe(t)?n.Te(t):Je(t)?n.Ne(t):n.y("unknown","Context was not of a valid kind"):n.y("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;let e=t.getContexts();if(!t.b)return e[0][1];let i={kind:"multi"};return e.forEach(r=>{let s=r[0],a=r[1];i[s]=a}),i}valueForKind(t,e=qt){return t.isKind?this.kinds:n.Ae(t,this.qt(e))}key(t=qt){var e;return(e=this.qt(t))==null?void 0:e.key}get isMultiKind(){return this.b}get canonicalKey(){return this.Y?this.C.key:this.b?Object.keys(this.L).sort().map(t=>`${t}:${je(this.L[t].key)}`).join(":"):`${this.kind}:${je(this.C.key)}`}get kinds(){return this.b?Object.keys(this.L):[this.kind]}get kindsAndKeys(){return this.b?Object.entries(this.L).reduce((t,[e,i])=>(t[e]=i.key,t),{}):{[this.kind]:this.C.key}}privateAttributes(t){var e;return((e=this.X)==null?void 0:e[t])||[]}getContexts(){return this.b?Object.entries(this.L):[[this.kind,this.C]]}get legacy(){return this.Gt}};b.UserKind=qt;var Fi=["key","kind","_meta","anonymous"].map(n=>new A(n,!0)),Ui=["name","ip","firstName","lastName","email","avatar","country"];function Vi(n,t){return n.depth===t.length&&t.every((e,i)=>e===n.getComponent(i))}function ji(n,t){let e=[],i={},r=[];for(e.push(...Object.keys(n).map(s=>({key:s,ptr:[s],source:n,parent:i,visited:[n]})));e.length;){let s=e.pop(),a=t.find(o=>Vi(o,s.ptr));if(a)r.push(a.redactionName);else{let o=s.source[s.key];o===null?s.parent[s.key]=o:Array.isArray(o)?s.parent[s.key]=[...o]:typeof o=="object"?s.visited.includes(o)||(s.parent[s.key]={},e.push(...Object.keys(o).map(c=>({key:c,ptr:[...s.ptr,c],source:o,parent:s.parent[s.key],visited:[...s.visited,o]})))):s.parent[s.key]=o}}return{cloned:i,excluded:r.sort()}}var Jt=class{constructor(t,e){this.$e=t,this.Re=e}filter(t,e=!1){let i=t.getContexts();if(i.length===1)return this.Jt(t,i[0][1],i[0][0],e);let r={kind:"multi"};return i.forEach(([s,a])=>{r[s]=this.Jt(t,a,s,e)}),r}Pe(t,e,i,r){return(r?Object.keys(e).map(s=>new A(s,!0)):[...this.Re,...t.privateAttributes(i)]).filter(s=>!Fi.some(a=>a.compare(s)))}Jt(t,e,i,r){let s=this.$e||r&&e.anonymous===!0,{cloned:a,excluded:o}=ji(e,this.Pe(t,e,i,s));return t.legacy&&Ui.forEach(c=>{c in a&&(a[c]=String(a[c]))}),o.length&&(a._meta||(a._meta={}),a._meta.redactedAttributes=o),a._meta&&(delete a._meta.privateAttributes,Object.keys(a._meta).length===0&&delete a._meta),a}},v;(function(n){n.Unknown="UNKNOWN",n.NetworkError="NETWORK_ERROR",n.ErrorResponse="ERROR_RESPONSE",n.InvalidData="INVALID_DATA"})(v||(v={}));var P=class extends Error{constructor(t,e,i,r=!0){super(e),this.kind=t,this.status=i,this.name="LaunchDarklyPollingError",this.recoverable=r}},S=class extends Error{constructor(t,e,i,r=!0){super(e),this.kind=t,this.code=i,this.name="LaunchDarklyStreamingError",this.recoverable=r}},U;(function(n){n[n.Disabled=0]="Disabled",n[n.Enabled=1]="Enabled"})(U||(U={}));var V;(function(n){n[n.AnalyticsEvents=0]="AnalyticsEvents",n[n.DiagnosticEvent=1]="DiagnosticEvent"})(V||(V={}));var R;(function(n){n[n.Succeeded=0]="Succeeded",n[n.Failed=1]="Failed",n[n.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(R||(R={}));function F(n){if(typeof n=="string")return n;if(n===void 0)return"undefined";if(n===null)return"null";if(Object.prototype.hasOwnProperty.call(n,"toString"))try{return n.toString()}catch(t){}if(typeof n=="bigint")return`${n}n`;try{return JSON.stringify(n)}catch(t){return t instanceof TypeError&&t.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function _i(n){return typeof n=="symbol"?"NaN":typeof n=="bigint"?`${n}n`:String(Number(n))}function Hi(n){return typeof n=="symbol"?"NaN":typeof n=="bigint"?`${n}n`:String(parseInt(n,10))}function Bi(n){return typeof n=="symbol"?"NaN":String(parseFloat(n))}var gt={s:n=>F(n),d:n=>_i(n),i:n=>Hi(n),f:n=>Bi(n),j:n=>F(n),o:n=>F(n),O:n=>F(n),c:()=>""};function zt(...n){var e;let t=n.shift();if(u.String.is(t)){let i="",r=0;for(;r<t.length;){let s=t.charAt(r);if(s==="%"){if(r+1<t.length){let o=t.charAt(r+1);if(o in gt&&n.length){let c=n.shift();i+=(e=gt[o])==null?void 0:e.call(gt,c)}else o==="%"?i+="%":i+=`%${o}`;r+=2}}else i+=s,r+=1}return n.length&&(i.length&&(i+=" "),i+=n.map(F).join(" ")),i}return n.map(F).join(" ")}var M={debug:0,info:1,warn:2,error:3,none:4},Ki=["debug","info","warn","error","none"],Wt=class n{static get(){return new n({})}constructor(t){var e,i,r;this.Ie=(i=M[(e=t.level)!=null?e:"info"])!=null?i:M.info,this.Me=(r=t.name)!=null?r:"LaunchDarkly",this.zt=t.destination,this.Wt=t.formatter}Fe(...t){var e;try{return this.Wt?(e=this.Wt)==null?void 0:e.call(this,...t):zt(...t)}catch(i){return zt(...t)}}Ue(t){try{this.zt(t)}catch(e){console.error(t)}}v(t,e){if(t>=this.Ie){let i=`${Ki[t]}: [${this.Me}]`;try{this.zt?this.Ue(`${i} ${this.Fe(...e)}`):console.error(...e)}catch(r){console.error(...e)}}}error(...t){this.v(M.error,t)}warn(...t){this.v(M.warn,t)}info(...t){this.v(M.info,t)}debug(...t){this.v(M.debug,t)}},Gi={error:u.Function,warn:u.Function,info:u.Function,debug:u.Function},K=class{constructor(t,e){Object.entries(Gi).forEach(([i,r])=>{if(!r.is(t[i]))throw new Error(`Provided logger instance must support logger.${i}(...) method`)}),this.t=t,this.Ve=e}v(t,e){try{this.t[t](...e)}catch(i){this.Ve[t](...e)}}error(...t){this.v("error",t)}warn(...t){this.v("warn",t)}info(...t){this.v("info",t)}debug(...t){this.v("debug",t)}},z=n=>{let t=new Wt({level:"info",destination:console.error,formatter:zt});return n?new K(n,t):t},w=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,i){return`Config option "${t}" had invalid value of ${e}, using minimum of ${i} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,i){return`Config option "${t}" should be of type ${e}, got ${i}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},qi=/^(\w|\.|-)+$/,Ji=u.stringMatchingRegex(qi),zi={is:(n,t)=>Ji.is(n)?n.length>64?{valid:!1,message:w.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:w.invalidTagValue(t)}},vt=class{constructor(t){let e={},i=t==null?void 0:t.application,r=t==null?void 0:t.logger;i&&Object.entries(i).forEach(([a,o])=>{if(o!=null){let{valid:c,message:l}=zi.is(o,`application.${a}`);c?a==="versionName"?e["application-version-name"]=[o]:e[`application-${a}`]=[o]:r==null||r.warn(l)}});let s=Object.keys(e);s.length&&(this.value=s.sort().flatMap(a=>e[a].sort().map(o=>`${a}/${o}`)).join(" "))}},Et=class{constructor(t,e,i){this.platform=i,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function jt(n){return n.replace(/\/+$/,"")}function oe(n){return n.replace(/^\/+/,"").replace(/\?$/,"")}var I=class n{constructor(t,e,i=n.DEFAULT_EVENTS,r="/bulk",s="/diagnostic",a=!0,o){this.streaming=jt(t),this.polling=jt(e),this.events=jt(i),this.analyticsEventPath=r,this.diagnosticEventPath=s,this.includeAuthorizationHeader=a,this.payloadFilterKey=o}};I.DEFAULT_EVENTS="https://events.launchdarkly.com";function ce(n,t){if(t.length===0)return n;let e=t.map(({key:i,value:r})=>`${i}=${r}`);return`${n}?${e.join("&")}`}function le(n,t,e){let i=oe(t),r=[...e];return n.payloadFilterKey&&r.push({key:"filter",value:n.payloadFilterKey}),ce(`${n.streaming}/${i}`,r)}function ze(n,t,e){let i=oe(t),r=[...e];return n.payloadFilterKey&&r.push({key:"filter",value:n.payloadFilterKey}),ce(`${n.polling}/${i}`,r)}function Be(n,t,e){let i=oe(t);return ce(`${n.events}/${i}`,e)}var G=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},q=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},j=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function W(n){return n>=400&&n<500?n===400||n===408||n===429:!0}function Wi(n){return n===413?!0:W(n)}function We(n,t){let e,i;return{promise:new Promise((s,a)=>{i=s,e=setTimeout(()=>{let o=`${t} timed out after ${n} seconds.`;a(new j(o))},n*1e3)}),cancel:()=>{i(),clearTimeout(e)}}}function ue(n){return n==null?n:JSON.parse(JSON.stringify(n))}function kt(n){return Math.trunc(n*1e3)}var Yi=n=>JSON.stringify(n)==="{}",St=(n,t)=>n&&Object.entries(n).reduce((e,[i,r])=>(r&&!Yi(r)&&!(t!=null&&t.includes(i))&&(e[i]=typeof r=="object"?St(r,t):r),e),{});function H(n,t){if(n===t)return!0;if(n&&t&&typeof n=="object"&&typeof t=="object"){if(n.constructor!==t.constructor)return!1;var e,i,r;if(Array.isArray(n)){if(e=n.length,e!=t.length)return!1;for(i=e;i--!==0;)if(!H(n[i],t[i]))return!1;return!0}if(n instanceof Map&&t instanceof Map){if(n.size!==t.size)return!1;for(i of n.entries())if(!t.has(i[0]))return!1;for(i of n.entries())if(!H(i[1],t.get(i[0])))return!1;return!0}if(n instanceof Set&&t instanceof Set){if(n.size!==t.size)return!1;for(i of n.entries())if(!t.has(i[0]))return!1;return!0}if(ArrayBuffer.isView(n)&&ArrayBuffer.isView(t)){if(e=n.length,e!=t.length)return!1;for(i=e;i--!==0;)if(n[i]!==t[i])return!1;return!0}if(n.constructor===RegExp)return n.source===t.source&&n.flags===t.flags;if(n.valueOf!==Object.prototype.valueOf)return n.valueOf()===t.valueOf();if(n.toString!==Object.prototype.toString)return n.toString()===t.toString();if(r=Object.keys(n),e=r.length,e!==Object.keys(t).length)return!1;for(i=e;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,r[i]))return!1;for(i=e;i--!==0;){var s=r[i];if(!H(n[s],t[s]))return!1}return!0}return n!==n&&t!==t}function Ye(n,t,e,i=!0,r="user-agent"){let{userAgentBase:s,version:a,wrapperName:o,wrapperVersion:c}=t.sdkData(),l={[r]:`${s!=null?s:"NodeJSClient"}/${a}`};return i&&(l.authorization=n),o&&(l["x-launchdarkly-wrapper"]=c?`${o}/${c}`:o),e!=null&&e.value&&(l["x-launchdarkly-tags"]=e.value),l}function O(n,t,e){let i;n.status?i=`error ${n.status}${n.status===401?" (invalid SDK key)":""}`:i=`I/O error (${n.message||"unknown error"})`;let r=e!=null?e:"giving up permanently";return`Received ${i} for ${t} - ${r}`}function he({status:n}){return n?W(n):!0}var de=(n,t)=>t.btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var Xi=async(n=1e3)=>new Promise(t=>{setTimeout(t,n)}),Xe=(n,t)=>new Promise((e,i)=>{setTimeout(()=>{let r=`${t} timed out after ${n} seconds.`;i(new j(r))},n*1e3)}),Yt=class{constructor(t,e,i){this.a=e,this.je=i,this.ft=[],this.Yt=Date.now(),this.Xt=this.Yt,this.Zt={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var i,r,s;let t=this.a.info.sdkData(),e=this.a.info.platformData();return{kind:"diagnostic-init",id:this.Zt,creationDate:this.Yt,sdk:t,configuration:this.je,platform:p({name:e.name,osArch:(i=e.os)==null?void 0:i.arch,osName:(r=e.os)==null?void 0:r.name,osVersion:(s=e.os)==null?void 0:s.version},e.additional||{})}}recordStreamInit(t,e,i){let r={timestamp:t,failed:e,durationMillis:i};this.ft.push(r)}createStatsEventAndReset(t,e,i){let r=Date.now(),s={kind:"diagnostic",id:this.Zt,creationDate:r,dataSinceDate:this.Xt,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:i,streamInits:this.ft};return this.ft=[],this.Xt=r,s}},Xt;(function(n){n.MalformedFlag="MALFORMED_FLAG",n.UserNotSpecified="USER_NOT_SPECIFIED",n.FlagNotFound="FLAG_NOT_FOUND",n.ClientNotReady="CLIENT_NOT_READY",n.WrongType="WRONG_TYPE"})(Xt||(Xt={}));var Zi=Xt,wt=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};wt.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var Zt=class{constructor(t,e){let{basicConfiguration:i,platform:r}=t,{serviceEndpoints:{analyticsEventPath:s,diagnosticEventPath:a}}=i,{crypto:o,requests:c}=r;this._e=p({},e),this.Qt=Be(i.serviceEndpoints,s,[]),this.He=Be(i.serviceEndpoints,a,[]),this.m=c,this.Be=o}async Z(t,e,i,r){let s={status:R.Succeeded},a=D(p({},this._e),{"content-type":"application/json"});i&&(a["x-launchdarkly-payload-id"]=i,a["x-launchDarkly-event-schema"]="4");let o;try{let{status:c,headers:l}=await this.m.fetch(e,{headers:a,body:JSON.stringify(t),method:"POST",keepalive:!0}),h=Date.parse(l.get("date")||"");if(h&&(s.serverTime=h),c<=204)return s;if(o=new G(O({status:c,message:"some events were dropped"},"event posting")),!W(c))return Wi(c)?s.status=R.Failed:s.status=R.FailedAndMustShutDown,s.error=o,s}catch(c){o=c}return o&&!r?(s.status=R.Failed,s.error=o,s):(await Xi(),this.Z(t,this.Qt,i,!1))}async sendEventData(t,e){let i=t===V.AnalyticsEvents?this.Be.randomUUID():void 0,r=t===V.AnalyticsEvents?this.Qt:this.He;return this.Z(e,r,i,!0)}};function Qt(n){return n.kind==="feature"}function Qi(n){return n.kind==="identify"}function tn(n){return n.kind==="migration_op"}var te=class{constructor(t,e,i,r,s,a){this.count=t,this.key=e,this.value=i,this.version=s,this.variation=a,this.default=r}increment(){this.count+=1}};function en(n){return`${n.key}:${n.variation!==null&&n.variation!==void 0?n.variation:""}:${n.version!==null&&n.version!==void 0?n.version:""}`}var ee=class{constructor(){this.V=0,this.Q=0,this.tt={},this.et={}}summarizeEvent(t){if(Qt(t)&&!t.excludeFromSummaries){let e=en(t),i=this.tt[e],r=this.et[t.key];r||(r=new Set,this.et[t.key]=r),t.context.kinds.forEach(s=>r.add(s)),i?i.increment():this.tt[e]=new te(1,t.key,t.value,t.default,t.version,t.variation),(this.V===0||t.creationDate<this.V)&&(this.V=t.creationDate),t.creationDate>this.Q&&(this.Q=t.creationDate)}}getSummary(){let t=Object.values(this.tt).reduce((e,i)=>{let r=e[i.key];r||(r={default:i.default,counters:[],contextKinds:[...this.et[i.key]]},e[i.key]=r);let s={value:i.value,count:i.count};return i.variation!==void 0&&i.variation!==null&&(s.variation=i.variation),i.version!==void 0&&i.version!==null?s.version=i.version:s.unknown=!0,r.counters.push(s),e},{});return{startDate:this.V,endDate:this.Q,features:t,kind:"summary"}}clearSummary(){this.V=0,this.Q=0,this.tt={},this.et={}}},ie=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}};function pt(n){let t=Math.trunc(n);return t===1?!0:t===0?!1:Math.floor(Math.random()*t)===0}var ne=class{constructor(t,e,i,r,s,a=!0){this.r=t,this.it=r,this.l=s,this.gt=new ee,this.nt=[],this.te=0,this.pt=0,this.mt=0,this.yt=!1,this.ee=0,this.vt=!1,this.Et=null,this.Ke=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.ie=new Zt(e,i),this.ne=new Jt(t.allAttributesPrivate,t.privateAttributes.map(o=>new A(o))),a&&this.start()}start(){var t,e;if(((t=this.it)==null?void 0:t.flushInterval)!==void 0&&(this.Et=setInterval(()=>{var i;(i=this.it)==null||i.flush()},this.it.flushInterval*1e3)),this.Ge=setInterval(async()=>{var i;try{await this.flush()}catch(r){(i=this.t)==null||i.debug(`Flush failed: ${r}`)}},this.r.flushInterval*1e3),this.l){let i=this.l.createInitEvent();this.re(i),this.se=setInterval(()=>{let r=this.l.createStatsEventAndReset(this.pt,this.mt,this.ee);this.pt=0,this.mt=0,this.re(r)},this.r.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}re(t){this.ie.sendEventData(V.DiagnosticEvent,t)}close(){clearInterval(this.Ge),this.Et&&clearInterval(this.Et),this.se&&clearInterval(this.se)}async flush(){var i;if(this.vt)throw new ie("Events cannot be posted because a permanent error has been encountered. This is most likely an invalid SDK key. The specific error information is logged independently.");let t=this.nt;this.nt=[];let e=this.gt.getSummary();this.gt.clearSummary(),Object.keys(e.features).length&&t.push(e),t.length&&(this.ee=t.length,(i=this.t)==null||i.debug("Flushing %d events",t.length),await this.Z(t))}sendEvent(t){var c;if(this.vt)return;if(tn(t)){if(pt(t.samplingRatio)){let l=p({},t);l.samplingRatio===1&&delete l.samplingRatio,this.rt(l)}return}this.gt.summarizeEvent(t);let e=Qt(t),i=e&&t.trackEvents||!e,r=this.qe(t),s=Qi(t),a=(c=this.it)==null?void 0:c.processContext(t.context);a||s||(this.mt+=1),a&&!s&&this.rt(this.wt({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),i&&pt(t.samplingRatio)&&this.rt(this.wt(t,!1)),r&&pt(t.samplingRatio)&&this.rt(this.wt(t,!0))}wt(t,e){switch(t.kind){case"feature":{let i={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.ne.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(i.samplingRatio=t.samplingRatio),t.prereqOf&&(i.prereqOf=t.prereqOf),t.variation!==void 0&&(i.variation=t.variation),t.version!==void 0&&(i.version=t.version),t.reason&&(i.reason=t.reason),i}case"index":case"identify":{let i={kind:t.kind,creationDate:t.creationDate,context:this.ne.filter(t.context)};return t.samplingRatio!==1&&(i.samplingRatio=t.samplingRatio),i}case"custom":{let i={kind:"custom",creationDate:t.creationDate,key:t.key,contextKeys:t.context.kindsAndKeys};return t.samplingRatio!==1&&(i.samplingRatio=t.samplingRatio),t.data!==void 0&&(i.data=t.data),t.metricValue!==void 0&&(i.metricValue=t.metricValue),t.url!==void 0&&(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){var e;this.nt.length<this.Ke?(this.nt.push(t),this.yt=!1):(this.yt||(this.yt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.pt+=1)}qe(t){return Qt(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.te&&t.debugEventsUntilDate>Date.now()}async Z(t){let e=await this.ie.sendEventData(V.AnalyticsEvents,t);if(e.status===R.FailedAndMustShutDown&&(this.vt=!0),e.serverTime&&(this.te=e.serverTime),e.error)throw e.error}},Dt=class{constructor(t,e,i,r,s=1,a){this.context=t,this.key=e,this.data=i,this.metricValue=r,this.samplingRatio=s,this.url=a,this.kind="custom",this.creationDate=Date.now(),this.context=t}},J=class{constructor(t,e,i,r,s,a,o,c,l,h,d,f,g=1){this.withReasons=t,this.context=e,this.key=i,this.samplingRatio=g,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=s,a!==void 0&&(this.version=a),o!==void 0&&(this.variation=o),c!==void 0&&(this.trackEvents=c),l!==void 0&&(this.prereqOf=l),h!==void 0&&(this.reason=h),d!==void 0&&(this.debugEventsUntilDate=d),f!==void 0&&(this.excludeFromSummaries=f)}},bt=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},re=class{close(){}async flush(){}sendEvent(){}},se=class{constructor(t){this.Dt=t}evalEvent(t){var e;return new J(this.Dt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.Dt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,i){return new J(this.Dt,i,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new bt(t,1)}customEvent(t,e,i,r,s=1){return new Dt(e,t,i!=null?i:void 0,r!=null?r:void 0,s)}},nn=(n,t,e,i)=>{e==null||e.error(`Stream received invalid data in "${n}" message`),e==null||e.debug(`Invalid JSON follows: ${t}`),i==null||i(new S(v.InvalidData,"Malformed JSON data in event stream"))},ae=class{constructor(t,e,i,r,s,a,o,c=1){this.e=r,this.l=a,this.u=o,this.Je=c;let{basicConfiguration:l,platform:h}=t,{logger:d}=l,{requests:f}=h;this.N=p({},s),this.t=d,this.m=f,this.bt=le(l.serviceEndpoints,e,i)}_(){this.E=Date.now()}A(t){this.E&&this.l&&this.l.recordStreamInit(this.E,!t,Date.now()-this.E),this.E=void 0}kt(t){var e,i,r;return he(t)?((r=this.t)==null||r.warn(O(t,"streaming request","will retry")),this.A(!1),this._(),!0):(this.A(!1),(e=this.u)==null||e.call(this,new S(v.ErrorResponse,t.message,t.status)),(i=this.t)==null||i.error(O(t,"streaming request")),!1)}start(){this._();let t=this.m.createEventSource(this.bt,{headers:this.N,errorFilter:e=>this.kt(e),initialRetryDelayMillis:1e3*this.Je,readTimeoutMillis:5*60*1e3,retryResetIntervalMillis:60*1e3});this.H=t,t.onclose=()=>{var e;(e=this.t)==null||e.info("Closed LaunchDarkly stream connection")},t.onerror=()=>{},t.onopen=()=>{var e;(e=this.t)==null||e.info("Opened LaunchDarkly stream connection")},t.onretrying=e=>{var i;(i=this.t)==null||i.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)},this.e.forEach(({deserializeData:e,processJson:i},r)=>{t.addEventListener(r,s=>{var a,o;if((a=this.t)==null||a.debug(`Received ${r} event`),s!=null&&s.data){this.A(!0);let{data:c}=s,l=e(c);if(!l){nn(r,c,this.t,this.u);return}i(l)}else(o=this.u)==null||o.call(this,new S(v.Unknown,"Unexpected payload from event stream"))})})}stop(){var t;(t=this.H)==null||t.close(),this.H=void 0}close(){this.stop()}},x=Object.freeze({__proto__:null,ClientMessages:wt,DiagnosticsManager:Yt,ErrorKinds:Zi,EventFactoryBase:se,EventProcessor:ne,InputCustomEvent:Dt,InputEvalEvent:J,InputIdentifyEvent:bt,NullEventProcessor:re,StreamingProcessor:ae,isLegacyUser:Je,isMultiKind:qe,isSingleKind:Ge,shouldSample:pt});var E;(function(n){n.Initializing="INITIALIZING",n.Valid="VALID",n.Interrupted="INTERRUPTED",n.SetOffline="SET_OFFLINE",n.Closed="CLOSED"})(E||(E={}));function sn(n){return n>=200&&n<=299}var xt=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}},ye=class{constructor(t,e,i,r,s){this.m=t,this.ze=e,this.N=i,this.We=r,this.Ye=s}async requestPayload(){let t;try{let e=await this.m.fetch(this.ze,{method:this.We,headers:this.N,body:this.Ye});if(sn(e.status))return await e.text();t=e.status}catch(e){throw new xt(e==null?void 0:e.message)}throw new xt(`Unexpected status code: ${t}`,t)}};function Oe(n,t,e,i,r,s,a,o,c,l){let h,d="GET",f=p({},s);c&&(d="REPORT",f["content-type"]="application/json",h=n);let g=c?e.pathReport(r,n):e.pathGet(r,n),m=[...a!=null?a:[]];o&&m.push({key:"withReasons",value:"true"}),l&&m.push({key:"h",value:l});let y=ze(t,g,m);return new ye(i,y,f,d,h)}var an={logger:u.Object,maxCachedContexts:u.numberWithMin(0),baseUri:u.String,streamUri:u.String,eventsUri:u.String,capacity:u.numberWithMin(1),diagnosticRecordingInterval:u.numberWithMin(2),flushInterval:u.numberWithMin(2),streamInitialReconnectDelay:u.numberWithMin(0),allAttributesPrivate:u.Boolean,debug:u.Boolean,diagnosticOptOut:u.Boolean,withReasons:u.Boolean,sendEvents:u.Boolean,pollInterval:u.numberWithMin(30),useReport:u.Boolean,privateAttributes:u.StringArray,applicationInfo:u.Object,wrapperName:u.String,wrapperVersion:u.String,payloadFilterKey:u.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:u.createTypeArray("Hook[]",{}),inspectors:u.createTypeArray("LDInspection",{})},on=60*5,ii="https://clientsdk.launchdarkly.com",ni="https://clientstream.launchdarkly.com";function cn(n){return n instanceof K?n:z(n)}var ve=class{constructor(t={},e={}){var r,s,a;this.logger=z(),this.baseUri=ii,this.eventsUri=I.DEFAULT_EVENTS,this.streamUri=ni,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=on,this.hooks=[],this.inspectors=[],this.logger=cn(t.logger),this.Xe(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new I(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=(r=t.useReport)!=null?r:!1,this.tags=new vt({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(s=e.userAgentHeaderName)!=null?s:"user-agent",this.trackEventModifier=(a=e.trackEventModifier)!=null?a:o=>o}Xe(t){let e=[];return Object.entries(t).forEach(([i,r])=>{let s=an[i];if(s)if(s.is(r))i==="logger"||(this[i]=r!=null?r:void 0);else{let a=s.getType();if(a==="boolean")e.push(w.wrongOptionTypeBoolean(i,typeof r)),this[i]=!!r;else if(a==="boolean | undefined | null")e.push(w.wrongOptionTypeBoolean(i,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[i]=!!r);else if(s instanceof B&&u.Number.is(r)){let{min:o}=s;e.push(w.optionBelowMinimum(i,r,o)),this[i]=o}else e.push(w.wrongOptionType(i,s.getType(),typeof r))}else e.push(w.unknownOption(i))}),e}};async function ri(n,t){if(n.digest)return n.digest(t);if(n.asyncDigest)return n.asyncDigest(t);throw new Error("Platform must implement digest or asyncDigest")}var si=async(n,{crypto:t,storage:e})=>{let i=await(e==null?void 0:e.get(n));return i||(i=t.randomUUID(),await(e==null?void 0:e.set(n,i))),i};function ai(n){return async t=>ri(n.createHash("sha256").update(t),"base64")}var k=async n=>n;async function X(n){return(await Promise.all(n.map(e=>e.transform(e.value)))).join("_")}async function ln(n,t){return X([{value:"LaunchDarkly",transform:k},{value:t,transform:ai(n)}])}async function un(n){return X([{value:"LaunchDarkly",transform:k},{value:"AnonymousKeys",transform:k},{value:n,transform:k}])}async function hn(n){return X([{value:"LaunchDarkly",transform:k},{value:"ContextKeys",transform:k},{value:n,transform:k}])}async function dn(n){return X([{value:n,transform:k},{value:"ContextIndex",transform:k}])}async function Ze(n,t,e){return X([{value:t,transform:k},{value:e.canonicalKey,transform:ai(n)}])}var{isLegacyUser:fn,isSingleKind:fe,isMultiKind:Qe}=x,oi="1.0",gn=n=>{let i=n,{kind:t}=i,e=Ut(i,["kind"]);return{kind:"multi",[t]:e}},pn=async({crypto:n,info:t},{applicationInfo:e})=>{var a;let{ld_application:i}=t.platformData(),r=(a=St(i))!=null?a:{},s=(e==null?void 0:e.id)||(r==null?void 0:r.id);if(s){let o=(e==null?void 0:e.version)||(r==null?void 0:r.version),c=(e==null?void 0:e.name)||(r==null?void 0:r.name),l=(e==null?void 0:e.versionName)||(r==null?void 0:r.versionName);return r=p(p(p(D(p({},r),{id:s}),o?{version:o}:{}),c?{name:c}:{}),l?{versionName:l}:{}),r.key=await ri(n.createHash("sha256").update(s),"base64"),r.envAttributesVersion=r.envAttributesVersion||oi,r}},mn=async n=>{var o,c,l,h;let{ld_device:t,os:e}=n.info.platformData(),i=(o=St(t))!=null?o:{},r=(e==null?void 0:e.name)||((c=i.os)==null?void 0:c.name),s=(e==null?void 0:e.version)||((l=i.os)==null?void 0:l.version),a=(h=i.os)==null?void 0:h.family;if((r||s||a)&&(i.os=p(p(p({},r?{name:r}:{}),s?{version:s}:{}),a?{family:a}:{})),Object.keys(i).filter(d=>d!=="key"&&d!=="envAttributesVersion").length){let d=await hn("ld_device");return i.key=await si(d,n),i.envAttributesVersion=i.envAttributesVersion||oi,i}},yn=async(n,t,e)=>{if(fn(n))return n;let i,r;if(fe(n)&&n.kind!=="ld_application"||Qe(n)&&!n.ld_application?i=await pn(t,e):e.logger.warn("Not adding ld_application environment attributes because it already exists."),fe(n)&&n.kind!=="ld_device"||Qe(n)&&!n.ld_device?r=await mn(t):e.logger.warn("Not adding ld_device environment attributes because it already exists."),i||r){let s=fe(n)?gn(n):n;return p(p(p({},s),i?{ld_application:i}:{}),r?{ld_device:r}:{})}return n},{isLegacyUser:vn,isMultiKind:En,isSingleKind:wn}=x,Ne=async(n,t,e)=>{let{anonymous:i,key:r}=t;if(i&&!r){let s=await un(n);t.key=await si(s,e)}},Dn=async(n,t)=>{await Ne(n.kind,n,t)},bn=async(n,t)=>{let r=n,{kind:e}=r,i=Ut(r,["kind"]);return Promise.all(Object.entries(i).map(([s,a])=>Ne(s,a,t)))},kn=async(n,t)=>{await Ne("user",n,t)},Sn=async(n,t)=>{let e=ue(n);return wn(e)&&await Dn(e,t),En(e)&&await bn(e,t),vn(e)&&await kn(e,t),e},xn=n=>({customBaseURI:n.serviceEndpoints.polling!==ii,customStreamURI:n.serviceEndpoints.streaming!==ni,customEventsURI:n.serviceEndpoints.events!==I.DEFAULT_EVENTS,eventsCapacity:n.capacity,eventsFlushIntervalMillis:kt(n.flushInterval),reconnectTimeMillis:kt(n.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:kt(n.diagnosticRecordingInterval),allAttributesPrivate:n.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Ln=(n,t,e)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new x.DiagnosticsManager(n,e,xn(t))};function ge(n,t){return{value:t!=null?t:null,variationIndex:null,reason:{kind:"ERROR",errorKind:n}}}function ti(n,t,e){return{value:n,variationIndex:t!=null?t:null,reason:e!=null?e:null}}var Cn=(n,t,e,i,r)=>{if(t.sendEvents)return new x.EventProcessor(D(p({},t),{eventsCapacity:t.capacity}),new Et(n,t,e),i,void 0,r,!1)},Lt=class extends x.EventFactoryBase{evalEventClient(t,e,i,r,s,a){let{trackEvents:o,debugEventsUntilDate:c,trackReason:l,flagVersion:h,version:d,variation:f}=r;return super.evalEvent({addExperimentData:l,context:s,debugEventsUntilDate:c,defaultVal:i,flagKey:t,reason:a,trackEvents:!!o,value:e,variation:f,version:h!=null?h:d})}},Y=class n{constructor(){this.container={index:new Array}}static fromJson(t){let e=new n;try{e.container=JSON.parse(t)}catch(i){}return e}toJson(){return JSON.stringify(this.container)}notice(t,e){let i=this.container.index.find(r=>r.id===t);i===void 0?this.container.index.push({id:t,timestamp:e}):i.timestamp=e}prune(t){let e=Math.max(t,0);return this.container.index.length>e?(this.container.index.sort((i,r)=>i.timestamp-r.timestamp),this.container.index.splice(0,this.container.index.length-e)):[]}},Ee=class{constructor(t,e,i,r,s,a,o=()=>Date.now()){this.a=t,this.St=e,this.Ze=i,this.g=r,this.k=s,this.t=a,this.st=o,this.ae=dn(this.St)}async init(t,e){this.k.init(t,e),await this.oe(t)}async upsert(t,e,i){return this.k.upsert(t,e,i)?(await this.oe(t),!0):!1}async loadCached(t){var r,s,a,o;let e=await Ze(this.a.crypto,this.St,t),i=await((r=this.a.storage)==null?void 0:r.get(e));if(i==null){if(i=await((s=this.a.storage)==null?void 0:s.get(t.canonicalKey)),i==null)return!1;await((a=this.a.storage)==null?void 0:a.set(e,i)),await((o=this.a.storage)==null?void 0:o.clear(t.canonicalKey))}try{let c=JSON.parse(i),l=Object.entries(c).reduce((h,[d,f])=>(h[d]={version:f.version,flag:f},h),{});return this.k.initCached(t,l),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(c){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${c.message}`),!1}}async Qe(){var e;if(this.$!==void 0)return this.$;let t=await((e=this.a.storage)==null?void 0:e.get(await this.ae));if(!t)return this.$=new Y,this.$;try{this.$=Y.fromJson(t),this.t.debug("Loaded context index from persistent storage")}catch(i){this.t.warn(`Could not load index from persistent storage: ${i.message}`),this.$=new Y}return this.$}async oe(t){var c,l;let e=await this.Qe(),i=await Ze(this.a.crypto,this.St,t);e.notice(i,this.st());let r=e.prune(this.Ze);await Promise.all(r.map(async h=>{var d;return(d=this.a.storage)==null?void 0:d.clear(h.id)})),await((c=this.a.storage)==null?void 0:c.set(await this.ae,e.toJson()));let s=this.g.getAll(),a=Object.entries(s).reduce((h,[d,f])=>(f.flag!==null&&f.flag!==void 0&&(h[d]=f.flag),h),{}),o=JSON.stringify(a);await((l=this.a.storage)==null?void 0:l.set(i,o))}},we=class{constructor(){this.B={}}init(t){this.B=Object.entries(t).reduce((e,[i,r])=>(e[i]=r,e),{})}insertOrUpdate(t,e){this.B[t]=e}get(t){if(Object.prototype.hasOwnProperty.call(this.B,t))return this.B[t]}getAll(){return this.B}};function An(n,t){let e=[];return Object.entries(n).forEach(([i,r])=>{let s=t[i];(!s||!H(r,s))&&e.push(i)}),Object.keys(t).forEach(i=>{n[i]||e.push(i)}),e}var De=class{constructor(t,e){this.K=new Array,this.g=t,this.t=e}init(t,e){this.ce=t.canonicalKey;let i=this.g.getAll();this.g.init(e);let r=An(i,e);r.length>0&&this.K.forEach(s=>{try{s(t,r,"init")}catch(a){}})}initCached(t,e){this.ce!==t.canonicalKey&&this.init(t,e)}upsert(t,e,i){if(this.ce!==t.canonicalKey)return this.t.warn("Received an update for an inactive context."),!1;let r=this.g.get(e);return r!==void 0&&r.version>=i.version?!1:(this.g.insertOrUpdate(e,i),this.K.forEach(s=>{try{s(t,[e],"patch")}catch(a){}}),!0)}on(t){this.K.push(t)}off(t){let e=this.K.indexOf(t);e>-1&&this.K.splice(e,1)}},be=class{constructor(t,e,i,r,s=()=>Date.now()){this.g=new we,this.k=new De(this.g,r),this.xt=this.ti(t,e,i,r,s)}async ti(t,e,i,r,s=()=>Date.now()){let a=await ln(t.crypto,e);return new Ee(t,a,i,this.g,this.k,r,s)}get(t){return this.g.get(t)}getAll(){return this.g.getAll()}setBootstrap(t,e){this.k.init(t,e)}async init(t,e){return(await this.xt).init(t,e)}async upsert(t,e,i){return(await this.xt).upsert(t,e,i)}async loadCached(t){return(await this.xt).loadCached(t)}on(t){this.k.on(t)}off(t){this.k.off(t)}},ei="unknown hook",ci="beforeEvaluation",li="afterEvaluation";function Tt(n,t,e,i,r){try{return i()}catch(s){return n==null||n.error(`An error was encountered in "${t}" of the "${e}" hook: ${s}`),r}}function Ot(n,t){try{return t.getMetadata().name||ei}catch(e){return n.error("Exception thrown getting metadata for hook. Unable to get hook name."),ei}}function Tn(n,t,e){return t.map(i=>Tt(n,ci,Ot(n,i),()=>{var r,s;return(s=(r=i==null?void 0:i.beforeEvaluation)==null?void 0:r.call(i,e,{}))!=null?s:{}},{}))}function On(n,t,e,i,r){for(let s=t.length-1;s>=0;s-=1){let a=t[s],o=i[s];Tt(n,li,Ot(n,a),()=>{var c,l;return(l=(c=a==null?void 0:a.afterEvaluation)==null?void 0:c.call(a,e,o,r))!=null?l:{}},{})}}function Nn(n,t,e){return t.map(i=>Tt(n,ci,Ot(n,i),()=>{var r,s;return(s=(r=i==null?void 0:i.beforeIdentify)==null?void 0:r.call(i,e,{}))!=null?s:{}},{}))}function $n(n,t,e,i,r){for(let s=t.length-1;s>=0;s-=1){let a=t[s],o=i[s];Tt(n,li,Ot(n,a),()=>{var c,l;return(l=(c=a==null?void 0:a.afterIdentify)==null?void 0:c.call(a,e,o,r))!=null?l:{}},{})}}var ke=class{constructor(t,e){this.t=t,this.G=[],this.G.push(...e)}withEvaluation(t,e,i,r){if(this.G.length===0)return r();let s=[...this.G],a={flagKey:t,context:e,defaultValue:i},o=Tn(this.t,s,a),c=r();return On(this.t,s,a,o,c),c}identify(t,e){let i=[...this.G],r={context:t,timeout:e},s=Nn(this.t,i,r);return a=>{$n(this.t,i,r,s,a)}}addHook(t){this.G.push(t)}};function Rn(n){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(t,e,i)=>(n.onFlagUsed(t.flagKey,i,t.context),e),afterIdentify(t,e,i){return n.onIdentityChanged(t.context),e}}}function Pn(n,t){return`an inspector: "${t}" of an invalid type (${n}) was configured`}function In(n,t){return`an inspector: "${t}" of type: "${n}" generated an exception`}function Mn(n,t){let e=!1,i={method:(...r)=>{try{n.method(...r)}catch(s){e||(e=!0,t.warn(In(i.type,i.name)))}},type:n.type,name:n.name,synchronous:n.synchronous};return i}var ui="flag-used",hi="flag-details-changed",di="flag-detail-changed",fi="client-identity-changed",Fn=[ui,hi,di,fi];function Un(n,t){let e=Fn.includes(n.type)&&n.method&&typeof n.method=="function";return e||t.warn(Pn(n.type,n.name)),e}var Se=class{constructor(t,e){this.R=[];let i=t.filter(r=>Un(r,e));this.R=i.map(r=>Mn(r,e))}hasInspectors(){return this.R.length!==0}onFlagUsed(t,e,i){this.R.forEach(r=>{r.type===ui&&r.method(t,e,i)})}onFlagsChanged(t){this.R.forEach(e=>{e.type===hi&&e.method(t)})}onFlagChanged(t,e){this.R.forEach(i=>{i.type===di&&i.method(t,e)})}onIdentityChanged(t){this.R.forEach(e=>{e.type===fi&&e.method(t)})}},xe=class{constructor(t){this.t=t,this.e=new Map}on(t,e){var i;this.e.has(t)?(i=this.e.get(t))==null||i.push(e):this.e.set(t,[e])}off(t,e){let i=this.e.get(t);if(i){if(e){let r=i.filter(s=>s!==e);r.length===0?this.e.delete(t):this.e.set(t,r);return}this.e.delete(t)}}Lt(t,e,...i){var r;try{t(...i)}catch(s){(r=this.t)==null||r.error(`Encountered error invoking handler for "${e}", detail: "${s}"`)}}emit(t,...e){let i=this.e.get(t);i==null||i.forEach(r=>this.Lt(r,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,i;return(i=(e=this.e.get(t))==null?void 0:e.length)!=null?i:0}},{ClientMessages:pe,ErrorKinds:me}=x,Vn=5,Ct=class{constructor(t,e,i,r,s,a){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=i,this.Ct=15,this.S=new Lt(!1),this.at=new Lt(!0),this.At=!1,!t)throw new Error("You must configure the client with a client-side SDK key");if(!i.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.r=new ve(r,a),this.logger=this.r.logger,this.le=Ye(this.sdkKey,this.platform.info,this.r.tags,this.r.serviceEndpoints.includeAuthorizationHeader,this.r.userAgentHeaderName),this.w=new be(this.platform,t,this.r.maxCachedContexts,this.r.logger),this.l=Ln(t,this.r,i),this.p=Cn(t,this.r,i,this.le,this.l),this.emitter=new xe,this.emitter.on("error",(o,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(o)}`)}),this.w.on((o,c,l)=>{this.ei(c,l);let h=b.toLDContext(o);this.emitter.emit("change",h,c),c.forEach(d=>{this.emitter.emit(`change:${d}`,h)})}),this.dataManager=s(this.w,this.r,this.le,this.emitter,this.l),this.P=new ke(this.logger,this.r.hooks),this.q=new Se(this.r.inspectors,this.logger),this.q.hasInspectors()&&this.P.addHook(Rn(this.q))}allFlags(){return Object.entries(this.w.getAll()).reduce((e,[i,r])=>(r.flag!==null&&r.flag!==void 0&&!r.flag.deleted&&(e[i]=r.flag.value),e),{})}async close(){var t,e;await this.flush(),(t=this.p)==null||t.close(),(e=this.xi)==null||e.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.p)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.D?ue(this.D):void 0}getInternalContext(){return this.I}ii(t,e){let i,r,s=new Promise((c,l)=>{i=c,r=l});if(e)return{identifyPromise:s,identifyResolve:i,identifyReject:r};let a=Xe(t,"identify");return{identifyPromise:Promise.race([a,s]).catch(c=>{throw c.message.includes("timed out")&&this.logger.error(`identify error: ${c}`),c}),identifyResolve:i,identifyReject:r}}async identify(t,e){var d,f;let i=(d=e==null?void 0:e.timeout)!=null?d:Vn,r=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Ct&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Ct} seconds. We recommend a timeout of less than ${this.Ct} seconds.`);let s=await Sn(t,this.platform);this.autoEnvAttributes===U.Enabled&&(s=await yn(s,this.platform,this.r));let a=b.fromLDContext(s);if(!a.valid){let g=new Error("Context was unspecified or had no key");return this.emitter.emit("error",s,g),Promise.reject(g)}this.D=s,this.I=a,(f=this.p)==null||f.sendEvent(this.S.identifyEvent(this.I));let{identifyPromise:o,identifyResolve:c,identifyReject:l}=this.ii(i,r);this.logger.debug(`Identifying ${JSON.stringify(this.I)}`);let h=this.P.identify(s,e==null?void 0:e.timeout);return await this.dataManager.identify(c,l,a,e),o.then(g=>(h({status:"completed"}),g),g=>{throw h({status:"error"}),g})}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,i){var r,s;if(!this.I||!this.I.valid){this.logger.warn(pe.MissingContextKeyNoEvent);return}i!==void 0&&!u.Number.is(i)&&((r=this.logger)==null||r.warn(pe.invalidMetricValue(typeof i))),(s=this.p)==null||s.sendEvent(this.r.trackEventModifier(this.S.customEvent(t,this.I,e,i)))}ot(t,e,i,r){var f,g,m;if(!this.D)return this.logger.debug(pe.MissingContextKeyNoEvent),ge(me.UserNotSpecified,e);let s=b.fromLDContext(this.D),a=this.w.get(t);if(a===void 0||a.flag.deleted){let y=e!=null?e:null,C=new q(`Unknown feature flag "${t}"; returning default value ${y}.`);return this.emitter.emit("error",this.D,C),(f=this.p)==null||f.sendEvent(this.S.unknownFlagEvent(t,y,s)),ge(me.FlagNotFound,e)}let{reason:o,value:c,variation:l,prerequisites:h}=a.flag;if(r){let[y,C]=r(c);if(!y){(g=this.p)==null||g.sendEvent(i.evalEventClient(t,e,e,a.flag,s,o));let Ft=new q(`Wrong type "${C}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.D,Ft),ge(me.WrongType,e)}}let d=ti(c,l,o);return c==null&&(this.logger.debug("Result value is null. Providing default value."),d.value=e),h==null||h.forEach(y=>{this.ot(y,void 0,this.S)}),(m=this.p)==null||m.sendEvent(i.evalEventClient(t,c,e,a.flag,s,o)),d}variation(t,e){let{value:i}=this.P.withEvaluation(t,this.D,e,()=>this.ot(t,e,this.S));return i}variationDetail(t,e){return this.P.withEvaluation(t,this.D,e,()=>this.ot(t,e,this.at))}M(t,e,i,r){return this.P.withEvaluation(t,this.D,e,()=>this.ot(t,e,i,r))}boolVariation(t,e){return this.M(t,e,this.S,i=>[u.Boolean.is(i),u.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.M(t,e,this.S,i=>[u.Number.is(i),u.Number.getType()]).value}stringVariation(t,e){return this.M(t,e,this.S,i=>[u.String.is(i),u.String.getType()]).value}boolVariationDetail(t,e){return this.M(t,e,this.at,i=>[u.Boolean.is(i),u.Boolean.getType()])}numberVariationDetail(t,e){return this.M(t,e,this.at,i=>[u.Number.is(i),u.Number.getType()])}stringVariationDetail(t,e){return this.M(t,e,this.at,i=>[u.String.is(i),u.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.P.addHook(t)}setEventSendingEnabled(t,e){var i,r,s,a;this.At!==t&&(this.At=t,t?(this.logger.debug("Starting event processor"),(i=this.p)==null||i.start()):e?((r=this.logger)==null||r.debug("Flushing event processor before disabling."),this.flush().then(()=>{var o,c;this.At||((o=this.logger)==null||o.debug("Stopping event processor."),(c=this.p)==null||c.close())})):((s=this.logger)==null||s.debug("Stopping event processor."),(a=this.p)==null||a.close()))}sendEvent(t){var e;(e=this.p)==null||e.sendEvent(t)}ei(t,e){if(!this.q.hasInspectors())return;let i={};t.forEach(r=>{let s=this.w.get(r);if(s!=null&&s.flag&&!s.flag.deleted){let{reason:a,value:o,variation:c}=s.flag;i[r]=ti(o,c,a)}}),e==="init"?this.q.onFlagsChanged(i):e==="patch"&&Object.entries(i).forEach(([r,s])=>{this.q.onFlagChanged(r,s)})}},Le=class{constructor(t,e,i){this.w=t,this.Tt=e,this.t=i}async handlePut(t,e){this.t.debug(`Got PUT: ${Object.keys(e)}`);let i=Object.entries(e).reduce((r,[s,a])=>(r[s]={version:a.version,flag:a},r),{});await this.w.init(t,i),this.Tt.requestStateUpdate(E.Valid)}async handlePatch(t,e){this.t.debug(`Got PATCH ${JSON.stringify(e,null,2)}`),this.w.upsert(t,e.key,{version:e.version,flag:e})}async handleDelete(t,e){this.t.debug(`Got DELETE ${JSON.stringify(e,null,2)}`),this.w.upsert(t,e.key,{version:e.version,flag:D(p({},e),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})}handleStreamingError(t){this.Tt.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.Tt.reportError(t.kind,t.message,t.status,t.recoverable)}},Ce=class{constructor(t,e=()=>Date.now()){this.x=t,this.ct=E.Closed,this.ue=e(),this.st=e}get status(){return{state:this.ct,stateSince:this.ue,lastError:this.ni}}he(t,e=!1){let i=t===E.Interrupted&&this.ct===E.Initializing?E.Initializing:t,r=this.ct!==i;r&&(this.ct=i,this.ue=this.st()),(r||e)&&this.x.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.he(t)}reportError(t,e,i,r=!1){let s={kind:t,message:e,statusCode:i,time:this.st()};this.ni=s,this.he(r?E.Interrupted:E.Closed,!0)}},Ae=class{constructor(t,e,i,r,s){this.ri=t,this.si=e,this.ai=i,this.u=r,this.t=s,this.de=!1}async fe(){var s,a,o,c,l,h,d;if(this.de)return;let t=f=>{var g,m,y;(g=this.t)==null||g.error("Polling received invalid data"),(m=this.t)==null||m.debug(`Invalid JSON follows: ${f}`),(y=this.u)==null||y.call(this,new P(v.InvalidData,"Malformed JSON data in polling response"))};(s=this.t)==null||s.debug("Polling LaunchDarkly for feature flag updates");let e=Date.now();try{let f=await this.ri.requestPayload();try{let g=JSON.parse(f);try{(a=this.ai)==null||a.call(this,g)}catch(m){(o=this.t)==null||o.error(`Exception from data handler: ${m}`)}}catch(g){t(f)}}catch(f){let g=f;if(g.status!==void 0&&!W(g.status)){(c=this.t)==null||c.error(O(f,"polling request")),(l=this.u)==null||l.call(this,new P(v.ErrorResponse,g.message,g.status));return}(h=this.t)==null||h.error(O(f,"polling request","will retry"))}let i=Date.now()-e,r=Math.max(this.si*1e3-i,0);(d=this.t)==null||d.debug("Elapsed: %d ms, sleeping for %d ms",i,r),this.Ot=setTimeout(()=>{this.fe()},r)}start(){this.fe()}stop(){this.Ot&&(clearTimeout(this.Ot),this.Ot=void 0),this.de=!0}close(){this.stop()}},jn=(n,t,e,i)=>{e==null||e.error(`Stream received invalid data in "${n}" message`),e==null||e.debug(`Invalid JSON follows: ${t}`),i==null||i(new S(v.InvalidData,"Malformed JSON data in event stream"))},Te=class{constructor(t,e,i,r,s,a,o,c,l){var f;this.oi=t,this.Nt=e,this.e=i,this.m=r,this.ci=a,this.l=o,this.u=c,this.t=l;let h;e.useReport&&!r.getEventSourceCapabilities().customMethod?h=e.paths.pathPing(s,t):h=e.useReport?e.paths.pathReport(s,t):e.paths.pathGet(s,t);let d=[...(f=e.queryParameters)!=null?f:[]];this.Nt.withReasons&&d.push({key:"withReasons",value:"true"}),this.m=r,this.N=p({},e.baseHeaders),this.t=l,this.bt=le(e.serviceEndpoints,h,d)}_(){this.E=Date.now()}A(t){this.E&&this.l&&this.l.recordStreamInit(this.E,!t,Date.now()-this.E),this.E=void 0}kt(t){var e,i,r;return he(t)?((r=this.t)==null||r.warn(O(t,"streaming request","will retry")),this.A(!1),this._(),!0):(this.A(!1),(e=this.u)==null||e.call(this,new S(v.ErrorResponse,t.message,t.status,!1)),(i=this.t)==null||i.error(O(t,"streaming request")),!1)}start(){this._();let t;this.Nt.useReport?(this.N["content-type"]="application/json",t={method:"REPORT",body:this.oi}):t={};let e=this.m.createEventSource(this.bt,D(p({headers:this.N},t),{errorFilter:i=>this.kt(i),initialRetryDelayMillis:this.Nt.initialRetryDelayMillis,readTimeoutMillis:5*60*1e3,retryResetIntervalMillis:60*1e3}));this.H=e,e.onclose=()=>{var i;(i=this.t)==null||i.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var i;(i=this.t)==null||i.info("Opened LaunchDarkly stream connection")},e.onretrying=i=>{var r;(r=this.t)==null||r.info(`Will retry stream connection in ${i.delayMillis} milliseconds`)},this.e.forEach(({deserializeData:i,processJson:r},s)=>{e.addEventListener(s,a=>{var o,c;if((o=this.t)==null||o.debug(`Received ${s} event`),a!=null&&a.data){this.A(!0);let{data:l}=a,h=i(l);if(!h){jn(s,l,this.t,this.u);return}r(h)}else(c=this.u)==null||c.call(this,new S(v.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var i,r,s,a,o,c,l;(i=this.t)==null||i.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let h=await this.ci.requestPayload();try{let d=JSON.parse(h);try{(r=this.e.get("put"))==null||r.processJson(d)}catch(f){(s=this.t)==null||s.error(`Exception from data handler: ${f}`)}}catch(d){(a=this.t)==null||a.error("Polling after ping received invalid data"),(o=this.t)==null||o.debug(`Invalid JSON follows: ${h}`),(c=this.u)==null||c.call(this,new P(v.InvalidData,"Malformed JSON data in ping polling response"))}}catch(h){let d=h;(l=this.u)==null||l.call(this,new P(v.ErrorResponse,d.message,d.status))}})}stop(){var t;(t=this.H)==null||t.close(),this.H=void 0}close(){this.stop()}},At=class{constructor(t,e,i,r,s,a,o,c,l){this.platform=t,this.flagManager=e,this.credential=i,this.config=r,this.getPollingPaths=s,this.getStreamingPaths=a,this.baseHeaders=o,this.emitter=c,this.diagnosticsManager=l,this.logger=r.logger,this.dataSourceStatusManager=new Ce(c),this.F=new Le(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.li=t}createPollingProcessor(t,e,i,r,s){let a=new Ae(i,this.config.pollInterval,async o=>{await this.F.handlePut(e,o),r==null||r()},o=>{this.emitter.emit("error",t,o),this.F.handlePollingError(o),s==null||s(o)},this.logger);this.updateProcessor=this.ge(a,this.dataSourceStatusManager)}createStreamingProcessor(t,e,i,r,s){var o;let a=new Te(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.li)==null?void 0:o.queryParameters},this.createStreamListeners(e,r),this.platform.requests,this.platform.encoding,i,this.diagnosticsManager,c=>{this.emitter.emit("error",t,c),this.F.handleStreamingError(c),s==null||s(c)},this.logger);this.updateProcessor=this.ge(a,this.dataSourceStatusManager)}createStreamListeners(t,e){let i=new Map;return i.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.F.handlePut(t,r),e==null||e()}}),i.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.F.handlePatch(t,r)}}),i.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.F.handleDelete(t,r)}}),i}ge(t,e){return{start:()=>{e.requestStateUpdate(E.Initializing),t.start()},stop:()=>{t.stop(),e.requestStateUpdate(E.Closed)},close:()=>{t.close(),e.requestStateUpdate(E.Closed)}}}};function Nt(){return typeof document!==void 0}function $e(){return typeof window!==void 0}function $t(n,t,e){return Nt()?(document.addEventListener(n,t,e),()=>{document.removeEventListener(n,t,e)}):()=>{}}function Rt(n,t,e){return Nt()?(window.addEventListener(n,t,e),()=>{window.removeEventListener(n,t,e)}):()=>{}}function L(){return $e()?window.location.href:""}function gi(){return $e()?window.location.search:""}function pi(){return $e()?window.location.hash:""}function mi(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function yi(){return Nt()?document.visibilityState:"visibile"}function vi(n){if(Nt())return document.querySelectorAll(n)}function Ei(n,t){let e=Object.keys(t),i="$flagsState",r="$valid",s=t[i];!s&&e.length&&n.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),t[r]===!1&&n.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let a={};return e.forEach(o=>{if(o!==i&&o!==r){let c;s&&s[o]?c=p({value:t[o]},s[o]):c={value:t[o],version:0},a[o]={version:c.version,flag:c}}}),a}var _n="[BrowserDataManager]",Z=class extends At{constructor(e,i,r,s,a,o,c,l,h,d){super(e,i,r,s,o,c,l,h,d);this.Li=a;this.J=void 0;this.$t=!1;this.J=a.streaming}T(e,...i){this.logger.debug(`${_n} ${e}`,...i)}async identify(e,i,r,s){this.context=r;let a=s;a!=null&&a.hash?this.setConnectionParams({queryParameters:[{key:"h",value:a.hash}]}):this.setConnectionParams(),this.Rt=a==null?void 0:a.hash,a!=null&&a.bootstrap?this.ui(r,a.bootstrap,e):(await this.flagManager.loadCached(r)&&this.T("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.hi(r,e,i)),this.Pt()}async hi(e,i,r){var s,a;try{this.dataSourceStatusManager.requestStateUpdate(E.Initializing);let o=JSON.stringify(b.toLDContext(e)),l=await Oe(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Rt).requestPayload();try{let d=this.createStreamListeners(e,i).get("put");d.processJson(d.deserializeData(l))}catch(h){this.dataSourceStatusManager.reportError(v.InvalidData,(s=h.message)!=null?s:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(v.NetworkError,(a=o.message)!=null?a:"unexpected network error",o.status),r(o)}}ui(e,i,r){this.flagManager.setBootstrap(e,Ei(this.logger,i)),this.T("Identify - Initialization completed from bootstrap"),r()}setForcedStreaming(e){this.J=e,this.Pt()}setAutomaticStreamingState(e){this.$t=e,this.Pt()}Pt(){let e=this.J||this.$t&&this.J===void 0;this.T(`Updating streaming state. forced(${this.J}) automatic(${this.$t})`),e?this.di():this.fi()}fi(){var e;this.updateProcessor&&this.T("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}di(){if(this.updateProcessor){this.T("Update processor already active. Not changing state.");return}if(!this.context){this.T("Context not set, not starting update processor.");return}this.T("Starting update processor."),this.gi(this.context)}gi(e,i,r){var c;let s=b.toLDContext(e);(c=this.updateProcessor)==null||c.close();let a=JSON.stringify(b.toLDContext(e)),o=Oe(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Rt);this.createStreamingProcessor(s,e,o,i,r),this.updateProcessor.start()}};function wi(n){let e=$t("visibilitychange",()=>{yi()==="hidden"&&n()}),i=Rt("pagehide",n);return()=>{e(),i()}}function Q(n){if(typeof n!="string")throw new TypeError("Expected a string");return n.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Hn(n,t,e,i){let s=((n.kind==="substring"||n.kind==="regex")&&i.includes("/")?t:t.replace(i,"")).replace(e,"");switch(n.kind){case"exact":return new RegExp(`^${Q(n.url)}/?$`).test(t);case"canonical":return new RegExp(`^${Q(n.url)}/?$`).test(s);case"substring":return new RegExp(`.*${Q(n.substring)}.*$`).test(s);case"regex":return new RegExp(n.pattern).test(s);default:return!1}}function Bn(n,t){let e=[];return t.forEach(i=>{let r=n.target,{selector:s}=i,a=vi(s);for(;r&&(a!=null&&a.length);){for(let o=0;o<a.length;o+=1)if(r===a[o]){e.push(i);break}r=r.parentNode}}),e}var tt=class{constructor(t,e){let i=t.filter(a=>{var o;return(o=a.urls)==null?void 0:o.some(c=>Hn(c,L(),gi(),pi()))}),r=i.filter(a=>a.kind==="pageview"),s=i.filter(a=>a.kind==="click");if(r.forEach(a=>e(a)),s.length){let a=o=>{Bn(o,s).forEach(c=>{e(c)})};this.pe=$t("click",a)}}close(){var t;(t=this.pe)==null||t.call(this)}};var Kn=300,Pt=class{constructor(t){this.It=L();let e=()=>{let r=L();r!==this.It&&(this.It=r,t())};this.Mt=setInterval(e,Kn);let i=Rt("popstate",e);this.me=()=>{i()}}close(){var t;this.Mt&&clearInterval(this.Mt),(t=this.me)==null||t.call(this)}};var et=class{constructor(t,e,i,r,s,a=o=>new Pt(o)){this.m=e;this.yi=r;this.mi=s;this.lt=[];this.ve=!1;this.ut=`${i}/sdk/goals/${t}`,this.ye=a(()=>{this.Ut()})}async initialize(){await this.pi(),this.Ut()}startTracking(){this.ve=!0,this.Ut()}Ut(){var t;this.ve&&((t=this.Ft)==null||t.close(),this.lt&&this.lt.length&&(this.Ft=new tt(this.lt,e=>{this.mi(L(),e)})))}async pi(){try{let t=await this.m.fetch(this.ut);this.lt=await t.json()}catch(t){this.yi(new G(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.ye)==null||t.close(),(e=this.Ft)==null||e.close()}};function Di(n){return n.kind==="click"}var Gn=2,bi={fetchGoals:!0,eventUrlTransformer:n=>n,streaming:void 0},qn={fetchGoals:u.Boolean,eventUrlTransformer:u.Function,streaming:u.Boolean};function ki(n){let t=p({},n);return Object.keys(bi).forEach(e=>{delete t[e]}),t}function Jn(n){var t;(t=n.flushInterval)!=null||(n.flushInterval=Gn)}function Re(n,t){let e=p({},bi);return Jn(e),Object.entries(qn).forEach(i=>{let[r,s]=i,a=n[r];a!==void 0&&(s.is(a)?e[r]=a:t.warn(w.wrongOptionType(r,s.getType(),typeof a)))}),e}var it=class{constructor(t,e){this.vi=t;this.Ee=[];switch(e){case"sha1":this.Vt="SHA-1";break;case"sha256":this.Vt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Ee.join(""),i=new TextEncoder().encode(e),r=await this.vi.subtle.digest(this.Vt,i);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(r)));case"hex":return[...new Uint8Array(r)].map(s=>s.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Ee.push(t),this}};var zn={start:0,end:3},Wn={start:4,end:5},Pe={start:6,end:7},Ie={start:8,end:8},Yn={start:9,end:9},Xn={start:10,end:15};function Zn(){if(crypto&&crypto.getRandomValues){let t=new Uint8Array(16);return crypto.getRandomValues(t),[...t.values()]}let n=[];for(let t=0;t<16;t+=1)n.push(Math.floor(Math.random()*256));return n}function _(n,t){let e="";for(let i=t.start;i<=t.end;i+=1)e+=n[i].toString(16).padStart(2,"0");return e}function Qn(n){return n[Ie.start]=(n[Ie.start]|128)&191,n[Pe.start]=n[Pe.start]&15|64,`${_(n,zn)}-${_(n,Wn)}-${_(n,Pe)}-${_(n,Ie)}${_(n,Yn)}-${_(n,Xn)}`}function tr(){let n=Zn();return Qn(n)}function Me(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():tr()}var nt=class{createHash(t){return new it(mi(),t)}randomUUID(){return Me()}};function er(n){let t=Array.from(n,e=>String.fromCodePoint(e)).join("");return btoa(t)}var rt=class{btoa(t){return er(new TextEncoder().encode(t))}};var st=class{platformData(){return{name:"JS"}}sdkData(){return{name:"@launchdarkly/js-client-sdk",version:"0.0.0",userAgentBase:"JSClient"}}};var at=class{constructor(t,e,i=Math.random){this.Di=e;this.wi=i;this.jt=0;this._t=Math.max(1,t),this.we=Math.ceil(Math.log2(3e4/this._t))}z(){let t=Math.min(this.jt,this.we),e=this._t*2**t;return Math.min(e,3e4)}Ei(t){return t-Math.trunc(this.wi()*.5*t)}success(t=Date.now()){this.ht=t}fail(t=Date.now()){this.ht!==void 0&&t-this.ht>this.Di&&(this.jt=0),this.ht=void 0;let e=this.Ei(this.z());return this.jt+=1,e}};var ot=class{constructor(t,e){this.ut=t;this.e={};this.z=new at(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.De=e.errorFilter,this.be()}be(){this.U=new EventSource(this.ut),this.U.onopen=()=>{var t;this.z.success(),(t=this.onopen)==null||t.call(this)},this.U.onerror=t=>{var e;this.bi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.e).forEach(([t,e])=>{e.forEach(i=>{var r;(r=this.U)==null||r.addEventListener(t,i)})})}addEventListener(t,e){var i,r,s;(r=(i=this.e)[t])!=null||(i[t]=[]),this.e[t].push(e),(s=this.U)==null||s.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Ht),this.Ht=void 0,(t=this.U)==null||t.close(),(e=this.onclose)==null||e.call(this)}ki(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Ht=setTimeout(()=>{this.be()},t)}bi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.De(t))&&this.ki(this.z.fail())}};var ct=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new ot(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function Si(){return typeof localStorage!="undefined"}var lt=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(i){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${i}`)}}async get(t){var e;try{let i=localStorage.getItem(t);return i!=null?i:null}catch(i){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${i}`),null}}async set(t,e){var i;try{localStorage.setItem(t,e)}catch(r){(i=this.t)==null||i.error(`Error setting key in localStorage: ${t}, reason: ${r}`)}}};var ut=class{constructor(t){this.encoding=new rt;this.info=new st;this.crypto=new nt;this.requests=new ct;Si()&&(this.storage=new lt(t))}};var It=class extends Ct{constructor(t,e,i={},r){var f;let{logger:s,debug:a}=i,o=s!=null?s:z({debug:a?console.debug:()=>{},info:console.info,warn:console.warn,error:console.error}),c=(f=i.baseUri)!=null?f:"https://clientsdk.launchdarkly.com",l=r!=null?r:new ut(o),h=Re(i,o),{eventUrlTransformer:d}=h;super(t,e,l,ki(D(p({},i),{logger:o})),(g,m,y,C,Ft)=>new Z(l,g,t,m,h,()=>({pathGet(N,$){return`/sdk/evalx/${t}/contexts/${de($,N)}`},pathReport(N,$){return`/sdk/evalx/${t}/context`},pathPing(N,$){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(N,$){return`/eval/${t}/${de($,N)}`},pathReport(N,$){return`/eval/${t}`},pathPing(N,$){return`/ping/${t}`}}),y,C,Ft),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:g=>new x.InputCustomEvent(g.context,g.key,g.data,g.metricValue,g.samplingRatio,d(L()))}),this.setEventSendingEnabled(!0,!1),h.fetchGoals&&(this.Bt=new et(t,l.requests,c,g=>{o.error(g.message)},(g,m)=>{let y=this.getInternalContext();if(!y)return;let C=d(g);Di(m)?this.sendEvent({kind:"click",url:C,samplingRatio:1,key:m.key,creationDate:Date.now(),context:y,selector:m.selector}):this.sendEvent({kind:"pageview",url:C,samplingRatio:1,key:m.key,creationDate:Date.now(),context:y})}),this.Bt.initialize(),h.automaticBackgroundHandling&&wi(()=>this.flush()))}async identify(t,e){var i;await super.identify(t,e),(i=this.Bt)==null||i.startTracking()}setStreaming(t){this.dataManager.setForcedStreaming(t)}ke(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.ke()}off(t,e){super.off(t,e),this.ke()}};var xi=["ready","failed","initialized"],ht=class{constructor(t){this.n=t;this.e=new Map}on(t,e){var i;xi.includes(t)?this.e.has(t)?(i=this.e.get(t))==null||i.push(e):this.e.set(t,[e]):this.n.on(t,e)}off(t,e){if(xi.includes(t)){let i=this.e.get(t);if(!i)return;if(e){let r=i.filter(s=>s!==e);r.length===0?this.e.delete(t):this.e.set(t,r);return}this.e.delete(t)}else this.n.off(t,e)}Lt(t,e,...i){try{t(...i)}catch(r){this.n.logger.error(`Encountered error invoking handler for "${e}", detail: "${r}"`)}}emit(t,...e){let i=this.e.get(t);i==null||i.forEach(r=>this.Lt(r,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,i;return(i=(e=this.e.get(t))==null?void 0:e.length)!=null?i:0}};function Mt(n,t){let e=n.then(i=>(t&&setTimeout(()=>{t(null,i)},0),i),i=>{if(t)setTimeout(()=>{t(i,null)},0);else return Promise.reject(i)});return t?void 0:e}var dt=class{constructor(t,e,i){this.Kt="initializing";let r=i==null?void 0:i.bootstrap,s=i==null?void 0:i.hash,a=p({},i);delete a.bootstrap,delete a.hash,this.n=new It(t,U.Disabled,i),this.x=new ht(this.n),this.logger=this.n.logger,this.Si(e,r,s)}async Si(t,e,i){var r,s;try{await this.n.identify(t,{noTimeout:!0,bootstrap:e,hash:i}),this.Kt="success",(r=this.Se)==null||r.call(this),this.x.emit("initialized")}catch(a){this.Le=a,this.Kt="failure",(s=this.xe)==null||s.call(this,a),this.x.emit("failed",a)}this.x.emit("ready")}allFlags(){return this.n.allFlags()}boolVariation(t,e){return this.n.boolVariation(t,e)}boolVariationDetail(t,e){return this.n.boolVariationDetail(t,e)}jsonVariation(t,e){return this.n.jsonVariation(t,e)}jsonVariationDetail(t,e){return this.n.jsonVariationDetail(t,e)}numberVariation(t,e){return this.n.numberVariation(t,e)}numberVariationDetail(t,e){return this.n.numberVariationDetail(t,e)}off(t,e){this.x.off(t,e)}on(t,e){this.x.on(t,e)}stringVariation(t,e){return this.n.stringVariation(t,e)}stringVariationDetail(t,e){return this.n.stringVariationDetail(t,e)}track(t,e,i){this.n.track(t,e,i)}variation(t,e){return this.n.variation(t,e)}variationDetail(t,e){return this.n.variationDetail(t,e)}addHook(t){this.n.addHook(t)}setStreaming(t){this.n.setStreaming(t)}identify(t,e,i){return Mt(this.n.identify(t,{hash:e}).then(()=>this.allFlags()),i)}close(t){return Mt(this.n.close().then(),t)}flush(t){return Mt(this.n.flush().then(()=>{}),t)}getContext(){return this.n.getContext()}waitForInitialization(t){var e;if(this.W)return this.Ce(this.W,t);switch(this.Kt){case"success":return Promise.resolve();case"failure":return Promise.reject(this.Le);case"initializing":break;default:throw new Error("Unexpected initialization state. This represents an implementation error in the SDK.")}return t===void 0&&((e=this.logger)==null||e.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),this.W||(this.W=new Promise((i,r)=>{this.Se=i,this.xe=r})),this.Ce(this.W,t)}async waitUntilReady(){try{await this.waitForInitialization()}catch(t){}}Ce(t,e){if(e){let i=We(e,"waitForInitialization");return Promise.race([t.then(()=>i.cancel()),i.promise]).catch(r=>{var s;throw r instanceof j&&((s=this.logger)==null||s.error(r.message)),r})}return t}};function Ws(n,t,e){return new dt(n,t,e)}export{Ws as initialize};