@contentful/optimization-core 0.1.0-alpha

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 (111) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +408 -0
  3. package/dist/Consent.d.ts +44 -0
  4. package/dist/Consent.d.ts.map +1 -0
  5. package/dist/Consent.js +2 -0
  6. package/dist/Consent.js.map +1 -0
  7. package/dist/CoreBase.d.ts +161 -0
  8. package/dist/CoreBase.d.ts.map +1 -0
  9. package/dist/CoreBase.js +151 -0
  10. package/dist/CoreBase.js.map +1 -0
  11. package/dist/CoreStateful.d.ts +142 -0
  12. package/dist/CoreStateful.d.ts.map +1 -0
  13. package/dist/CoreStateful.js +137 -0
  14. package/dist/CoreStateful.js.map +1 -0
  15. package/dist/CoreStateless.d.ts +53 -0
  16. package/dist/CoreStateless.d.ts.map +1 -0
  17. package/dist/CoreStateless.js +43 -0
  18. package/dist/CoreStateless.js.map +1 -0
  19. package/dist/ProductBase.d.ts +83 -0
  20. package/dist/ProductBase.d.ts.map +1 -0
  21. package/dist/ProductBase.js +50 -0
  22. package/dist/ProductBase.js.map +1 -0
  23. package/dist/analytics/AnalyticsBase.d.ts +35 -0
  24. package/dist/analytics/AnalyticsBase.d.ts.map +1 -0
  25. package/dist/analytics/AnalyticsBase.js +13 -0
  26. package/dist/analytics/AnalyticsBase.js.map +1 -0
  27. package/dist/analytics/AnalyticsStateful.d.ts +138 -0
  28. package/dist/analytics/AnalyticsStateful.d.ts.map +1 -0
  29. package/dist/analytics/AnalyticsStateful.js +179 -0
  30. package/dist/analytics/AnalyticsStateful.js.map +1 -0
  31. package/dist/analytics/AnalyticsStateless.d.ts +48 -0
  32. package/dist/analytics/AnalyticsStateless.d.ts.map +1 -0
  33. package/dist/analytics/AnalyticsStateless.js +61 -0
  34. package/dist/analytics/AnalyticsStateless.js.map +1 -0
  35. package/dist/analytics/index.d.ts +5 -0
  36. package/dist/analytics/index.d.ts.map +1 -0
  37. package/dist/analytics/index.js +5 -0
  38. package/dist/analytics/index.js.map +1 -0
  39. package/dist/global-constants.d.ts +18 -0
  40. package/dist/global-constants.d.ts.map +1 -0
  41. package/dist/global-constants.js +18 -0
  42. package/dist/global-constants.js.map +1 -0
  43. package/dist/index.cjs +1808 -0
  44. package/dist/index.cjs.map +1 -0
  45. package/dist/index.d.ts +15 -0
  46. package/dist/index.d.ts.map +1 -0
  47. package/dist/index.js +15 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/index.mjs +1535 -0
  50. package/dist/index.mjs.map +1 -0
  51. package/dist/lib/decorators/guardedBy.d.ts +113 -0
  52. package/dist/lib/decorators/guardedBy.d.ts.map +1 -0
  53. package/dist/lib/decorators/guardedBy.js +143 -0
  54. package/dist/lib/decorators/guardedBy.js.map +1 -0
  55. package/dist/lib/decorators/index.d.ts +2 -0
  56. package/dist/lib/decorators/index.d.ts.map +1 -0
  57. package/dist/lib/decorators/index.js +2 -0
  58. package/dist/lib/decorators/index.js.map +1 -0
  59. package/dist/lib/interceptor/InterceptorManager.d.ts +127 -0
  60. package/dist/lib/interceptor/InterceptorManager.d.ts.map +1 -0
  61. package/dist/lib/interceptor/InterceptorManager.js +125 -0
  62. package/dist/lib/interceptor/InterceptorManager.js.map +1 -0
  63. package/dist/lib/interceptor/index.d.ts +2 -0
  64. package/dist/lib/interceptor/index.d.ts.map +1 -0
  65. package/dist/lib/interceptor/index.js +2 -0
  66. package/dist/lib/interceptor/index.js.map +1 -0
  67. package/dist/lib/value-presence/ValuePresence.d.ts +123 -0
  68. package/dist/lib/value-presence/ValuePresence.d.ts.map +1 -0
  69. package/dist/lib/value-presence/ValuePresence.js +141 -0
  70. package/dist/lib/value-presence/ValuePresence.js.map +1 -0
  71. package/dist/lib/value-presence/index.d.ts +2 -0
  72. package/dist/lib/value-presence/index.d.ts.map +1 -0
  73. package/dist/lib/value-presence/index.js +2 -0
  74. package/dist/lib/value-presence/index.js.map +1 -0
  75. package/dist/personalization/PersonalizationBase.d.ts +184 -0
  76. package/dist/personalization/PersonalizationBase.d.ts.map +1 -0
  77. package/dist/personalization/PersonalizationBase.js +76 -0
  78. package/dist/personalization/PersonalizationBase.js.map +1 -0
  79. package/dist/personalization/PersonalizationStateful.d.ts +226 -0
  80. package/dist/personalization/PersonalizationStateful.d.ts.map +1 -0
  81. package/dist/personalization/PersonalizationStateful.js +297 -0
  82. package/dist/personalization/PersonalizationStateful.js.map +1 -0
  83. package/dist/personalization/PersonalizationStateless.d.ts +74 -0
  84. package/dist/personalization/PersonalizationStateless.d.ts.map +1 -0
  85. package/dist/personalization/PersonalizationStateless.js +98 -0
  86. package/dist/personalization/PersonalizationStateless.js.map +1 -0
  87. package/dist/personalization/index.d.ts +6 -0
  88. package/dist/personalization/index.d.ts.map +1 -0
  89. package/dist/personalization/index.js +6 -0
  90. package/dist/personalization/index.js.map +1 -0
  91. package/dist/personalization/resolvers/FlagsResolver.d.ts +35 -0
  92. package/dist/personalization/resolvers/FlagsResolver.d.ts.map +1 -0
  93. package/dist/personalization/resolvers/FlagsResolver.js +47 -0
  94. package/dist/personalization/resolvers/FlagsResolver.js.map +1 -0
  95. package/dist/personalization/resolvers/MergeTagValueResolver.d.ts +74 -0
  96. package/dist/personalization/resolvers/MergeTagValueResolver.d.ts.map +1 -0
  97. package/dist/personalization/resolvers/MergeTagValueResolver.js +109 -0
  98. package/dist/personalization/resolvers/MergeTagValueResolver.js.map +1 -0
  99. package/dist/personalization/resolvers/PersonalizedEntryResolver.d.ts +142 -0
  100. package/dist/personalization/resolvers/PersonalizedEntryResolver.d.ts.map +1 -0
  101. package/dist/personalization/resolvers/PersonalizedEntryResolver.js +196 -0
  102. package/dist/personalization/resolvers/PersonalizedEntryResolver.js.map +1 -0
  103. package/dist/personalization/resolvers/index.d.ts +7 -0
  104. package/dist/personalization/resolvers/index.d.ts.map +1 -0
  105. package/dist/personalization/resolvers/index.js +7 -0
  106. package/dist/personalization/resolvers/index.js.map +1 -0
  107. package/dist/signals.d.ts +35 -0
  108. package/dist/signals.d.ts.map +1 -0
  109. package/dist/signals.js +30 -0
  110. package/dist/signals.js.map +1 -0
  111. package/package.json +29 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (C) 2026 Contentful Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,408 @@
