Skip to content

RevTurbineCustomerSdk

The core RevTurbine customer-facing SDK.

Provides methods for:

  • Identityidentify(), resetIdentity()
  • PlacementsregisterPlacement(), getPlacementDecision(), getPlacement()
  • EntitlementscheckEntitlement(), updateUsage()
  • TrialsgetTrialStatus()
  • Eventscapture(), trackEvent(), emitSemantic()
  • InteractionstrackTreatmentInteraction(), dismiss(), convert()
  • ContextsetUserContext(), setPageContext(), refreshPageContext()
const sdk = initRevTurbine({
tenantId: 'tenant_abc',
apiKey: 'rt_live_xxx',
endpoint: 'https://edge.example.com',
mode: 'react',
});
sdk.identify('user_123', { plan: 'pro' });
const decision = await sdk.getPlacementDecision({ placementId, userId: 'user_123' });

can(handle, context?): Promise<{ }>

Check whether the user can do something — the advertised alias of checkEntitlement. Returns the rich EntitlementResult (allowed, status, reason, and limit/used/remaining for limit-bearing entitlements). This client check is a UX convenience — for billing-critical or abuse-sensitive actions, re-run the same check on your server before granting access.

string

RevTurbineEntitlementContext

Promise<{ }>

const access = await rt.can('generate_image');
if (!access.allowed) showUpgrade();

dispose(): void

Stop background clickstream flushing and release page-unload listeners. Flushes any buffered events one last time. Call when tearing down an SDK instance (e.g. SPA unmount) to avoid a dangling interval/listeners.

void


emitTrigger(trigger, payload?, options?): Promise<void>

Emit a canonical trigger event recognised by the decision engine.

Convenience wrapper over emitSemantic that constrains the event name to RevTurbineTriggerEvent and attaches standard context (user_id, plan, timestamp) automatically.

"payment_failed" | "feature_gated" | "trial_midpoint" | "trial_expiring" | "trial_expired" | "usage_limit_approaching" | "usage_limit_reached" | "credit_balance_low" | "seat_limit_reached" | "cancel_intent" | "auto_renewal_reminder" | "onboarding_complete" | "invite_teammate_prompt" | "referral_offer" | "plan_upgrade_nudge"

RevTurbineTriggerPayload

RevTurbineEventOptions

Promise<void>

await sdk.emitTrigger('usage_limit_approaching', { usage_percent: 85, threshold: 80 });
await sdk.emitTrigger('trial_expiring', { days_remaining: 2 });
await sdk.emitTrigger('feature_gated', { feature: 'advanced_automation' });

explainPlacementDecision(input): Promise<RevTurbinePlacementDecisionExplanation>

Explain why a placement decision was selected.

Returns a structured diagnostic payload that includes:

  • Segment membership evaluation with predicate-level pass/fail details
  • Entitlement-rule matching outcomes for current targeting context
  • Placement decision metadata (rule_id, reason codes, suppression)

Useful for debuggers, QA tooling, and customer-facing explainability UIs.

RevTurbinePlacementDecisionInput

Promise<RevTurbinePlacementDecisionExplanation>


fetchClientContext(clientToken?): Promise<void>

Enrich the held UserContext with the user’s server-known CLIENT-SAFE context (plan 157). Fetches GET /api/sdk/client-context with the provided client token (rt_client_, minted by the customer’s backend via the server SDK’s clientSessions.create), maps the client-safe fields (trial state, coarse billing health) into the UserContext, and merges them in — these fields are RevTurbine-authoritative, so they refresh the held context.

The token is held in memory only (never storage / URL / logs). Enrichment is best-effort: a network error or non-200 never throws into the app; on 401 (expired / revoked) the held token is cleared. Server-side entitlement checks remain authoritative regardless of what the browser sees.

string

the rt_client_ token; when omitted, reuses the last one.

Promise<void>


fetchUserContext(userId): Promise<UserTargetingContext>

Fetch the resolved user context from the decision API. Returns the user’s matched segments, traits, plan, and usage — used to determine which placement payloads are eligible for display.

string

Promise<UserTargetingContext>


flushEvents(): Promise<void>

