# Mindful Web Marko Omeda+IdentityX Integrations
Omeda+IdentityX components for Mindful Web/Marko websites.

Based on the identity provider(s) in use, install and configure ***only one*** of these packages. *The other packages can be installed separately if needed, but this package should be the only one configured.*

1. [omeda-identity-x](../marko-web-omeda-identity-x): For sites with both Omeda and IdentityX.
2. [omeda](../marko-web-omeda): For sites with Omeda, but **without** IdentityX.
3. [identity-x](../marko-web-identity-x): For sites with IdentityX, but **without** Omeda.

Additional information can be found in the [Omeda](https://training.omeda.com/knowledge-base/api-overview/) and [IdentityX](https://docs.parameter1.com/identity-x) API documentation.

## Configuration
All configuration data must be passed to the middleware when loaded (See [Middleware Setup](#1-middleware-setup) below.)

| Property  | Required? | Description | Default value |
| - | - | - | - |
| `brandKey` | **Yes** | The Omeda Brand key (such as `orgcd`).
| `clientKey` | No | The Omeda client key (such as `client_orgc`.) *Required if sending deployment optIns via the underlying omeda package!* [marko-web-omeda docs](../marko-web-omeda)
| `appId` | **Yes** | The Omeda application API read token
| `inputId` | **Yes** | The Omeda application API write token
| `rapidIdentProductId` | No — **deprecated**, see [Website products](#website-products-do-not-use-rapididentproductid) | The Omeda identifier for a Website product (ProductType=7). Sends the product on **every** rapid identification, which cuts a duplicate Omeda order each time. Put the website product in the site's deduped opt-in hook instead. | _none_
| `idxConfig` | **Yes** | An instance of the IdentityX configuration class (see [marko-web-identity-x#1](../marko-web-identity-x/config.js)) | _n/a_
| `idxRouteTemplates` | **Yes** | An object containing the Marko templates to use for each IdentityX endpoint. (see [marko-web-identity-x#2](../marko-web-identity-x/index.js))
| `omedaPromoCodeCookieName` | No | The name of the cookie to look for a persisted/original promo code. | `omeda_promo_code` |
| `omedaPromoCodeDefault` | No | The default promo code to send with all Omeda requests. Falls back to input ID default configured by Omeda. |
| `idxOmedaRapidIdentifyProp` | No | The property (in the express app context) where the O+IdX rapid identification service is located. | `$idxOmedaRapidIdentify` |
| `omedaGraphQLClientProp` | No | The property (in the express app context) where the Omeda GraphQL client is located. | `$omedaGraphQLClient` |
| `omedaRapidIdentifyProp` | No | The property (in the express app context) where the Omeda rapid identification service is located. | `$omedaRapidIdentify` |
| `appendBehaviorToHook` | No | An array of objects defining behaviors to append to rapid identification calls.
| `appendBehaviorToHook[].hook` | | The name of the hook, such as `onLoginLinkSent`
| `appendBehaviorToHook[].behaviorId` || The Omeda Behavior ID to append to the rapid identification call.
| `appendDemographicToHook` | No | An array of objects defining demographics to append to rapid identification calls.
| `appendDemographicToHook[].hook` | | The name of the hook, such as `onLoginLinkSent`
| `appendDemographicToHook[].demographicId` || The Omeda Demographic ID to append.
| `appendDemographicToHook[].valueIds` || An array of Omeda Demographic Value IDs (`Int`s) to append
| `appendDemographicToHook[].writeInValue` || A string to include as an OEC/Other value
| `appendPromoCodeToHook` | No | An array of objects defining demographics to append to rapid identification calls.
| `appendPromoCodeToHook[].hook` | | The name of the hook, such as `onLoginLinkSent`
| `appendPromoCodeToHook[].promoCode` || The Omeda Promo Code (`String`) to append.

### Website products: do not use `rapidIdentProductId`

`rapidIdentProductId` reads like site *identification* metadata, distinct from subscriptions. It
isn't. It is forwarded as `productId` to the rapid identification call, and in the omeda GraphQL
`rapidCustomerIdentification` resolver it is merged with `input.subscriptions` into a single
`Products` array on Save Customer and Order:

```js
const productMap = new Map([...(input.productId ? [[input.productId, true]] : [])]);
// …
subscriptions.forEach(({ id, receive }) => {
  subscriptionMap.set(id, receive);
  if (!productMap.has(id)) productMap.set(id, receive);
});
// …
Products: [...productMap].map(([OmedaProductId, Receive]) => ({ … }))
```

Omeda cuts an order for whatever lands in `Products`. So `rapidIdentProductId` orders the website
product on **every** identification — every login-link send, auth success and profile update — which
is a duplicate order per login, not a one-time attribution.

**Do this instead.** Leave `rapidIdentProductId` unset and list the website product in the site's
`identityXOptInHooks.onLoginLinkSent.productIds`. The site's `onLoginLinkSentFormatter` (in each
repo's `packages/global/config/omeda-identity-x.js`) filters those ids through this package's
[`getOmedaSubscriptionIds`](./omeda-data/get-omeda-subscription-ids.js) before building
`payload.appendSubscriptions`, so the product is ordered once — when the customer doesn't already
hold it — and every later identification is a no-op:

```js
// sites/<site>/config/identity-x-opt-in-hooks.js
module.exports = {
  onLoginLinkSent: {
    productIds: [
      15375, // <Site> Website — deduped against the live Omeda record; ordered only when missing
    ],
  },
};
```

```js
// sites/<site>/config/omeda-identity-x.js — no `rapidIdentProductId`
module.exports = configure({ omedaConfig, idxConfig, websiteBehaviorAttributeId, omedaPromoCodePrefix });
```

The website product still belongs on the customer's record — it just needs to get there once. The
field is retained for backwards compatibility and is optional in the Joi schema; it should not be
set on new sites.

History: the duplicate orders were found and fixed on allured (allured-business-media-websites#395,
Oct 2025) and the placement was rolled out fleet-wide through Aug 2026 (ab-media-websites#539,
ironmarkets-websites#993, cox-matthews-associates-websites#534, fusable-websites#1040,
watt-global-media-websites#731, industrial-media-websites#623). This README previously listed the
field as **required** and did not document the hook at all, which is what led two of those PRs to
initially move the ids the wrong way.

A related trap when reading site configs: some repos' `onAuthenticationSuccess.productIds` hold
**deployment type** ids despite the key name, because that formatter matches
`product.deploymentTypeId` and emits `deploymentTypes`. Check which formatter consumes a list before
assuming its ids are products.

### Per-source overrides (`source`)

A hook's appends are otherwise unconditional — every login source gets the same products, opt-ins
and demographics. Add a `source` map to vary them by where the conversion came from:

```js
// sites/<site>/config/identity-x-opt-in-hooks.js
module.exports = {
  onLoginLinkSent: {
    productIds: [15375],
    deploymentTypeIds: [332],
    source: {
      contentGating: { productIds: [] },   // no product for either content gate…
      contentGate: { productIds: [42] },   // …except this one specifically
    },
  },
};
```

Resolve it in a formatter with
[`resolveOptInHookConfig`](./utils/resolve-opt-in-hook-config.js), which returns `undefined` when
the hook isn't configured, so the usual early bail is unchanged:

```js
const resolveOptInHookConfig = require('@mindful-web/marko-web-omeda-identity-x/utils/resolve-opt-in-hook-config');

const { demographics, deploymentTypeIds, productIds } = resolveOptInHookConfig({
  optInHooks: identityXOptInHooks,
  hook: 'onLoginLinkSent',
  source: loginSource,
}) || {};
```

**Layering** is `base → bucket → exact source`, each a shallow **per-key replace**: only the keys
an override names are replaced, the rest inherit. That is what lets `productIds: []` mean "no
products for this source" while leaving `deploymentTypeIds` alone. An empty array is truthy, so the
existing `(productIds || []).reduce(...)` in every formatter produces no appends unchanged. An
exact-source key always beats the bucket containing it.

**Keys** may be a bucket or an exact login source, in any casing (`contentGate`,
`content_meter_login` and `CONTENT_GATE` are equivalent). The buckets are the four areas of the
Insights → Audience → Audience Conversion report:

| Bucket key | Login sources |
|---|---|
| `contentGating` | `contentGate`, `content_meter_login` |
| `newsletter` (or `newsletterSignups`) | `newsletterSignup`, `recommendedSignup` |
| `featureGating` | `comments`, `contentAccess`, `contentDownload`, `equipmentCalculator`, `loadAnalyzer`, `top250`, `pib_login`, `contactCompany`, `ingredientIssues` |
| `other` | `default`, `subscribe`, `google-one-tap`, `idxApi` |

Two groupings surprise people, and both are deliberate upstream: **`comments` is feature gating**,
not other; and **`contentAccess` / `contentDownload` are feature gating**, not content gating (they
gate an asset rather than an article, and have no Views signal). Sources in no bucket —
`change-email`, `progressiveProfile`, `truckHistoryReport`, `poultryTrendsLiveChartPage` — are
reachable only by an exact-source key.

The bucket definitions are mirrored from `mindful-reporting`'s
`packages/audience/repo/src/repos/member-events/conversion-sources.ts`; there is no package shared
between the two repos, so [`conversion-source-buckets.js`](./utils/conversion-source-buckets.js)
duplicates them. **Edit both together** — a source missing here silently falls back to the base
config rather than erroring.

Two caveats:

- **Each hook names the value differently.** `onLoginLinkSent` receives `source`,
  `onAuthenticationSuccess` receives `loginSource`, `onUserProfileUpdate` receives `actionSource`.
  Pass whichever local holds it.
- **`onUserProfileUpdate` reports which surface saved the profile, not a registration source.**
  Both routes that fire it now pass one: `routes/profile.js` sends `profileUpdate` and
  `routes/progressive-profile.js` sends `progressiveProfile` (a client-supplied
  `additionalEventData.actionSource` still wins over either). Neither is in any conversion bucket,
  so **only an exact-source key matches them** — a `newsletter` or `contentGating` bucket override
  will never apply to this hook. Before mindful-web#341 no route passed a source at all and every
  override here was inert; if you are reading an older tenant config that relied on that, it now
  resolves.

An unrecognized, empty or missing source is never an error: the set of login sources is open (any
site template can introduce a new `source="…"`), so it resolves to the base config.

### Customer re-sync interval

`userResyncIntervalMs` is read from the **IdentityX** config (`idxConfig`), not from the properties
above. It sets the lifetime of the `__idx_omeda_sync` cookie, which is what suppresses repeat Omeda
customer re-syncs.

| Property | Required? | Description | Default value |
| - | - | - | - |
| `userResyncIntervalMs` | No | **Milliseconds** between Omeda customer re-syncs for a given user. | `604800000` (1 week) |
| `userResyncInterval` | No | **Deprecated** alias of `userResyncIntervalMs`. | _n/a_ |

The unit matters: a re-sync costs two Omeda GraphQL round trips plus an IdentityX write, so a value
of `604800` supplied as "a week in seconds" resolves to ten minutes and re-syncs on nearly every page
view. Non-numeric or non-positive values are ignored with a warning and the default applies.

## Usage
This package:
1. Configures the underlying [omeda](../marko-web-omeda) and [identity-x](../marko-web-identity-x) packages
2. Hooks into the IdentityX library to push Omeda data to IdX and push IdX data to Omeda when profile updates happen
3. Makes the rapid identification endpoint (`/__idx/omeda-rapid-ident`) available on a mindful-web website
4. (Optional) Provides a Vue component to call the rapid identification endpoint

### 1. Middleware Setup
To make the local omeda mountpoint available, load the middleware exported by this package. For most applications, this will be done in the `startServer` function passed to the marko-web package.

See config section above and the Omeda and IdentityX package documentation for available configurations.

```js
const handler = require('@mindful-web/marko-web-omeda-identity-x');
const omedaConfig = require('./config/omeda');
const idXConfig = require('./config/identity-x');
const idxRouteTemplates = require('./templates/user');

startServer({
  onStart: async (app) => {
    handler(app, {
      ...omedaConfig,
      idxConfig,
      idxRouteTemplates,
    })
  },
}
```

It can also be loaded as a standard Express route middleware.
```js
module.exports = (app) => {
  handler(app, { ...omedaConfig, idxConfig, idxRouteTemplates });
};
```

### 2. Rapid Identification

To use the Rapid Identification hook, load the Vue component in your Browser config. When enabled, the Omeda Rapid Identification API will be called automatically when the `oly_enc_id` URL query parameter is present.
```js
import OmedaIdentityX from '@mindful-web/marko-web-omeda-identity-x/browser';

export default (Browser) => {
  OmedaIdentityX(Browser);
};
```
