Developer

Runtime API

Reference the Apex SDK runtime functions for initialization, tracking, consent, flags, diagnostics, and assignment state.

Import runtime functions from @drip-apex/sdk, or call the browser globals after the hosted script has loaded. The globals are compatibility surfaces, but they do not all have the same shape.

Browser global surfaces

SurfaceShape and function names
window.DripThe hosted IIFE's module namespace. It exposes the named SDK exports, including init, track, trackStep, trackGoal, trackRevenue, setConsent, flush, getAssignments, getExperiments, getRuntimeTools, and the flag and diagnostics functions documented below.
window.dripThe callable queue-compatible runtime API. It exposes init, track, step and its additive alias trackStep, goal/revenue/consent/lifecycle methods, flush, assignment/cart/experiment helpers, getTools and its additive alias getRuntimeTools, get, flag evaluation, signals, diagnostics, and push.
window.ApexThe same callable runtime API object as window.drip, with the same function names.
Experiment and variation custom JSRuns as page code with no injected arguments. Read window.Drip, window.drip, window.Apex, or window.apexTools explicitly.
Project prerequisite JS arguments drip and DripBoth receive the same small rule API with get(key) and context, not the browser runtime API. The separate context argument describes the prerequisite evaluation.
window.apexToolsThe runtime-tools object itself, not the callable API. It exposes custom-JS and page-trigger helpers such as waitForElement, elementInView, and domChanged; do not call getRuntimeTools on this object.

The tables below use the npm/window.Drip export names. On window.drip and window.Apex, trackStep/step and getRuntimeTools/getTools are equivalent aliases.

Initialization and state

FunctionSignatureUse
init(config: InitConfig) => Assignment[]Initialize the SDK with inline experiments or fetched config.
reInit(forceReapply?: boolean) => Assignment[]Re-evaluate assignments manually, optionally forcing mutations to reapply.
recheckPrerequisites() => voidRe-run project prerequisite gates and start or stop analytics if consent or state changed.
getAssignments() => Assignment[]Read current active assignments.
getExperiments() => Experiment[]Read loaded experiment configs.
getRuntimeTools() => ApexRuntimeToolsGet the runtime tools object used by custom JS and page triggers.
getDiagnostics() => SdkDiagnosticsRead public diagnostics; debug-only fields appear only when debug mode is enabled.
getCartAttributes() => CartAttributeEntry[]Build the authoritative cart-attribute attribution stamp for a headless Shopify cart.
getCartMetafields(options?: { namespace?: string }) => Array<{ key: string; type: string; value: string }>Build an optional BI mirror for cartMetafieldsSet. key is composite (namespace.attributeKey); namespaces accept 2–255 ASCII letters, digits, _, or -, and invalid values fall back to apex. See the headless integration guide.
getCartMetafieldStaleKeys(options?: { namespace?: string }) => string[]Return every mirrorable composite key missing from the current getCartMetafields() output. Pass these keys to cartMetafieldDelete to clear stale optional mirror values. Use the same namespace option for both helpers.

Tracking

FunctionSignatureUse
track(type: string, data?: Record<string, unknown>, experimentId?: string, variationId?: string) => voidSend a custom event and trigger matching custom goals. Defaults to the first active assignment when IDs are omitted.
trackStep(name: string, data?: Record<string, unknown>) => voidSend a virtual funnel step as funnel_step; dedupes once per session unless data.oncePerSession is false.
trackGoal(goalId: string, data?: Record<string, unknown>) => voidTrigger a configured Apex goal by ID for current assignments.
trackRevenue(revenue: number, data?: RevenueEventData) => voidRecord each purchase at shop scope and attribute it to every running test assigned to the visitor.
flush() => Promise<void>Start analytics if ready and flush queued events. Resolves immediately when no tracker exists.
ts
import { flush, track, trackGoal, trackRevenue, trackStep } from "@drip-apex/sdk";
 
track("add_to_cart", { product_id: "example-product", value: 49 });
trackStep("postcode_submitted");
trackGoal("checkout-started");
trackRevenue(119, { orderId: "order-example-1002", currency: "EUR" });
 
await flush();

Blocked calls and held events

track() drops custom events when consent blocks tracking, Do Not Track is active, or screenshot mode is enabled. These calls are not replayed after consent changes. When tracking is allowed but an apply or analytics activation gate is pending, custom events wait for that gate and then use the refreshed assignments. Revoking consent while they wait prevents replay. If no tracker can start and no gate is pending, the call is dropped. A false project tracking prerequisite does not by itself create a queue.