Flush any buffered clickstream events to POST /api/track immediately.

Called on the size threshold, the RevTurbineEventBatchingOptions interval timer, and page-unload. Best-effort and non-throwing — delivery failures are swallowed (plan 95 REQ-3). Safe to call when the buffer is empty (no-op).

Promise<void>


gate<T>(action, fn, context?): Promise<RevTurbineGateResult<T>>

Gate an action behind an entitlement — the advertised gate(action, fn) verb. Checks the entitlement for action; if allowed, runs fn and returns its result; otherwise does NOT run fn and returns the entitlement so the caller can surface a paywall (e.g. render an <RTSlot>). See RevTurbineGateResult.

T

string

() => T | Promise<T>

RevTurbineEntitlementContext

Promise<RevTurbineGateResult<T>>

const gated = await rt.gate('export_pdf', () => exportPdf());
if (!gated.ran) openPaywall(gated.entitlement);

getBranding(): ResolvedBranding

Resolve the branding to render with, down the four-rung ladder (plan 118): the explicit branding init option → the config’s deprecated embedded theme (dev-warns) → the apiBranding init option → DEFAULT_BRANDING.

Branding is a display concern only — it never affects placement decisions or entitlement checks. The result is always complete, so callers can render unconditionally even when no branding was supplied.

ResolvedBranding

The merged branding and the ladder rung it came from.


getEntitlements(): Record<string, EntitlementResult>

Return the SDK-resolved entitlement snapshot for the active user.

The returned object is keyed by entitlement handle and reflects the latest results from local/runtime checks tracked by the SDK.

Record<string, EntitlementResult>


getExportedConfig(): { } | undefined

Returns the legacy-compatible evaluator snapshot loaded at initialization. Canonical consumers should retain their Playbook or use normalizeConfigArtifactOrThrow at their ingestion boundary.

{ } | undefined


getPersonalizationTokens(payload?): RevTurbinePersonalizationTokens

Return the SDK-resolved personalization token map.

Reads from the transient personalization map on the user context, which holds both SDK-derived tokens (plan_name, usage_current, etc.) and app-provided tokens set via setPersonalization() or identify().

