@revturbine/sdk 0.2.13

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 (147) hide show
  1. package/dist/headless.js +131 -0
  2. package/dist/headless.js.map +1 -0
  3. package/dist/index.js +131 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/types/server-node/client.d.ts +75 -0
  6. package/dist/types/server-node/client.d.ts.map +1 -0
  7. package/dist/types/server-node/index.d.ts +37 -0
  8. package/dist/types/server-node/index.d.ts.map +1 -0
  9. package/dist/types/server-node/local-server.d.ts +60 -0
  10. package/dist/types/server-node/local-server.d.ts.map +1 -0
  11. package/dist/types/server-node/types.d.ts +68 -0
  12. package/dist/types/server-node/types.d.ts.map +1 -0
  13. package/dist/types/web-sdk/adapters/api.d.ts +24 -0
  14. package/dist/types/web-sdk/adapters/api.d.ts.map +1 -0
  15. package/dist/types/web-sdk/analytics.d.ts +111 -0
  16. package/dist/types/web-sdk/analytics.d.ts.map +1 -0
  17. package/dist/types/web-sdk/api-client.d.ts +44 -0
  18. package/dist/types/web-sdk/api-client.d.ts.map +1 -0
  19. package/dist/types/web-sdk/browser-runtime.d.ts +62 -0
  20. package/dist/types/web-sdk/browser-runtime.d.ts.map +1 -0
  21. package/dist/types/web-sdk/controllers.d.ts +363 -0
  22. package/dist/types/web-sdk/controllers.d.ts.map +1 -0
  23. package/dist/types/web-sdk/customer-side.d.ts +1367 -0
  24. package/dist/types/web-sdk/customer-side.d.ts.map +1 -0
  25. package/dist/types/web-sdk/env.d.ts +5 -0
  26. package/dist/types/web-sdk/env.d.ts.map +1 -0
  27. package/dist/types/web-sdk/generated.d.ts +8 -0
  28. package/dist/types/web-sdk/generated.d.ts.map +1 -0
  29. package/dist/types/web-sdk/headless.d.ts +69 -0
  30. package/dist/types/web-sdk/headless.d.ts.map +1 -0
  31. package/dist/types/web-sdk/index.d.ts +51 -0
  32. package/dist/types/web-sdk/index.d.ts.map +1 -0
  33. package/dist/types/web-sdk/placements/AccessGateSurfaceSlot.d.ts +88 -0
  34. package/dist/types/web-sdk/placements/AccessGateSurfaceSlot.d.ts.map +1 -0
  35. package/dist/types/web-sdk/placements/FixedSurfaceSlot.d.ts +56 -0
  36. package/dist/types/web-sdk/placements/FixedSurfaceSlot.d.ts.map +1 -0
  37. package/dist/types/web-sdk/placements/MessageSurfaceSlot.d.ts +87 -0
  38. package/dist/types/web-sdk/placements/MessageSurfaceSlot.d.ts.map +1 -0
  39. package/dist/types/web-sdk/placements/PlacementRenderer.d.ts +57 -0
  40. package/dist/types/web-sdk/placements/PlacementRenderer.d.ts.map +1 -0
  41. package/dist/types/web-sdk/placements/SurfaceSlotComponent.d.ts +70 -0
  42. package/dist/types/web-sdk/placements/SurfaceSlotComponent.d.ts.map +1 -0
  43. package/dist/types/web-sdk/placements/abstract/BannerFrame.d.ts +53 -0
  44. package/dist/types/web-sdk/placements/abstract/BannerFrame.d.ts.map +1 -0
  45. package/dist/types/web-sdk/placements/abstract/InlineCardPlacement.d.ts +52 -0
  46. package/dist/types/web-sdk/placements/abstract/InlineCardPlacement.d.ts.map +1 -0
  47. package/dist/types/web-sdk/placements/abstract/ModalFrame.d.ts +68 -0
  48. package/dist/types/web-sdk/placements/abstract/ModalFrame.d.ts.map +1 -0
  49. package/dist/types/web-sdk/placements/abstract/QuotaMeterFrame.d.ts +76 -0
  50. package/dist/types/web-sdk/placements/abstract/QuotaMeterFrame.d.ts.map +1 -0
  51. package/dist/types/web-sdk/placements/abstract/index.d.ts +9 -0
  52. package/dist/types/web-sdk/placements/abstract/index.d.ts.map +1 -0
  53. package/dist/types/web-sdk/placements/builtin.d.ts +18 -0
  54. package/dist/types/web-sdk/placements/builtin.d.ts.map +1 -0
  55. package/dist/types/web-sdk/placements/cta-resolvers.d.ts +67 -0
  56. package/dist/types/web-sdk/placements/cta-resolvers.d.ts.map +1 -0
  57. package/dist/types/web-sdk/placements/index.d.ts +28 -0
  58. package/dist/types/web-sdk/placements/index.d.ts.map +1 -0
  59. package/dist/types/web-sdk/placements/local-resolver.d.ts +8 -0
  60. package/dist/types/web-sdk/placements/local-resolver.d.ts.map +1 -0
  61. package/dist/types/web-sdk/placements/payload-resolution.d.ts +8 -0
  62. package/dist/types/web-sdk/placements/payload-resolution.d.ts.map +1 -0
  63. package/dist/types/web-sdk/placements/recommendation.d.ts +35 -0
  64. package/dist/types/web-sdk/placements/recommendation.d.ts.map +1 -0
  65. package/dist/types/web-sdk/placements/registry.d.ts +84 -0
  66. package/dist/types/web-sdk/placements/registry.d.ts.map +1 -0
  67. package/dist/types/web-sdk/placements/slots/AgentConnectorSlot.d.ts +11 -0
  68. package/dist/types/web-sdk/placements/slots/AgentConnectorSlot.d.ts.map +1 -0
  69. package/dist/types/web-sdk/placements/slots/BannerSlot.d.ts +35 -0
  70. package/dist/types/web-sdk/placements/slots/BannerSlot.d.ts.map +1 -0
  71. package/dist/types/web-sdk/placements/slots/ButtonSlot.d.ts +23 -0
  72. package/dist/types/web-sdk/placements/slots/ButtonSlot.d.ts.map +1 -0
  73. package/dist/types/web-sdk/placements/slots/ChannelPreviewSlots.d.ts +48 -0
  74. package/dist/types/web-sdk/placements/slots/ChannelPreviewSlots.d.ts.map +1 -0
  75. package/dist/types/web-sdk/placements/slots/CliSlot.d.ts +11 -0
  76. package/dist/types/web-sdk/placements/slots/CliSlot.d.ts.map +1 -0
  77. package/dist/types/web-sdk/placements/slots/CreditBalanceSlot.d.ts +19 -0
  78. package/dist/types/web-sdk/placements/slots/CreditBalanceSlot.d.ts.map +1 -0
  79. package/dist/types/web-sdk/placements/slots/FullPageSlot.d.ts +14 -0
  80. package/dist/types/web-sdk/placements/slots/FullPageSlot.d.ts.map +1 -0
  81. package/dist/types/web-sdk/placements/slots/InPageSlot.d.ts +13 -0
  82. package/dist/types/web-sdk/placements/slots/InPageSlot.d.ts.map +1 -0
  83. package/dist/types/web-sdk/placements/slots/InlineEmbedSlot.d.ts +16 -0
  84. package/dist/types/web-sdk/placements/slots/InlineEmbedSlot.d.ts.map +1 -0
  85. package/dist/types/web-sdk/placements/slots/ModalSlot.d.ts +30 -0
  86. package/dist/types/web-sdk/placements/slots/ModalSlot.d.ts.map +1 -0
  87. package/dist/types/web-sdk/placements/slots/QuotaMeterSlot.d.ts +19 -0
  88. package/dist/types/web-sdk/placements/slots/QuotaMeterSlot.d.ts.map +1 -0
  89. package/dist/types/web-sdk/placements/slots/ToastSlot.d.ts +17 -0
  90. package/dist/types/web-sdk/placements/slots/ToastSlot.d.ts.map +1 -0
  91. package/dist/types/web-sdk/placements/slots/TooltipSlot.d.ts +15 -0
  92. package/dist/types/web-sdk/placements/slots/TooltipSlot.d.ts.map +1 -0
  93. package/dist/types/web-sdk/placements/slots/index.d.ts +14 -0
  94. package/dist/types/web-sdk/placements/slots/index.d.ts.map +1 -0
  95. package/dist/types/web-sdk/placements/surface-slot-constants.d.ts +13 -0
  96. package/dist/types/web-sdk/placements/surface-slot-constants.d.ts.map +1 -0
  97. package/dist/types/web-sdk/placements/surface-template-defaults.d.ts +16 -0
  98. package/dist/types/web-sdk/placements/surface-template-defaults.d.ts.map +1 -0
  99. package/dist/types/web-sdk/placements/token-derivation.d.ts +7 -0
  100. package/dist/types/web-sdk/placements/token-derivation.d.ts.map +1 -0
  101. package/dist/types/web-sdk/placements/types.d.ts +226 -0
  102. package/dist/types/web-sdk/placements/types.d.ts.map +1 -0
  103. package/dist/types/web-sdk/placements/usePlacementPersonalization.d.ts +20 -0
  104. package/dist/types/web-sdk/placements/usePlacementPersonalization.d.ts.map +1 -0
  105. package/dist/types/web-sdk/placements/useSurfaceSlot.d.ts +60 -0
  106. package/dist/types/web-sdk/placements/useSurfaceSlot.d.ts.map +1 -0
  107. package/dist/types/web-sdk/providers/index.d.ts +3 -0
  108. package/dist/types/web-sdk/providers/index.d.ts.map +1 -0
  109. package/dist/types/web-sdk/providers/registry.d.ts +8 -0
  110. package/dist/types/web-sdk/providers/registry.d.ts.map +1 -0
  111. package/dist/types/web-sdk/providers/types.d.ts +8 -0
  112. package/dist/types/web-sdk/providers/types.d.ts.map +1 -0
  113. package/dist/types/web-sdk/react/Placement.d.ts +50 -0
  114. package/dist/types/web-sdk/react/Placement.d.ts.map +1 -0
  115. package/dist/types/web-sdk/react/PlacementDecisionInspector.d.ts +40 -0
  116. package/dist/types/web-sdk/react/PlacementDecisionInspector.d.ts.map +1 -0
  117. package/dist/types/web-sdk/react/RevTurbineProvider.d.ts +31 -0
  118. package/dist/types/web-sdk/react/RevTurbineProvider.d.ts.map +1 -0
  119. package/dist/types/web-sdk/react/SurfaceTypes.d.ts +19 -0
  120. package/dist/types/web-sdk/react/SurfaceTypes.d.ts.map +1 -0
  121. package/dist/types/web-sdk/react/UserProfile.d.ts +23 -0
  122. package/dist/types/web-sdk/react/UserProfile.d.ts.map +1 -0
  123. package/dist/types/web-sdk/react/index.d.ts +11 -0
  124. package/dist/types/web-sdk/react/index.d.ts.map +1 -0
  125. package/dist/types/web-sdk/react/useEntitlement.d.ts +53 -0
  126. package/dist/types/web-sdk/react/useEntitlement.d.ts.map +1 -0
  127. package/dist/types/web-sdk/react/usePlacement.d.ts +63 -0
  128. package/dist/types/web-sdk/react/usePlacement.d.ts.map +1 -0
  129. package/dist/types/web-sdk/react/useRevTurbine.d.ts +17 -0
  130. package/dist/types/web-sdk/react/useRevTurbine.d.ts.map +1 -0
  131. package/dist/types/web-sdk/react/useUsageSnapshot.d.ts +7 -0
  132. package/dist/types/web-sdk/react/useUsageSnapshot.d.ts.map +1 -0
  133. package/dist/types/web-sdk/segments.d.ts +9 -0
  134. package/dist/types/web-sdk/segments.d.ts.map +1 -0
  135. package/dist/types/web-sdk/storage.d.ts +38 -0
  136. package/dist/types/web-sdk/storage.d.ts.map +1 -0
  137. package/dist/types/web-sdk/theme/ThemeContext.d.ts +18 -0
  138. package/dist/types/web-sdk/theme/ThemeContext.d.ts.map +1 -0
  139. package/dist/types/web-sdk/theme/defaults.d.ts +13 -0
  140. package/dist/types/web-sdk/theme/defaults.d.ts.map +1 -0
  141. package/dist/types/web-sdk/theme/index.d.ts +6 -0
  142. package/dist/types/web-sdk/theme/index.d.ts.map +1 -0
  143. package/dist/types/web-sdk/theme/theme-loader.d.ts +26 -0
  144. package/dist/types/web-sdk/theme/theme-loader.d.ts.map +1 -0
  145. package/dist/types/web-sdk/theme/types.d.ts +121 -0
  146. package/dist/types/web-sdk/theme/types.d.ts.map +1 -0
  147. package/package.json +57 -0