getDiagnostics().customEventsHeld is a boolean that means custom tracking is currently blocked. It does not mean a dropped call was saved. The matching fields are getDiagnostics().tracking.blocked and blockedReason. getDiagnostics().tracking.customEventsHeld does not exist. tracking.heldEvents counts events waiting behind activation gates.

Delivery when leaving a page

On pagehide, beforeunload, or a hidden visibilitychange, the tracker drains queued events with navigator.sendBeacon(), preferring the proxy endpoint when configured, then the direct endpoint. If beacons are refused or unavailable, it uses a direct fetch() POST with keepalive: true. Normal defaults are 20 events and 48,000 bytes per batch; one oversized event can exceed that batch target. The lifecycle drain budgets 60,000 bytes across its payloads, including an active batch. On terminal unload, overflow and failed deliveries are saved for recovery in sessionStorage when storage is available. Browser delivery and recovery are best effort, not a receipt. A back/forward-cache page keeps unsent events for its return. flush() flushes the normal queue; it does not restore dropped calls.

Tracking-state changes

Call setConsent(granted) to change consent. It rechecks project prerequisites. Call recheckPrerequisites() after changing state used by a prerequisite, then read getDiagnostics().tracking to observe whether tracking can run. With idle tracking startup, read it again after startup. There is no dedicated public tracking-state-change event or subscription. The document event drip_runtime_status reports load-stage changes in event.detail; it is not a notification for every tracking-state change. drip_initialized marks initialization.

Exposure deduplication

The SDK deduplicates assignment exposures with the key entityId:variationId:assignmentEpoch. The entity is the experiment ID, or the personalization ID for a personalization; a missing epoch becomes an empty string. The in-memory key set follows retained assignments in this page runtime, including SPA reevaluations. A removed key or a different arm or epoch can allow a new exposure. Pending network exposure delivery is handled separately from recording the key. With persistent storage allowed, stored experiment/variation exposures can also suppress a restored off-target assignment across page loads. An assignment activated by a page rule owes a fresh exposure on that page. This is not a blanket once-per-session guarantee.

FunctionSignatureUse
setConsent(granted: boolean) => voidPersist consent state, clear storage when denied, and recheck assignment/tracking prerequisites.

Feature flags

FunctionSignatureUse
evaluateFlag(flagId: string, context?) => booleanReturn true when the visitor is assigned to a non-control variation.
evaluateFlagValueevaluateFlagValue<T>(flagId, fallback?, context?)Return the assigned variation value, or the fallback when unavailable.
ts
import { evaluateFlag, evaluateFlagValue } from "@drip-apex/sdk";
 
const enabled = evaluateFlag("checkout-progress-ui");
const ctaCopy = evaluateFlagValue("checkout-cta-copy", "Continue to checkout");

Diagnostics

ts
import { getDiagnostics } from "@drip-apex/sdk";
 
const diagnostics = getDiagnostics();
console.log({
  initialized: diagnostics.initialized,
  assignments: diagnostics.assignments,
  configSource: diagnostics.configSource,
  runtime: diagnostics.runtime
});

getDiagnostics() is safe for support tooling because it redacts consent and tracking-block details unless SDK debug mode is enabled.

All builds expose customEventsHeld and tracking. The latter reports whether the tracker is started, whether calls are blocked, the reason (consent_required, dnt, screenshot_mode, or not_started), how many events are waiting behind an activation gate, and whether sent events are QA-tagged. This lets QA distinguish a console call from an event that reached the wire.

Decision timing

Read window.drip.getDiagnostics().load.timing (or the imported getDiagnostics().load.timing) in any build, including a forced preview. The same values are page-readable on window.__dripPerf without enabling debug or analytics.

Diagnostics fieldwindow.__dripPerf fieldMeaning
navigationStartAtnavigation_start_atNavigation origin, epoch milliseconds from performance.timeOrigin, with a Date.now() - performance.now() fallback.
configFetchedAtconfig_fetched_atConfig fetch resolved, epoch milliseconds. Absent when no successful fetch occurred.
decisionAtdecision_atAssignment ready, the existing assignment_ready_at mark, in epoch milliseconds.
firstMutationAtfirst_mutation_atFirst DOM mutation, epoch milliseconds, when one occurred.
revealAtreveal_atAnti-flicker reveal, epoch milliseconds, when recorded.
decisionLatencyMsdecision_latency_msdecisionAt - navigationStartAt, milliseconds since navigation.
forcedExperimentIdsforced_experiment_idsExperiment IDs in the active force map. Empty for natural loads.