Pass the placement’s payload (its recommendation_strategy / recommendation_plan_override fields) to resolve the {{recommended_plan_handle}} / {{recommended_plan_name}} tokens for that specific placement (plan #47, Appendix C.3). Without a payload the map carries the user-level next_tier_up default; with one, the placement’s authored strategy (e.g. a custom forced plan) overlays those two tokens. All other tokens are unaffected.

Optional placement payload carrying the per-placement recommendation strategy. Omit for the user-level default.

string | null

RecommendationStrategy | null

RevTurbinePersonalizationTokens


getPolicy(): RevTurbinePolicySnapshot

Return current SDK policy snapshot.

RevTurbinePolicySnapshot


getTargeting(): RevTurbineTargeting

Return the SDK-resolved targeting snapshot for the active user.

Includes user id, segment ids, traits, plan, and merged usage so demo surfaces can display the same context used by placement eligibility.

RevTurbineTargeting


getTelemetryConsent(): TelemetryConsent

The current behavior-telemetry consent state (plan 144 TASK-8).

TelemetryConsent


getTelemetryCounters(): TelemetryCounters

A snapshot of the telemetry pipeline counters (plan 144 TASK-8) — created / dropped / redacted / sampled / deduped / queued / sent / failed. A cheap diagnostic for “why did my events not arrive?”. Returns a copy, so mutating it never touches the SDK’s live tallies.

TelemetryCounters


getUsage(): RevTurbineUsageSnapshot

Return the SDK-resolved usage snapshot for the active user.

Keys are usage units (derived from configured usage token prefixes when available), and values include current usage plus optional limit when known.

RevTurbineUsageSnapshot


getUserContext(): object

Build the full persistence-ready UserContext from the current SDK state. Includes tenant_id and user_id required for API storage.

object


hydrate(payload): void

Hydrate the SDK with a server-evaluated payload.

Call this on the client after receiving a ServerEvaluationPayload from the server-side SDK. Pre-populates the decision cache, entitlements, trial status, and user context so the client SDK avoids redundant API calls.

void

// In your React component / page hydration:
const sdk = initRevTurbine({ tenantId, apiKey, endpoint, mode: 'react' });
sdk.hydrate(serverPayload);

identify<T>(userId, context?): void

Identify the current user and (optionally) supply their context.

Accepts the canonical IdentifyContextInput — recognized by the presence of account_id / email / plan / plan_handle / usage / entitlements / custom — or a legacy plain-traits object, which is stored under custom unchanged. plan_handle is THE plan matching identity (the plan’s unique_handle, plan 191 REQ-1); the plan object is display metadata and never participates in matching, and nothing in custom ever drives plan resolution (REQ-2).

Guardrails: an empty id rejects the call; an email-shaped id warns in dev (ids stay opaque — pass emails as { email }); unrecognized top-level keys are named in a dev warning instead of being dropped or routed silently. Legacy-traits behavior is unchanged beyond the diagnostic.

T extends IdentifyContextInput

string

Exact<IdentifyContextInput, T>

void

rt.identify('user_123', { plan_handle: 'pro' }); // THE matching identity
rt.identify('user_123', { plan_handle: 'pro', plan: { handle: 'pro', name: 'Professional' } });

onUserContextChange(listener): () => void

Subscribe to user-context changes — identify(), setUserContext(), update(), updateUsage(), and resetIdentity() (plan 194 REQ-3).

Returns an unsubscribe function. Listeners must never throw; one that does is caught here rather than allowed to break the verb that fired it.

() => void

() => void

const unsubscribe = rt.onUserContextChange(() => refreshMyUi());

persistPlacementTypes(types): Promise<void>

Persist authored placement types to a configured backend.

Requires an explicit placementTypes endpoint override. RevTurbine hosts no /api/sdk/placement-types route — the default path was never built, and there is no table behind it — so without an override this method is a no-op rather than a guaranteed 404. It previously threw persist_placement_types_failed:404 in every non-local_only mode, which made a documented method unusable on the documented default path.

Supply endpointOverrides.placementTypes (or override the provider hook of the same name) to send these somewhere real.

RevTurbinePlacementTypeEntity[]

Promise<void>


recordClickThru(placementId, payloadId?, surfaceTemplateId?, metadata?, cooldownMs?): Promise<void>

Record a bare placement click-through — the user clicked the CTA but did not confirm the conversion (e.g. abandoned checkout). Time-boxed like a dismiss; the placement may return (plan 167). For a confirmed conversion use recordConversion.

string

The placement’s stable rule_id.

string

Optional payload variant id.

string

Optional surface template id.

RevTurbineImpressionMetadata

Optional metadata persisted with the record.

number

Optional explicit cooldown window (ms). Defaults to 7 days.

Promise<void>


recordConversion(placementId, payloadId?, surfaceTemplateId?, metadata?): Promise<void>

Record a confirmed conversion — the user completed the CTA action. The placement is permanently retired for this user; subsequent getPlacementDecision calls return visible: false for good (plan 167).

string

The placement’s stable rule_id.

string

Optional payload variant id.

string

Optional surface template id.

RevTurbineImpressionMetadata

Optional metadata persisted with the record.

Promise<void>


recordDismissal(placementId, payloadId?, surfaceTemplateId?, metadata?, cooldownMs?): Promise<void>

Record a placement dismissal — the user explicitly closed it (“No thanks”). Time-boxed: the placement is hidden for the dismiss cooldown (cooldown_after_dismiss_days, default 7 days) and re-shows once it elapses (plan 167). NOT permanent — for a confirmed conversion use recordConversion.

string

The placement’s stable rule_id.

string

Optional payload variant id.

string

Optional surface template id.

RevTurbineImpressionMetadata

Optional metadata persisted with the record.

number

Optional explicit cooldown window (ms). Defaults to 7 days.

Promise<void>


recordImpression(placementId, payloadId?, surfaceTemplateId?, metadata?): Promise<void>

Record that a placement was rendered to the user. Plan 43 TASK-9.

Writes an impressed record to the SDK’s ImpressionHistory, which persists to localStorage via StorageImpressionStore (or in-memory storage in non-browser environments). The impression contributes to:

  • Frequency caps (cap.v1) — once-per-period limits count this impression against the user’s quota for the placement.
  • Trial milestone supersession analytics — for trial_progress ladders, the supersession diagnostic uses delivery state to distinguish “replaced an undelivered placement” (counts in superseded_placement_ids) from “lower threshold was already shown” (NOT counted — spec §3.5 “supersession only applies to undelivered placements”).
  • Generic milestone supersession (content.milestone_order) — the order-based variant in applyContentMilestoneSupersession.

Call this from consumer code when the placement is actually shown to the user (e.g., from a React component’s useEffect on mount, or after the rendering call returns). The SDK does NOT auto-record impressions — surfaces are rendered by consumer code, so only the consumer knows when a placement was actually presented (vs. fetched but not displayed).

Safe to call multiple times for the same placement — duplicates append additional impression records (used by frequency caps to count delivery events).

string

The placement’s stable rule_id (e.g. 'pl_trial_progress_70'). Match decision.output.rule_id from getPlacementDecision.

string

Optional payload variant id, for variant-level analytics.

string

Optional surface template id, for per-surface cap accounting.

RevTurbineImpressionMetadata

Optional metadata persisted with the record.

Promise<void>

const decision = await sdk.getPlacementDecision({ placementId: 'slot_trial_modal' });
if (decision.visible && decision.output?.rule_id) {
renderBanner(decision.output);
await sdk.recordImpression(decision.output.rule_id, decision.output.output_id);
}

registerPlacement(config): Promise<string>

RevTurbinePlacementConfig

Promise<string>


reportSdkError(reason, message?): void

Report that the SDK itself failed (plan 182 TASK-5).

sdk_error was declared in the meta taxonomy with no emitter. This is the “the SDK malfunctioned” signal — distinct from resolution_failure, which means a decision produced nothing. It rides the same anonymous events_sdk_meta lane: no tenant, no user, no placement identity.

Deduped on reason for the session and capped, mirroring emitResolutionFailure — an SDK failing inside a render loop must not become a telemetry flood. Best-effort and never throwing: this is called from catch blocks, so it must not manufacture a second failure.

string

Stable, categorical cause (e.g. provider_init_failed) — what dashboards group by.

string

Human-readable detail for triage, sent on the same footing as sdk_validation_warning’s message, which already ships on this lane.

void


reset(): void

Clear the current user — the advertised alias of resetIdentity (e.g. on sign-out).

void


resetUserContext(): void

Hard-reset the user context to a blank slate — removes EVERY user-context value (id, plan, email, account_id, custom, usage, entitlements, personalization) plus usage balances, and clears the decision cache, interaction state, and impression history.

Unlike resetIdentity (a sign-out that re-infers anonymous context when the inferUser policy is on), this performs no inference, so the resulting context is guaranteed empty. Mostly for demo / fixture flows that reset cleanly between scenarios.

void

// Between demo personas:
rt.resetUserContext();
rt.identify('demo_pro', { plan_handle: 'pro' });

setApiBranding(branding): void

Supply the branding-API rung after init.

apiBranding can be passed at construction when the host fetches branding itself, but with fetchThemeOverride the SDK fetches GET /api/sdk/theme after the instance exists. Without this setter that fetched value reached only the React theme context, so getBranding() and useRevTurbineTheme() could report different branding for the same tenant (plan 184).

{ } | undefined

Branding from the Branding API. Overrides config-embedded branding but never the explicit branding init option.

void


setTelemetryConsent(consent): void

Update behavior-telemetry consent at runtime (plan 144 TASK-8 / REQ-12).

Takes effect on the next event with no provider remount: denied / pending stop event creation immediately, so nothing reaches ingest, registered consumers, or integrations; granted resumes emission. Does not affect the keyless anonymous SDK-init beacon, which has its own RevTurbineInitOptions.anonymousTelemetry switch (REQ-13).

TelemetryConsent

the new consent state

void


setTrialInstances(instances, options?): Promise<{ }>

Derive and push the user’s trial status from their TrialInstance records, resolving the matching free/reverse trial rule straight from the initialized RevTurbineConfig’s free_trial_rules / reverse_trial_rules.

The config-driven counterpart to setTrialStatus: instead of the host app pre-deriving a UserTrialStatus, the SDK evaluates the tenant’s trial rules against the supplied instances via @revt-eng/core’s evaluateTrialStatus and pushes the result into the local trial context that gates trial_progress / trial_ending / trial_ended / trial_converted placements. The same evaluator runs in the Python server SDK, so both decide identically.

Requires an initialized exported config (static mode, or any mode with a config provider). Returns the derived status, or { in_trial: false } when no active trial instance applies.

readonly object[]

The user’s trial instance records.

Optional nowIso clock pin (defaults to the current time) and basePlanHandle (the base plan a reverse-trial user reverts to, surfaced as plan_handle).

string

string

Promise<{ }>


track(name, data?): Promise<void>

Track an event — the advertised alias of trackEvent. Powers analytics, frequency caps, attribution, and experiments.

string

SdkEventProperties

Promise<void>

rt.track('ai_generation_completed', { credits: 3 });

trackControlPlaneEvent(eventType, payload?, options?): Promise<void>

Emit a typed control-plane semantic event (plan 112).

The dogfood-faithful surface for RevTurbine’s own product activity: eventType is constrained to the canonical ControlPlaneEventType taxonomy and the system/workflow source classification is stamped automatically. Forwards through the same ingest + consumer path as capture — so the event lands in clickstream AND any registered analytics resolver (e.g. a PostHog provider from createPostHogAnalyticsProvider).

Identity comes from the active user context set via identify / setUserContext: the operator is user_id and the acting RevTurbine customer tenant is account_id. tenant_id is stamped server-side and is never carried on the event (plan 112 REQ-3/REQ-4).

"web_signed_up" | "web_signed_in" | "cli_signed_up" | "cli_signed_in" | "cli_command_executed" | "changeset_submitted" | "changeset_approved" | "changeset_rejected" | "changeset_deployed" | "changeset_launched" | "changeset_parked" | "changeset_resumed" | "changeset_discarded" | "changeset_archived" | "config_imported" | "config_exported" | "entity_created" | "entity_updated" | "entity_deleted" | "web_api_error"

A canonical control-plane event type.

SdkEventProperties = {}

Optional event-specific properties (e.g. { resource, resource_id }).

RevTurbineEventOptions

Emit options, e.g. { immediate: true } to bypass batching.

Promise<void>

sdk.identify('operator_42', { account_id: 'tn_acme' });
await sdk.trackControlPlaneEvent('changeset_deployed', { change_set_id: 'cs_9' });

update<T>(patch): void

Patch the session-bound user context — the advertised update(patch) verb. Accepts every session-scoped RevTurbineUserContext field except the identity handle id (see RevTurbineUpdateInput); to (re)establish identity use identify.

usage routes through updateUsage (absolute balances + usage threshold-crossing events); every other recognized field routes through setUserContext, which merges with upsert semantics — an omitted field never clobbers a previously-set value. Both stores are updated independently, so update({ plan, usage }) applies each without interference. Keys outside the recognized set are dropped with a dev-only warning — they never reach the context, and update({ <handle>: n }) is not a usage report.

T extends RevTurbineUpdateInput

Exact<RevTurbineUpdateInput, T>

void

// Bump reported usage:
rt.update({ usage: { generations: 25 } });
// Reflect a plan change and new traits in one call (identity unchanged):
rt.update({ plan_handle: 'pro', custom: { role: 'admin' } });

validateUiPathResolvers(options?): Promise<RevTurbineUiPathResolverValidationReport>

Validate that each configured UI path action has a resolver implementation.

By default this validates localRuntime.exportedConfig.content_ui_paths (when present) against:

  • uiPathResolvers passed at SDK init
  • optional resolvers passed to this method
  • CTA handlers from domain providers (domain: 'cta'), unless disabled

RevTurbineUiPathResolverValidationOptions = {}

Promise<RevTurbineUiPathResolverValidationReport>