1
+ <p align="center">
2
+ <a href="https://www.contentful.com/developers/docs/personalization/">
3
+ <img alt="Contentful Logo" title="Contentful" src="../../contentful-icon.png" width="150">
4
+ </a>
5
+ </p>
6
+
7
+ <h1 align="center">Contentful Personalization & Analytics</h1>
8
+
9
+ <h3 align="center">Optimization Core SDK</h3>
10
+
11
+ <div align="center">
12
+
13
+ [Readme](./README.md) · [Reference](https://contentful.github.io/optimization) ·
14
+ [Contributing](/CONTRIBUTING.md)
15
+
16
+ </div>
17
+
18
+ > [!WARNING]
19
+ >
20
+ > The Optimization SDK Suite is currently ALPHA! Breaking changes may be published at any time.
21
+
22
+ The Optimization Core SDK encapsulates all platform-agnostic functionality and business logic. All
23
+ other SDKs descend from the Core SDK.
24
+
25
+ <details>
26
+ <summary>Table of Contents</summary>
27
+ <!-- mtoc-start -->
28
+
29
+ - [Getting Started](#getting-started)
30
+ - [Working with Stateless Core](#working-with-stateless-core)
31
+ - [Working with Stateful Core](#working-with-stateful-core)
32
+ - [Configuration](#configuration)
33
+ - [Top-level Configuration Options](#top-level-configuration-options)
34
+ - [Analytics Options](#analytics-options)
35
+ - [Event Builder Options](#event-builder-options)
36
+ - [Fetch Options](#fetch-options)
37
+ - [Personalization Options](#personalization-options)
38
+ - [Core Methods](#core-methods)
39
+ - [Personalization Data Resolution Methods](#personalization-data-resolution-methods)
40
+ - [`getCustomFlag`](#getcustomflag)
41
+ - [`personalizeEntry`](#personalizeentry)
42
+ - [`getMergeTagValue`](#getmergetagvalue)
43
+ - [Personalization and Analytics Event Methods](#personalization-and-analytics-event-methods)
44
+ - [`identify`](#identify)
45
+ - [`page`](#page)
46
+ - [`track`](#track)
47
+ - [`trackComponentView`](#trackcomponentview)
48
+ - [`trackFlagView`](#trackflagview)
49
+ - [Stateful-only Core Methods](#stateful-only-core-methods)
50
+ - [`consent`](#consent)
51
+ - [`reset`](#reset)
52
+ - [Stateful-only Core Properties](#stateful-only-core-properties)
53
+ - [Interceptors](#interceptors)
54
+ - [Life-cycle Interceptors](#life-cycle-interceptors)
55
+
56
+ <!-- mtoc-end -->
57
+ </details>
58
+
59
+ ## Getting Started
60
+
61
+ Install using an NPM-compatible package manager, pnpm for example:
62
+
63
+ ```sh
64
+ pnpm install @contentful/optimization-core
65
+ ```
66
+
67
+ Import either the stateful or stateless Core class, depending on the target environment; both CJS
68
+ and ESM module systems are supported, ESM preferred:
69
+
70
+ ```ts
71
+ import { CoreStateful } from '@contentful/optimization-core'
72
+ // or
73
+ import { CoreStateless } from '@contentful/optimization-core'
74
+ ```
75
+
76
+ Configure and initialize the Core SDK:
77
+
78
+ ```ts
79
+ const optimization = new CoreStateful({ clientId: 'abc123' })
80
+ // or
81
+ const optimization = new CoreStateless({ clientId: 'abc123' })
82
+ ```
83
+
84
+ ## Working with Stateless Core
85
+
86
+ The `CoreStateless` class is intended to be used as the basis for SDKs that would run in stateless
87
+ environments such as Node-based servers and server-side functions in meta-frameworks such as
88
+ Next.js.
89
+
90
+ In stateless environments, Core will not maintain any internal state, which includes user consent.
91
+ These concerns should be handled by consumers to fit their specific architectural and design
92
+ specifications.
93
+
94
+ ## Working with Stateful Core
95
+
96
+ The `CoreStateful` class is intended to be used as the basis for SDKs that would run in stateful
97
+ environments such as Web front-ends and mobile applications (via JavaScript runtime containers).
98
+
99
+ In stateful environments, Core maintains state internally for consent, an event stream, and
100
+ profile-related data that is commonly obtained from requests to the Experience API. These states are
101
+ exposed externally as read-only observables.
102
+
103
+ ## Configuration
104
+
105
+ ### Top-level Configuration Options
106
+
107
+ | Option | Required? | Default | Description |
108
+ | ----------------- | --------- | ----------------------------- | --------------------------------------------------------------------- |
109
+ | `analytics` | No | See "Analytics Options" | Configuration specific to the Analytics/Insights API |
110
+ | `clientId` | Yes | N/A | The Ninetailed API Key which can be found in the Ninetailed Admin app |
111
+ | `environment` | No | `'main'` | The Ninetailed environment configured in the Ninetailed Admin app |
112
+ | `eventBuilder` | No | See "Event Builder Options" | Event builder configuration (channel/library metadata, etc.) |
113
+ | `fetchOptions` | No | See "Fetch Options" | Configuration for Fetch timeout and retry functionality |
114
+ | `logLevel` | No | `'error'` | Minimum log level for the default console sin |
115
+ | `personalization` | No | See "Personalization Options" | Configuration specific to the Personalization/Experience API |
116
+
117
+ The following configuration options apply only in stateful environments:
118
+
119
+ | Option | Required? | Default | Description |
120
+ | -------------------------- | --------- | ---------------------- | ----------------------------------------------------------------- |
121
+ | `allowedEventTypes` | No | `['identify', 'page']` | Allow-listed event types permitted when consent is not set |
122
+ | `defaults` | No | `undefined` | Set of default state values applied on initialization |
123
+ | `getAnonymousId` | No | `undefined` | Function used to obtain an anonymous user identifier |
124
+ | `preventedComponentEvents` | No | `undefined` | Initial duplication prevention configuration for component events |
125
+
126
+ Configuration method signatures:
127
+
128
+ - `getAnonymousId`: `() => string | undefined`
129
+
130
+ ### Analytics Options
131
+
132
+ | Option | Required? | Default | Description |
133
+ | --------- | --------- | ------------------------------------------ | ----------------------------- |
134
+ | `baseUrl` | No | `'https://ingest.insights.ninetailed.co/'` | Base URL for the Insights API |
135
+
136
+ The following configuration options apply only in stateful environments:
137
+
138
+ | Option | Required? | Default | Description |
139
+ | --------------- | --------- | ----------- | ------------------------------------------------------------------------ |
140
+ | `beaconHandler` | No | `undefined` | Handler used to enqueue events via the Beacon API or a similar mechanism |
141
+
142
+ Configuration method signatures:
143
+
144
+ - `beaconHandler`: `(url: string | URL, data: BatchInsightsEventArray) => boolean`
145
+
146
+ ### Event Builder Options
147
+
148
+ Event builder options should only be supplied when building an SDK on top of Core or any of its
149
+ descendent SDKs.
150
+
151
+ | Option | Required? | Default | Description |
152
+ | --------- | --------- | ----------- | ---------------------------------------------------------------------------------- |
153
+ | `app` | No | `undefined` | The application definition used to attribute events to a specific consumer app |
154
+ | `channel` | Yes | N/A | The channel that identifies where events originate from (e.g. `'web'`, `'mobile'`) |
155
+ | `library` | Yes | N/A | The client library metadata that is attached to all events |
156
+
157
+ The `channel` option may contain one of the following values:
158
+
159
+ - `web`
160
+ - `mobile`
161
+ - `server`
162
+
163
+ The following configuration options apply only in stateful environments:
164
+
165
+ | Option | Required? | Default | Description |
166
+ | ------------------- | --------- | ------------------------------- | --------------------------------------------------------------------- |
167
+ | `getLocale` | No | `() => 'en-US'` | Function used to resolve the locale for outgoing events |
168
+ | `getPageProperties` | No | `() => DEFAULT_PAGE_PROPERTIES` | Function that returns the current page properties |
169
+ | `getUserAgent` | No | `() => undefined` | Function used to obtain the current user agent string when applicable |
170
+
171
+ Configuration method signatures:
172
+
173
+ - `getLocale`: `() => string | undefined`
174
+ - `getPageProperties`:
175
+
176
+ ```ts
177
+ () => {
178
+ path: string,
179
+ query: Record<string, string>,
180
+ referrer: string,
181
+ search: string,
182
+ title?: string,
183
+ url: string
184
+ }
185
+ ```
186
+
187
+ - `getUserAgent`: `() => string | undefined`
188
+
189
+ ### Fetch Options
190
+
191
+ Fetch options allow for configuration of a Fetch API-compatible fetch method and the retry/timeout
192
+ logic integrated into the Optimization API Client. Specify the `fetchMethod` when the host
193
+ application environment does not offer a `fetch` method that is compatible with the standard Fetch
194
+ API in its global scope.
195
+
196
+ | Option | Required? | Default | Description |
197
+ | ------------------ | --------- | ----------- | --------------------------------------------------------------------- |
198
+ | `fetchMethod` | No | `undefined` | Signature of a fetch method used by the API clients |
199
+ | `intervalTimeout` | No | `0` | Delay (in milliseconds) between retry attempts |
200
+ | `onFailedAttempt` | No | `undefined` | Callback invoked whenever a retry attempt fails |
201
+ | `onRequestTimeout` | No | `undefined` | Callback invoked when a request exceeds the configured timeout |
202
+ | `requestTimeout` | No | `3000` | Maximum time (in milliseconds) to wait for a response before aborting |
203
+ | `retries` | No | `1` | Maximum number of retry attempts |
204
+
205
+ Configuration method signatures:
206
+
207
+ - `fetchMethod`: `(url: string | URL, init: RequestInit) => Promise<Response>`
208
+ - `onFailedAttempt` and `onRequestTimeout`: `(options: FetchMethodCallbackOptions) => void`
209
+
210
+ ### Personalization Options
211
+
212
+ | Option | Required? | Default | Description |
213
+ | ----------------- | --------- | ------------------------------------- | ------------------------------------------------------------------- |
214
+ | `baseUrl` | No | `'https://experience.ninetailed.co/'` | Base URL for the Experience API |
215
+ | `enabledFeatures` | No | `['ip-enrichment', 'location']` | Enabled features which the API may use for each request |
216
+ | `ip` | No | `undefined` | IP address to override the API behavior for IP analysis |
217
+ | `locale` | No | `'en-US'` (in API) | Locale used to translate `location.city` and `location.country` |
218
+ | `plainText` | No | `false` | Sends performance-critical endpoints in plain text |
219
+ | `preflight` | No | `false` | Instructs the API to aggregate a new profile state but not store it |
220
+
221
+ ## Core Methods
222
+
223
+ The methods in this section are available in both stateful and stateless Core classes. However, be
224
+ aware that there are some minor differences in argument usage between stateful and stateless Core
225
+ implementations.
226
+
227
+ Arguments marked with an asterisk (\*) are always required.
228
+
229
+ ### Personalization Data Resolution Methods
230
+
231
+ #### `getCustomFlag`
232
+
233
+ Get the specified Custom Flag's value from the provided changes array, or from the current internal
234
+ state in stateful implementations.
235
+
236
+ Arguments:
237
+
238
+ - `name`\*: The name/key of the Custom Flag
239
+ - `changes`: Changes array
240
+
241
+ Returns:
242
+
243
+ - The resolved value for the specified Custom Flag, or `undefined` if it cannot be found.
244
+
245
+ > [!NOTE]
246
+ >
247
+ > If the `changes` argument is omitted in stateless implementations, the method will return
248
+ > `undefined`.
249
+
250
+ #### `personalizeEntry`
251
+
252
+ Resolve a baseline Contentful entry to a personalized variant using the provided selected
253
+ personalizations, or from the current internal state in stateful implementations.
254
+
255
+ Type arguments:
256
+
257
+ - `S`: Entry skeleton type
258
+ - `M`: Chain modifiers
259
+ - `L`: Locale code
260
+
261
+ Arguments:
262
+
263
+ - `entry`\*: The entry to personalize
264
+ - `personalizations`: Selected personalizations
265
+
266
+ Returns:
267
+
268
+ - The resolved personalized entry variant, or the supplied baseline entry if baseline is the
269
+ selected variant or a variant cannot be found.
270
+
271
+ > [!NOTE]
272
+ >
273
+ > If the `personalizations` argument is omitted in stateless implementations, the method will return
274
+ > the baseline entry.
275
+
276
+ #### `getMergeTagValue`
277
+
278
+ Resolve a "Merge Tag" to a value based on the current (or provided) profile. A "Merge Tag" is a
279
+ special Rich Text fragment supported by Contentful that specifies a profile data member to be
280
+ injected into the Rich Text when rendered.
281
+
282
+ Arguments:
283
+
284
+ - `embeddedNodeEntryTarget`\*: The merge tag entry node to resolve
285
+ - `profile`: The user profile
286
+
287
+ > [!NOTE]
288
+ >
289
+ > If the `profile` argument is omitted in stateless implementations, the method will return the
290
+ > merge tag's fallback value.
291
+
292
+ ### Personalization and Analytics Event Methods
293
+
294
+ Each method except `trackFlagView` may return an `OptimizationData` object containing:
295
+
296
+ - `changes`: Currently used for Custom Flags
297
+ - `personalizations`: Selected personalizations for the profile
298
+ - `profile`: Profile associated with the evaluated events
299
+
300
+ #### `identify`
301
+
302
+ Identify the current profile/visitor to associate traits with a profile.
303
+
304
+ Arguments:
305
+
306
+ - `payload`\*: Identify event builder arguments object, including an optional `profile` property
307
+ with a `PartialProfile` value that requires only an `id`
308
+
309
+ #### `page`
310
+
311
+ Record a personalization page view.
312
+
313
+ Arguments:
314
+
315
+ - `payload`\*: Page view event builder arguments object, including an optional `profile` property
316
+ with a `PartialProfile` value that requires only an `id`
317
+
318
+ #### `track`
319
+
320
+ Record a personalization custom track event.
321
+
322
+ Arguments:
323
+
324
+ - `payload`\*: Track event builder arguments object, including an optional `profile` property with a
325
+ `PartialProfile` value that requires only an `id`
326
+
327
+ #### `trackComponentView`
328
+
329
+ Record an analytics component view event. When the payload marks the component as "sticky", an
330
+ additional personalization component view is recorded. This method only returns `OptimizationData`
331
+ when the component is marked as "sticky".
332
+
333
+ Arguments:
334
+
335
+ - `payload`\*: Component view event builder arguments object, including an optional `profile`
336
+ property with a `PartialProfile` value that requires only an `id`
337
+ - `duplicationScope`: Arbitrary string that may be used to scope component view duplication; used in
338
+ Stateful implementations
339
+
340
+ #### `trackFlagView`
341
+
342
+ Track a feature flag view via analytics. This is functionally the same as a non-sticky component
343
+ view event.
344
+
345
+ Arguments:
346
+
347
+ - `payload`\*: Component view event builder arguments object, including an optional `profile`
348
+ property with a `PartialProfile` value that requires only an `id`
349
+ - `duplicationScope`: Arbitrary string that may be used to scope component view duplication; used in
350
+ Stateful implementations
351
+
352
+ ## Stateful-only Core Methods
353
+
354
+ ### `consent`
355
+
356
+ Updates the user consent state.
357
+
358
+ Arguments:
359
+
360
+ - `accept`: A boolean value specifying whether the user has accepted (`true`) or denied (`false`). A
361
+ value of `undefined` implies that the user has not yet explicitly chosen whether to consent.
362
+
363
+ ### `reset`
364
+
365
+ Resets all internal state _except_ consent. This method expects no arguments and returns no value.
366
+
367
+ ## Stateful-only Core Properties
368
+
369
+ - `states`: Returns an object mapping of observables for all internal states
370
+ - `consent`: The current state of user consent
371
+ - `eventStream`: The latest event to be queued
372
+ - `flags`: All current resolved Custom Flags
373
+ - `profile`: The current user profile
374
+ - `personalizations`: The current collection of selected personalizations
375
+
376
+ Each state except `consent` and `eventStream` is updated internally whenever a response from the
377
+ Experience API contains a new or updated respective state.
378
+
379
+ Example `states` observable usage:
380
+
381
+ ```ts
382
+ optimization.states.profile.subscribe((profile) => {
383
+ console.log(`Profile ${profile.id} updated!`)
384
+ })
385
+ ```
386
+
387
+ ## Interceptors
388
+
389
+ Interceptors may be used to read and/or modify data flowing through the Core SDK.
390
+
391
+ ### Life-cycle Interceptors
392
+
393
+ - `event`: Intercepts an event's data _before_ it is queued and/or emitted
394
+ - `state`: Intercepts state data retrieved from an Experience API call _before_ updating the SDK's
395
+ internal state
396
+
397
+ Example interceptor usage:
398
+
399
+ ```ts
400
+ optimization.interceptors.event((event) => {
401
+ event.properties.timestamp = new Date().toISOString()
402
+ })
403
+ ```
404
+
405
+ > [!WARNING]
406
+ >
407
+ > Interceptors are intended to enable low-level interoperability; to simply read and react to
408
+ > Optimization SDK events, use the `states` observables.
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Controller for updating the current consent state.
3
+ *
4
+ * @internal
5
+ * @remarks
6
+ * Intended for internal wiring between Core classes and the consent signal/store.
7
+ */
8
+ export interface ConsentController {
9
+ /**
10
+ * Update the runtime consent state.
11
+ *
12
+ * @param accept - `true` when the user has granted consent; `false` otherwise.
13
+ */
14
+ consent: (accept: boolean) => void;
15
+ }
16
+ /**
17
+ * Contract implemented by classes that gate operations based on consent.
18
+ *
19
+ * @internal
20
+ * @remarks
21
+ * These methods are consumed by the `@guardedBy` decorator to decide whether to
22
+ * proceed with an operation and how to report blocked calls.
23
+ */
24
+ export interface ConsentGuard {
25
+ /**
26
+ * Determine whether the named operation is permitted given current consent and
27
+ * any allow‑list configuration.
28
+ *
29
+ * @param name - Logical operation/method name (e.g., `'track'`, `'page'`).
30
+ * @returns `true` if the operation may proceed; otherwise `false`.
31
+ * @remarks
32
+ * The mapping between method names and event type strings may be product‑specific.
33
+ */
34
+ hasConsent: (name: string) => boolean;
35
+ /**
36
+ * Hook invoked when an operation is blocked due to missing consent.
37
+ *
38
+ * @param name - The blocked operation/method name.
39
+ * @param args - The original call arguments, provided for diagnostics/telemetry.
40
+ * @returns Nothing. Implementations typically log and/or emit diagnostics.
41
+ */
42
+ onBlockedByConsent: (name: string, args: unknown[]) => void;
43
+ }
44
+ //# sourceMappingURL=Consent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Consent.d.ts","sourceRoot":"","sources":["../src/Consent.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAA;CACnC;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;;;;OAQG;IACH,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAA;IAErC;;;;;;OAMG;IACH,kBAAkB,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAA;CAC5D"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Consent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Consent.js","sourceRoot":"","sources":["../src/Consent.ts"],"names":[],"mappings":""}
@@ -0,0 +1,161 @@
1
+ import { ApiClient, EventBuilder, type InsightsEvent as AnalyticsEvent, type ApiClientConfig, type ChangeArray, type ComponentViewBuilderArgs, type EventBuilderConfig, type ExperienceApiClientConfig, type GlobalApiConfigProperties, type IdentifyBuilderArgs, type InsightsApiClientConfig, type Json, type MergeTagEntry, type OptimizationData, type PageViewBuilderArgs, type PartialProfile, type ExperienceEvent as PersonalizationEvent, type Profile, type ScreenViewBuilderArgs, type SelectedPersonalizationArray, type TrackBuilderArgs } from '@contentful/optimization-api-client';
2
+ import type { ChainModifiers, Entry, EntrySkeletonType, LocaleCode } from 'contentful';
3
+ import type { LogLevels } from 'logger';
4
+ import type AnalyticsBase from './analytics/AnalyticsBase';
5
+ import { InterceptorManager } from './lib/interceptor';
6
+ import type { ResolvedData } from './personalization';
7
+ import type PersonalizationBase from './personalization/PersonalizationBase';
8
+ /**
9
+ * Lifecycle container for event and state interceptors.
10
+ *
11
+ * @public
12
+ */
13
+ export interface LifecycleInterceptors {
14
+ /** Interceptors invoked for individual events prior to validation/sending. */
15
+ event: InterceptorManager<AnalyticsEvent | PersonalizationEvent>;
16
+ /** Interceptors invoked before optimization state updates. */
17
+ state: InterceptorManager<OptimizationData>;
18
+ }
19
+ /**
20
+ * Options for configuring the {@link CoreBase} runtime and underlying clients.
21
+ *
22
+ * @public
23
+ */
24
+ export interface CoreConfig extends Pick<ApiClientConfig, GlobalApiConfigProperties> {
25
+ /**
26
+ * Configuration for the personalization (Experience) API client.
27
+ */
28
+ personalization?: Omit<ExperienceApiClientConfig, GlobalApiConfigProperties>;
29
+ /**
30
+ * Configuration for the analytics (Insights) API client.
31
+ */
32
+ analytics?: Omit<InsightsApiClientConfig, GlobalApiConfigProperties>;
33
+ /**
34
+ * Event builder configuration (channel/library metadata, etc.).
35
+ */
36
+ eventBuilder?: EventBuilderConfig;
37
+ /** Minimum log level for the default console sink. */
38
+ logLevel?: LogLevels;
39
+ }
40
+ /**
41
+ * Internal base that wires the API client, event builder, and logging.
42
+ *
43
+ * @internal
44
+ */
45
+ declare abstract class CoreBase {
46
+ /** Product implementation for analytics. */
47
+ abstract readonly analytics: AnalyticsBase;
48
+ /** Product implementation for personalization. */
49
+ abstract readonly personalization: PersonalizationBase;
50
+ /** Shared Optimization API client instance. */
51
+ readonly api: ApiClient;
52
+ /** Shared event builder instance. */
53
+ readonly eventBuilder: EventBuilder;
54
+ /** Resolved core configuration (minus any name metadata). */
55
+ readonly config: Omit<CoreConfig, 'name'>;
56
+ readonly interceptors: LifecycleInterceptors;
57
+ /**
58
+ * Create the core with API client and logging preconfigured.
59
+ *
60
+ * @param config - Core configuration including API and builder options.
61
+ * @example
62
+ * ```ts
63
+ * const sdk = new CoreStateless({ clientId: 'abc123', environment: 'prod' })
64
+ * ```
65
+ */
66
+ constructor(config: CoreConfig);
67
+ /**
68
+ * Get the value of a custom flag derived from a set of optimization changes.
69
+ *
70
+ * @param name - The flag key to resolve.
71
+ * @param changes - Optional change list to resolve from
72
+ * @returns The resolved JSON value for the flag if available.
73
+ * @remarks
74
+ * This is a convenience wrapper around personalization’s flag resolution.
75
+ */
76
+ getCustomFlag(name: string, changes?: ChangeArray): Json;
77
+ /**
78
+ * Resolve a Contentful entry to the appropriate personalized variant (or
79
+ * return the baseline entry if no matching variant is selected).
80
+ *
81
+ * @typeParam S - Entry skeleton type.
82
+ * @typeParam M - Chain modifiers.
83
+ * @typeParam L - Locale code.
84
+ * @param entry - The baseline entry to resolve.
85
+ * @param personalizations - Optional selection array for the current profile.
86
+ * @returns {@link ResolvedData} containing the resolved entry and
87
+ * personalization metadata (if any).
88
+ */
89
+ personalizeEntry<S extends EntrySkeletonType, M extends ChainModifiers = ChainModifiers, L extends LocaleCode = LocaleCode>(entry: Entry<S, M, L>, personalizations?: SelectedPersonalizationArray): ResolvedData<S, M, L>;
90
+ /**
91
+ * Resolve a merge-tag value from the given entry node and profile.
92
+ *
93
+ * @param embeddedEntryNodeTarget - The merge-tag entry node to resolve.
94
+ * @param profile - Optional profile used for value lookup.
95
+ * @returns The resolved value (typically a string) or `undefined` if not found.
96
+ */
97
+ getMergeTagValue(embeddedEntryNodeTarget: MergeTagEntry, profile?: Profile): unknown;
98
+ /**
99
+ * Convenience wrapper for sending an `identify` event via personalization.
100
+ *
101
+ * @param payload - Identify builder arguments.
102
+ * @returns The resulting {@link OptimizationData} for the identified user.
103
+ */
104
+ identify(payload: IdentifyBuilderArgs & {
105
+ profile?: PartialProfile;
106
+ }): Promise<OptimizationData | undefined>;
107
+ /**
108
+ * Convenience wrapper for sending a `page` event via personalization.
109
+ *
110
+ * @param payload - Page view builder arguments.
111
+ * @returns The evaluated {@link OptimizationData} for this page view.
112
+ */
113
+ page(payload: PageViewBuilderArgs & {
114
+ profile?: PartialProfile;
115
+ }): Promise<OptimizationData | undefined>;
116
+ /**
117
+ * Convenience wrapper for sending a `screen` event via personalization.
118
+ *
119
+ * @param payload - Screen view builder arguments.
120
+ * @returns The evaluated {@link OptimizationData} for this screen view.
121
+ */
122
+ screen(payload: ScreenViewBuilderArgs & {
123
+ profile?: PartialProfile;
124
+ }): Promise<OptimizationData | undefined>;
125
+ /**
126
+ * Convenience wrapper for sending a custom `track` event via personalization.
127
+ *
128
+ * @param payload - Track builder arguments.
129
+ * @returns The evaluated {@link OptimizationData} for this event.
130
+ */
131
+ track(payload: TrackBuilderArgs & {
132
+ profile?: PartialProfile;
133
+ }): Promise<OptimizationData | undefined>;
134
+ /**
135
+ * Track a component view in both personalization and analytics.
136
+ *
137
+ * @param payload - Component view builder arguments. When `payload.sticky` is
138
+ * `true`, the event will also be sent via personalization as a sticky
139
+ * component view.
140
+ * @param duplicationScope - Optional string used to scope duplication used in Stateful
141
+ * implementations
142
+ * @returns A promise that resolves when all delegated calls complete.
143
+ * @remarks
144
+ * The sticky behavior is delegated to personalization; analytics is always
145
+ * invoked regardless of `sticky`.
146
+ */
147
+ trackComponentView(payload: ComponentViewBuilderArgs & {
148
+ profile?: PartialProfile;
149
+ }, duplicationScope?: string): Promise<OptimizationData | undefined>;
150
+ /**
151
+ * Track a feature flag view via analytics.
152
+ *
153
+ * @param payload - Component view builder arguments used to build the flag view event.
154
+ * @param duplicationScope - Optional string used to scope duplication used in Stateful
155
+ * implementations
156
+ * @returns A promise that resolves when processing completes.
157
+ */
158
+ trackFlagView(payload: ComponentViewBuilderArgs, duplicationScope?: string): Promise<void>;
159
+ }
160
+ export default CoreBase;
161
+ //# sourceMapping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