The initial page's decisionAt, decisionLatencyMs, and load.assignmentReadyAt remain unchanged on SPA route changes. timing.lastRouteChange is null until a route evaluation completes, then contains { startedAt, decisionAt, decisionLatencyMs }. Both timestamps are epoch milliseconds; its latency is decisionAt - startedAt for that route evaluation, independent of how long the page has been open. The matching window.__dripPerf fields are last_route_change_started_at, last_route_change_decision_at, and last_route_change_decision_latency_ms (all null before the first route evaluation). A route_change sdk_perf event uses this route-local latency; an init event uses navigation-relative latency.

window.__dripPerf.qa_session_id identifies the QA session (also available as getDiagnostics().qaSessionId). Unreached timestamps are absent, not zero. Timing diagnostics do not change consent or telemetry gates. The sdk_perf event includes decision_latency_ms and forced_experiment_ids when telemetry is allowed.

js
const timing = window.drip.getDiagnostics().load.timing;
console.table(timing);
console.log(window.__dripPerf.decision_latency_ms);

The runtime remains unchanged. Natural runtime decides within tens of milliseconds of SDK start when config ships inline with the snippet (measured p50 12 ms / p95 54 ms on a large storefront). QA previews, screenshot-mode previews and cookie-forced sessions take the QA config lane and fetch fresh config over the network (measured p50 1.3 s / p95 7 s); they are not representative of launch behaviour. URL-forced sessions without a qa parameter keep the inline or cached config, so these measurements do not describe them. No config preload or anti-flicker hold is planned.

Config request

Without inline experiments, init() with shopId and endpoint makes a GET request to <normalized endpoint>/config?shopId=<shop ID>. It adds env when the active environment is not production. The QA config lane adds drip_qa=1, plus drip_qa_sdk=current for the current QA build, drip_harness when a harness token exists, and drip_force when a force map exists.

Match the request's pathname /config on the configured Worker origin in a network probe. Do not match the entire URL or depend on query order or token values. Later optional-capture admission checks also use GET /config, with shopId, env and a changing apex_config_refresh value.

An inline experiments array, including an empty array, skips this initial config fetch. The hosted snippet supplies inline experiments on its natural lane; the QA config lane omits them and fetches fresh config. A valid stored config can apply first, but still refreshes from the network in the background. The QA config lane bypasses that cache. Blocking /config alone therefore does not prevent assignments already available inline or in the cache.

Custom JS timing

The inline bootstrap computes assignments; it does not execute experiment or variation custom JS. Both snippet-embedded and fetched experiments use the SDK's assignment apply path. That path schedules DOM mutations, then custom code. Selector waits can finish later, so custom JS cannot assume every mutation has landed.

Custom code waits for DOMContentLoaded if the document is still loading. Experiment JS runs first in that callback. Variation JS follows through promise callbacks, after any external CSS and external JS loads settle. With spa.applyTiming: "after_hydration", visual work waits for the hydration gate. An eligible inline early_reassert assignment with custom JS also waits for hydration; forced QA previews under early_reassert defer their apply too. A mutation hold can defer apply as well. Inline config alone does not mean custom JS runs before hydration.

drip_initialized is dispatched at the end of each initialization pass. It does not wait for deferred apply, DOM readiness, external assets or variation JS. Experiment JS can run before it when apply is immediate and the DOM is ready, or after it when apply or DOM readiness is deferred.

There is no once-per-visitor custom JS guarantee. A cache refresh does not automatically run code twice: unchanged current cached config skips network activation, and retained artifacts are reconciled. A later teardown and apply or an artifact replay can execute custom JS again. Early reassertion repairs ordinary DOM mutations without replaying custom JS.

QA build only: page readout

In QA previews, Drip.qa.state() returns plain JSON with the requested and applied arm, targeting gates and their observations, goal counts, device provenance, and tracking state. It reports information only and does not approve a test. Live storefront builds never expose Drip.qa. Each experiment includes anti_flicker: mode, timeout, hidden selectors, hide/reveal times, reveal reason, first custom-JS run time and config source, using the performance.now() clock; QA links report network-path timings. The times follow Apex's anti-flicker rules that name the experiment's own selectors or hide the whole page; how page CSS rendered the element is not part of it. estimated: true marks a reading that depends on what the snippet did before the SDK loaded (for example a redirect hide that ended at its 3 s deadline before boot). For an external JS file the custom-JS time is when its top-level code finished; a file that failed, was blocked or threw an error while running reads null.