@@ -0,0 +1,1367 @@
1
+ import { DomainProviderRegistry } from './providers/registry';
2
+ import type { AnyDomainProvider } from './providers/types';
3
+ import type { RevTurbineStorage } from './storage';
4
+ import type { ServerEvaluationPayload as GeneratedServerEvaluationPayload, EntitlementStatus as SchemaEntitlementStatus, ExportedConfig, ExportedConfigSegmentsItem, ContentUiPath, UserContext, UserTrialStatus, TriggerEventType } from '@revt-eng/schema';
5
+ import type { JsonValue, JsonObject, PredicateEvaluationResult } from '@revt-eng/core';
6
+ import { ImpressionHistory } from '@revt-eng/core';
7
+ import { PlacementTypeRegistry } from './placements/registry';
8
+ import { type RecommendationStrategy } from './placements/recommendation';
9
+ import { type LocalPlacementDataset } from './placements/local-resolver';
10
+ export type { JsonValue, JsonObject } from '@revt-eng/core';
11
+ /** Extensible metadata bag attached to placements, events, and interactions. */
12
+ export type SdkMetadata = Record<string, JsonValue>;
13
+ /** User-provided traits or custom context (inherently untyped from customer code). */
14
+ export type SdkTraits = Record<string, JsonValue>;
15
+ /** Properties attached to analytics events. */
16
+ export type SdkEventProperties = Record<string, JsonValue>;
17
+ export interface RevTurbineSdkProvider {
18
+ getPlacement?: (config: RevTurbinePlacementRequestConfig) => Promise<PlacementOutput | null>;
19
+ checkEntitlement?: (handle: string, context?: RevTurbineEntitlementContext) => Promise<EntitlementResult>;
20
+ persistPlacementTypes?: (types: RevTurbinePlacementTypeEntity[]) => Promise<void>;
21
+ identify?: (userId: string, contextOrTraits?: UserContextInput | SdkTraits) => void;
22
+ }
23
+ export type RevTurbineProviderFactory = (options: RevTurbineInitOptions) => RevTurbineSdkProvider;
24
+ export type RevTurbineProviderFailureSlotBehavior = 'placeholder' | 'invisible';
25
+ interface RevTurbineProviderOptionAugmentations {
26
+ provider?: RevTurbineSdkProvider | RevTurbineProviderFactory;
27
+ providerFallbacks?: Array<RevTurbineSdkProvider | RevTurbineProviderFactory>;
28
+ }
29
+ export type RevTurbineInitWithProviderOptions = RevTurbineInitOptions & RevTurbineProviderOptionAugmentations;
30
+ /**
31
+ * Minimal initialization options for local-only mode.
32
+ *
33
+ * When `localRuntime.exportedConfig` is provided, core transport options can be
34
+ * omitted and the SDK will inject safe local defaults.
35
+ */
36
+ export type RevTurbineLocalOnlyMinimalInitOptions = Omit<RevTurbineInitOptions, 'tenantId' | 'apiKey' | 'endpoint' | 'mode' | 'runtimeMode' | 'localRuntime'> & {
37
+ tenantId?: string;
38
+ apiKey?: string;
39
+ endpoint?: string;
40
+ mode?: RevTurbineSdkMode;
41
+ runtimeMode?: 'local_only';
42
+ localRuntime: RevTurbineLocalRuntimeOptions & {
43
+ exportedConfig: ExportedConfig;
44
+ };
45
+ };
46
+ /**
47
+ * Public SDK initialization input.
48
+ *
49
+ * Accepts either full options for any runtime mode, or local-only minimal
50
+ * options when `localRuntime.exportedConfig` is provided.
51
+ */
52
+ export type RevTurbineInitInputOptions = RevTurbineInitWithProviderOptions | (RevTurbineLocalOnlyMinimalInitOptions & RevTurbineProviderOptionAugmentations);
53
+ /**
54
+ * SDK integration mode.
55
+ * - `snippet` — lightweight script tag embed
56
+ * - `react` — React component integration
57
+ * - `iframe` — sandboxed iframe embed
58
+ */
59
+ export type RevTurbineSdkMode = 'snippet' | 'react' | 'iframe';
60
+ /**
61
+ * Canonical surface type for placement rendering.
62
+ * Re-exported from `@revt-eng/core` — single source of truth.
63
+ */
64
+ export type { RevTurbineSurfaceType } from '@revt-eng/core';
65
+ import type { RevTurbineSurfaceType } from '@revt-eng/core';
66
+ /**
67
+ * Convenience input type for identify / setUserContext calls.
68
+ * Omits the persistence envelope fields (`tenant_id`, `user_id`,
69
+ * `created_at`, `updated_at`) which the SDK populates automatically.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * sdk.identify('user_123', {
74
+ * account_id: 'acct_456',
75
+ * email: 'jane@acme.com',
76
+ * plan: { id: 'pro', name: 'Professional' },
77
+ * entitlements: { data_export: true },
78
+ * custom: { role: 'editor' },
79
+ * });
80
+ * ```
81
+ */
82
+ export type UserContextInput = Omit<UserContext, 'id' | 'tenant_id' | 'user_id' | 'created_at' | 'updated_at'>;
83
+ /**
84
+ * A placement output returned by the decision engine.
85
+ * Re-exported from `@revt-eng/core`.
86
+ */
87
+ export type { PlacementOutput } from '@revt-eng/core';
88
+ import type { PlacementOutput } from '@revt-eng/core';
89
+ /**
90
+ * Canonical entitlement check status.
91
+ * Re-exported from `@revt-eng/schema`.
92
+ */
93
+ export type EntitlementStatus = SchemaEntitlementStatus;
94
+ /**
95
+ * Result from an entitlement check.
96
+ * Re-exported from `@revt-eng/core`.
97
+ */
98
+ export type { EntitlementResult } from '@revt-eng/core';
99
+ import type { EntitlementResult } from '@revt-eng/core';
100
+ export type { RevTurbineEntitlementContext } from '@revt-eng/core';
101
+ import type { RevTurbineEntitlementContext } from '@revt-eng/core';
102
+ export interface RevTurbinePlacementRequestConfig {
103
+ /** Slot identifier used for slot-based decisions. */
104
+ slotId?: string;
105
+ /** Surface type declared by the slot integration point. */
106
+ surfaceType?: RevTurbineSurfaceType;
107
+ /** Entitlement handle used for entitlement-based decisions. */
108
+ entitlementHandle?: string;
109
+ /** Optional plan context when rendering plan-specific placements. */
110
+ planHandle?: string;
111
+ /** Optional placement handle for chaining from a prior CTA path. */
112
+ placementHandle?: string;
113
+ /**
114
+ * When true, restrict candidate resolution to Fixed-category placements
115
+ * only for this call. Use when a slot is reserved for PM-wired content
116
+ * (e.g., a header upgrade button that should never show an RT-initiated
117
+ * nudge). RT-initiated placements (Usage/Trial/Conversion/Retention) are
118
+ * filtered out even if they would otherwise match the slot.
119
+ *
120
+ * Defaults to `false`. See placement-prioritization-logic spec §1 and
121
+ * placement-studio-ui.md Appendix C.2 "Restricting a slot to Fixed".
122
+ */
123
+ fixedOnly?: boolean;
124
+ }
125
+ /** Tenant-scoped placement type metadata persisted by SDK integrations. */
126
+ export interface RevTurbinePlacementTypeEntity {
127
+ id: string;
128
+ label: string;
129
+ description: string;
130
+ surfaceType: RevTurbineSurfaceType;
131
+ priority?: number;
132
+ }
133
+ /**
134
+ * Current trial status for the identified user.
135
+ *
136
+ * Re-exported from the schema's {@link UserTrialStatus} — uses the
137
+ * canonical snake_case field names (`in_trial`, `trial_type`, etc.)
138
+ * to match the wire format and avoid brittle remapping.
139
+ */
140
+ export type RevTurbineTrialContext = UserTrialStatus;
141
+ /**
142
+ * Arbitrary key/value metadata persisted with an impression record.
143
+ *
144
+ * Free-form by design — consumers attach whatever context is useful
145
+ * for downstream analytics (CTA type, variant id, surface slot id,
146
+ * experiment arm, etc.). The shape is intentionally untyped because
147
+ * it's a passthrough into the scaffold's ImpressionRecord.metadata
148
+ * field, which is the same type (`Record<string, unknown>`) on the
149
+ * persistence side. Defining the alias here gives the SDK type-
150
+ * safety scan one place to suppress instead of three identical
151
+ * parameter sites.
152
+ */
153
+ export type RevTurbineImpressionMetadata = Record<string, unknown>;
154
+ /** Map of entitlement handle → current usage count. */
155
+ export type UsageBalances = Record<string, number>;
156
+ /**
157
+ * Outcome of {@link RevTurbineCustomerSdk.gate} — the advertised `gate(action, fn)`
158
+ * verb. When the action was permitted, `ran` is `true` and `result` holds the
159
+ * callback's return value; otherwise `ran` is `false`, the callback did not run,
160
+ * and the caller should surface the `entitlement` (e.g. render an `<RTSlot>` paywall).
161
+ */
162
+ export type RevTurbineGateResult<T> = {
163
+ ran: true;
164
+ result: T;
165
+ entitlement: EntitlementResult;
166
+ } | {
167
+ ran: false;
168
+ entitlement: EntitlementResult;
169
+ };
170
+ /**
171
+ * Input to {@link RevTurbineCustomerSdk.update} — the advertised `update({ usage })`
172
+ * verb. Patches customer-reported usage balances; for identity or full user-context
173
+ * changes use {@link RevTurbineCustomerSdk.identify} / {@link RevTurbineCustomerSdk.setUserContext}.
174
+ */
175
+ export interface RevTurbineUpdateInput {
176
+ /** Usage balances to merge into the current snapshot (absolute values). */
177
+ usage?: UsageBalances;
178
+ }
179
+ /** Usage snapshot entry for a usage unit. */
180
+ export interface RevTurbineUsageSnapshotEntry {
181
+ /** Current consumed amount for the usage unit. */
182
+ current: number;
183
+ /** Configured limit for the usage unit when available. */
184
+ limit?: number;
185
+ }
186
+ /** Map of usage unit -> usage snapshot. */
187
+ export type RevTurbineUsageSnapshot = Record<string, RevTurbineUsageSnapshotEntry>;
188
+ /** Snapshot of policy-related SDK runtime settings and loaded config metadata. */
189
+ export interface RevTurbinePolicySnapshot {
190
+ contextPolicy: Required<RevTurbineContextPolicy>;
191
+ placementBehavior: RevTurbinePlacementBehaviorFlags;
192
+ runtimeMode: RevTurbineRuntimeMode;
193
+ exportedConfigVersion?: string;
194
+ }
195
+ export type RevTurbinePersonalizationTokens = Record<string, string | number>;
196
+ /**
197
+ * Snapshot of the active targeting context used by placement eligibility.
198
+ */
199
+ export interface RevTurbineTargeting extends UserTargetingContext {
200
+ /** Segment definitions configured in the active ExportedConfig. */
201
+ configuredSegments: ExportedConfigSegmentsItem[];
202
+ /** Predicate fields discovered from configured segments (targeting dimensions). */
203
+ configuredTraitFields: string[];
204
+ }
205
+ /**
206
+ * Payload shape accepted by {@link RevTurbineCustomerSdk.hydrate}.
207
+ *
208
+ * This is a re-export of the generated `ServerEvaluationPayload` from the
209
+ * schema, which is the contract between the server-side SDK's `evaluate()`
210
+ * output and the client-side SDK's hydration input.
211
+ */
212
+ export type ServerEvaluationHydrationPayload = GeneratedServerEvaluationPayload;
213
+ /**
214
+ * SDK-local user context state.
215
+ *
216
+ * Extends the canonical {@link UserContextInput} with a local `id` field
217
+ * for user identification. The full persistence-ready {@link UserContext}
218
+ * (with `tenant_id`, `user_id`, timestamps) is built by the SDK via
219
+ * {@link RevTurbineCustomerSdk.getUserContext getUserContext()}.
220
+ *
221
+ * `custom` is widened to `Record<string, unknown>` at the SDK boundary
222
+ * for customer convenience; values are narrowed to `TraitValue` when
223
+ * persisted via the API.
224
+ */
225
+ export interface RevTurbineUserContext extends Omit<UserContextInput, 'custom' | 'entitlements' | 'usage' | 'personalization' | 'derived_computed_at' | 'context_hash'> {
226
+ /** Authenticated user identifier. When undefined, the SDK uses an anonymous ID. */
227
+ id?: string;
228
+ /**
229
+ * Server-computed derived-entitlement cache stamp (plan 74). Optional at the
230
+ * SDK input boundary — local mode does not compute it; the control plane
231
+ * populates and round-trips it, defaulting to `null` when absent.
232
+ */
233
+ derived_computed_at?: UserContextInput['derived_computed_at'];
234
+ /**
235
+ * Server-computed user-context hash (plan 74). Optional at the SDK input
236
+ * boundary for the same reason as `derived_computed_at`.
237
+ */
238
+ context_hash?: UserContextInput['context_hash'];
239
+ /** Customer-defined fields for segmentation and personalization. */
240
+ custom?: SdkTraits;
241
+ /** Feature entitlements granted by plan + entitlement rules. */
242
+ entitlements?: Record<string, boolean>;
243
+ /** Usage entries derived from credits / usage_limit entitlements, keyed by handle. */
244
+ usage?: UserContextInput['usage'];
245
+ /**
246
+ * Transient personalization token map.
247
+ *
248
+ * Holds SDK-derived tokens (plan_name, usage_current, etc.) merged with
249
+ * app-provided tokens. Not persisted — rebuilt on each SDK session.
250
+ * Widened to accept `unknown` at the SDK boundary; narrowed to
251
+ * `string | number` when serialized.
252
+ */
253
+ personalization?: SdkTraits;
254
+ }
255
+ /** Page-level context automatically inferred or manually set. */
256
+ export interface RevTurbinePageContext {
257
+ /** Fully qualified page URL. */
258
+ url?: string;
259
+ /** Document title. */
260
+ title?: string;
261
+ /** HTTP referrer. */
262
+ referrer?: string;
263
+ /** Semantic tags for page classification (e.g. `['pricing', 'upgrade']`). */
264
+ tags?: string[];
265
+ }
266
+ /**
267
+ * Controls automatic context inference behavior.
268
+ * All flags default to `true` when omitted.
269
+ */
270
+ export interface RevTurbineContextPolicy {
271
+ /** Infer anonymous user context from browser APIs. */
272
+ inferUser?: boolean;
273
+ /** Infer page context (URL, title, referrer) from `window.location`. */
274
+ inferPage?: boolean;
275
+ /** Automatically track SPA route changes via History API patching. */
276
+ routerAutoTrack?: boolean;
277
+ }
278
+ /**
279
+ * Feature flags for placement pipeline behavior that may alter decision semantics.
280
+ *
281
+ * All flags default to `false` to preserve backward compatibility.
282
+ */
283
+ export interface RevTurbinePlacementBehaviorFlags {
284
+ /** Enable client-side payload cap enforcement (max-per-period + cooldown precedence). */
285
+ enableClientCapsEnforcement: boolean;
286
+ /** Enable automatic gated placement rendering helpers on entitlement denial. */
287
+ enableAutoGatedPlacement: boolean;
288
+ /** Enable automatic trial lifecycle trigger derivation in local-only mode. */
289
+ enableTrialAutoTriggers: boolean;
290
+ }
291
+ /** Resolver function for a UI path action type. */
292
+ export type RevTurbineUiPathResolver = (uiPath: JsonObject) => void | Promise<void>;
293
+ /** Map of `action_type` -> resolver implementation supplied by the customer app. */
294
+ export type RevTurbineUiPathResolverMap = Record<string, NonNullable<RevTurbineUiPathResolver>>;
295
+ /** Extracts `action_type` string literals from a UI path array type. */
296
+ export type RevTurbineUiPathActionTypes<TUiPaths extends readonly unknown[]> = Extract<{
297
+ [Index in keyof TUiPaths]: TUiPaths[Index] extends {
298
+ action_type: infer ActionType;
299
+ } ? ActionType : never;
300
+ }[number], string>;
301
+ /** Resolver map that requires handlers for every `action_type` present in `TUiPaths`. */
302
+ export type RevTurbineRequiredUiPathResolvers<TUiPaths extends readonly unknown[]> = {
303
+ [ActionType in RevTurbineUiPathActionTypes<TUiPaths>]: RevTurbineUiPathResolver;
304
+ };
305
+ /**
306
+ * Compile-time helper for authoring complete UI-path resolver maps.
307
+ *
308
+ * When `uiPaths` is provided as a `const` array, TypeScript enforces that
309
+ * `resolvers` contains every `action_type` key.
310
+ */
311
+ export declare function defineUiPathResolvers<const TUiPaths extends readonly unknown[]>(uiPaths: TUiPaths, resolvers: RevTurbineRequiredUiPathResolvers<TUiPaths> & RevTurbineUiPathResolverMap): RevTurbineUiPathResolverMap;
312
+ export interface RevTurbineUiPathResolverValidationIssue {
313
+ uiPathId?: string;
314
+ name?: string;
315
+ actionType: string;
316
+ reason: 'missing_resolver' | 'missing_action_type';
317
+ }
318
+ export interface RevTurbineUiPathResolverValidationReport {
319
+ valid: boolean;
320
+ totalUiPaths: number;
321
+ resolvedUiPaths: number;
322
+ issues: RevTurbineUiPathResolverValidationIssue[];
323
+ }
324
+ export interface RevTurbineUiPathResolverValidationOptions {
325
+ /** Optional explicit UI path definitions to validate. Defaults to exportedConfig.content_ui_paths. */
326
+ uiPaths?: ContentUiPath[];
327
+ /** Additional action resolver map to validate against for this invocation. */
328
+ resolvers?: RevTurbineUiPathResolverMap;
329
+ /** Include CTA handler provider resolvers from domain providers. Default true. */
330
+ includeProviderHandlers?: boolean;
331
+ /** Throw when missing resolver coverage is detected. Default false. */
332
+ throwOnMissing?: boolean;
333
+ }
334
+ /**
335
+ * Provider abstraction for ExportedConfig access inside the SDK.
336
+ *
337
+ * Local mode typically uses a static provider backed by `localRuntime.exportedConfig`.
338
+ * Other modes can provide custom or REST-backed resolvers via `refresh()`.
339
+ */
340
+ export interface RevTurbineConfigProvider {
341
+ /** Return the latest available ExportedConfig snapshot. */
342
+ getExportedConfig(): ExportedConfig | undefined;
343
+ /** Optionally refresh the snapshot (for example, from a REST API). */
344
+ refresh?(): Promise<ExportedConfig | undefined>;
345
+ }
346
+ /**
347
+ * Options for initializing the RevTurbine SDK.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * import { initRevTurbine } from '@revt-eng/sdk';
352
+ *
353
+ * const sdk = initRevTurbine({
354
+ * tenantId: 'tenant_abc',
355
+ * apiKey: 'rt_live_xxx',
356
+ * endpoint: 'https://api.revturbine.io',
357
+ * mode: 'react',
358
+ * });
359
+ * ```
360
+ */
361
+ export interface RevTurbineInitOptions {
362
+ /** Your RevTurbine tenant identifier. */
363
+ tenantId: string;
364
+ /** API key for authentication. */
365
+ apiKey: string;
366
+ /**
367
+ * Public ingest key for SDK clickstream ingestion (`POST /api/track`).
368
+ *
369
+ * Mint one in your RevTurbine tenant under **Settings → Ingest keys**.
370
+ * This is a tenant-scoped, embeddable `public` token distinct from
371
+ * {@link apiKey}: it authorizes *only* event ingestion (the
372
+ * `ingest:write` scope) and carries no role authority, so it is safe
373
+ * to ship in client bundles. When omitted, the SDK falls back to
374
+ * {@link apiKey} for the ingest request — but `/api/track` accepts
375
+ * **only** a `public` token, so a non-public `apiKey` fallback will be
376
+ * rejected. Set this for any integration that emits events.
377
+ */
378
+ ingestPublicKey?: string;
379
+ /**
380
+ * Environment identifier stamped on every ingested clickstream event
381
+ * (`TrackEvent.environment_id`, e.g. `'prod'` / `'staging'`). Lets a
382
+ * tenant separate analytics by deployment environment. Defaults to
383
+ * `'default'` when omitted.
384
+ */
385
+ environmentId?: string;
386
+ /** Base URL of the RevTurbine API Edge. */
387
+ endpoint: string;
388
+ /** SDK integration mode. */
389
+ mode: RevTurbineSdkMode;
390
+ /**
391
+ * SDK deployment/runtime mode:
392
+ * - `revturbine_server` (default): standard RevTurbine-hosted endpoints.
393
+ * - `custom_endpoints`: customer-provided endpoint replacements.
394
+ * - `local_only`: no server calls, runtime data initialized locally.
395
+ */
396
+ runtimeMode?: RevTurbineRuntimeMode;
397
+ /** Optional endpoint overrides used in `custom_endpoints` mode. */
398
+ endpointOverrides?: Partial<RevTurbineEndpointOverrides>;
399
+ /** Optional provider for ExportedConfig-backed data (plans, segments, rules, ui paths). */
400
+ configProvider?: RevTurbineConfigProvider;
401
+ /** Local-only runtime configuration used in `local_only` mode. */
402
+ localRuntime?: RevTurbineLocalRuntimeOptions;
403
+ /**
404
+ * Slot behavior after provider-chain failure disables the SDK.
405
+ * - `invisible` (default): slots return hidden decisions.
406
+ * - `placeholder`: slots return visible placeholder content.
407
+ */
408
+ providerFailureSlotBehavior?: RevTurbineProviderFailureSlotBehavior;
409
+ /** Typed domain providers (plan, entitlements, segments, content, rules, traits). */
410
+ domainProviders?: AnyDomainProvider[];
411
+ /** Optional UI path resolver map used by `validateUiPathResolvers()`. */
412
+ uiPathResolvers?: RevTurbineUiPathResolverMap;
413
+ user?: RevTurbineUserContext;
414
+ page?: RevTurbinePageContext;
415
+ contextPolicy?: RevTurbineContextPolicy;
416
+ /**
417
+ * Opt-in flags for placement decision behavior changes.
418
+ *
419
+ * Defaults are conservative (`false`) so existing integrations do not change behavior
420
+ * until explicitly enabled.
421
+ */
422
+ placementBehavior?: Partial<RevTurbinePlacementBehaviorFlags>;
423
+ extension?: {
424
+ enabled?: boolean;
425
+ };
426
+ /**
427
+ * Persistent storage provider (survives page reloads).
428
+ * Browser default: `localStorage`. Server default: in-memory.
429
+ * Override with a Redis/cookie/DB-backed implementation for SSR persistence.
430
+ */
431
+ persistentStorage?: RevTurbineStorage;
432
+ /**
433
+ * Session-scoped storage provider (cleared when the tab/session ends).
434
+ * Browser default: `sessionStorage`. Server default: in-memory.
435
+ */
436
+ sessionStorage?: RevTurbineStorage;
437
+ }
438
+ /** Base init options shared by all runtime mode helper builders. */
439
+ export type RevTurbineInitBaseOptions = Omit<RevTurbineInitOptions, 'runtimeMode' | 'endpointOverrides' | 'localRuntime'>;
440
+ export type RevTurbineRuntimeMode = 'revturbine_server' | 'custom_endpoints' | 'local_only';
441
+ /**
442
+ * Per-operation endpoint path/URL overrides for `custom_endpoints` mode.
443
+ * Each key maps to a fully-qualified URL or an `endpoint`-relative path.
444
+ */
445
+ export interface RevTurbineEndpointOverrides {
446
+ decideContext: string;
447
+ bootstrapContext: string;
448
+ decide: string;
449
+ getPlacement: string;
450
+ checkEntitlement: string;
451
+ userContext: string;
452
+ trialStatus: string;
453
+ ingestEvents: string;
454
+ touchpointTransition: string;
455
+ legacyInteractions: string;
456
+ placementTypes: string;
457
+ surfaceSlots: string;
458
+ }
459
+ export interface RevTurbineLocalRuntimeData {
460
+ placementDecisionsByPlacementId?: Record<string, RevTurbinePlacementDecision>;
461
+ placementsByLookupKey?: Record<string, PlacementOutput | null>;
462
+ entitlementByHandle?: Record<string, EntitlementResult>;
463
+ userContextByUserId?: Record<string, UserTargetingContext>;
464
+ trialStatus?: RevTurbineTrialContext;
465
+ }
466
+ export interface RevTurbineLocalRuntimeResolvers {
467
+ getPlacementDecision?: (input: RevTurbinePlacementDecisionInput, placement?: RevTurbinePlacementRecord, context?: JsonObject) => RevTurbinePlacementDecision | Promise<RevTurbinePlacementDecision>;
468
+ getPlacement?: (config: RevTurbinePlacementRequestConfig) => PlacementOutput | null | Promise<PlacementOutput | null>;
469
+ checkEntitlement?: (handle: string, context?: RevTurbineEntitlementContext) => EntitlementResult | Promise<EntitlementResult>;
470
+ fetchUserContext?: (userId: string) => UserTargetingContext | Promise<UserTargetingContext>;
471
+ getTrialStatus?: () => RevTurbineTrialContext | Promise<RevTurbineTrialContext>;
472
+ /** Optional ExportedConfig resolver for provider-backed config access in any mode. */
473
+ resolveExportedConfig?: () => ExportedConfig | Promise<ExportedConfig>;
474
+ }
475
+ export interface RevTurbineLocalRuntimeOptions {
476
+ /**
477
+ * Full ExportedConfig snapshot loaded at initialization for local-only execution.
478
+ * Contains plans, entitlements, entitlement rules, segments, ui paths,
479
+ * surface templates, trial, and theme. Providers and resolvers can read
480
+ * this to hydrate domain state without a server.
481
+ */
482
+ exportedConfig?: ExportedConfig;
483
+ /** Optional static placements dataset used by the SDK's built-in local resolver. */
484
+ placements?: LocalPlacementDataset;
485
+ /**
486
+ * Arbitrary configuration/context/content passed at initialization for local-only execution.
487
+ * This is persisted under localStorage and used as runtime source-of-truth.
488
+ */
489
+ initialData?: RevTurbineLocalRuntimeData;
490
+ /** Optional resolver callbacks for advanced local decisioning behavior. */
491
+ resolvers?: RevTurbineLocalRuntimeResolvers;
492
+ /** Optional explicit storage key for persisted local-only runtime state. */
493
+ storageKey?: string;
494
+ /**
495
+ * Reactive context callback. When provided, the SDK calls this before every
496
+ * local decision request and passes the result as the third argument to
497
+ * `resolvers.getPlacementDecision`.
498
+ *
499
+ * This allows local resolvers to react to user context changes (plan state,
500
+ * trial day, usage counters) without rebuilding the provider.
501
+ */
502
+ getContext?: () => JsonObject | Promise<JsonObject>;
503
+ }
504
+ type RevTurbineBaseInitWithoutRuntimeSpecifics = Omit<RevTurbineInitOptions, 'runtimeMode' | 'localRuntime' | 'uiPathResolvers'>;
505
+ /**
506
+ * Strict initialization mode for compile-time safety:
507
+ * when using `local_only` runtime with `localRuntime.exportedConfig`,
508
+ * `uiPathResolvers` is required.
509
+ */
510
+ export type RevTurbineInitOptionsStrict = (RevTurbineBaseInitWithoutRuntimeSpecifics & {
511
+ runtimeMode: 'local_only';
512
+ localRuntime: RevTurbineLocalRuntimeOptions & {
513
+ exportedConfig: ExportedConfig;
514
+ };
515
+ uiPathResolvers: RevTurbineUiPathResolverMap;
516
+ }) | (RevTurbineBaseInitWithoutRuntimeSpecifics & {
517
+ runtimeMode: 'local_only';
518
+ localRuntime: RevTurbineLocalRuntimeOptions & {
519
+ exportedConfig?: undefined;
520
+ };
521
+ uiPathResolvers?: RevTurbineUiPathResolverMap;
522
+ }) | (RevTurbineBaseInitWithoutRuntimeSpecifics & {
523
+ runtimeMode?: Exclude<RevTurbineRuntimeMode, 'local_only'>;
524
+ localRuntime?: RevTurbineLocalRuntimeOptions;
525
+ uiPathResolvers?: RevTurbineUiPathResolverMap;
526
+ });
527
+ /**
528
+ * Build a server-backed SDK config (default runtime mode).
529
+ */
530
+ export declare function createServerRuntimeConfig(options: RevTurbineInitBaseOptions): RevTurbineInitOptions;
531
+ /**
532
+ * Build a custom-endpoint SDK config.
533
+ */
534
+ export declare function createCustomEndpointRuntimeConfig(options: RevTurbineInitBaseOptions & {
535
+ endpointOverrides: Partial<RevTurbineEndpointOverrides>;
536
+ }): RevTurbineInitOptions;
537
+ /**
538
+ * Build a local-only SDK config.
539
+ */
540
+ export declare function createLocalRuntimeConfig<const TUiPaths extends readonly unknown[]>(options: RevTurbineInitBaseOptions & {
541
+ localRuntime: RevTurbineLocalRuntimeOptions & {
542
+ exportedConfig: Omit<ExportedConfig, 'content_ui_paths'> & {
543
+ content_ui_paths: TUiPaths;
544
+ };
545
+ };
546
+ uiPathResolvers: RevTurbineRequiredUiPathResolvers<TUiPaths> & RevTurbineUiPathResolverMap;
547
+ }): RevTurbineInitOptions;
548
+ export declare function createLocalRuntimeConfig(options: RevTurbineInitBaseOptions & {
549
+ localRuntime: RevTurbineLocalRuntimeOptions;
550
+ uiPathResolvers?: RevTurbineUiPathResolverMap;
551
+ }): RevTurbineInitOptions;
552
+ /**
553
+ * Build a strict local-only SDK config.
554
+ *
555
+ * Unlike {@link createLocalRuntimeConfig}, this helper always requires
556
+ * `exportedConfig.content_ui_paths` and complete `uiPathResolvers` coverage at
557
+ * compile time for action types present in that exported config.
558
+ */
559
+ export declare function createStrictLocalRuntimeConfig<const TUiPaths extends readonly unknown[]>(options: RevTurbineInitBaseOptions & {
560
+ localRuntime: RevTurbineLocalRuntimeOptions & {
561
+ exportedConfig: Omit<ExportedConfig, 'content_ui_paths'> & {
562
+ content_ui_paths: TUiPaths;
563
+ };
564
+ };
565
+ uiPathResolvers: RevTurbineRequiredUiPathResolvers<TUiPaths> & RevTurbineUiPathResolverMap;
566
+ }): RevTurbineInitOptions;
567
+ /** Optional context for slot-based placement requests. */
568
+ export interface RevTurbineSlotPlacementRequestOptions {
569
+ entitlementHandle?: string;
570
+ planHandle?: string;
571
+ placementHandle?: string;
572
+ }
573
+ /** Optional context for entitlement-based placement requests. */
574
+ export interface RevTurbineEntitlementPlacementRequestOptions {
575
+ slotId?: string;
576
+ surfaceType?: RevTurbineSurfaceType;
577
+ planHandle?: string;
578
+ placementHandle?: string;
579
+ }
580
+ /** Optional context for chained placement requests. */
581
+ export interface RevTurbineChainedPlacementRequestOptions {
582
+ slotId?: string;
583
+ surfaceType?: RevTurbineSurfaceType;
584
+ entitlementHandle?: string;
585
+ planHandle?: string;
586
+ }
587
+ /**
588
+ * Create a typed placement request for slot + surface lookups.
589
+ */
590
+ export declare function createSlotPlacementRequest(slotId: string, surfaceType: RevTurbineSurfaceType, options?: RevTurbineSlotPlacementRequestOptions): RevTurbinePlacementRequestConfig;
591
+ /**
592
+ * Create a typed placement request for entitlement-gated lookups.
593
+ */
594
+ export declare function createEntitlementPlacementRequest(entitlementHandle: string, options?: RevTurbineEntitlementPlacementRequestOptions): RevTurbinePlacementRequestConfig;
595
+ /**
596
+ * Create a typed placement request for chained/CTA follow-up lookups.
597
+ */
598
+ export declare function createChainedPlacementRequest(placementHandle: string, options?: RevTurbineChainedPlacementRequestOptions): RevTurbinePlacementRequestConfig;
599
+ /**
600
+ * Configuration for registering a placement slot.
601
+ * The combination of name + route + scope key produces a deterministic placement ID.
602
+ *
603
+ * @deprecated Use `RevTurbineSurfaceSlotConfig`.
604
+ */
605
+ export interface RevTurbinePlacementConfig {
606
+ /** Human-readable placement name (e.g. `'pricing_banner'`). */
607
+ name: string;
608
+ /** Optional scope key to differentiate placements on the same route. */
609
+ placementScopeKey?: string;
610
+ /** Arbitrary metadata attached to the placement for analytics. */
611
+ metadata?: SdkMetadata;
612
+ }
613
+ /**
614
+ * Canonical configuration for a renderable surface slot.
615
+ *
616
+ * `id` must be unique within the customer app integration.
617
+ */
618
+ export interface RevTurbineSurfaceSlotConfig {
619
+ /** Required unique identifier for the surface slot. */
620
+ id: string;
621
+ /** Optional human-readable label used for analytics and debugging. */
622
+ name?: string;
623
+ /**
624
+ * Surface template IDs that this slot accepts.
625
+ *
626
+ * When provided, only placements whose surface template matches one of
627
+ * these IDs are eligible to render in this slot. This acts as a filter
628
+ * at decision time — both the local resolver and the remote
629
+ * decide-context endpoint use this constraint.
630
+ */
631
+ surfaceTemplateIds?: string[];
632
+ /** Arbitrary metadata attached to the slot for analytics and traceability. */
633
+ metadata?: SdkMetadata;
634
+ }
635
+ export type { RevTurbinePlacementRecord } from '@revt-eng/core';
636
+ import type { RevTurbinePlacementRecord } from '@revt-eng/core';
637
+ export interface RevTurbinePlacementContent {
638
+ placementId: string;
639
+ requestId: string;
640
+ decisionSource: 'remote' | 'fallback';
641
+ content: RevTurbineDecisionContent;
642
+ }
643
+ /**
644
+ * Simplified content fields carried on placement decisions.
645
+ * Re-exported from `@revt-eng/core`.
646
+ */
647
+ export type { RevTurbineDecisionContent } from '@revt-eng/core';
648
+ import type { RevTurbineDecisionContent } from '@revt-eng/core';
649
+ export type { RevTurbineContextMode } from '@revt-eng/core';
650
+ import type { RevTurbineContextMode } from '@revt-eng/core';
651
+ export type { RevTurbineMeterUsageOverride } from '@revt-eng/core';
652
+ export type { RevTurbinePlacementDecisionOverrides } from '@revt-eng/core';
653
+ import type { RevTurbinePlacementDecisionOverrides } from '@revt-eng/core';
654
+ /**
655
+ * Input for requesting a placement decision.
656
+ * Re-exported from `@revt-eng/core`.
657
+ */
658
+ export type { RevTurbinePlacementDecisionInput } from '@revt-eng/core';
659
+ import type { RevTurbinePlacementDecisionInput } from '@revt-eng/core';
660
+ export interface RevTurbineBootstrapDecisionInput {
661
+ userId: string;
662
+ contextMode?: RevTurbineContextMode;
663
+ overrides?: RevTurbinePlacementDecisionOverrides;
664
+ traits?: Record<string, string | number | boolean>;
665
+ ttlMs?: number;
666
+ placementIds: string[];
667
+ }
668
+ /**
669
+ * A placement decision returned by the decision engine.
670
+ * Re-exported from `@revt-eng/core`.
671
+ */
672
+ export type { RevTurbinePlacementDecision } from '@revt-eng/core';
673
+ import type { RevTurbinePlacementDecision } from '@revt-eng/core';
674
+ /** Predicate-level evaluation detail for segment matching diagnostics. */
675
+ export type RevTurbineSegmentPredicateEvaluation = PredicateEvaluationResult;
676
+ /** Segment-level evaluation detail for placement diagnostics. */
677
+ export interface RevTurbineSegmentEvaluation {
678
+ segmentId: string;
679
+ segmentName?: string;
680
+ matched: boolean;
681
+ predicates: RevTurbineSegmentPredicateEvaluation[];
682
+ }
683
+ /** Entitlement-rule evaluation detail for placement diagnostics. */
684
+ export interface RevTurbineEntitlementRuleEvaluation {
685
+ ruleId: string;
686
+ entitlementId?: string;
687
+ entitlementHandle?: string;
688
+ kind?: string;
689
+ /** Human-readable plan scopes resolved from `planIds` (e.g. `starter`, `professional`). */
690
+ planScopes: string[];
691
+ planIds: string[];
692
+ /**
693
+ * Segment IDs the rule is scoped to. Empty array means "matches all users".
694
+ * Evaluated with intra-dimension OR + cross-dimension AND per spec §2.5
695
+ * (plan #39 REQ-8).
696
+ */
697
+ segmentIds?: string[];
698
+ matchesPlan: boolean;
699
+ matchesSegment: boolean;
700
+ matched: boolean;
701
+ outcome: EntitlementStatus | 'unknown';
702
+ /** Human-readable description of what this rule grants (e.g. "grants access", "sets limit to 5,000 calls / month"). */
703
+ outcomeDescription?: string;
704
+ reason?: string;
705
+ }
706
+ /** Placement rule signals extracted from the selected placement output. */
707
+ export interface RevTurbinePlacementRuleEvaluation {
708
+ ruleId?: string;
709
+ decisionId?: string;
710
+ category?: string;
711
+ suppressionReason?: string;
712
+ reasonCodes: string[];
713
+ capPolicies: Array<{
714
+ count: number;
715
+ period: 'session' | 'day' | 'week' | 'month' | 'lifetime';
716
+ cooldownMs?: number;
717
+ }>;
718
+ }
719
+ /** Placement payload eligibility detail for explainability UI. */
720
+ export interface RevTurbinePlacementPayloadEvaluation {
721
+ payloadId: string;
722
+ placementId: string;
723
+ placementName: string;
724
+ status: 'draft' | 'active' | 'disabled';
725
+ planIds: string[];
726
+ planScopes: string[];
727
+ segmentChips: string[];
728
+ surfaceTemplateIds: string[];
729
+ matchesPlan: boolean;
730
+ matchesSegment: boolean;
731
+ eligible: boolean;
732
+ selected: boolean;
733
+ }
734
+ /** Structured explanation object for placement decision visualization. */
735
+ export interface RevTurbinePlacementDecisionExplanation {
736
+ generatedAt: string;
737
+ input: RevTurbinePlacementDecisionInput;
738
+ decision: RevTurbinePlacementDecision;
739
+ targeting: RevTurbineTargeting;
740
+ policy: RevTurbinePolicySnapshot;
741
+ entitlements: Record<string, EntitlementResult>;
742
+ segments: RevTurbineSegmentEvaluation[];
743
+ entitlementRules: RevTurbineEntitlementRuleEvaluation[];
744
+ eligiblePayloads: RevTurbinePlacementPayloadEvaluation[];
745
+ placementRules: RevTurbinePlacementRuleEvaluation;
746
+ }
747
+ /**
748
+ * Types of user interactions with a placement treatment.
749
+ * Re-exported from `@revt-eng/core`.
750
+ */
751
+ export type { RevTurbineTreatmentInteractionType } from '@revt-eng/core';
752
+ import type { RevTurbineTreatmentInteractionType } from '@revt-eng/core';
753
+ export type { RevTurbineTreatmentInteractionInput } from '@revt-eng/core';
754
+ import type { RevTurbineTreatmentInteractionInput } from '@revt-eng/core';
755
+ /**
756
+ * Optional fields for constructing typed interaction payloads.
757
+ */
758
+ export interface RevTurbineTreatmentInteractionOptions {
759
+ treatmentId?: string;
760
+ interactionAt?: string;
761
+ metadata?: SdkMetadata;
762
+ }
763
+ /**
764
+ * Create a typed treatment interaction payload.
765
+ */
766
+ export declare function createTreatmentInteraction(userId: string, placementId: string, interactionType: RevTurbineTreatmentInteractionType, options?: RevTurbineTreatmentInteractionOptions): RevTurbineTreatmentInteractionInput;
767
+ export interface RevTurbineEventOptions {
768
+ immediate?: boolean;
769
+ }
770
+ /**
771
+ * User targeting context for payload eligibility.
772
+ * Re-exported from `@revt-eng/core`.
773
+ */
774
+ export type { UserTargetingContext } from '@revt-eng/core';
775
+ import type { UserTargetingContext } from '@revt-eng/core';
776
+ /** A named semantic event with structured payload. */
777
+ export interface RevTurbineSemanticEvent {
778
+ /** Event type name (e.g. `'checkout_started'`). */
779
+ eventType: string;
780
+ /** Structured event payload. */
781
+ payload: SdkEventProperties;
782
+ /** Delivery options. */
783
+ options?: RevTurbineEventOptions;
784
+ }
785
+ /**
786
+ * Canonical trigger event names recognised by the SDK and decision engine.
787
+ *
788
+ * These correspond to the placement categories defined in the product requirements
789
+ * (trial lifecycle, usage/limits, feature gating, retention, expansion).
790
+ */
791
+ export type RevTurbineTriggerEvent = TriggerEventType;
792
+ /** Payload for trial-related trigger events. */
793
+ export interface TrialTriggerPayload {
794
+ days_remaining?: number;
795
+ }
796
+ /** Payload for usage/limit trigger events. */
797
+ export interface UsageTriggerPayload {
798
+ /** The entitlement handle this usage event refers to. */
799
+ entitlement_handle?: string;
800
+ /** Current usage count for the entitlement. */
801
+ current_usage?: number;
802
+ /** Usage limit configured for the entitlement on the active plan. */
803
+ usage_limit?: number;
804
+ usage_percent?: number;
805
+ threshold?: number;
806
+ balance?: number;
807
+ allocation?: number;
808
+ seats_used?: number;
809
+ seats_allowed?: number;
810
+ }
811
+ /** Payload for feature-gate trigger events. */
812
+ export interface FeatureGateTriggerPayload {
813
+ feature: string;
814
+ }
815
+ /** Payload for payment-related trigger events. */
816
+ export interface PaymentTriggerPayload {
817
+ retry_count?: number;
818
+ renewal_date?: string;
819
+ }
820
+ /** Union of all typed trigger payloads. */
821
+ export type RevTurbineTriggerPayload = TrialTriggerPayload | UsageTriggerPayload | FeatureGateTriggerPayload | PaymentTriggerPayload | SdkEventProperties;
822
+ /**
823
+ * Create a typed semantic event payload.
824
+ */
825
+ export declare function createSemanticEvent(eventType: string, payload: SdkEventProperties, options?: RevTurbineEventOptions): RevTurbineSemanticEvent;
826
+ export type { RevTurbineEventEnvelope } from '@revt-eng/core';
827
+ /**
828
+ * The core RevTurbine customer-facing SDK.
829
+ *
830
+ * Provides methods for:
831
+ * - **Identity** — `identify()`, `resetIdentity()`
832
+ * - **Placements** — `registerPlacement()`, `getPlacementDecision()`, `getPlacement()`
833
+ * - **Entitlements** — `checkEntitlement()`, `updateUsage()`
834
+ * - **Trials** — `getTrialStatus()`
835
+ * - **Events** — `capture()`, `trackEvent()`, `emitSemantic()`
836
+ * - **Interactions** — `trackTreatmentInteraction()`, `dismiss()`, `convert()`
837
+ * - **Context** — `setUserContext()`, `setPageContext()`, `refreshPageContext()`
838
+ *
839
+ * @example
840
+ * ```ts
841
+ * const sdk = initRevTurbine({
842
+ * tenantId: 'tenant_abc',
843
+ * apiKey: 'rt_live_xxx',
844
+ * endpoint: 'https://api.revturbine.io',
845
+ * mode: 'react',
846
+ * });
847
+ *
848
+ * sdk.identify('user_123', { plan: 'pro' });
849
+ * const decision = await sdk.getPlacementDecision({ placementId, userId: 'user_123' });
850
+ * ```
851
+ */
852
+ export declare class RevTurbineCustomerSdk {
853
+ private readonly tenantId;
854
+ private readonly apiKey;
855
+ private readonly ingestPublicKey?;
856
+ private readonly environmentId;
857
+ private readonly endpoint;
858
+ private readonly runtimeMode;
859
+ private readonly endpointOverrides;
860
+ private readonly localRuntime?;
861
+ private readonly localStorageKey;
862
+ private readonly mode;
863
+ private readonly policy;
864
+ private readonly extensionEnabled;
865
+ private readonly placementBehavior;
866
+ private readonly providerFailureSlotBehavior;
867
+ private readonly uiPathResolvers;
868
+ private readonly persistentStore;
869
+ private readonly sessionStore;
870
+ private readonly anonymousId;
871
+ private readonly sessionId;
872
+ private readonly decisionCache;
873
+ private readonly interactionState;
874
+ private readonly interactionQueue;
875
+ private readonly defaultDecisionTtlMs;
876
+ private readonly defaultDismissCooldownMs;
877
+ private readonly defaultRemindLaterMs;
878
+ private readonly defaultUsageWarningPercent;
879
+ private readonly defaultTrialExpiringDays;
880
+ private readonly events;
881
+ private readonly placements;
882
+ private readonly syncedSurfaceSlotIds;
883
+ private userContext;
884
+ private pageContext;
885
+ private usageBalances;
886
+ private localDecisionsByPlacementId;
887
+ private localPlacementsByLookupKey;
888
+ private localEntitlementsByHandle;
889
+ private localUserContextsByUserId;
890
+ private localTrialStatus;
891
+ private readonly presentationCapsByKey;
892
+ private readonly usageLimitByEntitlement;
893
+ private readonly usageTokenPrefixByEntitlement;
894
+ private readonly segmentIdsByPredicateField;
895
+ private readonly configuredSegmentsById;
896
+ private readonly dirtySegmentIds;
897
+ private readonly segmentMembershipBySegmentId;
898
+ private segmentMembershipUserId?;
899
+ private lastTrialTriggerStage;
900
+ private readonly configProvider?;
901
+ private readonly defaultLocalPlacementDecisionResolver?;
902
+ private sdkDisabledByProviderFailure;
903
+ private sdkDisabledReason?;
904
+ readonly providerRegistry: DomainProviderRegistry;
905
+ readonly placementTypeRegistry: PlacementTypeRegistry;
906
+ readonly impressionHistory: ImpressionHistory;
907
+ constructor(options: RevTurbineInitOptions);
908
+ private isLocalOnlyMode;
909
+ private resolveConfigProvider;
910
+ private refreshExportedConfigSnapshot;
911
+ private getConfiguredExportedConfig;
912
+ private rebuildSegmentPredicateFieldIndex;
913
+ private buildDefaultLocalPlacementDecisionResolver;
914
+ /**
915
+ * Build a minimal provider context from the SDK's user state when no
916
+ * explicit domain providers are registered. This allows the local
917
+ * placement resolver to access plan and usage data for token
918
+ * interpolation (e.g. `{{usage_remaining}}`).
919
+ */
920
+ private synthesizeProviderContext;
921
+ private markAllSegmentsDirty;
922
+ private markSegmentsDirtyForFields;
923
+ private toSegmentEvaluationTraits;
924
+ private buildTargetingState;
925
+ private markSegmentsDirtyFromContextChange;
926
+ /** Resolve current pathname from page context or window.location (server-safe). */
927
+ private currentPathname;
928
+ disableForProviderFailure(reason: string): void;
929
+ private isDisabledByProviderFailure;
930
+ private disabledDecisionForPlacement;
931
+ private disabledPlacementOutputForConfig;
932
+ private endpointFor;
933
+ private localPlacementLookupKey;
934
+ private localLookupMatchesConfig;
935
+ private localOutputMatchesConfig;
936
+ private applyCategoryConflictSuppression;
937
+ private resolveLocalPlacementFromCandidates;
938
+ private localPlacementForConfig;
939
+ private hydrateLocalRuntimeState;
940
+ private persistLocalRuntimeState;
941
+ private decisionCacheStorageKey;
942
+ private interactionStateStorageKey;
943
+ private presentationCapsStorageKey;
944
+ private hydrateDecisionCache;
945
+ private persistDecisionCache;
946
+ private hydrateInteractionState;
947
+ private persistInteractionState;
948
+ private hydratePresentationCaps;
949
+ private persistPresentationCaps;
950
+ /**
951
+ * The set of identifiers (lowercased plan id + unique_handle) that name the
952
+ * user's CURRENT plan, so an `entitlement_rule` whose plan target carries
953
+ * either form is matched. The app may set `plan.id` to the handle (`"free"`)
954
+ * or the config id (`"plan_free"`); both resolve to the same plan here.
955
+ */
956
+ private activePlanIdentifiers;
957
+ /** Whether a rule's plan targets include the active plan (no plan target = applies to all plans). */
958
+ private ruleTargetsActivePlan;
959
+ private hydrateUsageLimitRulesFromExportedConfig;
960
+ private recalculateDerivedUsageTraits;
961
+ /**
962
+ * Resolves `{{recommended_plan_handle}}` and `{{recommended_plan_name}}`
963
+ * tokens against the user's current commercial plan (per Appendix C.3
964
+ * and targeting-studio-ui.md §4.1 — the base plan, NOT the trial-grant
965
+ * overlay). Falls back to empty strings when the user has no current
966
+ * plan, the plan is at the top of the hierarchy, or the exported config
967
+ * has no plans.
968
+ *
969
+ * Q-3 (plan #46) audit: `userContext.plan.id` is the commercial plan;
970
+ * `effectivePlanHandle` (resolved separately in `deriveLocalEntitlement`
971
+ * for reverse-trial grants) is the trial overlay. The spec example
972
+ * "Free user on Pro reverse trial → recommends Pro" works because Free
973
+ * is the base; next-tier-up from Free is Pro.
974
+ */
975
+ private deriveRecommendedPlanTokens;
976
+ /**
977
+ * Return the SDK-resolved personalization token map.
978
+ *
979
+ * Reads from the transient `personalization` map on the user context,
980
+ * which holds both SDK-derived tokens (plan_name, usage_current, etc.)
981
+ * and app-provided tokens set via `setPersonalization()` or `identify()`.
982
+ *
983
+ * Pass the placement's payload (its `recommendation_strategy` /
984
+ * `recommendation_plan_override` fields) to resolve the
985
+ * `{{recommended_plan_handle}}` / `{{recommended_plan_name}}` tokens for
986
+ * that specific placement (plan #47, Appendix C.3). Without a payload the
987
+ * map carries the user-level `next_tier_up` default; with one, the
988
+ * placement's authored strategy (e.g. a `custom` forced plan) overlays
989
+ * those two tokens. All other tokens are unaffected.
990
+ *
991
+ * @param payload Optional placement payload carrying the per-placement
992
+ * recommendation strategy. Omit for the user-level default.
993
+ */
994
+ getPersonalizationTokens(payload?: {
995
+ recommendation_strategy?: RecommendationStrategy | null;
996
+ recommendation_plan_override?: string | null;
997
+ }): RevTurbinePersonalizationTokens;
998
+ /**
999
+ * Return the SDK-resolved entitlement snapshot for the active user.
1000
+ *
1001
+ * The returned object is keyed by entitlement handle and reflects the
1002
+ * latest results from local/runtime checks tracked by the SDK.
1003
+ */
1004
+ getEntitlements(): Record<string, EntitlementResult>;
1005
+ /**
1006
+ * Return the SDK-resolved usage snapshot for the active user.
1007
+ *
1008
+ * Keys are usage units (derived from configured usage token prefixes when available),
1009
+ * and values include current usage plus optional limit when known.
1010
+ */
1011
+ getUsage(): RevTurbineUsageSnapshot;
1012
+ /**
1013
+ * Return current SDK policy snapshot.
1014
+ */
1015
+ getPolicy(): RevTurbinePolicySnapshot;
1016
+ private deriveLocalEntitlementFromConfiguredRules;
1017
+ /**
1018
+ * Inline adapter — given a UserTrialStatus + the tenant's
1019
+ * reverse_trial_rules from ExportedConfig, derive the inputs that
1020
+ * close plan 43 TASK-2. Returns undefined fields when the user
1021
+ * isn't on an active reverse trial, when no rule matches, or when
1022
+ * the rule has no entitlements_during_trial[].
1023
+ *
1024
+ * Why inline (not calling scaffold's deriveReverseTrialGrants):
1025
+ * the scaffold helper takes a `TrialInstance` (DB-side state) and
1026
+ * matches by `rule_id`. The SDK only holds `UserTrialStatus` (the
1027
+ * transient runtime shape) and doesn't see the rule_id. We match
1028
+ * by `fallback_plan_id === plan_handle` instead — that's the
1029
+ * single configured rule the user can be on per spec §2.4.2.
1030
+ */
1031
+ private resolveReverseTrialGrants;
1032
+ /**
1033
+ * Return the SDK-resolved targeting snapshot for the active user.
1034
+ *
1035
+ * Includes user id, segment ids, traits, plan, and merged usage so demo
1036
+ * surfaces can display the same context used by placement eligibility.
1037
+ */
1038
+ getTargeting(): RevTurbineTargeting;
1039
+ /**
1040
+ * Explain why a placement decision was selected.
1041
+ *
1042
+ * Returns a structured diagnostic payload that includes:
1043
+ * - Segment membership evaluation with predicate-level pass/fail details
1044
+ * - Entitlement-rule matching outcomes for current targeting context
1045
+ * - Placement decision metadata (`rule_id`, reason codes, suppression)
1046
+ *
1047
+ * Useful for debuggers, QA tooling, and customer-facing explainability UIs.
1048
+ */
1049
+ explainPlacementDecision(input: RevTurbinePlacementDecisionInput): Promise<RevTurbinePlacementDecisionExplanation>;
1050
+ private usageThresholdForEntitlement;
1051
+ private evaluateUsageThresholdCrossings;
1052
+ private deriveTrialTriggerStage;
1053
+ private evaluateTrialLifecycleTriggers;
1054
+ private resolveAnonymousId;
1055
+ private installBridge;
1056
+ private installRouteTracking;
1057
+ private mergeUserContext;
1058
+ private mergePageContext;
1059
+ private collectPageContextIssues;
1060
+ private collectPayloadIssues;
1061
+ private buildValidationWarningEvent;
1062
+ private toEventEnvelope;
1063
+ private sendEvents;
1064
+ private dispatchToEventConsumers;
1065
+ capture(eventName: string, properties: SdkEventProperties, options?: RevTurbineEventOptions): Promise<void>;
1066
+ emitSemantic(eventType: string, payload: SdkEventProperties, options?: RevTurbineEventOptions): Promise<void>;
1067
+ /**
1068
+ * Optimized routine to evaluate segment membership and usage thresholds.
1069
+ * Should be called on every user context or usage update.
1070
+ *
1071
+ * @param update - Partial user context or usage update payload
1072
+ * @param isUsageUpdate - If true, also check usage thresholds
1073
+ */
1074
+ private evaluateUserSegmentsAndUsage;
1075
+ setUserContext(userContext: RevTurbineUserContext): void;
1076
+ setPageContext(pageContext: RevTurbinePageContext): void;
1077
+ refreshPageContext(): void;
1078
+ /**
1079
+ * Hydrate the SDK with a server-evaluated payload.
1080
+ *
1081
+ * Call this on the client after receiving a `ServerEvaluationPayload`
1082
+ * from the server-side SDK. Pre-populates the decision cache,
1083
+ * entitlements, trial status, and user context so the client SDK
1084
+ * avoids redundant API calls.
1085
+ *
1086
+ * @example
1087
+ * ```ts
1088
+ * // In your React component / page hydration:
1089
+ * const sdk = initRevTurbine({ tenantId, apiKey, endpoint, mode: 'react' });
1090
+ * sdk.hydrate(serverPayload);
1091
+ * ```
1092
+ */
1093
+ hydrate(payload: ServerEvaluationHydrationPayload): void;
1094
+ generatePlacementId(input: {
1095
+ placementName: string;
1096
+ placementScopeKey?: string;
1097
+ normalizedPageRoute?: string;
1098
+ }): Promise<string>;
1099
+ /**
1100
+ * @deprecated Use `registerSurfaceSlot`.
1101
+ */
1102
+ registerPlacement(config: RevTurbinePlacementConfig): Promise<string>;
1103
+ private upsertSurfaceSlot;
1104
+ registerSurfaceSlot(config: RevTurbineSurfaceSlotConfig): Promise<string>;
1105
+ persistPlacementTypes(types: RevTurbinePlacementTypeEntity[]): Promise<void>;
1106
+ private stableStringify;
1107
+ private decisionCacheKey;
1108
+ private interactionStateKey;
1109
+ private readDecisionCache;
1110
+ private writeDecisionCache;
1111
+ private suppressionForState;
1112
+ private placementCapKey;
1113
+ private extractPlacementCapPolicies;
1114
+ private applyPlacementCapsIfNeeded;
1115
+ /**
1116
+ * Plan 43 TASK-14 — gate a getPlacementDecision result on `cap.v1` policies.
1117
+ *
1118
+ * On the first decision pass (`tick: true`), the cap state is ticked when
1119
+ * the cap allows firing — so a placement with
1120
+ * `max_per_period: { count: 1, period: 'lifetime' }` is consumed once.
1121
+ * On a cache-hit re-evaluation (`tick: false`), the cap state is only
1122
+ * read, so subsequent identical inputs observe the consumed budget and
1123
+ * the decision flips to `visible: false` with a `cap_exceeded` reason.
1124
+ * Without this re-evaluation, the decision cache would return the
1125
+ * stale `visible: true` from before the tick. When
1126
+ * `enableClientCapsEnforcement` is false, this helper is a no-op.
1127
+ */
1128
+ private gateDecisionByCaps;
1129
+ private normalizeDecisionFromResponse;
1130
+ getPlacementDecision(input: RevTurbinePlacementDecisionInput): Promise<RevTurbinePlacementDecision>;
1131
+ preloadPlacementDecisions(inputs: RevTurbinePlacementDecisionInput[]): Promise<void>;
1132
+ bootstrapPlacementDecisions(inputs: RevTurbinePlacementDecisionInput[]): Promise<void>;
1133
+ private updateInteractionState;
1134
+ private flushInteractionQueue;
1135
+ trackTreatmentInteraction(input: RevTurbineTreatmentInteractionInput): Promise<void>;
1136
+ getPlacementContent(placementId: string, request?: JsonObject): Promise<RevTurbinePlacementContent>;
1137
+ private normalizePlacementOutput;
1138
+ private normalizeEntitlementResult;
1139
+ private validateTrialStatusShape;
1140
+ getPlacement(config: RevTurbinePlacementRequestConfig): Promise<PlacementOutput | null>;
1141
+ checkEntitlement(handle: string, context?: RevTurbineEntitlementContext): Promise<EntitlementResult>;
1142
+ updateUsage(balances: UsageBalances): void;
1143
+ /**
1144
+ * Build the full persistence-ready {@link UserContext} from the current
1145
+ * SDK state. Includes `tenant_id` and `user_id` required for API storage.
1146
+ */
1147
+ getUserContext(): UserContext;
1148
+ /**
1149
+ * Fetch the resolved user context from the decision API.
1150
+ * Returns the user's matched segments, traits, plan, and usage — used
1151
+ * to determine which placement payloads are eligible for display.
1152
+ */
1153
+ fetchUserContext(userId: string): Promise<UserTargetingContext>;
1154
+ /**
1155
+ * Record that a placement was rendered to the user. Plan 43 TASK-9.
1156
+ *
1157
+ * Writes an `impressed` record to the SDK's `ImpressionHistory`,
1158
+ * which persists to `localStorage` via `StorageImpressionStore`
1159
+ * (or in-memory storage in non-browser environments). The
1160
+ * impression contributes to:
1161
+ *
1162
+ * - **Frequency caps (`cap.v1`)** — once-per-period limits
1163
+ * count this impression against the user's quota for the
1164
+ * placement.
1165
+ * - **Trial milestone supersession analytics** — for trial_progress
1166
+ * ladders, the supersession diagnostic uses delivery state
1167
+ * to distinguish "replaced an undelivered placement" (counts
1168
+ * in `superseded_placement_ids`) from "lower threshold was
1169
+ * already shown" (NOT counted — spec §3.5 "supersession only
1170
+ * applies to undelivered placements").
1171
+ * - **Generic milestone supersession (`content.milestone_order`)**
1172
+ * — the order-based variant in `applyContentMilestoneSupersession`.
1173
+ *
1174
+ * Call this from consumer code when the placement is actually
1175
+ * shown to the user (e.g., from a React component's `useEffect`
1176
+ * on mount, or after the rendering call returns). The SDK does
1177
+ * NOT auto-record impressions — surfaces are rendered by consumer
1178
+ * code, so only the consumer knows when a placement was actually
1179
+ * presented (vs. fetched but not displayed).
1180
+ *
1181
+ * Safe to call multiple times for the same placement — duplicates
1182
+ * append additional impression records (used by frequency caps to
1183
+ * count delivery events).
1184
+ *
1185
+ * @param placementId - The placement's stable rule_id (e.g.
1186
+ * `'pl_trial_progress_70'`). Match `decision.output.rule_id`
1187
+ * from `getPlacementDecision`.
1188
+ * @param payloadId - Optional payload variant id, for
1189
+ * variant-level analytics.
1190
+ * @param surfaceTemplateId - Optional surface template id, for
1191
+ * per-surface cap accounting.
1192
+ * @param metadata - Optional metadata persisted with the record.
1193
+ *
1194
+ * @example
1195
+ * ```ts
1196
+ * const decision = await sdk.getPlacementDecision({ placementId: 'slot_trial_modal' });
1197
+ * if (decision.visible && decision.output?.rule_id) {
1198
+ * renderBanner(decision.output);
1199
+ * await sdk.recordImpression(decision.output.rule_id, decision.output.output_id);
1200
+ * }
1201
+ * ```
1202
+ */
1203
+ recordImpression(placementId: string, payloadId?: string, surfaceTemplateId?: string, metadata?: RevTurbineImpressionMetadata): Promise<void>;
1204
+ /**
1205
+ * Record a placement dismissal — the user explicitly closed it.
1206
+ * The placement is permanently retired for this user; subsequent
1207
+ * `getPlacementDecision` calls return `visible: false`.
1208
+ *
1209
+ * @param placementId - The placement's stable rule_id.
1210
+ * @param payloadId - Optional payload variant id.
1211
+ * @param surfaceTemplateId - Optional surface template id.
1212
+ * @param metadata - Optional metadata persisted with the record.
1213
+ */
1214
+ recordDismissal(placementId: string, payloadId?: string, surfaceTemplateId?: string, metadata?: RevTurbineImpressionMetadata): Promise<void>;
1215
+ /**
1216
+ * Record a placement click-through — the user engaged with the CTA.
1217
+ * The placement is permanently retired for this user.
1218
+ *
1219
+ * @param placementId - The placement's stable rule_id.
1220
+ * @param payloadId - Optional payload variant id.
1221
+ * @param surfaceTemplateId - Optional surface template id.
1222
+ * @param metadata - Optional metadata persisted with the record.
1223
+ */
1224
+ recordClickThru(placementId: string, payloadId?: string, surfaceTemplateId?: string, metadata?: RevTurbineImpressionMetadata): Promise<void>;
1225
+ getTrialStatus(): Promise<RevTurbineTrialContext>;
1226
+ /**
1227
+ * Returns the ExportedConfig snapshot loaded at initialization, if any.
1228
+ * Available only in `local_only` mode when `exportedConfig` was provided.
1229
+ */
1230
+ getExportedConfig(): ExportedConfig | undefined;
1231
+ /**
1232
+ * Validate that each configured UI path action has a resolver implementation.
1233
+ *
1234
+ * By default this validates `localRuntime.exportedConfig.content_ui_paths` (when present)
1235
+ * against:
1236
+ * - `uiPathResolvers` passed at SDK init
1237
+ * - optional `resolvers` passed to this method
1238
+ * - CTA handlers from domain providers (`domain: 'cta'`), unless disabled
1239
+ */
1240
+ validateUiPathResolvers(options?: RevTurbineUiPathResolverValidationOptions): Promise<RevTurbineUiPathResolverValidationReport>;
1241
+ private assertUiPathResolverCoverageOrThrow;
1242
+ dismiss(outputId: string): Promise<void>;
1243
+ snooze(outputId: string, seconds?: number): Promise<void>;
1244
+ convert(outputId: string): Promise<void>;
1245
+ /**
1246
+ * Emit a canonical trigger event recognised by the decision engine.
1247
+ *
1248
+ * Convenience wrapper over {@link emitSemantic} that constrains the event
1249
+ * name to {@link RevTurbineTriggerEvent} and attaches standard context
1250
+ * (user_id, plan, timestamp) automatically.
1251
+ *
1252
+ * @example
1253
+ * ```ts
1254
+ * await sdk.emitTrigger('usage_limit_approaching', { usage_percent: 85, threshold: 80 });
1255
+ * await sdk.emitTrigger('trial_expiring', { days_remaining: 2 });
1256
+ * await sdk.emitTrigger('feature_gated', { feature: 'advanced_automation' });
1257
+ * ```
1258
+ */
1259
+ emitTrigger(trigger: RevTurbineTriggerEvent, payload?: RevTurbineTriggerPayload, options?: RevTurbineEventOptions): Promise<void>;
1260
+ trackEvent(name: string, data?: SdkEventProperties): Promise<void>;
1261
+ identify(userId: string, contextOrTraits?: UserContextInput | SdkTraits): void;
1262
+ resetIdentity(): void;
1263
+ /**
1264
+ * Hard-reset the user context to a blank slate — removes EVERY user-context
1265
+ * value (`id`, `plan`, `email`, `account_id`, `custom`, `usage`,
1266
+ * `entitlements`, `personalization`) plus usage balances, and clears the
1267
+ * decision cache, interaction state, and impression history.
1268
+ *
1269
+ * Unlike {@link resetIdentity} (a sign-out that re-infers anonymous context
1270
+ * when the `inferUser` policy is on), this performs **no** inference, so the
1271
+ * resulting context is guaranteed empty. Mostly for demo / fixture flows that
1272
+ * reset cleanly between scenarios.
1273
+ *
1274
+ * @example
1275
+ * // Between demo personas:
1276
+ * rt.resetUserContext();
1277
+ * rt.identify('demo_pro', { plan: { id: 'pro', name: 'Pro' } });
1278
+ */
1279
+ resetUserContext(): void;
1280
+ /**
1281
+ * Shared teardown for {@link resetIdentity} / {@link resetUserContext}:
1282
+ * blanks the user context and usage balances, recomputes derived traits, and
1283
+ * clears the decision cache, interaction state, and impression history.
1284
+ * `reinfer` controls whether anonymous context is re-inferred (sign-out) or
1285
+ * the context is left fully empty (hard reset).
1286
+ */
1287
+ private clearAllUserState;
1288
+ /**
1289
+ * Check whether the user can do something — the advertised alias of
1290
+ * {@link checkEntitlement}. Returns the rich {@link EntitlementResult}
1291
+ * (`allowed`, `status`, `reason`, limits, `enforcement`). For billing-critical
1292
+ * entitlements, confirm `enforcement === 'server_required'` on your backend.
1293
+ *
1294
+ * @example
1295
+ * const access = await rt.can('generate_image');
1296
+ * if (!access.allowed) showUpgrade();
1297
+ */
1298
+ can(handle: string, context?: RevTurbineEntitlementContext): Promise<EntitlementResult>;
1299
+ /**
1300
+ * Gate an action behind an entitlement — the advertised `gate(action, fn)` verb.
1301
+ * Checks the entitlement for `action`; if allowed, runs `fn` and returns its
1302
+ * result; otherwise does NOT run `fn` and returns the entitlement so the caller
1303
+ * can surface a paywall (e.g. render an `<RTSlot>`). See {@link RevTurbineGateResult}.
1304
+ *
1305
+ * @example
1306
+ * const gated = await rt.gate('export_pdf', () => exportPdf());
1307
+ * if (!gated.ran) openPaywall(gated.entitlement);
1308
+ */
1309
+ gate<T>(action: string, fn: () => T | Promise<T>, context?: RevTurbineEntitlementContext): Promise<RevTurbineGateResult<T>>;
1310
+ /**
1311
+ * Track an event — the advertised alias of {@link trackEvent}. Powers
1312
+ * analytics, frequency caps, attribution, and experiments.
1313
+ *
1314
+ * @example
1315
+ * rt.track('ai_generation_completed', { credits: 3 });
1316
+ */
1317
+ track(name: string, data?: SdkEventProperties): Promise<void>;
1318
+ /**
1319
+ * Patch customer-reported usage — the advertised `update({ usage })` verb,
1320
+ * delegating to {@link updateUsage}. For identity or full user-context changes
1321
+ * use {@link identify} / {@link setUserContext}.
1322
+ *
1323
+ * @example
1324
+ * rt.update({ usage: { generations: 25 } });
1325
+ */
1326
+ update(patch: RevTurbineUpdateInput): void;
1327
+ /**
1328
+ * Clear the current user — the advertised alias of {@link resetIdentity}
1329
+ * (e.g. on sign-out).
1330
+ */
1331
+ reset(): void;
1332
+ onRouteChange(change: {
1333
+ path: string;
1334
+ title?: string;
1335
+ tags?: string[];
1336
+ }): void;
1337
+ }
1338
+ /**
1339
+ * Initialize the RevTurbine SDK.
1340
+ *
1341
+ * This is the primary entry point for browser integration.
1342
+ * Also available as `window.RevTurbine.init()` for non-module environments.
1343
+ *
1344
+ * @param options - SDK initialization options
1345
+ * @returns A configured SDK instance
1346
+ *
1347
+ * @example
1348
+ * ```ts
1349
+ * import { initRevTurbine } from '@revt-eng/sdk';
1350
+ *
1351
+ * const sdk = initRevTurbine({
1352
+ * tenantId: 'tenant_abc',
1353
+ * apiKey: 'rt_live_xxx',
1354
+ * endpoint: 'https://api.revturbine.io',
1355
+ * mode: 'snippet',
1356
+ * });
1357
+ * ```
1358
+ */
1359
+ export declare function initRevTurbine(options: RevTurbineInitInputOptions): RevTurbineCustomerSdk;
1360
+ declare global {
1361
+ interface Window {
1362
+ RevTurbine?: {
1363
+ init: typeof initRevTurbine;
1364
+ };
1365
+ }
1366
+ }
1367
+ //# sourceMappingURL=customer-side.d.ts.map