@dotcms/experiments 1.4.0-next.1 → 1.4.0-next.3

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.
@@ -1,12 +0,0 @@
1
- import { DotExperiments } from '../dot-experiments';
2
- /**
3
- * `DotExperimentsContext` is a React context that is designed to provide an instance of
4
- * `DotExperiments` to all of the components within its tree that are Consumers of this context.
5
- *
6
- * The context is created with a default value of `null`. It is meant to be provided a real value
7
- * using the `DotExperimentsProvider` component.
8
- *
9
- * @see {@link https://reactjs.org/docs/context.html|React Context}
10
- */
11
- declare const DotExperimentsContext: import("react").Context<DotExperiments | null>;
12
- export default DotExperimentsContext;
@@ -1,289 +0,0 @@
1
- import { DotExperimentConfig, Experiment, Variant } from './shared/models';
2
- /**
3
- * `DotExperiments` is a Typescript class to handles all operations related to fetching, storing, parsing, and navigating
4
- * data for Experiments (A/B Testing).
5
- *
6
- * It requires a configuration object for instantiation, please instance it using the method `getInstance` sending
7
- * an object with `api-key`, `server` and `debug`.
8
- *
9
- * Here's an example of how you can instantiate DotExperiments class:
10
- * @example
11
- * ```typescript
12
- * const instance = DotExperiments.getInstance({
13
- * server: "yourServerUrl",
14
- * "api-key": "yourApiKey"
15
- * });
16
- * ```
17
- *
18
- * @export
19
- * @class DotExperiments
20
- *
21
- */
22
- export declare class DotExperiments {
23
- private readonly config;
24
- /**
25
- * The instance of the DotExperiments class.
26
- * @private
27
- */
28
- private static instance;
29
- /**
30
- * Represents the default configuration for the DotExperiment library.
31
- * @property {boolean} trackPageView - Specifies whether to track page view or not. Default value is true.
32
- */
33
- private static readonly defaultConfig;
34
- /**
35
- * Represents the promise for the initialization process.
36
- * @private
37
- */
38
- private initializationPromise;
39
- /**
40
- * Represents the analytics client for Analytics.
41
- * @private
42
- */
43
- private analytics;
44
- /**
45
- * Class representing a database handler for IndexDB.
46
- * @class
47
- */
48
- private persistenceHandler;
49
- /**
50
- * Represents the stored data in the IndexedDB.
51
- * @private
52
- */
53
- private experimentsAssigned;
54
- /**
55
- * A logger utility for logging messages.
56
- *
57
- * @class
58
- */
59
- private logger;
60
- /**
61
- * Represents the current location.
62
- * @private
63
- */
64
- private currentLocation;
65
- /**
66
- * Represents the previous location.
67
- *
68
- * @type {string}
69
- */
70
- private prevLocation;
71
- private constructor();
72
- /**
73
- * Retrieves the array of experiments assigned to an instance of the class.
74
- *
75
- * @return {Experiment[]} An array containing the experiments assigned to the instance.
76
- */
77
- get experiments(): Experiment[];
78
- /**
79
- * Returns a custom redirect function. If a custom redirect function is not configured,
80
- * the default redirect function will be used.
81
- *
82
- * @return {function} A function that accepts a URL string parameter and performs a redirect.
83
- * If no parameter is provided, the function will not perform any action.
84
- */
85
- get customRedirectFn(): (url: string) => void;
86
- /**
87
- * Retrieves the current location.
88
- *
89
- * @returns {Location} The current location.
90
- */
91
- get location(): Location;
92
- /**
93
- * Retrieves instance of DotExperiments class if it doesn't exist create a new one.
94
- * If the instance does not exist, it creates a new instance with the provided configuration and calls the `getExperimentData` method.
95
- *
96
- * @param {DotExperimentConfig} config - The configuration object for initializing the DotExperiments instance.
97
- * @return {DotExperiments} - The instance of the DotExperiments class.
98
- */
99
- static getInstance(config?: DotExperimentConfig): DotExperiments;
100
- /**
101
- * Waits for the initialization process to be completed.
102
- *
103
- * @return {Promise<void>} A Promise that resolves when the initialization is ready.
104
- */
105
- ready(): Promise<void>;
106
- /**
107
- * This method appends variant parameters to navigation links based on the provided navClass.
108
- *
109
- * Note: In order for this method's functionality to apply, you need to define a class for the navigation elements (anchors)
110
- * to which you would like this functionality applied and pass it as an argument when calling this method.
111
- *
112
- * @param {string} navClass - The class of the navigation elements to which variant parameters should be appended. Such elements should be anchors (`<a>`).
113
- *
114
- * @example
115
- * <ul class="navbar-nav me-auto mb-2 mb-md-0">
116
- * <li class="nav-item">
117
- * <a class="nav-link " aria-current="page" href="/">Home</a>
118
- * </li>
119
- * <li class="nav-item ">
120
- * <a class="nav-link active" href="/blog">Travel Blog</a>
121
- * </li>
122
- * <li class="nav-item">
123
- * <a class="nav-link" href="/destinations">Destinations</a>
124
- * </li>
125
- * </ul>
126
- *
127
- * dotExperiment.ready().then(() => {
128
- * dotExperiment.appendVariantParams('.navbar-nav .nav-link');
129
- * });
130
- * appendVariantParams('nav-item-class');
131
- *
132
- * @returns {void}
133
- */
134
- appendVariantParams(navClass: string): void;
135
- /**
136
- * Retrieves the current debug status.
137
- *
138
- * @private
139
- * @returns {boolean} - The debug status.
140
- */
141
- getIsDebugActive(): boolean;
142
- /**
143
- * Updates the current location and checks if a variant should be applied.
144
- * Redirects to the variant URL if necessary.
145
- *
146
- * @param {Location} location - The new location.
147
- * @param redirectFunction
148
- */
149
- locationChanged(location: Location, redirectFunction?: (url: string) => void): Promise<void>;
150
- /**
151
- * Tracks a page view event in the analytics system.
152
- *
153
- * @return {void}
154
- */
155
- trackPageView(): void;
156
- /**
157
- * This method is used to retrieve the variant associated with a given URL.
158
- *
159
- * It checks if the URL is part of an experiment by verifying it against an experiment's regex. If the URL matches the regex of an experiment,
160
- * it returns the variant attached to that experiment; otherwise, it returns null.
161
- *
162
- * @param {string | null} path - The URL to check for a variant. This should be the path of the URL.
163
- *
164
- * @returns {Variant | null} The variant associated with the URL if it exists, null otherwise.
165
- */
166
- getVariantFromHref(path: string | null): Variant | null;
167
- /**
168
- * Returns the experiment variant name as a URL search parameter.
169
- *
170
- * @param {string|null} path - The path to the current page.
171
- * @returns {URLSearchParams} - The URL search parameters containing the experiment variant name.
172
- */
173
- getVariantAsQueryParam(path: string | null): URLSearchParams;
174
- /**
175
- * Determines whether a page view should be tracked.
176
- *
177
- * @private
178
- * @returns {boolean} True if a page view should be tracked, otherwise false.
179
- */
180
- private shouldTrackPageView;
181
- /**
182
- * Tracks an event using the analytics service.
183
- *
184
- * @param {string} typeName - The type of event to track.
185
- * @param {EventPayload} [payload] - Optional payload associated with the event.
186
- * @return {void}
187
- */
188
- private track;
189
- /**
190
- * Initializes the application using lazy initialization. This method performs
191
- * necessary setup steps and should be invoked to ensure proper execution of the application.
192
- *
193
- * Note: This method uses lazy initialization. Make sure to call this method to ensure
194
- * the application works correctly.
195
- *
196
- * @return {Promise<void>} A promise that resolves when the initialization is complete.
197
- */
198
- private initialize;
199
- /**
200
- * Fetches experiments from the server.
201
- *
202
- * @private
203
- * @returns {Promise<AssignedExperiments>} - The entity object returned from the server.
204
- * @throws {Error} - If an HTTP error occurs or an error occurs during the fetch request.
205
- */
206
- private getExperimentsFromServer;
207
- /**
208
- * This method is responsible for retrieving and persisting experiment data from the server to the local indexDB database.
209
- *
210
- * - Checks whether making a request to the server to fetch experiment data is required.
211
- * - Sends the request to the server for data if required.
212
- * - Parses the fetched data to the form required for storage in the database.
213
- * - Persists the data in the indexDB database.
214
- *
215
- * @private
216
- * @method verifyExperimentData
217
- * @async
218
- * @throws {Error} Throws an error with details if there is any failure in loading the experiments or during their persistence in indexDB.
219
- *
220
- * @returns {Promise<void>} An empty promise that fulfills once the experiment data has been successfully loaded and persisted.
221
- */
222
- private verifyExperimentData;
223
- /**
224
- * Persists the parsed experiment data into the indexDB database.
225
- *
226
- * The method does the following:
227
- * - Receives the parsed data.
228
- * - Updates the creation date.
229
- * - Clears existing data from the indexDB database.
230
- * - Stores the new data in the indexDB database.
231
- *
232
- * If there are no experiments in the received data, the method will not attempt to clear or persist anything and will return immediately.
233
- *.
234
- *
235
- * @note This method utilizes Promises for the asynchronous handling of data persistence. Errors during data persistence are caught and logged, but not re-thrown.
236
- *
237
- * @private
238
- * @method persistExperiments
239
- * @throws Nothing – Errors are caught and logged, but not re-thrown.
240
- *
241
- * @param experiments
242
- */
243
- private persistExperiments;
244
- /**
245
- * Initializes the database handler.
246
- *
247
- * This private method instantiates the class handling the IndexDB database
248
- * and assigns this instance to 'persistenceHandler'.
249
- *
250
- * @private
251
- */
252
- private initializeDatabaseHandler;
253
- /**
254
- * Initializes the Jitsu analytics client.
255
- *
256
- * This private method sets up the Jitsu client responsible for sending events
257
- * to the server with the provided configuration. It also uses the parsed data
258
- * and registers it as global within Jitsu.
259
- *
260
- * @private
261
- */
262
- private initAnalyticsClient;
263
- /**
264
- * Updates the analytics client's data using the experiments data
265
- * currently available in the IndexDB database, based on the current location.
266
- *
267
- * Retrieves and processes the experiments information according to the
268
- * current location into a suitable format for `analytics.set()`.
269
- *
270
- * @private
271
- * @method refreshAnalyticsForCurrentLocation
272
- * @returns {void}
273
- */
274
- private refreshAnalyticsForCurrentLocation;
275
- /**
276
- * Determines whether analytics should be checked.
277
- *
278
- * @private
279
- * @returns {Promise<boolean>} A boolean value indicating whether analytics should be checked.
280
- */
281
- private shouldFetchNewData;
282
- /**
283
- * Retrieves persisted data from the database.
284
- *
285
- * @private
286
- * @returns {Promise<void>} A promise that resolves with no value.
287
- */
288
- private getPersistedData;
289
- }
@@ -1,17 +0,0 @@
1
- import { DotCMSPageAsset } from '@dotcms/types';
2
- /**
3
- * A React Hook that determines whether to wait for the correct variant in an A/B testing scenario.
4
- * This is used to avoid flickering - showing the original content before redirecting to the assigned variant.
5
- *
6
- * The hook uses the running experiment id and viewAs (containing variantId) from the provided data.
7
- * It then works with the DotExperimentsContext to synchronize between the assigned variant and the one requested.
8
- * If the hook is executed inside an editor or if no running experiment id is provided, it immediately signals not to wait for the variant.
9
- * Similarly, if the assigned variant matches the requested one, it signals not to wait for the variant.
10
- * By default, the hook signals to wait for the variant.
11
- *
12
- * @param {Object} data - An object containing the runningExperimentId and viewAs (containing variantId).
13
- * @returns {Object} An object with a function `shouldWaitForVariant` that, when called, returns `true` if it should wait for the correct variant, `false` otherwise.
14
- */
15
- export declare const useExperimentVariant: (data: DotCMSPageAsset) => {
16
- shouldWaitForVariant: boolean;
17
- };
@@ -1,14 +0,0 @@
1
- import { DotExperiments } from '../dot-experiments';
2
- /**
3
- * Custom hook `useExperiments`.
4
- *
5
- * This hook is designed to handle changes in the location of the current DotExperiments
6
- * instance and set a global click handler that redirects the application when an element with an
7
- * assigned variant is clicked.
8
- *
9
- * It also manages adding or removing the experimentation query parameter from the URL as
10
- * appropriate when a click occurs.
11
- *
12
- * @returns {void}
13
- */
14
- export declare const useExperiments: (instance: DotExperiments | null) => void;
@@ -1,95 +0,0 @@
1
- /**
2
- * The key for identifying the Window key for SdkExperiment.
3
- *
4
- * @constant {string}
5
- */
6
- export declare const EXPERIMENT_WINDOWS_KEY = "dotExperiment";
7
- /**
8
- * The default variant name for an experiment.
9
- *
10
- * @type {string}
11
- * @constant
12
- */
13
- export declare const EXPERIMENT_DEFAULT_VARIANT_NAME = "DEFAULT";
14
- /**
15
- * The key used to store or retrieve the information in the SessionStore
16
- *
17
- * @constant {string}
18
- */
19
- export declare const EXPERIMENT_QUERY_PARAM_KEY = "variantName";
20
- /**
21
- * The key used to store or retrieve the information in the SessionStore
22
- * indicating whether an experiment has already been checked.
23
- *
24
- * @constant {string}
25
- */
26
- export declare const EXPERIMENT_ALREADY_CHECKED_KEY = "experimentAlreadyCheck";
27
- /**
28
- * EXPERIMENT_FETCH_EXPIRE_TIME is a constant that represents the name of the variable used to store
29
- * the expire time for experiment fetching. It is a string value 'experimentFetchExpireTime'.
30
- *
31
- * @constant {string}
32
- */
33
- export declare const EXPERIMENT_FETCH_EXPIRE_TIME_KEY = "experimentFetchExpireTime";
34
- /**
35
- * The duration in milliseconds for which data should be stored in the local storage.
36
- *
37
- * @type {number}
38
- * @constant
39
- * @default 86400000 (A day)
40
- *
41
- */
42
- export declare const LOCAL_STORAGE_TIME_DURATION_MILLISECONDS: number;
43
- /**
44
- * The name of the experiment script file.
45
- *
46
- * @constant {string}
47
- */
48
- export declare const EXPERIMENT_SCRIPT_FILE_NAME = "dot-experiments.min.iife.js";
49
- /**
50
- * The prefix used for the experiment script data attributes.
51
- *
52
- * @constant {string}
53
- */
54
- export declare const EXPERIMENT_SCRIPT_DATA_PREFIX = "data-experiment-";
55
- /**
56
- * Array containing the allowed data attributes for an experiment.
57
- *
58
- * @type {Array.<string>}
59
- * @constant
60
- */
61
- export declare const EXPERIMENT_ALLOWED_DATA_ATTRIBUTES: string[];
62
- /**
63
- * API_EXPERIMENTS_URL
64
- *
65
- * The URL of the endpoint to check if a user is included in experiments.
66
- *
67
- * @type {string}
68
- * @constant
69
- */
70
- export declare const API_EXPERIMENTS_URL = "api/v1/experiments/isUserIncluded";
71
- /**
72
- * The name of the experiment database store in indexDB.
73
- *
74
- * @type {string}
75
- * @constant
76
- */
77
- export declare const EXPERIMENT_DB_STORE_NAME = "dotExperimentStore";
78
- /**
79
- * The path to the key in the database IndexDB representing the running experiment data.
80
- * @type {string}
81
- */
82
- export declare const EXPERIMENT_DB_KEY_PATH = "running_experiment";
83
- /**
84
- * Enumeration of debug levels.
85
- *
86
- * @enum {string}
87
- * @readonly
88
- */
89
- export declare enum DEBUG_LEVELS {
90
- NONE = "NONE",
91
- DEBUG = "DEBUG",
92
- WARN = "WARN",
93
- ERROR = "ERROR"
94
- }
95
- export declare const PAGE_VIEW_EVENT_NAME = "pageview";
@@ -1,43 +0,0 @@
1
- import { Experiment, ExperimentEvent, IsUserIncludedApiResponse } from '../models';
2
- /**
3
- * Represents the response object for the IsUserIncluded API.
4
- * @typedef {Object} IsUserIncludedResponse
5
- * @property {IsUserIncludedApiResponse} entity - The response entity.
6
- * @property {string[]} errors - Array of error messages, if any.
7
- * @property {Object} i18nMessagesMap - Map of internationalization messages.
8
- * @property {string[]} messages - Array of additional messages, if any.
9
- */
10
- export declare const IsUserIncludedResponse: IsUserIncludedApiResponse;
11
- export declare const NewIsUserIncludedResponse: IsUserIncludedApiResponse;
12
- export declare const After15DaysIsUserIncludedResponse: IsUserIncludedApiResponse;
13
- export declare const NoExperimentsIsUserIncludedResponse: IsUserIncludedApiResponse;
14
- export declare const MOCK_CURRENT_TIMESTAMP = 1704096000000;
15
- export declare const TIME_15_DAYS_MILLISECONDS: number;
16
- export declare const TIME_5_DAYS_MILLISECONDS: number;
17
- export declare const MockDataStoredIndexDB: Experiment[];
18
- export declare const MockDataStoredIndexDBNew: Experiment[];
19
- export declare const MockDataStoredIndexDBWithNew: Experiment[];
20
- export declare const MockDataStoredIndexDBWithNew15DaysLater: Experiment[];
21
- /**
22
- * Represents an event that indicates the expected experiments parsed from a response to send to Analytics.
23
- *
24
- * @typedef {Object} ExpectedExperimentsParsedEvent
25
- * @property {ExperimentEvent[]} experiments - An array of experiment events.
26
- */
27
- export declare const ExpectedExperimentsParsedEvent: ExperimentEvent[];
28
- /**
29
- * Represents a mock location object.
30
- *
31
- * @typedef {Object} LocationMock
32
- * @property {string} href - The complete URL.
33
- *
34
- */
35
- export declare const LocationMock: Location;
36
- export declare const sessionStorageMock: {
37
- getItem: (key: string) => string | null;
38
- setItem: (key: string, value: string) => void;
39
- removeItem: (key: string) => void;
40
- clear: () => void;
41
- key: (index: number) => string | null;
42
- readonly length: number;
43
- };
@@ -1,209 +0,0 @@
1
- /**
2
- * Represents the configuration for the SDK experiment.
3
- *
4
- * @interface DotExperimentConfig
5
- */
6
- export interface DotExperimentConfig {
7
- /**
8
- * This is `Analytics Key` provided by Analytics Integration App at DotCMS.
9
- */
10
- apiKey: string;
11
- /**
12
- * The URL of the Public DotCMS Host server for the SDK to connect to.
13
- */
14
- server: string;
15
- /**
16
- * A flag that determines whether the experiment is in debug mode or not. When in debug mode, the SDK could provide more logging information.
17
- */
18
- debug: boolean;
19
- /**
20
- * An optional property. True by default to automatically track page views. It's useful for understanding user behavior in the experiment.
21
- */
22
- trackPageView?: boolean;
23
- /**
24
- * An optional property. It is a function that handles URL redirections. When supplied, the SDK will call this function instead of using the default browser redirect when it's necessary to redirect the page.
25
- * @param url
26
- */
27
- redirectFn?: (url: string) => void;
28
- }
29
- /**
30
- * Represents the configuration for the LookBackWindow.
31
- *
32
- * @interface LookBackWindow
33
- */
34
- export interface LookBackWindow {
35
- /**
36
- * Defines the time period in milliseconds when the LookBackWindow should expire.
37
- */
38
- expireMillis: number;
39
- /**
40
- * A value indicating the expiration timestamp of the experiment.
41
- */
42
- expireTime?: number;
43
- /**
44
- * Represents the associated value with the LookBackWindow.
45
- */
46
- value: string;
47
- }
48
- /**
49
- * Represents the configurations for checking whether the current page is an Experiment page, or a target.
50
- *
51
- * @interface Regexs
52
- */
53
- interface Regexs {
54
- /**
55
- * A regular expression for validating if the page is an Experiment page.
56
- */
57
- isExperimentPage: string;
58
- /**
59
- * A regular expression for validating if the page is the target page. This can be null.
60
- */
61
- isTargetPage: string | null;
62
- }
63
- /**
64
- * Represents a variant that is applied when a request is made.
65
- *
66
- * @interface Variant
67
- */
68
- export interface Variant {
69
- /**
70
- * The name of the variant.
71
- */
72
- name: string;
73
- /**
74
- * The fully qualified URL where the variant is being applied, with query parameters already set.
75
- */
76
- url: string;
77
- }
78
- /**
79
- * Represents an experiment with all its configurations.
80
- *
81
- * @interface Experiment
82
- */
83
- export interface Experiment {
84
- /**
85
- * The unique identifier for the experiment.
86
- */
87
- id: string;
88
- /**
89
- * The lookback window object for the experiment.
90
- */
91
- lookBackWindow: LookBackWindow;
92
- /**
93
- * The name of the experiment.
94
- */
95
- name: string;
96
- /**
97
- * The URL of the page where the experiment is applied.
98
- */
99
- pageUrl: string;
100
- /**
101
- * The object containing regular expressions for validating pages.
102
- */
103
- regexs: Regexs;
104
- /**
105
- * The unique running identifier for the experiment.
106
- */
107
- runningId: string;
108
- /**
109
- * The variant applied to the user making the request.
110
- */
111
- variant: Variant;
112
- }
113
- /**
114
- * Represents the experiments assigned and their details.
115
- *
116
- * @interface AssignedExperiments
117
- */
118
- export interface AssignedExperiments {
119
- /**
120
- * The ids of the experiments that are excluded in the assignment.
121
- */
122
- excludedExperimentIds: string[];
123
- /**
124
- * An array representing the assigned experiments.
125
- */
126
- experiments: Experiment[];
127
- /**
128
- * The ids of the experiments included in the assignment.
129
- */
130
- includedExperimentIds: string[];
131
- /**
132
- * The ids of the experiments that are excluded in the request and have ended.
133
- */
134
- excludedExperimentIdsEnded: string[];
135
- }
136
- /**
137
- * Represents the response from the backend when fetching an experiment and the excludedExperimentIdsEnded.
138
- */
139
- export type FetchExperiments = Pick<AssignedExperiments, 'excludedExperimentIdsEnded' | 'experiments'>;
140
- /**
141
- * Represents the response from backend holding information about running experiments and variant assignment.
142
- *
143
- * @interface IsUserIncludedApiResponse
144
- */
145
- export interface IsUserIncludedApiResponse {
146
- /**
147
- * The object holding all experiment-related information.
148
- */
149
- entity: AssignedExperiments;
150
- /**
151
- * An array holding possible error messages.
152
- */
153
- errors: string[];
154
- /**
155
- * A map that holds internationalization (i18n) messages.
156
- */
157
- i18nMessagesMap: Record<string, string>;
158
- /**
159
- * An array of generic messages.
160
- */
161
- messages: string[];
162
- }
163
- /**
164
- * Represents a single experiment event.
165
- *
166
- * @interface ExperimentEvent
167
- */
168
- export interface ExperimentEvent {
169
- /**
170
- * The name or identifier of the experiment.
171
- */
172
- experiment: string;
173
- /**
174
- * The unique running identifier of the experiment.
175
- */
176
- runningId: string;
177
- /**
178
- * A flag that determines if the current page is the one where the experiment is conducted.
179
- */
180
- isExperimentPage: boolean;
181
- /**
182
- * A flag that determines if the current page is the target page of the experiment.
183
- */
184
- isTargetPage: boolean;
185
- /**
186
- * Represents the time period for which the experiment is valid or should be considered.
187
- */
188
- lookBackWindow: string;
189
- /**
190
- * Represents the variant of the experiment to specify different versions of an experiment.
191
- */
192
- variant: string;
193
- }
194
- /**
195
- * Represents parsed data of an experiment that is ready to be sent to Analytics.
196
- *
197
- * @interface ExperimentParsed
198
- */
199
- export interface ExperimentParsed {
200
- /**
201
- * The URL of the experiment. It helps track the location or origin of the experiment.
202
- */
203
- href: string;
204
- /**
205
- * An array holding details of individual experiments being conducted.
206
- */
207
- experiments: ExperimentEvent[];
208
- }
209
- export {};