API reference
React Native SDK v1.2.0 — API reference
Everything is reachable from the Optima singleton, exported from
@optima/react-native:
import { Optima } from "@optima/react-native";
await Optima.init({ key, endpoint });
const o = Optima.instance; // never throws; the live client, or the disabled clientEvery public entry point is guarded. An internal failure — a thrown
exception anywhere inside the SDK's own code — becomes an error {op, cause}
event (see Events) plus a debug log line; it is never rethrown
into your app. identify(...), consent.set(...) and flush() are the
calls where you might want to know the outcome of the first network
attempt rather than just observe events, so they return a Promise;
everything else fires-and-forgets by design and returns immediately.
Threading. Every public method returns synchronously — nothing blocks
the calling (JS) thread, including a call made from inside a render.
Listeners registered with on(...) run on the JS thread, so it's safe to
update React state directly from inside one (though the ./ui hooks below
are the idiomatic way to consume most of this reactively). A Promise
returned by identify/consent.set/flush resolves once the first
network attempt has settled (success, a terminal rejection, or a scheduled
retry) — not once every retry has exhausted; a call issued while Optima.init
is still hydrating resolves once that queued call has actually run against
the real runtime, in the order you issued it relative to any other queued
call.
Optima / OptimaClient
Optima.init(config: OptimaConfig): Promise<void>
Constructs the runtime: hydrates persisted state from AsyncStorage (or your
injected Storage port) in one getMany call, resolves AppInfo (config.app
→ expo-application → react-native-device-info → "unknown"), registers
app-lifecycle and deep-link listeners, kicks off the tracker inventory load,
and emits ready. A second call while already initializing/ready is a
no-op returning the same promise, with a
"Optima.init called twice; the first configuration stays" warning — the
first configuration always wins. See
chapter 1 for the
failure-tolerant construction contract (a thrown error anywhere in
construction is caught, logged as "Optima.init failed; SDK disabled", and
leaves the facade in the disabled state rather than rejecting the returned
promise or crashing your app).
Optima.instance: OptimaClient
The same object for the life of the process, whether or not init has
been called, is still running, or failed — see amendment 3 in the design
spec. There are four states; see
chapter 1 for the full
table. In short: before init has even been called (idle) and while it
is in flight (initializing), mutating methods (track, identify,
consent.set, reset, flush, push.setToken, …) queue their call —
capped at 100 entries, oldest dropped with one warning beyond that — and
replay it in order once the runtime is ready; read-only accessors
(deviceId, language, consent.get(), isReady) return safe fallbacks ("", "en", an
empty ConsentState, false) in both of those states. Only after a
failed init (it was called and threw) does it become the genuinely
disabled client: every method is a no-op, content.slot(name) hands
back a permanently-empty handle, forms.load resolves {kind: "failed"},
push.parse returns null, and the first call logs one warning
("Optima used without an initialized SDK; calls are no-ops") — exactly
once, no matter how many no-op calls follow. Use Optima.isInitialized
when you need to know which state you're in.
Optima.isInitialized: boolean
true once init has completed successfully (the ready state).
false in every other state: idle (before init is called),
initializing (hydrating), and failed (init was called and threw).
track(category: string, name?: string, props?: Record<string, unknown>): void
Queues one hit to the on-disk outbox. category is required, 1–128
characters — an out-of-range value throws inside the guard and surfaces as
an error {op: "track"} event rather than propagating. name and props
are both optional; props values are validated to PropValue (string ≤
4096 chars, finite number, boolean, or string[] of ≤4096-char
elements) — anything else for a given key is dropped (logged at debug, never
failing the rest of the hit). Sends: the built Hit batches into POST /edge/v1/track (see Hits and transport
below) — nothing is sent synchronously by this call itself. Emits: track
once the containing batch is acked (a 2xx); a terminally-rejected
(4xx) batch emits error {op: "track"} instead, never track (never one
event per track() call either way — it's always per-batch). Threading:
non-blocking, returns immediately.
screen(name: string, props?: Record<string, unknown>): void
track("screen_view", name, props) plus automatic attribution enrichment
(UTM/click-id props; the session id and session_start are stamped on every
hit, track included). It also sets the current screen used by the
content engine's targeting (see
chapter 5) and triggers a re-fetch of
every declared content slot. Call it from your navigation wiring
(chapter 1) or manually wherever a
screen change happens. Sends/emits/threading: identical to track above,
since it is a track call under the hood.
captureReferrer(referrer: string): void
Feeds an Android Play Install Referrer query string (e.g.
utm_source=google-play&utm_medium=organic) into the same attribution store
the launching deep link writes to — the recognised keys (utm_source,
utm_medium, utm_campaign, utm_term, utm_content, gclid, fbclid)
are then repeated as props on every enriched (screen()) hit, not just for
the session, but until reset() clears the persisted _optima_utm store.
First capture wins — a referrer (or launching deep link) arriving after
attribution has already been captured is ignored, and capturing twice is
harmless. The SDK does not depend on any install-referrer library; fetch the
string with your own (e.g. react-native-installreferrer on Android) and
call this once, typically on first launch. Sends nothing by itself and emits
nothing; errors are guarded into an error {op: "capture_referrer"} event.
identify(identifiers: Record<string, string>, attributes?: Record<string, unknown>, opts?: { assertion?: IdentityAssertion }): Promise<void>
Attaches allowlisted identifiers and/or profile attributes to this device.
This attaches identifiers nobody owns yet; an identifier another
customer already owns is not attached (it is recorded as an unverified
claim for identity rules) unless opts.assertion — minted by your backend
with the SDK key's identify secret — proves it. A call with identifiers,
attributes, and assertion all empty/absent is skipped locally (logged at
debug, nothing sent — "identify: nothing to send"). At most 16 identifier
keys are sent (each key ≤128 chars, each value 1–4096 chars); anything
beyond that is silently truncated to the first 16 by key iteration order.
Under beforeDecision: "buffer" the call is held: in memory only, max 10 calls, sent at the first decision with the then-current consent; held calls older than 30 minutes are dropped at the decision; reset() drops held calls.
Sends: POST /edge/v1/identify with {device_id, identifiers, attributes, consent, assertion} — identifiers/attributes are filtered server-side
against the admin-configured identify_allowed_keys/identify_allowed_attributes
allowlists, and anything not on the allowlist comes back in the response's
dropped array rather than failing the whole call. Emits: identify {accepted, dropped} on success; error {op: "identify", cause} after the
5-attempt retry ladder is exhausted, or immediately on a terminal 4xx.
Threading: returns a Promise that resolves once the first attempt settles
(await it if you need to know the call has actually landed, e.g. before
navigating away from a login screen — nothing requires you to).
reset(): void
"A different person is using this device now" — call it on logout on any
shared/kiosk device. In order: clears the outbox, rotates the device id
(a fresh UUIDv4, _optima_did), clears consent (_optima_consent), clears
the session (_optima_sid), clears attribution (_optima_utm), clears the
content "seen" memory (_optima_seen), then runs every reset hook — the
content engine resets every slot to empty (fenced by a per-slot generation
counter so an in-flight fetch from before the reset can't resurrect stale
items), the tracker gate forgets its loaded-inventory flag (the persisted
{etag, entries} survive — see chapter 4),
and the remembered push token is re-sent under the new device id
(identify({push_token_<platform>: token})) — because the physical device
still has that push registration and the new profile on it should still
receive pushes, unless you don't want that (see
chapter 7 for the setToken(null) escape
hatch). The push token itself is the one storage key reset() does not
clear. Sends/emits: nothing synchronous of its own beyond the hooks above.
Threading: synchronous — everything it does is local state mutation plus
scheduling background work (the identify re-attach runs async).
deviceId: string
The SDK-minted device id (_optima_did), a UUIDv4 generated once on first
use and persisted — never derived from any hardware identifier or
advertising id. Read-only from the public API; it rotates only via
reset(). "" on the disabled client or before init resolves.
language: string
The detected device language tag — AppInfo.language, e.g. "en-US",
read from expo-localization when installed (else "en"); the same value
every hit carries as context.language. "en" on the disabled client or
before init resolves. OptimaHost/OptimaSlot use it as the default for
their lang prop and as the banner's device-language fallback step.
flush(): Promise<void>
Forces an immediate attempt to drain the outbox, bypassing the normal 20-hit
batch size / 2-second coalesce window. It does not wait for an
already-armed backoff retry timer — that timer is a separate, independent
schedule that keeps running regardless; flush() is skipped only while
another flush's own network round trip is currently in flight (a
concurrency guard, not a backoff one). Sends: whatever is currently queued,
via the same POST /edge/v1/track path as an automatic flush. Emits: the
same track/error events an automatic flush would. Also called
automatically on app background. Threading: returns a Promise that
resolves once that one flush attempt (success, terminal rejection, or a
newly-armed retry) has run — call it again if you need the outbox fully
drained after a very large backlog.
on<K extends EventName>(name: K, cb: (payload: EventPayloads[K]) => void): () => void
Registers a listener for one event name; returns an unsubscribe function.
const off = Optima.instance.on("error", (e) => console.warn("optima error in", e.op, e.cause));
// later
off();ready is replayed to a listener attached after Optima.init has
already completed — subscribing to "ready" never races against when you
happened to call on. Every other event is fire-forward only (no replay). A
throwing listener is caught and logged; it never disrupts other listeners or
the SDK's own internal state.
Hits and transport (track / screen)
Every track/screen call builds a Hit: a message_id (UUID), an RFC
3339 ts, a context object (language, screen_w, screen_h, ua in
the form <android|ios>/<osVersion>/<appId>/<appVersion>/sdk-rn-<version>,
url in the app://<appId>/<screen> form — see
chapter 5 — and title set to the current
screen name), and props (the session id, session_start on a fresh
session, attribution props on screen() calls, plus whatever you passed,
each validated to PropValue). Hits queue into an append-only outbox (one
JSON array under _optima_q, capped at 200 entries — oldest dropped first
once full) and flush as a batch:
- when 20 hits are queued,
- 2 seconds after the first hit lands in an otherwise-idle queue
(coalescing — a burst of
track()calls inside that window ships as one request), - on app background,
- or on an explicit
flush().
Only one flush is in flight at a time. Each POST /edge/v1/track request
carries device_id, sent_at, the batch of hits, and the current
consent declaration (see chapter 4 for the omit-vs-[]
rule — this is why every batch, not just the first, carries consent). A
2xx response acks the whole batch (removes it from the outbox, emits
track); a 4xx is terminal — the batch is still acked (removed) and an
error {op: "track"} event fires, because retrying a rejected batch forever
would wedge the outbox behind a hit the server will never accept. A 401 or
403 specifically also clears the entire outbox, not just the failed
batch — see chapter 9.
A 429/5xx/network failure keeps the batch queued and retries on a
backoff ladder — 1s → 2s → 5s → 15s → 60s, resetting to the start of the
ladder on the next success, and honouring a server-sent Retry-After header
over the ladder's own step when present.
ConsentApi (optima.consent)
See chapter 4 for the full behavioural writeup (the banner,
the omit-vs-[] rule, CMP passthrough, revocation, gating third-party
SDKs). This section is the reference.
consent.get(): ConsentState
Returns the current state synchronously, from memory (backed by
_optima_consent). ConsentState is {v, decisions, decidedAt, bannerId, policy, lang} — see Types below, and the isDecided/grantedPurposes
helper functions exported alongside it.
consent.set(decisions: Record<string, boolean>, meta?: { bannerId?: string; lang?: string; policy?: Record<string, unknown> }): Promise<void>
Records a decision. Writes locally first (so consent.get() reflects it
immediately, before any network round trip), emits consent:change {state},
and — for any purpose that flips from true to false relative to the
previous state — also emits consent:revoked {purposes}. Then it POSTs
/edge/v1/consent with {device_id, consents: [{purpose, granted}, ...], consent (the vendor-level block: tcf/gcm/keys, purposes omitted), banner_id?, lang?} on the same 5-attempt retry ladder as identify (Retry-After
honoured; a final give-up emits error {op: "consent"}). meta carries
bannerId/lang/policy when the decision came from the built-in banner or
your own consent UI referencing a specific banner/policy version. If
beforeDecision = "buffer" and this is the first decision ever recorded,
it also unblocks the tracker's flush queue, since a decision now exists.
Threading: returns a Promise that resolves once the local write and the
first POST attempt have both happened.
consent.setKeys(keys: Record<string, boolean>): void, consent.setGCM(g: Record<string, "granted" | "denied">): void, consent.setTCF(tc: string): void
Vendor-level consent signals that ride alongside — never instead of — the
purposes array (when source = "optima") on every subsequent request.
setKeys sets arbitrary named boolean flags; setGCM sets Google Consent
Mode-style values keyed by GCM parameter name (ad_storage,
analytics_storage, ...); setTCF sets the raw IAB TCF consent string. All
three are synchronous, local-only calls — they take effect on the next
request built, they do not themselves trigger a network call. See
chapter 4 for why setTCF on React Native
is a manual call (fed from your CMP's SDK or a tcfSource port) rather than
an automatic prefs read.
consent.can(trackerName: string): boolean
Answers "does the current consent state permit trackerName to run", by
looking trackerName up in the once-per-process /edge/v1/trackers
inventory and checking whether its declared purpose is currently granted.
Returns false for an unknown tracker name or while the inventory hasn't
loaded yet (fail-closed — a tracker you can't confirm consent for doesn't
run). See chapter 4 for the
Firebase Analytics gating example this exists for.
consent.on(cb: (s: ConsentState) => void): () => void
Subscribes to consent:change, unwrapped to just the new ConsentState —
useConsent() in ./ui is built on this.
ContentApi (optima.content)
See chapter 5 for the full behavioural writeup. This section is the reference.
content.slot(name: string): SlotHandle
Declares a content slot: fetches GET /edge/v1/content?slot=<name>&screen= <currentScreen>&url=app://<appId>/<currentScreen>&device_id=<id>
immediately, and again on every subsequent screen() change or
refresh(), with If-None-Match caching per slot. A response belonging to
an already-superseded screen is discarded (a per-slot generation counter
fences it) — you will never see a stale screen's items flash into a slot
you're currently looking at; a screen change also drops the slot's stored
ETag, so a 304 for the new screen can never resurrect the old screen's
items (see chapter 5 for why this matters
— a same-screen refresh() still revalidates with If-None-Match as usual).
SlotHandle is {get(): Presentation[], subscribe(cb): () => void} — call
get() for the current list, subscribe for change notifications (the
shape useSyncExternalStore expects; useSlot in ./ui is built directly
on this). Calling slot(name) for a name you've already declared returns
the existing handle — it does not re-declare or re-fetch.
content.declaredSlots() returns every name ever passed here (which is how
OptimaHost discovers every slot in the app without keeping its own
registry), and content.onDeclaredSlotsChange(cb) subscribes to that set
changing.
Called before Optima.init resolves, content.slot(name) still works: it
hands back a SlotHandle that starts empty and rebinds to the engine's real
slot store the moment the runtime is ready, replaying any subscriber
notifications at that point — useSlot/OptimaSlot/OptimaHost are safe to
mount before init.
content.fetch(slot: string): Promise<ContentItem[]>
A one-shot fetch: same request shape as slot(...), but declares
nothing (doesn't add to declaredSlots, doesn't get re-fetched on
screen() changes) and applies no display rules, frequency capping, or
placement resolution — you get the raw ContentItem[] back and decide what
to do with it yourself. This is the headless entry point; see
chapter 5. Returns an empty array on any
network/server failure (never throws; a content_fetch error event fires
first).
content.report(p: Presentation, action: "impression" | "click" | "dismiss"): void
Reports feedback for a presentation you're displaying — note the parameter
is a Presentation (the object SlotHandle.get() returns), not the raw
ContentItem. Impressions are deduped per (slot, item id) automatically —
reporting the same item's impression twice is a no-op the second time, until
the slot's content actually changes (a fresh fetch resets that memory). A
presentation from an already-superseded fetch is ignored (logged at debug)
rather than reported or acted on locally. Batches (≤50, 1-second coalesce,
also flushed on app background) to POST /edge/v1/content/events with
{token, action, ts} per event, using the item's own delivery token.
Also, locally and without waiting on the network: an "impression" marks
the item "shown" for frequency-rule purposes (once/per_days rules,
_optima_seen); a "dismiss" marks it "dismissed" (for ttl_days) and
removes it from the slot's list; a "click" on a campaign item with
stop_on_click = true also removes it from the list. max_impressions
(part of the campaign display block) is enforced server-side only — the
SDK reports every impression it sees.
report(p, "dismiss") on a banner_consent presentation hides that banner for the rest of the process (the built-in banner does this on every decision); it never writes frequency memory, and reset() clears it. A banner whose id was decided stays hidden for the rest of the app process even if re-served with the same id; a re-ask under a NEW banner id shows immediately.
With display.htmlMode = "off", an unstructured item never becomes a
Presentation at all — it is emitted as a content:item {slot, item} event
instead, and it is not counted in content:loaded.count.
content.refresh(): void
Re-fetches every currently declared slot immediately, without waiting for
the next screen() change. Useful after consent.set(...) changes what
should be visible — the built-in ConsentBannerRenderer calls this itself
right after posting a decision, so a served banner_consent item stops
being returned on the very next poll.
content.register(type: string, renderer: unknown): void
Registers a renderer for a custom structured content type your backend
authors, so ./ui's RenderPresentation can find it instead of falling
through to a plain content:item event. The parameter is unknown at this
(headless) layer — in practice you pass a React component matching the
OptimaRenderer type from ./ui (see The ui entry
below). content.rendererFor(type) reads the registry back (used
internally by RenderPresentation).
content.declaredSlots(): ReadonlySet<string> / content.onDeclaredSlotsChange(cb: () => void): () => void
See content.slot above.
FormsApi (optima.forms)
See chapter 6 for the full writeup.
forms.load(id: string, opts?: { lang?: string; assertion?: IdentityAssertion }): Promise<FormResult>
GET /edge/v1/forms/{id}?device_id=&lang= → a discriminated-union
FormResult: {kind: "loaded", definition, submit} on success —
definition: FormDefinition (see Types below), and a bound
submit: (values: Record<string, unknown>) => Promise<SubmitResult> closure
that already carries the form's render nonce, so you never handle it
yourself; {kind: "not_found"} on a 404; {kind: "failed", status?, cause?}
on anything else, including a network failure. Calling the bound
submit(values) does POST /edge/v1/forms/{id}/submit with the honeypot
field silently included and empty (_hp), the nonce, device_id, the
assertion when given, and your values (unsupported value types — anything
that isn't string/boolean/finite number — are dropped with a debug
log, never sent). A 409 response counts as success ({kind: "accepted"},
the form was already submitted by this device — not an error state to
surface to the user). Emits form:submitted {id, dropped, doubleOptIn} on
any accepted outcome (including the 409 case).
forms.pageUrl(url: string): string
Appends device_id=<id> (as a new query parameter, or &-joined if the URL
already has one) to a hosted form page URL, for opening with Linking.openURL
— see chapter 6.
NbaApi (optima.nba)
nba.respond(nbaId: string, action: NbaAction, extra?: { reason?: string; referenceId?: string; value?: number }): void
Records a Next-Best-Action response. nbaId must be exactly 26 characters (a
ULID) — anything else is dropped locally at debug level
("nba.respond dropped: nba_id must be 26 characters") without a network
call. action is one of "presented" | "accepted" | "postponed" | "rejected" | "realized". extra optionally carries reason (≤4096 chars),
referenceId (≤4096 chars), value (a finite number). Batches (≤50,
1-second coalesce, flushed on background) to POST /edge/v1/nba/responses
with {events: [{nba_id, action, reason, reference_id, value, ts (seconds)}]}.
A 404 response permanently disables the queue for the rest of the
process's lifetime — the operator's kill switch is treated as "NBA
responses aren't a thing right now," not a transient error, so the SDK stops
trying and drops anything already queued, logging one debug line. Restarting
the process re-enables the queue on the next respond() call, in case the
operator has since flipped the switch back on.
PushApi (optima.push)
See chapter 7 for the full FCM/APNs integration recipes.
push.setToken(token: string | null, opts?: { platform?: "fcm" | "apns" }): void
Stores the push registration token (_optima_push_token, as {platform, token}) and, if it changed (or is being set for the first time), immediately
calls identify({push_token_<platform>: token}) to attach it to the current
profile. opts.platform defaults from Platform.OS ("apns" on iOS,
"fcm" everywhere else). Passing null forgets the token locally without
sending anything — it does not clear the server-side value; see
chapter 7. A no-op if the new value (and
platform) equal what's already stored, so it's safe to call unconditionally
on every app start / token-refresh callback.
push.parse(data: Record<string, unknown>): OptimaPush | null
Parses an incoming push message's data payload into OptimaPush. Returns
null if none of the SDK's reserved keys (deep_link, buttons,
optima_open, image_url) are present — i.e. this wasn't a push the SDK's
delivery pipeline built. OptimaPush is {deepLink, buttons, data, openToken}: buttons accepts either a JSON-string array (FCM data
payloads are all-string) or an already-parsed array (expo-notifications
delivers typed values) and parses it into PushButton[] ({id, label, deepLink}); data is every other extra key (your own custom data), with
the reserved keys filtered out; openToken is the raw optima_open value
(you generally don't need this directly — trackOpen below consumes it for
you).
push.trackOpen(data: Record<string, unknown>): boolean
Call from your notification-response handler
(messaging().onNotificationOpenedApp/getInitialNotification for
@react-native-firebase/messaging, or
addNotificationResponseReceivedListener/getLastNotificationResponseAsync
for expo-notifications). If optima_open is present and non-blank, fires
GET /edge/v1/o/{token} fire-and-forget (on the same backoff ladder as
everything else, up to 5 attempts, failures only logged at debug — never
surfaced as an error event, since a missed open record shouldn't disturb
the app) and returns true immediately (it does not wait for the request to
land). Returns false, doing nothing, if optima_open is absent — i.e.
this either wasn't an Optima-sent push, or the template it came from didn't
have open tracking enabled. See chapter 7 for the backend
prerequisites this token depends on.
NavigationApi (optima.navigation)
Router-agnostic screen tracking for apps that don't call screen()
manually. See chapter 1.
navigation.onReady(state: NavState | undefined): void / navigation.onStateChange(state: NavState | undefined): void
Both walk state.routes[state.index ?? routes.length - 1] recursively
through nested navigators (focusedRouteName, also exported standalone) to
find the currently-focused route name, and call screen(name) only when
that name actually changed since the last call — so a NavigationContainer
re-render that doesn't change the focused route never double-reports.
NavState is a structural type ({index?: number; routes: Array<{name: string; state?: NavState}>}) — there is no dependency on
@react-navigation/native's own types; any object shaped like its
NavigationState works, including a hand-built one in a test. Expo Router
apps use useScreenTracking (./ui) instead of this API directly — see
chapter 1.
OptimaConfig
See chapter 2 for every key's default and meaning.
Ports
Every platform touch the core makes is behind one of these eight interfaces
(src/ports.ts), defaulted in src/platform/ and overridable per key via
config.ports — see chapter 2 for two
worked examples (an MMKV Storage, a CMP-backed TcfSource). All eight are
exported as types from @optima/react-native.
interface Storage {
getMany(keys: readonly string[]): Promise<Record<string, string | null>>;
set(key: string, value: string): Promise<void>;
remove(key: string): Promise<void>;
}
// Default: AsyncStorageStore, over @react-native-async-storage/async-storage.
interface HttpRequest { method: "GET" | "POST"; url: string; headers: Record<string, string>; body?: string; timeoutMs: number }
interface HttpResponse { status: number; headers: Record<string, string>; text: string }
interface Http { request(req: HttpRequest): Promise<HttpResponse> }
// Default: FetchHttp — global `fetch` with a 10s AbortController timeout.
// Resolves for every HTTP status; rejects only on a network failure or timeout
// (the SDK turns that rejection into a "retry" Outcome, never an uncaught throw).
interface Clock { now(): number }
// Default: `{ now: () => Date.now() }`.
interface AppLifecycle { onForeground(cb: () => void): () => void; onBackground(cb: () => void): () => void }
// Default: AppStateLifecycle, over React Native's AppState — "active" is
// foreground, "background"/"inactive" is background (iOS's transient
// "inactive" on the way down is deduped against a following "background").
interface TcfSource { read(): Promise<string | null>; onChange?(cb: (tc: string | null) => void): () => void }
// Default: `{ read: async () => null }` — no TCF source unless you inject one
// or call consent.setTCF yourself; see chapter 4's CMP passthrough section.
interface AppInfo { id: string; version: string; osName: string; osVersion: string; language: string; screenW: number; screenH: number }
// Default: detectAppInfo — config.app → expo-application → react-native-device-info
// → "unknown"/"unknown" with one warning; osName/osVersion from Platform.OS/
// Platform.Version; language from expo-localization, else "en"; screenW/screenH
// from React Native's Dimensions.
interface Logger { debug(msg: string, data?: unknown): void; warn(msg: string, data?: unknown): void }
// Default: ConsoleLogger — warn always logs; debug is gated on config.debug.
interface LinkSource { initialUrl(): Promise<string | null>; onUrl(cb: (url: string) => void): () => void }
// Default: LinkingSource, over React Native's Linking (getInitialURL / the
// "url" event) — this is amendment 2 in the design spec: deep links are a
// port like every other platform touch, not read from Linking directly.
interface Ports { storage: Storage; http: Http; clock: Clock; lifecycle: AppLifecycle; tcfSource: TcfSource; appInfo: AppInfo; logger: Logger; links: LinkSource }Other exports
A handful of smaller exports round out the public surface — most of these
are what the tables and interfaces above are built from, exported so a
custom integration (a test fake, an alternate ui layer) can reference the
exact same types and constants the SDK itself uses:
| Export | From | What it is |
|---|---|---|
SDK_VERSION | . | The current SDK version string ("1.0.0") — also what X-Optima-SDK: react-native/<v> and every hit's ua suffix carry. |
resolveConfig(input: OptimaConfig): ResolvedConfig / type ResolvedConfig | . | The pure function (and its return type) Optima.init uses internally to validate and apply defaults to your OptimaConfig — see chapter 2. Exported mainly for tests that want to assert on resolved config without going through a full init. |
screenUrl(appId: string, screen: string): string | . | Builds the app://<appId>/<screen> convention string — see chapter 5. |
ConsentMeta | . | { bannerId?: string; lang?: string; policy?: Record<string, unknown> } — the type of consent.set's second parameter. |
ConsentDecl | . | { purposes?: string[]; tcf?: string; gcm?: Record<string, GcmValue>; keys?: Record<string, boolean> } — the shape of the consent block a request body carries; mostly useful if you're inspecting a captured request in a test. |
Hit / HitContext | . | Hit: { message_id, category, name?, ts, context, props? }; HitContext: { url, title?, language, screen_w, screen_h, ua } — the wire shape track/screen build; see Hits and transport above. |
PropValue | . | string | number | boolean | string[] — the type every validated prop value narrows to. |
NbaExtra | . | { reason?: string; referenceId?: string; value?: number } — the type of nba.respond's third parameter. |
BeforeDecision | . | The literal type "buffer" | "send" — see chapter 2. |
ConsentSource | . | The literal type "optima" | "cmp" — see chapter 2. |
HtmlMode | . | The literal type "webview" | "off" — see chapter 2. |
GcmValue | . | The literal type "granted" | "denied" — the value type consent.setGCM's map takes. |
Types
ConsentState
interface ConsentState {
v: 1;
decisions: Record<string, boolean>;
decidedAt?: number;
bannerId?: string;
policy?: Record<string, unknown>;
lang?: string;
}
const emptyConsent: () => ConsentState;
const isDecided: (s: ConsentState) => boolean; // decidedAt !== undefined
const grantedPurposes: (s: ConsentState) => string[]; // decisions filtered true, sortedPresentation / ContentItem / DisplayRule
type ContentAction = "impression" | "click" | "dismiss";
interface Presentation { slot: string; item: ContentItem; placement: "inline" | "overlay"; dismissible: boolean }
interface CampaignDisplay { dismissible: boolean; maxImpressions: number; stopOnClick: boolean }
interface ContentItem {
id: string; type: string; format: "structured" | "unstructured";
payload: Record<string, unknown> | null; html: string | null; priority: number;
origin: string | null; channel: string | null; token: string | null; // origin === "campaign" for an onsite-campaign item
campaignDisplay: CampaignDisplay | null; displayJson: Record<string, unknown> | null;
}
const isCampaign: (i: ContentItem) => boolean; // i.origin === "campaign"
const displayRuleOf: (i: ContentItem) => DisplayRule;
interface DisplayTrigger { on: "load" | "delay" | "event"; delayMs: number; event: string | null }
type DisplayFrequency = "always" | "session" | "once" | { perDays: number };
interface DisplayRule {
placement: "inline" | "overlay" | null; position: string; style: string;
trigger: DisplayTrigger; frequency: DisplayFrequency; dismissible: boolean | null; ttlDays: number | null;
}Full field-by-field targeting/rule semantics live in chapter 5.
FormDefinition / FormResult / SubmitResult
interface FormField { key: string; kind: string; inputType: string; label: string; placeholder: string | null; required: boolean; options: Array<{ value: string; label: string }> }
interface FormDefinition { id: string; slug: string; name: string; lang: string; fields: FormField[]; successMessage: string | null; successRedirectUrl: string | null; doubleOptIn: boolean; minSubmitIntervalSec: number }
type SubmitResult =
| { kind: "accepted"; dropped: string[]; doubleOptIn: boolean }
| { kind: "rejected"; status: number; message: string }
| { kind: "failed"; cause?: unknown };
type FormResult =
| { kind: "loaded"; definition: FormDefinition; submit: (values: Record<string, unknown>) => Promise<SubmitResult> }
| { kind: "not_found" }
| { kind: "failed"; status?: number; cause?: unknown };OptimaPush
interface PushButton { id: string; label: string; deepLink: string | null }
interface OptimaPush { deepLink: string | null; buttons: PushButton[]; data: Record<string, unknown>; openToken: string | null }NavState
interface NavState { index?: number; routes: Array<{ name: string; state?: NavState }> }IdentityAssertion
interface IdentityAssertion { key: string; value: string; exp: number; sig: string }Minted by your backend using the SDK key's identify secret — see
chapter 3's identify
and the console's Edge → SDK keys → Identify signing dialog for the minting
recipe.
Events
EventName is a string union; names are identical to the Web and
Android/iOS SDKs' where the same concept exists.
| Event | Payload | When |
|---|---|---|
ready | {version: string} | Once, right after Optima.init finishes constructing the runtime. Replayed to any listener attached later. |
track | {accepted: number, dropped: Array<Record<string, string>>, hits: number} | After every acked (2xx) POST /edge/v1/track batch — hits is the batch size, accepted/dropped come from the server response. A terminally-rejected (4xx) batch emits error instead, never track. |
identify | {accepted: number, dropped: Array<Record<string, string>>} | After a successful POST /edge/v1/identify. |
consent:change | {state: ConsentState} | Every time consent.set(...) completes its local write, and on reset() (with a fresh, undecided state). |
consent:revoked | {purposes: string[]} | Alongside consent:change, only when at least one purpose flipped true → false. |
content:loaded | {slot: string, count: number} | After each content fetch for a declared slot resolves — count excludes items dropped as platform-inapplicable (web_personalization) and items diverted to a content:item event instead of a presentation. |
content:item | {slot: string, item: ContentItem} | For an item that doesn't become a Presentation: an unregistered structured type, a banner_consent item while consent.source = "cmp", or an unstructured item while display.htmlMode = "off". |
form:submitted | {id: string, dropped: string[], doubleOptIn: boolean} | On any accepted form submission outcome, including the "already submitted" 409 case. |
tracker:fired | {name: string, kind: string} | When a pixel-kind managed tracker fires (see chapter 4). |
error | {op: string, cause: unknown, status?: number} | Any guarded operation that threw, or gave up after its retry ladder. op names the operation ("track", "identify", "consent", "forms_submit", "content_fetch", "storage", "lifecycle", "attribution", "nba", "push", etc.) so you can filter for the ones you care about. |
The ui entry (@optima/react-native/ui)
Everything below is a separate entry point (imports react, react-native,
and lazily react-native-webview for the HTML renderer only). See
chapter 5 for how these fit into a full screen and
chapter 6 for OptimaForm.
<OptimaHost client? theme? style? lang? />
interface OptimaHostProps { client?: OptimaClient; theme?: OptimaTheme; style?: StyleProp<ViewStyle>; lang?: string }Place once, near the root of your app. Draws every overlay-placement
presentation from every slot declared anywhere in the app — it subscribes to
the declared-slots set (so a slot declared elsewhere in the tree, even after
OptimaHost itself has mounted, is picked up automatically) and to each of
those slots' content individually, plus the implicit content.overlaySlot
("__overlay") the engine uses for items with no explicit slot, in an
absolute-fill, pointerEvents="box-none" View split into a top group and a
bottom group by each item's display.position; display.style: "modal"
items get their own absolute-fill layer instead, so a full-screen backdrop
is never laid out inside a zero-height edge group. lang defaults to
client.language (the detected device language); the built-in consent
banner resolves copy from it and falls back to the device language — see
chapter 4. This is also where the
built-in two-stage consent banner renders (a banner_consent item is always
placement: "overlay"). Renders nothing (and subscribes to nothing beyond
the declared-slots set) when there's nothing to show. Safe to mount before
Optima.init resolves.
<OptimaSlot name client? theme? style? lang? />
Declares (via content.slot(name)) and renders inline-placement
presentations for one named slot, in place, wherever you put this component
in your layout. An inline-placement item with no OptimaSlot for its slot
name anywhere in your tree simply never renders — see
chapter 5. Renders null when the slot
has nothing inline to show. lang defaults to client.language, exactly as
on OptimaHost.
<OptimaForm id lang? assertion? client? theme? style? submitLabel? onSuccess? onError? />
interface OptimaFormProps {
id: string; lang?: string; assertion?: IdentityAssertion; client?: OptimaClient;
theme?: OptimaTheme; style?: StyleProp<ViewStyle>; submitLabel?: string;
onSuccess?(r: { dropped: string[]; doubleOptIn: boolean }): void;
onError?(e: FormErrorInfo): void;
}
type FormErrorInfo = { kind: "not_found" | "failed" | "rejected" | "validation"; message?: string };A minimal field-driven renderer over forms.load/submit — TextInput for
text/email/number/phone/textarea fields (keyboard type inferred from
inputType), Switch for checkboxes, a pressable option row for select
fields only (any other inputType — including radio, if a form defines
one — falls back to the plain TextInput branch; see
chapter 6), client-side
required-field validation before submit, and success/double-opt-in/error
copy. Resets and reloads whenever id,
lang, or assertion changes — mount it fresh (or change key) if you
need to force a reload for an unrelated reason. See
chapter 6 for the full behaviour, including the double-submit
and unmount guards.
RenderPresentation / OptimaRenderer
type OptimaRenderer = React.ComponentType<{ presentation: Presentation; actions: RenderActions; theme: OptimaTheme }>;RenderPresentation is what OptimaHost/OptimaSlot use internally to pick
a renderer for one Presentation: the built-in consent-banner renderer for
banner_consent; the HTML renderer for format === "unstructured"; the
built-in in-app renderer for mobile_inapp/banner/web_banner; otherwise
whatever content.rendererFor(item.type) returns (your own, registered via
content.register), or nothing at all. It reports the impression once on
mount for every renderer except the consent banner (which has its own
lifecycle). You do not call RenderPresentation directly unless you're
building a custom host.
makeActions / RenderActions
interface RenderActions { onImpression: () => void; onClick: () => void; onDismiss: () => void; openUrl: (url: string) => void }
function makeActions(client: OptimaClient, p: Presentation): RenderActions;onImpression/onClick/onDismiss call content.report(p, ...) with the
matching action; openUrl calls Linking.openURL, rejecting file:,
content:, and javascript: schemes outright and swallowing any error from
an unhandleable URL so a malformed link never crashes the host. Handed to
every renderer (built-in or your own registered one) — this is what
content.register(type, MyComponent) expects MyComponent to receive as
its actions prop:
Optima.instance.content.register("product_carousel", function ProductCarousel({ presentation, actions, theme }) {
const skus = (presentation.item.payload?.skus as string[] | undefined) ?? [];
useEffect(() => { /* impression already reported by RenderPresentation on mount */ }, []);
return <Carousel skus={skus} onPress={(sku) => { actions.onClick(); actions.openUrl(`app://com.shop.app/Product/${sku}`); }} />;
});Built-in renderers (./ui/renderers)
InAppRenderer—mobile_inapp/banner/web_banner: title/body/image/CTA as acard, edge-to-edgebar, or centredmodal(fromdisplay.style), with a dismiss (✕) control when the presentation is dismissible.HtmlRenderer—format === "unstructured"items, an isolatedreact-native-webview. See chapter 5.ConsentBannerRenderer—banner_consentitems, the two-stage built-in banner. See chapter 4.
You don't import or use these directly — RenderPresentation selects them.
They're exported from ./ui's barrel (InAppRenderer/HtmlRenderer/
ConsentBannerRenderer) mainly so you can read their source or compose your
own host around them.
OptimaTheme / defaultTheme
interface OptimaTheme { surface: string; onSurface: string; primary: string; onPrimary: string; muted: string; radius: number }
const defaultTheme: OptimaTheme; // { surface: "#ffffff", onSurface: "#111111", primary: "#2f5bea", onPrimary: "#ffffff", muted: "#6b7280", radius: 12 }The flat colour/shape palette the built-in renderers (in-app card/bar/modal,
consent banner) style themselves with — no Material/Paper/design-system
coupling. Override it by passing your own OptimaTheme object to
OptimaHost/OptimaSlot/OptimaForm instead of the default.
Hooks (./ui)
useOptima(client?: OptimaClient): OptimaClient— returnsclient ?? Optima.instance. Every other hook accepts an optionalclientand calls this internally; pass your own only in tests (a fakeOptimaClient) or if you're deliberately running two clients.useConsent(client?): ConsentState— subscribes toconsent.on, viauseSyncExternalStore; re-renders on everyconsent:change.useSlot(name: string, client?): Presentation[]— declares the slot (content.slot(name)) and subscribes to it, viauseSyncExternalStore; the array reference is stable across renders when nothing changed (a cached empty snapshot avoidsuseSyncExternalStore's "new empty array every call" infinite-render trap).OptimaSlotis a thin wrapper over this hook plus aninline-placement filter.useDeclaredSlots(client?): string[]— the live list of every declared slot name, re-synced oncontent.onDeclaredSlotsChangeand once more the moment the client transitions toready(a lazy pre-init slot handle can only promise a callback onready).OptimaHostis built on this.useOptimaEvent<K extends EventName>(name: K, cb: Listener<K>, client?): void— subscribescbto eventnamefor the lifetime of the component (re-subscribing ifclient,name, orcb's identity change); a thin wrapper overclient.on(name, cb)inside auseEffect.useScreenTracking(pathname: string | null | undefined, client?): void— Expo Router integration: callsscreen(pathname)once per distinct pathname change (skipsnull/undefinedand a repeat of the last-reported pathname). See chapter 1.
All hooks are safe to render before Optima.init resolves — they read
Optima.instance (a stable object throughout) and the underlying
subscriptions rebind transparently once the real runtime exists.
TrackerGate (internal)
Not part of the public API, mentioned here because tracker:fired events
and consent.can(...) both depend on it: the SDK fetches GET /edge/v1/trackers once per process, persisting the inventory and its
ETag together (_optima_trk) so the next process's first load
revalidates with If-None-Match and keeps the persisted entries on a 304.
For kind = "pixel" rows, it fires a GET request against the configured
URL (with {{url}}/{{ts}} substituted) once per screen view when the
tracker's purpose is currently granted and the current app:// URL matches
its url_patterns glob. script/html-kind rows are recognised but
intentionally inert on React Native — the first one encountered logs one
debug line ("managed script/html tags are not runnable in React Native; ignored"), and none after that. page-kind rows are simply skipped with no
log at all. See chapter 8.