Run apex qa page script (or the MCP tool qa_page_script) to get a one-line script for the open preview tab. Use --wrap function for browser tools that accept a function. A missing QA readout returns status: "unavailable" with reason: "sdk_qa_readout_missing"; unknown goals remain null.

The panel and readout share one goal ledger. goal_counts.since_ms marks its creation and source says whether the panel or readout created it. Page URLs contain paths only; free text is scrubbed for personal data.

Drip.qa.state().goals reports configured goals and their observed fire counts in the current QA session, not the visitor's lifetime conversions or all store visitors. The ledger counts each goal fire unless countOnce caps that goal at one in this QA ledger. Counts carry across page loads in the same tab and QA session through sessionStorage. Without storage they remain in memory for the current page. A new QA session starts a separate ledger. Exiting QA through the panel clears it; signed-session expiry deletes its stored state. goal_counts.since_ms is the page-local store creation time, not the start time of persisted counts.

Change ledger

Drip.qa.changes() reports what each change did when Apex applied it. Every application pass is a numbered generation with a trigger (initial, route, dom_reapply, force_reload, manual, prerequisite or reapply) and its own timestamps in milliseconds since page start: started_at_ms, decision_at_ms, first_mutation_at_ms, last_mutation_at_ms, sync_done_at_ms and ended_at_ms (when the next pass opened).

Each row names the experiment, the arm, the change (its index, custom_js or custom_css), the action, the selector, how many elements matched, and the outcome: applied, missed (with its match count, open shadow roots included), error (with a scrubbed message), pending, async_unknown or superseded (the pass was replaced or its selector wait torn down before the change landed). Custom JS is never applied: the ledger cannot see work it schedules through promises or await. Once it ran it stays pending (async: true when it registered timers, listeners or observers, or returned a promise) until it throws, which is recorded on the pass that scheduled the failing work, or the next pass opens; then it is async_unknown. Custom JS its error budget already stopped is an error. Artifact replays are generations too. config_source says whether the config came from the network, the cache or inline.

Drip.qa.changes({ generation: 2 }) returns one generation. await Drip.qa.whenGeneration(2, { timeoutMs: 10000 }) resolves when that pass has finished its synchronous applies, or returns timed_out: true with the rows still pending. There is no promise that every change has landed. The ledger keeps the last 8 generations and 500 rows and sets truncated: true when it dropped older ones.

apex qa page script reads both parts by default (--include state,changes) and returns { schema: "apex.sdk_page_script_result.v1", state, changes }. --include state returns the readout alone, as before. An older QA build without the ledger answers changes with reason: "sdk_qa_changes_missing".

QA build only: switch arm

Drip.qa.switchArm(experimentId, armIdOrName) pins one arm in a QA preview and reloads the same page: path, query and language prefix stay, the force parameters are dropped and drip_qa=1 is kept. It returns { navigating: true, target_url, requested_arm } before the reload starts and never confirms the switch. Call Drip.qa.state() in the new page to read the arm that applied. An unknown arm returns { navigating: false, reason: "arm_not_found", arms }; outside a QA session it returns reason: "qa_mode_off".

The pinned arm lives in one cookie per store, shared by every tab, so two tabs on one store show the arm pinned last. To get a link for every arm on chosen pages instead, run apex preview <experiment> --arms all --page <path> --lines (MCP qa_arm_links).

QA build only: observer inventory

Drip.qa.observers() returns a raw inventory of variant-owned MutationObservers, IntersectionObservers, ResizeObservers, and event listeners. Its apex.sdk_qa_observers.v1 response has observers and truncated: rows show the creating experiment and arm, a scrubbed target label, current connectivity, observation state, bounded options, and callback count. Listener rows also show the event type and capture/once/passive flags. The newest 200 records are retained. Host registrations are excluded. This readout is absent from live and heatmap builds.

Drip.qa.state() includes sdk_version and sdk_channel (artifact or current). Agent arm links opt into the current build with drip_qa=1&drip_qa_sdk=current. On this channel, sdk_channel_note says consent and click-ID observations on the current channel are unverified while #15385 is open (fix tracked in #15056); it is null on the artifact channel.