@arcxp/compass-sdk
v1.2.0
Published
Compass SDK — Arc XP personalization at the core.
Readme
@arcxp/compass-sdk
ArcCompass client-side SDK for the user-events collector, published as an ESM module for build-pipeline consumers (React / Next / anything with a bundler).
This package is the bundled (build-time) install: npm install
@arcxp/compass-sdk, then import the client into your app so it ships in your
own bundle. If you'd rather load the SDK at runtime from a hosted CDN
<script> tag (no build step), use the loader-snippet integration documented at
dev.arcxp.com → Compass Web SDK Integration Guide.
That guide covers both channels end to end.
Quickstart (bundled / ESM)
Install the package, construct a client, then call init() once and track()
for each event.
npm install @arcxp/compass-sdk1. Identify the item on each page
Every event is attributed to the content item the reader is on. Put this tag in
the <head> for each article, with content set to the item's ID (your CMS/ANS
content ID):
<meta name="arc-compass:item-id" content="ABCD1234EFGH5678" />The SDK reads this tag automatically, so you don't have to thread the ID through
every track() call (you can still pass a per-call itemId to override it).
Write the tag whenever your route has the ID, including after an awaited content load. Server-rendered pages and single-page apps both work, and an SPA has no ordering to honour. See Single-page apps below.
2. Identify the Site
Every host rendering an <arc-compass-*> Experience needs a Site, single-site
or not: both Experience reads require one. A host that only sends events can
skip this — site_id is optional on the event envelope.
Two ways to supply it, in priority order:
siteIdoninit()(below), when the Site is a property of the deployment. This is the one source that needs nothing rendered first, so prefer it if your Experience tags are in your server-rendered markup.<meta name="arc-compass:site-id" content="my-cool-site" />, when the Site varies by route. The SDK reads this tag each time it needs a Site, so you may write it at any point in your render.
3. Initialize and track
page_view is captured automatically for the item the page loads with, and
again whenever the page becomes about a different item (disable with
autoPageView: false):
import { ArcCompassClient } from "@arcxp/compass-sdk";
const arcCompass = new ArcCompassClient();
arcCompass.init({
// Your org's Arc edge origin, with no path. The SDK derives the event ingest
// base (`/collect-web/v1`) and the Experiences base from it.
origin: "https://<org-id>-config-prod.api.arc-cdn.net",
apiKey: "<arc-delivery-token>",
// Optional. The Site every event and Experience is attributed to. Takes
// priority over the `arc-compass:site-id` meta tag, which stays the fallback
// when this is unset. Pass it here when your Site is fixed per deployment,
// and leave it out in favour of the tag when it varies by route.
// siteId: "my-cool-site",
// Optional overrides, for a deployment that serves events and Experiences
// from different hosts. Each defaults to the value derived from `origin`.
// `domain` is the full ingest base (the SDK appends `/events/batch`);
// `experiencesDomain` is the base every SDK-rendered Experience reads from.
// domain: "https://<org-id>-config-prod.api.arc-cdn.net/collect-web/v1",
// experiencesDomain: "https://<org-id>-config-prod.api.arc-cdn.net",
});
// Single boolean gate. Pass `true` only once the Reader has consented to BOTH
// analytics and personalization — if your CMP exposes the two purposes
// separately, AND them together before calling this. Nothing is sent or
// persisted until you do.
//
// The SDK stores nothing, so call this on every page load. Until you do, no
// event is sent and SDK-rendered Experiences render nothing — silently.
arcCompass.setConsent(true);Hold onto the client instance (module singleton, React context, etc.) and reuse
it across your app — do not call init() twice on the same client.
Single-page apps
Automatic capture watches the item-id tag, so there is no ordering you have to
honour. Write the tag whenever your route knows the ID: before or after
pushState, in a render effect, or once an awaited fetch resolves. The
page_view fires when the tag lands:
// React Router + any head manager. No SDK call, and no ordering requirement.
function Article({ id }) {
const { data } = useArticle(id); // resolves after the route has rendered
return (
<>
<Helmet>
{data && <meta name="arc-compass:item-id" content={data.itemId} />}
</Helmet>
{/* … */}
</>
);
}Two route changes produce no page_view:
- A change that lands on the same item. A query or hash change, or a
replaceStatethat only normalises the URL, is not a new view of new content. - A route with no item, such as a homepage or section front. Clear the tag, or leave it out, on those routes. Returning to an article you viewed earlier fires again.
The site-id tag has no ordering requirement either: it is read each time a Site
is needed rather than captured at init(), so a route that writes it from an
awaited render attributes that route's events correctly, and an Experience the
same render mounts finds its Site.
One case still wants siteId on init(): an <arc-compass-*> tag already
present in your server-rendered markup. Each Experience fetches once when it
mounts and does not retry, so with consent already granted it can run before a
later render writes the tag, and then shows nothing until something re-mounts it
(refreshExperiences()). A Site passed to init() is resolvable from the first
moment, so that race cannot happen.
To drive capture yourself, set autoPageView: false and call
track('page_view', { itemId }) on each content route. Routes with no item send
nothing either way.
The package pins to semantic versioning; use a major range (^1) to receive
backwards-compatible fixes. See the
Distribution & FAQ
guide for the full channel comparison, including the hosted <script> bundle,
exact-version pinning, and the self-host fallback.
Declarative install (no JavaScript)
The hosted <script> bundle can configure itself from markup, so a page needs
no hand-written JavaScript to integrate. Put the config on the <script> tag
that loads the bundle, then place an Experience tag:
<meta name="arc-compass:item-id" content="ABCD1234EFGH5678" />
<script
src="<hosted compass-sdk.iife.min.js URL>"
data-arc-compass-origin="https://<org-id>-config-prod.api.arc-cdn.net"
data-arc-compass-api-key="<arc-delivery-token>"
data-arc-compass-site-id="my-cool-site"
></script>
<arc-compass-recommendations-list surface-id="article-footer"></arc-compass-recommendations-list>Each attribute maps to the init() option of the same name:
| Attribute | init() option | Value |
| ------------------------------------ | ------------------- | ----------------------------------------- |
| data-arc-compass-origin | origin | Required, unless domain is set |
| data-arc-compass-api-key | apiKey | Required |
| data-arc-compass-site-id | siteId | Optional |
| data-arc-compass-domain | domain | Optional override |
| data-arc-compass-experiences-domain| experiencesDomain | Optional override |
| data-arc-compass-cookie-domain | cookieDomain | Optional |
| data-arc-compass-attribution-root | attributionRoot | A CSS selector, or false |
| data-arc-compass-auto-page-view | autoPageView | Present means on; false or 0 turns it off |
| data-arc-compass-debug | debug | Present means on; false or 0 turns it off |
When the <script> tag can't carry attributes, such as when a tag manager
injects it, use <meta name="arc-compass:origin" content="…"> and so on with
the same names. An attribute wins over the meta tag for the same field. The
Site is the exception: <meta name="arc-compass:site-id"> keeps its usual
meaning (read at each point of use, so it can change per route) and does not
count as config.
The bundle initializes itself at DOMContentLoaded when the page declares an
origin, a domain or an apiKey. An init() call made before then, whether
queued by the loader snippet or made directly, takes precedence and the declared config
is ignored. Calls such as setUserId(), track() and
observeRecommendations() made before either init are held and applied, in
order, right after it.
The SDK initializes only once, so an init() made after the SDK has
initialized itself from the declared config can't take effect: none of its
options apply, including onError. The SDK logs a console.error instead of
throwing. If you need options that markup can't express, such as onError,
call init() before DOMContentLoaded (an inline script, or the loader
snippet), or drop the declared config. If the declared config is invalid (say,
no apiKey), the SDK logs a console.error and an explicit init() still
works.
Consent is not part of this config: call ArcCompass.setConsent(true) once the
Reader has consented, as in the Quickstart. Until
then nothing is sent and Experiences render nothing.
Recommendation attribution
Every recommendation the SDK renders reports back on itself. An
<arc-compass-recommendations-list> or <arc-compass-recommendations-carousel>
binds each card it draws to a shared detector, which emits a
recommendation_exposure when the reader actually sees the card and a
recommendation_click when they act on it. The collector joins the two into
Confirmed CTR. There is nothing to wire up: rendering an Experience is opting
in.
An exposure fires when a card has been at least 50% visible for a continuous second, not when it renders. A rail below the fold reports nothing until the reader scrolls to it, so the denominator of your CTR is recommendations that were genuinely seen. Clicks are captured by delegation on the list itself, so the thumbnail, the headline and the byline all resolve to the same card.
Both events carry an attribution_context, forwarded from the Recommender
response verbatim — the SDK renames and recomputes nothing:
| Field | Meaning |
| ---------------- | ------------------------------------------------------------------- |
| exposure_id | The rendered set. Every item in one response shares it, and that is what lets a click confirm an exposure. |
| attribution_id | The opaque per-item join token the Recommender issued. |
| surface_id | Where the set was rendered, as the tenant configured it. The rollup partition. |
| position | The zero-based slot the API served the item in — not the index it happened to render at. |
| issued_at | When the Recommender issued the context. |
| source | Omitted on the wire; the collector defaults it to fy. Only FY-sourced attribution counts toward Confirmed CTR. |
A complete pair, as the SDK POSTs them to /events/batch — the reader saw the
card, then clicked it:
[
{
"user_id": "a3f1c7e2-9b64-4d0a-8f21-6c5e0d7b4a19",
"item_id": "ZSGXFR2KNFCMPN3VHPWQR3BGCE",
"event_type": "recommendation_exposure",
"timestamp": "2026-09-24T14:30:00.000Z",
"session_id": "6d2b9a41-0f3e-4c58-9a17-2e8b5c1d3f60",
"site_id": "the-daily",
"attribution_context": {
"exposure_id": "exp-7f3c1d9e",
"attribution_id": "attr-2a9f4c",
"surface_id": "homepage-rail",
"position": 1,
"issued_at": "2026-09-24T14:29:58.000Z"
}
},
{
"user_id": "a3f1c7e2-9b64-4d0a-8f21-6c5e0d7b4a19",
"item_id": "ZSGXFR2KNFCMPN3VHPWQR3BGCE",
"event_type": "recommendation_click",
"timestamp": "2026-09-24T14:30:07.500Z",
"session_id": "6d2b9a41-0f3e-4c58-9a17-2e8b5c1d3f60",
"site_id": "the-daily",
"attribution_context": {
"exposure_id": "exp-7f3c1d9e",
"attribution_id": "attr-2a9f4c",
"surface_id": "homepage-rail",
"position": 1,
"issued_at": "2026-09-24T14:29:58.000Z"
}
}
]Those two envelopes are rebuilt from the real envelope builder on every test
run, so they stay an accurate sample rather than an illustration. user_id and
session_id are pinned here; in the browser they come from the visitor's own
anonymous identity.
These two events are analytics-only. They report on the recommender, they do not train it: neither reaches AWS Personalize as an interaction, so an exposure never doubles as engagement (ADR-003). Reader behaviour is what trains the model, through the ordinary event types.
Host-rendered surfaces
If you render recommendations yourself rather than using an Experience — your
own component, a PageBuilder block — the SDK cannot know which element is which
item. Declare that mapping by stamping data-arc-compass-* attributes on each
rendered card and the same detector picks them up, with identical exposure and
click semantics. ArcCompass.trackExposure(element, attribution) is the
imperative equivalent. Both are documented in the
Attribution
guide.
Documentation
Customer usage docs live on the Arc XP developer portal, in the Compass Web SDK section under Content Recommendations:
- Integration Guide — both the hosted
<script>and bundled/ESM channels, start to finish - Consent & Identity
- Events & Reliability
- Recommendation Attribution
- Distribution & FAQ
The published npm package ships TypeScript declarations (dist/compass-sdk.d.ts),
so the full typed API surface is available in-editor for ESM/TypeScript consumers.
Development
pnpm install
pnpm run lint # ESLint
pnpm run typecheck # tsc --noEmit
pnpm run test # Vitest unit tests with coverage
pnpm run test:e2e # Playwright browser tests
pnpm run build # tsup → dist/
pnpm run size # gzipped-size check
pnpm run verify # all of the abovetest:e2e runs the suite against every project in playwright.config.ts (chromium, firefox, webkit). In the
devcontainer .devcontainer/pre-firewall.sh fetches them at container creation, since the firewall blocks Playwright's
CDN afterwards; they land in ~/.cache/ms-playwright, which is not where the image's PLAYWRIGHT_BROWSERS_PATH points,
so the root Makefile re-points that variable when DEVCONTAINER=true. Run the suite through make web-e2e /
make web-verify rather than pnpm run test:e2e directly, or firefox and webkit will not be found. Anywhere else, run
pnpm exec playwright install once first.
Demo server
pnpm run demo starts demo/serve.mjs, a stand-alone server for trying the SDK in a browser:
| Route | Serves |
| ---------------------------------------- | ---------------------------------------------------------------- |
| GET / | demo/index.html, a sample news article |
| GET /sdk/compass-sdk.iife.js | The built bundle from dist/ |
| POST /events/batch | Stub collector; logs each batch and buffers it |
| GET /captured | The in-memory batch buffer, for the initial render |
| GET /captured/stream | SSE feed that pushes each new batch as it arrives |
| POST /__reset | Clears the buffer and notifies stream subscribers |
| GET /recommendations | Stub recommender for <arc-compass-recommendations-carousel> |
| GET /img/<slug>.svg | Generated card thumbnails for that stub |
| GET /experiences/storyline/v1/catch-up | Mocked Catch-Up Card, per persona (demo/catch-up-fixtures.mjs) |
| GET /catch-up/img | SVG placeholder thumbnails for the mocked card |
To send demo events to a real collector, run demo/collect-proxy.mjs, a local stand-in for the
collect-web ASI. It answers the SDK's cross-origin preflight, translates the browser-held
X-Api-Key into the arc-organization header the collector authenticates on, and forwards the
batch unchanged. Target and tenant come from env vars, so no secrets are committed:
ARC_ORG=staging COLLECTOR_URL=https://fy-collector-staging-us-east-1.app-recommend.aws.arc.pub \
node ./demo/collect-proxy.mjsThen load the demo with ?collector=http://127.0.0.1:5174 so the SDK posts to the proxy.
Recommendations fixture
demo/fixtures/recommendations.mjs is shared by the demo and the Playwright fixture server. It
follows the SDK's response contract, not the PageBuilder block's: display fields live under card,
which is what src/experiences/recommendations.ts reads. A body copied from the block's docs
validates but renders nothing, because every item loses its title and url. An item missing item_id
or attribution_id is dropped because its events could never join back to their slot.
| Field | Validator behaviour |
| -------------------------------------- | ------------------------------------------------- |
| recommendations[].item_id | Required; an item without it is dropped |
| recommendations[].attribution_id | Required; an item without it is dropped |
| recommendations[].position | Required, non-negative integer |
| recommendations[].card.title | Required to render; otherwise the item is skipped |
| recommendations[].card.url | Required to render, http(s) only |
| recommendations[].card.thumbnail_url | Optional |
| recommendations[].card.author | Optional |
| recommendations[].card.categories | Optional array; the card shows the first |
| attribution.exposure_id | Required; missing it collapses the whole set |
| attribution.surface_id | Echoed back from the request |
| attribution.issued_at | Echoed verbatim onto every event |
The fixture has six items because the track is grid-auto-columns: minmax(220px, 1fr): six overflow
any realistic demo width, so the carousel arrows appear. With fewer, the component renders a static
row.
Size budget
scripts/check-size.mjs fails the build when the gzipped, minified IIFE exceeds
DEFAULT_BUDGET_GZIP_BYTES. The IIFE is what hosts load via <script>, so its gzipped transfer
size is what matters for page performance.
The ceiling is a whole-bundle guardrail, not a derived performance target. Every locale is inlined
into the single IIFE (src/experiences/i18n/catalogs.ts, about 0.6 KB gzipped each), and every
Experience ships whether or not a page uses it, so one number caps unrelated features together. When
a feature pushes past it:
- Bump the budget deliberately, with review, only when the feature genuinely needs the headroom. Do not raise it to cover accidental bloat, and do not shave random bytes to sit under it.
- Common trims don't help:
charset: utf8saves raw bytes but roughly nothing gzipped, no legal comments are retained, and raising the buildtargetis a browser-support decision, not a byte tweak.
COMPASS_SIZE_BUDGET_BYTES overrides the budget for experiments; CI uses the committed default.
Release and smoke tests
scripts/release-artifact.mjs assembles release/ from dist/, mirroring the CDN layout
one-to-one, so publishing is a sync of release/ to the distribution origin (see
.github/workflows/web-sdk-release.yml). Everything sits under an arc-rec/ prefix so the URL path stays
portable across delivery domains; keep it in sync with the tofu web-sdk-cdn unit's app_prefix:
arc-rec/v<version>/compass-sdk.iife.min.js immutable IIFE, the recommended embed (+ .map)
arc-rec/v<version>/compass-sdk.esm.js immutable ESM (+ .map)
arc-rec/v<version>/compass-sdk.d.ts immutable types
arc-rec/v<version>/manifest.json pinned: this version's manifest, immutable
arc-rec/manifest.json latest: the newest stable version's manifest
arc-rec/manifest-next.json next: the newest version's manifest, prereleases includedFilenames are stable within each directory and the version lives in the path. The exact-version
directory is immutable and cached forever; never overwrite a published one. The version comes from
COMPASS_RELEASE_VERSION when set (for example from a CI tag), otherwise package.json.
The three manifests share one schema: name, version, major, channel (pinned, latest or
next), prerelease, the recommended embed (embedPath / embedIntegrity: the exact-version IIFE
and its SRI hash), and artifacts (the exact-version directory's bundles with byte sizes, sha256 and
SRI hashes). A channel manifest is identical to its version's pinned one but for channel.
The channels are named after the npm dist-tags. A stable version can move both latest and next; a
prerelease moves only next and never writes manifest.json. That makes manifest-next.json the newest
version of any kind, while npm's next takes only prereleases (a publish sets one dist-tag) and can lag
behind latest. scripts/plan-manifests.mjs moves a channel only
when its live version is missing or older, so neither moves backward: a retry of rc.1 after rc.2
leaves next alone, as does a 1.2.1 hotfix while next is on 1.3.0-rc.1. A prerelease found in
latest counts as missing, so any stable version replaces it. Test environments that
should track the newest candidate read manifest-next.json; tests pinned to one version read its
v<version>/manifest.json.
Publication never writes the floating arc-rec/v<major>/ alias: the release job refuses a
release/ tree that contains it, and it uploads only arc-rec/v<version>/ and the channel
manifests. The alias is an optional auto-update URL that moves only by a separate, approved
promotion, so it is never paired with an integrity hash
(ADR-019, as amended). On npm a stable
version publishes to latest and a prerelease (1.2.0-rc.1) to next, forward-only like the CDN
channels (scripts/plan-npm-tag.mjs): a version older than the one the tag names, such as a 1.2.1
hotfix after 1.3.0, publishes to a per-line tag (latest-1.2, next-1.3) instead, which moves only
forward too; a version older than that gets its own exact tag (latest-1.2.0), so no tag moves
backward.
The recommended integrations are the exact-version URL with its integrity and
crossorigin="anonymous", or the npm package with a committed lockfile.
The release workflow's own logic lives in scripts rather than inline YAML, so unit tests can run it
against fake aws, gh, npm and curl binaries: scripts/release-lock.sh (one release at a
time), scripts/plan-release.sh (which channels need the version, and the npm dist-tag),
scripts/publish-cdn-files.sh (the exact-version upload) and scripts/publish-cdn-channels.sh (the
channel manifests). They need bash and jq; the tests that depend on jq skip without it.
Two post-release smoke tests confirm the published artifacts, since a successful sync or publish doesn't prove the bytes are live:
scripts/smoke-cdn.mjsruns afterrelease-cdn. It is credential-free and treats the version's published pinned manifest as the source of truth: every artifact it lists must be an immutable exact-version file, reachable and matching its recorded sha256/sha384 (SRI), andembedPathmust be the exact-version IIFE. Each channel the release moved must then report the version and match the pinned manifest, andmanifest.jsonmust never report a prerelease (a missing one passes, since there is none before the first stable release). The channel manifests aremax-age=300and invalidation is fire-and-forget, so it polls until they report the expected version; any read that doesn't answer is retried until the deadline, while wrong bytes fail at once. Env:COMPASS_RELEASE_VERSION(defaultpackage.json),COMPASS_CDN_BASE(default the prod distribution),COMPASS_SMOKE_TIMEOUT_MS(default 180000),COMPASS_SMOKE_POLL_MS(default 5000),COMPASS_SMOKE_CHANNELS(the channels expected to report the version, comma-separated; defaultlatest,nextfor a stable version andnextfor a prerelease; the release job passes the onesrelease-cdnactually copied, ornone), andCOMPASS_SMOKE_PINNED_ONLY=1(check only the pinned manifest and its artifacts, whichrelease-cdndoes before copying a live pinned manifest into a channel). The pinned manifest must hash exactly the version's IIFE, ESM bundle and type declarations.scripts/smoke-npm.mjsruns afterrelease-npm. It installs the exact version from the public registry into an OS temp dir, so the repo.npmrc(the@wpmediascope map,minimum-release-age) can't interfere, then imports the ESM entry and checks the public surface and shipped dist files. A successful install also proves registry integrity, since npm verifies the tarball shasum. A just-published version can 404 briefly, so the install retries. Env:COMPASS_RELEASE_VERSION(defaultpackage.json),COMPASS_NPM_REGISTRY(default npmjs.org),COMPASS_NPM_SMOKE_ATTEMPTS(default 6),COMPASS_NPM_SPEC(default<name>@<version>; set it to a localnpm packtarball to dry-run, or<name>@<tag>to smoke a tag), andCOMPASS_NPM_DIST_TAG(unset by default; when set, the dist-tag must point at the version).
tests/browser/smoke-published.spec.ts is the functional counterpart to the CDN smoke: it loads the
pinned manifest's recommended embed in a real browser with SRI enforced and checks that it executes
and emits events.
