@disconetwork/core 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -73,7 +73,7 @@ type Recommendation = {
73
73
  offer: Offer;
74
74
  };
75
75
  /**
76
- * Publisher-configured copy / overrides. Keyed first by surface type
76
+ * Publisher-configured copy, boolean flags, and overrides. Keyed first by surface type
77
77
  * (`checkout`, `upfront`, …) and then by opaque server-defined keys —
78
78
  * see `applyCustomizationOrFallback` consumer-side helpers.
79
79
  *
@@ -81,9 +81,9 @@ type Recommendation = {
81
81
  * JavaScript field names.
82
82
  */
83
83
  type PublisherCustomization = {
84
- checkout?: Record<string, string>;
85
- upfront?: Record<string, string>;
86
- } & Record<string, Record<string, string> | undefined>;
84
+ checkout?: Record<string, string | boolean>;
85
+ upfront?: Record<string, string | boolean>;
86
+ } & Record<string, Record<string, string | boolean> | undefined>;
87
87
  //#endregion
88
88
  //#region src/internal/InternalDiscoClient.d.ts
89
89
  /**
package/dist/internal.js CHANGED
@@ -192,7 +192,7 @@ function numericSuffix(value) {
192
192
  */
193
193
  const zProxyExtras = z.object({
194
194
  layout_id: z.string().optional(),
195
- publisher_customization: z.record(z.string(), z.record(z.string(), z.string())).nullish()
195
+ publisher_customization: z.record(z.string(), z.record(z.string(), z.union([z.string(), z.boolean()]))).nullish()
196
196
  });
197
197
  /**
198
198
  * Validate the proxy recommendations response and denormalize it into the
@@ -1 +1 @@
1
- {"version":3,"file":"internal.js","names":["#endpoint","#headers","#sessionId","#fetch","#dedupe","#isDeduped","#toBody","#env","#url","#headers","#fetch"],"sources":["../src/lib/http.ts","../src/TrackingManager.ts","../src/internal/denormalize.ts","../src/internal/recommendationsMapper.ts","../src/lib/schemas.ts","../src/internal/recommendationsRequestMapper.ts","../src/internal/InternalDiscoClient.ts"],"sourcesContent":["/**\n * Best-effort read of a non-2xx response body: try JSON, fall back to text,\n * then give up with `undefined`. Used by both clients to populate\n * `DiscoApiError.body` without ever throwing from the error path.\n */\nexport async function safeReadBody(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n }\n}\n","import type { BrandProperties, EventPayload } from \"./types.js\";\n\nexport type TrackingManagerConfig = {\n /**\n * Session identifier returned by the recommendations API. Stamped onto\n * every emitted event as `session_id`. A tracker is meaningless without\n * a session, so this is required — instantiate the manager only after\n * the recommendations response is in hand.\n */\n sessionId: string;\n\n /**\n * Absolute URL events are POSTed to. The external client points this at the\n * events service (`/events`); the internal client at the proxy\n * (`/track/partners_event/`). Prefer a client's `createTrackingManager` over\n * constructing this directly, so the endpoint and auth stay consistent with\n * the recommendations call.\n */\n endpoint: string;\n\n /**\n * Extra request headers — e.g. `{ \"x-api-key\": key }` for the external\n * events service. `Content-Type: application/json` is always sent.\n */\n headers?: Record<string, string>;\n\n /**\n * Override the global `fetch`. Primarily useful in tests and in runtimes\n * that provide a non-standard fetch implementation. Defaults to\n * `globalThis.fetch`.\n */\n fetch?: typeof fetch;\n};\n\n/**\n * Renderer-agnostic event tracker for Disco recommendation surfaces.\n *\n * Owns:\n * - the dedup set (so repeated display/view events for the same brand\n * don't get re-sent within a session)\n * - the network call to the partner-events endpoint\n * - payload formatting (snake_case keys, BE-friendly datetime)\n *\n * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s\n * `DiscoProvider`) when consuming from a React tree, or instantiate it\n * directly from any other JS environment.\n *\n * `track` is implemented as an instance-bound arrow function so consumers\n * can safely destructure it without losing `this`.\n */\nexport class TrackingManager {\n readonly #endpoint: string;\n readonly #headers: Record<string, string>;\n readonly #sessionId: string;\n readonly #fetch: typeof fetch;\n readonly #dedupe = new Set<string>();\n\n constructor(config: TrackingManagerConfig) {\n this.#endpoint = config.endpoint;\n this.#headers = config.headers ?? {};\n this.#sessionId = config.sessionId;\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n /**\n * Send a tracking event. Fire-and-forget — never throws.\n * Failures are logged via `console.error`.\n *\n * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and\n * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).\n */\n track = (event: EventPayload): void => {\n if (this.#isDeduped(event)) return;\n\n this.#fetch(this.#endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", ...this.#headers },\n body: JSON.stringify(this.#toBody(event)),\n keepalive: true,\n }).catch((error: unknown) => {\n console.error(\"Event tracking failed:\", error);\n });\n };\n\n #isDeduped(event: EventPayload): boolean {\n if (\n event.type === \"WIDGET_DISPLAY\" ||\n event.type === \"WIDGET_VIEW\" ||\n event.type === \"BRAND_DISPLAY\" ||\n event.type === \"BRAND_VIEW\"\n ) {\n const key =\n event.type + (\"brand\" in event ? event.brand.insertionId : \"widget\");\n if (this.#dedupe.has(key)) return true;\n this.#dedupe.add(key);\n }\n return false;\n }\n\n #toBody(event: EventPayload): Record<string, unknown> {\n const commonEventFields = {\n session_id: this.#sessionId,\n event_name: event.type,\n // RFC-3339 with an explicit offset. \"+00:00\" is accepted by both the\n // events service and the legacy proxy validator (the latter can't parse\n // the bare \"Z\" suffix).\n event_datetime: new Date().toISOString().replace(\"Z\", \"+00:00\"),\n placement_details: event.placement\n ? {\n display_mode: event.placement.displayMode,\n view: event.placement.view,\n layout_id: event.placement.layoutId,\n }\n : undefined,\n };\n\n switch (event.type) {\n case \"BRAND_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n initiating_target: event.target,\n asset_id: event.assetId,\n };\n case \"BRAND_DISPLAY\":\n case \"BRAND_VIEW\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n initiating_target: event.target,\n };\n case \"PRODUCT_DISPLAY\":\n case \"PRODUCT_VIEW\":\n case \"PRODUCT_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n product_properties: { product_id: event.product.productId },\n initiating_target: event.target,\n };\n case \"ELEMENT_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: event.brand\n ? brandProperties(event.brand)\n : undefined,\n initiating_target: event.target,\n };\n default:\n return commonEventFields;\n }\n }\n}\n\nfunction brandProperties(brand: BrandProperties) {\n return {\n offer_id: brand.offerId,\n advertiser_id: brand.advertiserId,\n insertion_id: brand.insertionId,\n };\n}\n","/**\n * Join the external normalized recommendations response into ordered,\n * render-ready `RecommendationGroup[]`.\n *\n * The external `DiscoClient` returns the API's normalized maps (offer-id keyed\n * recommendations + group entries that reference them); this performs the join\n * into denormalized groups. It is the shared join used both by the internal\n * proxy mapper (`mapRecommendationsResponse`) and by `@disconetwork/react-native`\n * — hence its home on the first-party `@disconetwork/core/internal` surface\n * rather than the partner-facing package root.\n */\n\n// Input is the *external* normalized response (what `transformResponse` /\n// `DiscoClient.getRecommendations` produce). The result types are the internal\n// denormalized ones — reused so this isn't a third parallel set of group types.\nimport type { RecommendationsResponse } from \"../external/recommendations.js\";\nimport type { Recommendation, RecommendationGroup } from \"./recommendations.js\";\n\n/**\n * Join the normalized response maps into ordered `RecommendationGroup[]`.\n *\n * Groups are ordered by the numeric suffix of their key (`group_0` before\n * `group_10`); within each group, entries are ordered by `insertionOrder`.\n * Groups missing their entry list or display properties are skipped, as are\n * entries whose `offerId` is absent from the recommendations map. Each result\n * recommendation's `id` is the offer's id and its `insertionId` comes from the\n * group entry.\n */\nexport function denormalize(\n response: RecommendationsResponse,\n): RecommendationGroup[] {\n const recommendations = response.recommendations;\n const groupEntries = response.recommendationGroups;\n const groupProps = response.recommendationGroupProperties ?? {};\n\n const orderedKeys = Object.keys(groupEntries).sort(\n (a, b) => numericSuffix(a) - numericSuffix(b),\n );\n\n const recommendationGroups: RecommendationGroup[] = [];\n for (const key of orderedKeys) {\n const entries = groupEntries[key];\n const props = groupProps[key];\n // Skip groups missing their entry list or display properties.\n if (!entries || !props) continue;\n\n const recs: Recommendation[] = [];\n for (const entry of entries) {\n // for (const entry of [...entries].sort(\n // (a, b) => a.insertionOrder - b.insertionOrder,\n // )) {\n const rec = recommendations[entry.offerId];\n if (!rec) continue; // entry references an absent recommendation\n recs.push({\n id: rec.offer.id,\n insertionId: entry.insertionId,\n advertiser: rec.advertiser,\n offer: rec.offer,\n });\n }\n\n recommendationGroups.push({\n heading: props.heading ?? null,\n slotContext: props.slotContext,\n recommendations: recs,\n });\n }\n\n return recommendationGroups;\n}\n\nfunction numericSuffix(value: string): number {\n const suffix = value.split(\"_\").pop() ?? \"\";\n const parsed = Number.parseInt(suffix, 10);\n return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;\n}\n","/**\n * Maps the proxy `/recommendations` response into the public, denormalized\n * `RecommendationsResponse` (`mapRecommendationsResponse`).\n *\n * The proxy response is the external `/recommendations` response **verbatim plus\n * a few extra top-level fields** (`layout_id`, `publisher_customization`, the\n * `widget_*` markers, …). So this reuses the external machinery — the generated\n * zod validator (`zRecommendationsResponse2`) and the external `transformResponse`\n * mapper — and only layers on the denormalization (the join into\n * `RecommendationGroup[]`) and the proxy extras.\n *\n * Validation is zod-backed: the external-wire part is validated by the generated\n * `zRecommendationsResponse2` and the proxy extras by a small local schema, so a\n * malformed server response surfaces as a `DiscoValidationError` rather than an\n * opaque `undefined`-access crash deep in the join.\n */\n\nimport { ZodError } from \"zod/v4\";\nimport { zRecommendationsResponse2 } from \"../api/generated/recommendations/zod.gen.js\";\nimport type { RecommendationsResponse as RecommendationsWireResponse } from \"../api/generated/recommendations/types.gen.js\";\nimport { transformResponse } from \"../external/recommendationsTransforms.js\";\nimport { denormalize } from \"./denormalize.js\";\nimport { DiscoValidationError } from \"../errors.js\";\nimport * as z from \"zod/v4\";\nimport type {\n RecommendationsResponse,\n PublisherCustomization,\n} from \"./recommendations.js\";\n\n// ─── Validation of the proxy extras ──────────────────────────────────────────\n//\n// The external-wire part is validated by the generated `zRecommendationsResponse2`\n// (which STRIPS unknown keys — so the proxy extras won't survive it). The few\n// extra top-level fields the proxy adds are validated separately by this small\n// schema, run against the same raw payload. zod/v4 — to match the generated\n// validator and so its `ZodError` is caught by the `zod/v4` import above.\nconst zProxyExtras = z.object({\n layout_id: z.string().optional(),\n publisher_customization: z\n .record(z.string(), z.record(z.string(), z.string()))\n .nullish(),\n});\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Validate the proxy recommendations response and denormalize it into the\n * public `RecommendationsResponse`.\n *\n * The proxy payload is the external wire response plus extras, so this reuses\n * the external machinery: validate the wire part with the generated\n * `zRecommendationsResponse2` and the extras with `zProxyExtras`, recase via\n * the external `transformResponse`, then denormalize the resulting maps into\n * `RecommendationGroup[]` (the internal value-add) and assemble the response\n * with the proxy extras layered on.\n *\n * Throws `DiscoValidationError` if the server payload doesn't match the\n * expected shape.\n *\n * @internal Built into `InternalDiscoClient.getRecommendations`; not part of\n * the public API. The wire shape is encapsulated by the client on purpose.\n */\nexport function mapRecommendationsResponse(\n raw: unknown,\n): RecommendationsResponse {\n let wire: RecommendationsWireResponse;\n let extras: z.infer<typeof zProxyExtras>;\n try {\n // The generated validator pins the external-wire shape; cast its (inferred)\n // output to the wire type `transformResponse` consumes — both describe the\n // same spec shape.\n wire = zRecommendationsResponse2.parse(raw) as RecommendationsWireResponse;\n extras = zProxyExtras.parse(raw);\n } catch (error) {\n if (error instanceof ZodError) {\n throw new DiscoValidationError(\n \"Failed to validate recommendations response\",\n error,\n raw,\n );\n }\n throw error;\n }\n\n // Reuse the external mapper for the leaf types + casing (free), then join the\n // normalized maps into the denormalized groups via the shared `denormalize`\n // helper (the same join the external surface exposes to consumers).\n const normalized = transformResponse(wire);\n const recommendationGroups = denormalize(normalized);\n\n return {\n sessionId: normalized.sessionId,\n layoutId: extras.layout_id ?? \"SHOPIFY_NATIVE_ESSENTIAL\",\n recommendationGroups,\n footer: normalized.footer,\n publisherCustomization:\n (extras.publisher_customization as PublisherCustomization | null) ?? null,\n };\n}\n","/**\n * Thin wrappers around Zod parsing that convert a thrown `ZodError` into a\n * `DiscoValidationError`, so validation failures surface as a Disco error type\n * rather than leaking Zod's internals to consumers. Modeled on the equivalent\n * helpers in Speakeasy-generated SDKs.\n */\n\nimport * as z from \"zod/v4\";\nimport { DiscoValidationError } from \"../errors.js\";\n\n/**\n * Run `fn` (typically a `schema.parse`) and, if it throws a `ZodError`, rethrow\n * it as a `DiscoValidationError`. Any non-Zod error propagates untouched.\n */\nexport function parse<Inp, Out>(\n rawValue: Inp,\n fn: (value: Inp) => Out,\n errorMessage: string,\n): Out {\n try {\n return fn(rawValue);\n } catch (err) {\n if (err instanceof z.ZodError) {\n throw new DiscoValidationError(errorMessage, err, rawValue);\n }\n throw err;\n }\n}\n","/**\n * Wire types for the recommendations *request* and `transformRequest`, which\n * builds the snake_case wire body from the public `RecommendationsRequest`.\n *\n * `InternalDiscoClient.getRecommendations` calls `transformRequest` to map the\n * camelCase request into the wire body before POSTing it.\n *\n * The mapping is Zod-backed: `RecommendationsRequest$outboundSchema` validates\n * the public request before the `.transform()` reshapes it into the wire body,\n * so a malformed request surfaces as a `DiscoValidationError` *before* it hits\n * the network. This mirrors how Speakeasy-generated SDKs use an\n * `$outboundSchema` per model.\n */\n\nimport * as z from \"zod/v4\";\nimport { parse } from \"../lib/schemas.js\";\nimport { remap } from \"../lib/primitives.js\";\nimport type {\n OrderDetails,\n PlacementDetails,\n Purchase,\n RecommendationsRequest,\n RunningExperiment,\n UserDetails,\n} from \"./recommendations.js\";\n\n// ─── Raw wire shape ──────────────────────────────────────────────────────────\n//\n// The endpoint nests most request fields under `recommendations_data`, with\n// monetary fields tucked into a `cost_details` sub-object, while experiments\n// and attributes sit at the top level. The public `RecommendationsRequest` is\n// a flatter façade over this; the outbound schema bridges the two.\n\ntype RawCostDetails = {\n amount?: number | string;\n currency_code?: string;\n};\n\ntype RawUserDetails = {\n email?: string;\n first_name?: string;\n last_name?: string;\n phone?: string;\n};\n\ntype RawPlacementDetails = {\n display_mode?: string;\n view?: string;\n};\n\ntype RawOrderDetails = {\n order_id?: string;\n cost_details?: RawCostDetails;\n};\n\ntype RawPurchase = {\n name?: string;\n type?: string;\n variant?: string;\n quantity?: number;\n product_id?: string;\n cost_details?: RawCostDetails;\n};\n\ntype RawRunningExperiment = {\n id: string;\n variant: string;\n};\n\ntype RawRecommendationsData = {\n user_details?: RawUserDetails;\n placement_details?: RawPlacementDetails;\n order_details?: RawOrderDetails;\n purchases?: RawPurchase[];\n};\n\ntype RawRecommendationsRequest = {\n recommendations_data?: RawRecommendationsData;\n running_experiments?: RawRunningExperiment[];\n attributes?: Record<string, unknown>;\n /**\n * Platform-specific top-level fields passed through untransformed\n * (e.g. `shopify_checkout_token`). The public type funnels these through\n * `extras`; on the raw body they're just additional keys.\n */\n [key: string]: unknown;\n};\n\n// ─── Outbound schemas ──────────────────────────────────────────────────────────\n//\n// Each schema validates a slice of the public (camelCase) request and\n// `.transform()`s it into the snake_case wire shape. Simple field renames go\n// through `remap`; the monetary fields fold into a `cost_details` sub-object\n// that's omitted entirely when no amount/currency is present. The\n// `z.ZodType<RawX, PublicX>` annotation pins input and output types\n// to the hand-written shapes so they can't drift.\n\nconst UserDetails$outboundSchema: z.ZodType<RawUserDetails, UserDetails> = z\n .object({\n email: z.string().optional(),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n phone: z.string().optional(),\n })\n .transform((v) =>\n remap(v, { firstName: \"first_name\", lastName: \"last_name\" }),\n );\n\nconst PlacementDetails$outboundSchema: z.ZodType<\n RawPlacementDetails,\n PlacementDetails\n> = z\n .object({\n displayMode: z.string().optional(),\n view: z.string().optional(),\n })\n .transform((v) => remap(v, { displayMode: \"display_mode\" }));\n\nconst OrderDetails$outboundSchema: z.ZodType<RawOrderDetails, OrderDetails> = z\n .object({\n id: z.string().optional(),\n amount: z.union([z.number(), z.string()]).optional(),\n currencyCode: z.string().optional(),\n })\n .transform((v) => ({\n order_id: v.id,\n cost_details:\n v.amount !== undefined || v.currencyCode !== undefined\n ? { amount: v.amount, currency_code: v.currencyCode }\n : undefined,\n }));\n\nconst Purchase$outboundSchema: z.ZodType<RawPurchase, Purchase> = z\n .object({\n name: z.string().optional(),\n type: z.string().optional(),\n variant: z.string().optional(),\n quantity: z.number().optional(),\n productId: z.string().optional(),\n amount: z.number().optional(),\n currencyCode: z.string().optional(),\n })\n .transform((v) => ({\n name: v.name,\n type: v.type,\n variant: v.variant,\n quantity: v.quantity,\n product_id: v.productId,\n cost_details:\n v.amount !== undefined || v.currencyCode !== undefined\n ? { amount: v.amount, currency_code: v.currencyCode }\n : undefined,\n }));\n\nconst RunningExperiment$outboundSchema: z.ZodType<\n RawRunningExperiment,\n RunningExperiment\n> = z.object({\n id: z.string(),\n variant: z.string(),\n});\n\n/**\n * Validates the public request and reshapes it into the raw wire body: nest\n * fields under `recommendations_data`, fold monetary fields into `cost_details`,\n * convert camelCase to snake_case, and spread `extras` at the top level\n * untransformed.\n */\nconst RecommendationsRequest$outboundSchema: z.ZodType<\n RawRecommendationsRequest,\n RecommendationsRequest\n> = z\n .object({\n user: UserDetails$outboundSchema.optional(),\n placement: PlacementDetails$outboundSchema.optional(),\n order: OrderDetails$outboundSchema.optional(),\n purchases: z.array(Purchase$outboundSchema).optional(),\n experiments: z.array(RunningExperiment$outboundSchema).optional(),\n attributes: z.record(z.string(), z.unknown()).optional(),\n extras: z.record(z.string(), z.unknown()).optional(),\n })\n .transform((v) => ({\n recommendations_data: {\n user_details: v.user,\n placement_details: v.placement,\n order_details: v.order,\n purchases: v.purchases,\n },\n running_experiments: v.experiments,\n attributes: v.attributes,\n ...v.extras,\n }));\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Build the raw request body from the public `RecommendationsRequest`: nest\n * fields under `recommendations_data`, fold monetary fields into `cost_details`\n * (omitted entirely when no amount/currency is present), and convert camelCase\n * to snake_case. `extras` is spread at the top level untransformed.\n *\n * Validates the input first and throws `DiscoValidationError` if the request\n * doesn't match the expected shape.\n *\n * @internal Built into `DiscoClient.getRecommendations`; not part of the public\n * API. The wire shape is encapsulated by the client on purpose.\n */\nexport function transformRequest(\n req: RecommendationsRequest,\n): RawRecommendationsRequest {\n return parse(\n req,\n (value) => RecommendationsRequest$outboundSchema.parse(value),\n \"Failed to validate recommendations request\",\n );\n}\n","import { validatePublicApiKey } from \"../apiKey.js\";\nimport type { DiscoEnv } from \"../env.js\";\nimport { DiscoApiError, DiscoNetworkError, isAbortError } from \"../errors.js\";\nimport { safeReadBody } from \"../lib/http.js\";\nimport { TrackingManager } from \"../TrackingManager.js\";\nimport type { EventTracker } from \"../types.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport { mapRecommendationsResponse } from \"./recommendationsMapper.js\";\nimport { transformRequest } from \"./recommendationsRequestMapper.js\";\n\n/**\n * Per-environment base URL for the internal/proxy backend — the legacy server\n * that orchestrates and forwards to the downstream services. Both the\n * recommendations and tracking endpoints sit under this origin, routed by path\n * (the client appends `/core/recommendations/…` and `/track/partners_event/`).\n */\nexport const INTERNAL_BASE_URL = {\n production: \"https://consumer.disconetwork.com\",\n staging: \"https://consumer.disconetwork-staging.com\",\n} as const satisfies Record<DiscoEnv, string>;\n\n/**\n * Authenticate with a scoped public API key. Sent as the `x-api-key`\n * header against the unified `/core/recommendations/` endpoint. Both\n * `disco_pk_live_…` and `disco_pk_sandbox_…` keys use production; there is\n * no separate `env` to set.\n *\n * Use this from partner apps and server-side code that hold a key.\n */\nexport type ApiKeyConfig = {\n apiKey: string;\n fetch?: typeof fetch;\n};\n\n/**\n * Authenticate by Shopify shop — for surfaces that must not embed a key,\n * notably the App-Store-deployed checkout extension. The request hits the\n * `/core/recommendations/shop_gid/<id>/` proxy with **no** API key; the\n * backend resolves the publisher from the shop and injects the key\n * server-side.\n *\n * `env` is required here to select the backend for shop-based authentication.\n * `shopGid` may be a full `gid://shopify/Shop/<id>` or the bare id.\n */\nexport type ShopGidConfig = {\n shopGid: string;\n env: DiscoEnv;\n fetch?: typeof fetch;\n};\n\nexport type DiscoClientConfig = ApiKeyConfig | ShopGidConfig;\n\nexport type GetRecommendationsOptions = {\n /** Forwarded to `fetch` so consumers can cancel in-flight requests. */\n signal?: AbortSignal;\n};\n\nexport type CreateTrackingManagerOptions = {\n /**\n * Override the fetch implementation used by the tracker. Defaults to the\n * same fetch implementation configured on the client.\n */\n fetch?: typeof fetch;\n};\n\n/**\n * Result of `getRecommendationsWithTracker`: the mapped recommendations\n * response plus a tracker already bound to its session.\n */\nexport type RecommendationsWithTracker = {\n /**\n * The mapped, denormalized recommendations response — the same friendly\n * camelCase shape `getRecommendations` returns.\n */\n data: RecommendationsResponse;\n /** Event tracker bound to this response's session. */\n tracker: EventTracker;\n};\n\n/**\n * Internal client for the legacy **proxy** recommendations endpoint\n * (`/core/recommendations/` on the backend), which orchestrates placement,\n * experiments, layout, and `publisher_customization` server-side and supports\n * `shopGid` auth for first-party surfaces (e.g. the Shopify checkout\n * extension).\n *\n * First-party / legacy only — exported from `@disconetwork/core/internal`.\n * External partners use the `DiscoClient` from the package root, which talks\n * directly to `disco-recommendations-api`.\n *\n * Renderer-agnostic: this class makes plain HTTP calls and has no React\n * dependency.\n */\nexport class InternalDiscoClient {\n readonly #env: DiscoEnv;\n readonly #url: string;\n readonly #headers: Record<string, string>;\n readonly #fetch: typeof fetch;\n\n get env(): DiscoEnv {\n return this.#env;\n }\n\n constructor(config: DiscoClientConfig) {\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (\"apiKey\" in config) {\n validatePublicApiKey(config.apiKey);\n this.#env = \"production\";\n this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/`;\n this.#headers = {\n \"x-api-key\": config.apiKey,\n \"Content-Type\": \"application/json\",\n };\n } else {\n this.#env = config.env;\n const shopId = stripShopGid(config.shopGid);\n this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;\n // No x-api-key: the backend resolves auth from the shop_gid.\n this.#headers = { \"Content-Type\": \"application/json\" };\n }\n }\n\n /**\n * Fetch recommendations for the given request.\n *\n * Validates and transforms the friendly camelCase `request` into the wire\n * body, POSTs it, then validates and denormalizes the response into the\n * friendly `RecommendationsResponse`. The snake_case wire format is fully\n * encapsulated — callers never see it.\n *\n * Throws `DiscoValidationError` if the request or response fails schema\n * validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`\n * if the request can't reach the server (an abort rejects with the native\n * `AbortError`). Parse failures propagate as-is.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RecommendationsResponse> => {\n // `transformRequest` validates the request and builds the wire body; its\n // `DiscoValidationError` must propagate, so it runs *before* the fetch try\n // (otherwise the catch below would mis-wrap it as a `DiscoNetworkError`).\n const body = JSON.stringify(transformRequest(request));\n let response: Response;\n try {\n response = await this.#fetch(this.#url, {\n method: \"POST\",\n headers: this.#headers,\n body,\n signal: options?.signal,\n });\n } catch (error) {\n // A cancellation propagates as-is; any other transport failure is wrapped.\n if (isAbortError(error)) throw error;\n throw new DiscoNetworkError(\n \"Recommendations request failed to reach the server\",\n error,\n );\n }\n\n if (!response.ok) {\n const body = await safeReadBody(response);\n throw new DiscoApiError(\n `Recommendations request failed: ${response.status} ${response.statusText}`,\n { status: response.status, statusText: response.statusText, body },\n );\n }\n\n return mapRecommendationsResponse(await response.json());\n };\n\n /**\n * Fetch recommendations and create a session-bound tracker in one call.\n *\n * Composition convenience over `getRecommendations` + `createTrackingManager`:\n * it derives the tracker's session from the response so callers don't have to\n * thread the session id through themselves (and can't bind a tracker to the\n * wrong session). The returned `data` is the mapped `RecommendationsResponse`.\n *\n * Throws `DiscoValidationError` / `DiscoApiError` the same as\n * `getRecommendations`.\n */\n getRecommendationsWithTracker = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions & CreateTrackingManagerOptions,\n ): Promise<RecommendationsWithTracker> => {\n const data = await this.getRecommendations(request, {\n signal: options?.signal,\n });\n const tracker = this.createTrackingManager(data.sessionId, {\n fetch: options?.fetch,\n });\n return { data, tracker };\n };\n\n /**\n * Create an event tracker bound to a recommendations session (the `sessionId`\n * from a `getRecommendations` response).\n *\n * The tracker uses the same environment as the recommendations call.\n * Both live and sandbox public keys use production.\n */\n createTrackingManager = (\n sessionId: string,\n options?: CreateTrackingManagerOptions,\n ): EventTracker =>\n new TrackingManager({\n sessionId,\n endpoint: `${INTERNAL_BASE_URL[this.#env]}/track/partners_event/`,\n fetch: options?.fetch ?? this.#fetch,\n });\n}\n\nfunction stripShopGid(shopGid: string): string {\n return shopGid.replace(\"gid://shopify/Shop/\", \"\");\n}\n"],"mappings":";;;;;;;;;;AAKA,eAAsB,aAAa,UAAsC;CACvE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,EAAE,KAAK;CACrC,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,SAAS,KAAK;EAC7B,QAAQ;GACN;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;ACmCA,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA;CACA,0BAAmB,IAAI,IAAY;CAEnC,YAAY,QAA+B;EACzC,KAAKA,YAAY,OAAO;EACxB,KAAKC,WAAW,OAAO,WAAW,CAAC;EACnC,KAAKC,aAAa,OAAO;EACzB,KAAKC,SAAS,OAAO,SAAS,WAAW,MAAM,KAAK,UAAU;CAChE;;;;;;;;CASA,SAAS,UAA8B;EACrC,IAAI,KAAKE,WAAW,KAAK,GAAG;EAE5B,KAAKF,OAAO,KAAKH,WAAW;GAC1B,QAAQ;GACR,SAAS;IAAE,gBAAgB;IAAoB,GAAG,KAAKC;GAAS;GAChE,MAAM,KAAK,UAAU,KAAKK,QAAQ,KAAK,CAAC;GACxC,WAAW;EACb,CAAC,EAAE,OAAO,UAAmB;GAC3B,QAAQ,MAAM,0BAA0B,KAAK;EAC/C,CAAC;CACH;CAEA,WAAW,OAA8B;EACvC,IACE,MAAM,SAAS,oBACf,MAAM,SAAS,iBACf,MAAM,SAAS,mBACf,MAAM,SAAS,cACf;GACA,MAAM,MACJ,M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AAM,KAAK,mBAAmB,SAAS,EAClD,QAAQ,SAAS,OACnB,CAAC;EAID,OAAO;GAAE;GAAM,SAHC,KAAK,sBAAsB,KAAK,WAAW,EACzD,OAAO,SAAS,MAClB,CACqB;EAAE;CACzB;;;;;;;;CASA,yBACE,WACA,YAEA,IAAI,gBAAgB;EAClB;EACA,UAAU,GAAG,kBAAkB,KAAKF,MAAM;EAC1C,OAAO,SAAS,SAAS,KAAKG;CAChC,CAAC;AACL;AAEA,SAAS,aAAa,SAAyB;CAC7C,OAAO,QAAQ,QAAQ,uBAAuB,EAAE;AAClD"}
1
+ {"version":3,"file":"internal.js","names":["#endpoint","#headers","#sessionId","#fetch","#dedupe","#isDeduped","#toBody","#env","#url","#headers","#fetch"],"sources":["../src/lib/http.ts","../src/TrackingManager.ts","../src/internal/denormalize.ts","../src/internal/recommendationsMapper.ts","../src/lib/schemas.ts","../src/internal/recommendationsRequestMapper.ts","../src/internal/InternalDiscoClient.ts"],"sourcesContent":["/**\n * Best-effort read of a non-2xx response body: try JSON, fall back to text,\n * then give up with `undefined`. Used by both clients to populate\n * `DiscoApiError.body` without ever throwing from the error path.\n */\nexport async function safeReadBody(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n }\n}\n","import type { BrandProperties, EventPayload } from \"./types.js\";\n\nexport type TrackingManagerConfig = {\n /**\n * Session identifier returned by the recommendations API. Stamped onto\n * every emitted event as `session_id`. A tracker is meaningless without\n * a session, so this is required — instantiate the manager only after\n * the recommendations response is in hand.\n */\n sessionId: string;\n\n /**\n * Absolute URL events are POSTed to. The external client points this at the\n * events service (`/events`); the internal client at the proxy\n * (`/track/partners_event/`). Prefer a client's `createTrackingManager` over\n * constructing this directly, so the endpoint and auth stay consistent with\n * the recommendations call.\n */\n endpoint: string;\n\n /**\n * Extra request headers — e.g. `{ \"x-api-key\": key }` for the external\n * events service. `Content-Type: application/json` is always sent.\n */\n headers?: Record<string, string>;\n\n /**\n * Override the global `fetch`. Primarily useful in tests and in runtimes\n * that provide a non-standard fetch implementation. Defaults to\n * `globalThis.fetch`.\n */\n fetch?: typeof fetch;\n};\n\n/**\n * Renderer-agnostic event tracker for Disco recommendation surfaces.\n *\n * Owns:\n * - the dedup set (so repeated display/view events for the same brand\n * don't get re-sent within a session)\n * - the network call to the partner-events endpoint\n * - payload formatting (snake_case keys, BE-friendly datetime)\n *\n * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s\n * `DiscoProvider`) when consuming from a React tree, or instantiate it\n * directly from any other JS environment.\n *\n * `track` is implemented as an instance-bound arrow function so consumers\n * can safely destructure it without losing `this`.\n */\nexport class TrackingManager {\n readonly #endpoint: string;\n readonly #headers: Record<string, string>;\n readonly #sessionId: string;\n readonly #fetch: typeof fetch;\n readonly #dedupe = new Set<string>();\n\n constructor(config: TrackingManagerConfig) {\n this.#endpoint = config.endpoint;\n this.#headers = config.headers ?? {};\n this.#sessionId = config.sessionId;\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n /**\n * Send a tracking event. Fire-and-forget — never throws.\n * Failures are logged via `console.error`.\n *\n * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and\n * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).\n */\n track = (event: EventPayload): void => {\n if (this.#isDeduped(event)) return;\n\n this.#fetch(this.#endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", ...this.#headers },\n body: JSON.stringify(this.#toBody(event)),\n keepalive: true,\n }).catch((error: unknown) => {\n console.error(\"Event tracking failed:\", error);\n });\n };\n\n #isDeduped(event: EventPayload): boolean {\n if (\n event.type === \"WIDGET_DISPLAY\" ||\n event.type === \"WIDGET_VIEW\" ||\n event.type === \"BRAND_DISPLAY\" ||\n event.type === \"BRAND_VIEW\"\n ) {\n const key =\n event.type + (\"brand\" in event ? event.brand.insertionId : \"widget\");\n if (this.#dedupe.has(key)) return true;\n this.#dedupe.add(key);\n }\n return false;\n }\n\n #toBody(event: EventPayload): Record<string, unknown> {\n const commonEventFields = {\n session_id: this.#sessionId,\n event_name: event.type,\n // RFC-3339 with an explicit offset. \"+00:00\" is accepted by both the\n // events service and the legacy proxy validator (the latter can't parse\n // the bare \"Z\" suffix).\n event_datetime: new Date().toISOString().replace(\"Z\", \"+00:00\"),\n placement_details: event.placement\n ? {\n display_mode: event.placement.displayMode,\n view: event.placement.view,\n layout_id: event.placement.layoutId,\n }\n : undefined,\n };\n\n switch (event.type) {\n case \"BRAND_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n initiating_target: event.target,\n asset_id: event.assetId,\n };\n case \"BRAND_DISPLAY\":\n case \"BRAND_VIEW\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n initiating_target: event.target,\n };\n case \"PRODUCT_DISPLAY\":\n case \"PRODUCT_VIEW\":\n case \"PRODUCT_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n product_properties: { product_id: event.product.productId },\n initiating_target: event.target,\n };\n case \"ELEMENT_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: event.brand\n ? brandProperties(event.brand)\n : undefined,\n initiating_target: event.target,\n };\n default:\n return commonEventFields;\n }\n }\n}\n\nfunction brandProperties(brand: BrandProperties) {\n return {\n offer_id: brand.offerId,\n advertiser_id: brand.advertiserId,\n insertion_id: brand.insertionId,\n };\n}\n","/**\n * Join the external normalized recommendations response into ordered,\n * render-ready `RecommendationGroup[]`.\n *\n * The external `DiscoClient` returns the API's normalized maps (offer-id keyed\n * recommendations + group entries that reference them); this performs the join\n * into denormalized groups. It is the shared join used both by the internal\n * proxy mapper (`mapRecommendationsResponse`) and by `@disconetwork/react-native`\n * — hence its home on the first-party `@disconetwork/core/internal` surface\n * rather than the partner-facing package root.\n */\n\n// Input is the *external* normalized response (what `transformResponse` /\n// `DiscoClient.getRecommendations` produce). The result types are the internal\n// denormalized ones — reused so this isn't a third parallel set of group types.\nimport type { RecommendationsResponse } from \"../external/recommendations.js\";\nimport type { Recommendation, RecommendationGroup } from \"./recommendations.js\";\n\n/**\n * Join the normalized response maps into ordered `RecommendationGroup[]`.\n *\n * Groups are ordered by the numeric suffix of their key (`group_0` before\n * `group_10`); within each group, entries are ordered by `insertionOrder`.\n * Groups missing their entry list or display properties are skipped, as are\n * entries whose `offerId` is absent from the recommendations map. Each result\n * recommendation's `id` is the offer's id and its `insertionId` comes from the\n * group entry.\n */\nexport function denormalize(\n response: RecommendationsResponse,\n): RecommendationGroup[] {\n const recommendations = response.recommendations;\n const groupEntries = response.recommendationGroups;\n const groupProps = response.recommendationGroupProperties ?? {};\n\n const orderedKeys = Object.keys(groupEntries).sort(\n (a, b) => numericSuffix(a) - numericSuffix(b),\n );\n\n const recommendationGroups: RecommendationGroup[] = [];\n for (const key of orderedKeys) {\n const entries = groupEntries[key];\n const props = groupProps[key];\n // Skip groups missing their entry list or display properties.\n if (!entries || !props) continue;\n\n const recs: Recommendation[] = [];\n for (const entry of entries) {\n // for (const entry of [...entries].sort(\n // (a, b) => a.insertionOrder - b.insertionOrder,\n // )) {\n const rec = recommendations[entry.offerId];\n if (!rec) continue; // entry references an absent recommendation\n recs.push({\n id: rec.offer.id,\n insertionId: entry.insertionId,\n advertiser: rec.advertiser,\n offer: rec.offer,\n });\n }\n\n recommendationGroups.push({\n heading: props.heading ?? null,\n slotContext: props.slotContext,\n recommendations: recs,\n });\n }\n\n return recommendationGroups;\n}\n\nfunction numericSuffix(value: string): number {\n const suffix = value.split(\"_\").pop() ?? \"\";\n const parsed = Number.parseInt(suffix, 10);\n return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;\n}\n","/**\n * Maps the proxy `/recommendations` response into the public, denormalized\n * `RecommendationsResponse` (`mapRecommendationsResponse`).\n *\n * The proxy response is the external `/recommendations` response **verbatim plus\n * a few extra top-level fields** (`layout_id`, `publisher_customization`, the\n * `widget_*` markers, …). So this reuses the external machinery — the generated\n * zod validator (`zRecommendationsResponse2`) and the external `transformResponse`\n * mapper — and only layers on the denormalization (the join into\n * `RecommendationGroup[]`) and the proxy extras.\n *\n * Validation is zod-backed: the external-wire part is validated by the generated\n * `zRecommendationsResponse2` and the proxy extras by a small local schema, so a\n * malformed server response surfaces as a `DiscoValidationError` rather than an\n * opaque `undefined`-access crash deep in the join.\n */\n\nimport { ZodError } from \"zod/v4\";\nimport { zRecommendationsResponse2 } from \"../api/generated/recommendations/zod.gen.js\";\nimport type { RecommendationsResponse as RecommendationsWireResponse } from \"../api/generated/recommendations/types.gen.js\";\nimport { transformResponse } from \"../external/recommendationsTransforms.js\";\nimport { denormalize } from \"./denormalize.js\";\nimport { DiscoValidationError } from \"../errors.js\";\nimport * as z from \"zod/v4\";\nimport type {\n RecommendationsResponse,\n PublisherCustomization,\n} from \"./recommendations.js\";\n\n// ─── Validation of the proxy extras ──────────────────────────────────────────\n//\n// The external-wire part is validated by the generated `zRecommendationsResponse2`\n// (which STRIPS unknown keys — so the proxy extras won't survive it). The few\n// extra top-level fields the proxy adds are validated separately by this small\n// schema, run against the same raw payload. zod/v4 — to match the generated\n// validator and so its `ZodError` is caught by the `zod/v4` import above.\nconst zProxyExtras = z.object({\n layout_id: z.string().optional(),\n publisher_customization: z\n .record(\n z.string(),\n z.record(z.string(), z.union([z.string(), z.boolean()])),\n )\n .nullish(),\n});\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Validate the proxy recommendations response and denormalize it into the\n * public `RecommendationsResponse`.\n *\n * The proxy payload is the external wire response plus extras, so this reuses\n * the external machinery: validate the wire part with the generated\n * `zRecommendationsResponse2` and the extras with `zProxyExtras`, recase via\n * the external `transformResponse`, then denormalize the resulting maps into\n * `RecommendationGroup[]` (the internal value-add) and assemble the response\n * with the proxy extras layered on.\n *\n * Throws `DiscoValidationError` if the server payload doesn't match the\n * expected shape.\n *\n * @internal Built into `InternalDiscoClient.getRecommendations`; not part of\n * the public API. The wire shape is encapsulated by the client on purpose.\n */\nexport function mapRecommendationsResponse(\n raw: unknown,\n): RecommendationsResponse {\n let wire: RecommendationsWireResponse;\n let extras: z.infer<typeof zProxyExtras>;\n try {\n // The generated validator pins the external-wire shape; cast its (inferred)\n // output to the wire type `transformResponse` consumes — both describe the\n // same spec shape.\n wire = zRecommendationsResponse2.parse(raw) as RecommendationsWireResponse;\n extras = zProxyExtras.parse(raw);\n } catch (error) {\n if (error instanceof ZodError) {\n throw new DiscoValidationError(\n \"Failed to validate recommendations response\",\n error,\n raw,\n );\n }\n throw error;\n }\n\n // Reuse the external mapper for the leaf types + casing (free), then join the\n // normalized maps into the denormalized groups via the shared `denormalize`\n // helper (the same join the external surface exposes to consumers).\n const normalized = transformResponse(wire);\n const recommendationGroups = denormalize(normalized);\n\n return {\n sessionId: normalized.sessionId,\n layoutId: extras.layout_id ?? \"SHOPIFY_NATIVE_ESSENTIAL\",\n recommendationGroups,\n footer: normalized.footer,\n publisherCustomization:\n (extras.publisher_customization as PublisherCustomization | null) ?? null,\n };\n}\n","/**\n * Thin wrappers around Zod parsing that convert a thrown `ZodError` into a\n * `DiscoValidationError`, so validation failures surface as a Disco error type\n * rather than leaking Zod's internals to consumers. Modeled on the equivalent\n * helpers in Speakeasy-generated SDKs.\n */\n\nimport * as z from \"zod/v4\";\nimport { DiscoValidationError } from \"../errors.js\";\n\n/**\n * Run `fn` (typically a `schema.parse`) and, if it throws a `ZodError`, rethrow\n * it as a `DiscoValidationError`. Any non-Zod error propagates untouched.\n */\nexport function parse<Inp, Out>(\n rawValue: Inp,\n fn: (value: Inp) => Out,\n errorMessage: string,\n): Out {\n try {\n return fn(rawValue);\n } catch (err) {\n if (err instanceof z.ZodError) {\n throw new DiscoValidationError(errorMessage, err, rawValue);\n }\n throw err;\n }\n}\n","/**\n * Wire types for the recommendations *request* and `transformRequest`, which\n * builds the snake_case wire body from the public `RecommendationsRequest`.\n *\n * `InternalDiscoClient.getRecommendations` calls `transformRequest` to map the\n * camelCase request into the wire body before POSTing it.\n *\n * The mapping is Zod-backed: `RecommendationsRequest$outboundSchema` validates\n * the public request before the `.transform()` reshapes it into the wire body,\n * so a malformed request surfaces as a `DiscoValidationError` *before* it hits\n * the network. This mirrors how Speakeasy-generated SDKs use an\n * `$outboundSchema` per model.\n */\n\nimport * as z from \"zod/v4\";\nimport { parse } from \"../lib/schemas.js\";\nimport { remap } from \"../lib/primitives.js\";\nimport type {\n OrderDetails,\n PlacementDetails,\n Purchase,\n RecommendationsRequest,\n RunningExperiment,\n UserDetails,\n} from \"./recommendations.js\";\n\n// ─── Raw wire shape ──────────────────────────────────────────────────────────\n//\n// The endpoint nests most request fields under `recommendations_data`, with\n// monetary fields tucked into a `cost_details` sub-object, while experiments\n// and attributes sit at the top level. The public `RecommendationsRequest` is\n// a flatter façade over this; the outbound schema bridges the two.\n\ntype RawCostDetails = {\n amount?: number | string;\n currency_code?: string;\n};\n\ntype RawUserDetails = {\n email?: string;\n first_name?: string;\n last_name?: string;\n phone?: string;\n};\n\ntype RawPlacementDetails = {\n display_mode?: string;\n view?: string;\n};\n\ntype RawOrderDetails = {\n order_id?: string;\n cost_details?: RawCostDetails;\n};\n\ntype RawPurchase = {\n name?: string;\n type?: string;\n variant?: string;\n quantity?: number;\n product_id?: string;\n cost_details?: RawCostDetails;\n};\n\ntype RawRunningExperiment = {\n id: string;\n variant: string;\n};\n\ntype RawRecommendationsData = {\n user_details?: RawUserDetails;\n placement_details?: RawPlacementDetails;\n order_details?: RawOrderDetails;\n purchases?: RawPurchase[];\n};\n\ntype RawRecommendationsRequest = {\n recommendations_data?: RawRecommendationsData;\n running_experiments?: RawRunningExperiment[];\n attributes?: Record<string, unknown>;\n /**\n * Platform-specific top-level fields passed through untransformed\n * (e.g. `shopify_checkout_token`). The public type funnels these through\n * `extras`; on the raw body they're just additional keys.\n */\n [key: string]: unknown;\n};\n\n// ─── Outbound schemas ──────────────────────────────────────────────────────────\n//\n// Each schema validates a slice of the public (camelCase) request and\n// `.transform()`s it into the snake_case wire shape. Simple field renames go\n// through `remap`; the monetary fields fold into a `cost_details` sub-object\n// that's omitted entirely when no amount/currency is present. The\n// `z.ZodType<RawX, PublicX>` annotation pins input and output types\n// to the hand-written shapes so they can't drift.\n\nconst UserDetails$outboundSchema: z.ZodType<RawUserDetails, UserDetails> = z\n .object({\n email: z.string().optional(),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n phone: z.string().optional(),\n })\n .transform((v) =>\n remap(v, { firstName: \"first_name\", lastName: \"last_name\" }),\n );\n\nconst PlacementDetails$outboundSchema: z.ZodType<\n RawPlacementDetails,\n PlacementDetails\n> = z\n .object({\n displayMode: z.string().optional(),\n view: z.string().optional(),\n })\n .transform((v) => remap(v, { displayMode: \"display_mode\" }));\n\nconst OrderDetails$outboundSchema: z.ZodType<RawOrderDetails, OrderDetails> = z\n .object({\n id: z.string().optional(),\n amount: z.union([z.number(), z.string()]).optional(),\n currencyCode: z.string().optional(),\n })\n .transform((v) => ({\n order_id: v.id,\n cost_details:\n v.amount !== undefined || v.currencyCode !== undefined\n ? { amount: v.amount, currency_code: v.currencyCode }\n : undefined,\n }));\n\nconst Purchase$outboundSchema: z.ZodType<RawPurchase, Purchase> = z\n .object({\n name: z.string().optional(),\n type: z.string().optional(),\n variant: z.string().optional(),\n quantity: z.number().optional(),\n productId: z.string().optional(),\n amount: z.number().optional(),\n currencyCode: z.string().optional(),\n })\n .transform((v) => ({\n name: v.name,\n type: v.type,\n variant: v.variant,\n quantity: v.quantity,\n product_id: v.productId,\n cost_details:\n v.amount !== undefined || v.currencyCode !== undefined\n ? { amount: v.amount, currency_code: v.currencyCode }\n : undefined,\n }));\n\nconst RunningExperiment$outboundSchema: z.ZodType<\n RawRunningExperiment,\n RunningExperiment\n> = z.object({\n id: z.string(),\n variant: z.string(),\n});\n\n/**\n * Validates the public request and reshapes it into the raw wire body: nest\n * fields under `recommendations_data`, fold monetary fields into `cost_details`,\n * convert camelCase to snake_case, and spread `extras` at the top level\n * untransformed.\n */\nconst RecommendationsRequest$outboundSchema: z.ZodType<\n RawRecommendationsRequest,\n RecommendationsRequest\n> = z\n .object({\n user: UserDetails$outboundSchema.optional(),\n placement: PlacementDetails$outboundSchema.optional(),\n order: OrderDetails$outboundSchema.optional(),\n purchases: z.array(Purchase$outboundSchema).optional(),\n experiments: z.array(RunningExperiment$outboundSchema).optional(),\n attributes: z.record(z.string(), z.unknown()).optional(),\n extras: z.record(z.string(), z.unknown()).optional(),\n })\n .transform((v) => ({\n recommendations_data: {\n user_details: v.user,\n placement_details: v.placement,\n order_details: v.order,\n purchases: v.purchases,\n },\n running_experiments: v.experiments,\n attributes: v.attributes,\n ...v.extras,\n }));\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Build the raw request body from the public `RecommendationsRequest`: nest\n * fields under `recommendations_data`, fold monetary fields into `cost_details`\n * (omitted entirely when no amount/currency is present), and convert camelCase\n * to snake_case. `extras` is spread at the top level untransformed.\n *\n * Validates the input first and throws `DiscoValidationError` if the request\n * doesn't match the expected shape.\n *\n * @internal Built into `DiscoClient.getRecommendations`; not part of the public\n * API. The wire shape is encapsulated by the client on purpose.\n */\nexport function transformRequest(\n req: RecommendationsRequest,\n): RawRecommendationsRequest {\n return parse(\n req,\n (value) => RecommendationsRequest$outboundSchema.parse(value),\n \"Failed to validate recommendations request\",\n );\n}\n","import { validatePublicApiKey } from \"../apiKey.js\";\nimport type { DiscoEnv } from \"../env.js\";\nimport { DiscoApiError, DiscoNetworkError, isAbortError } from \"../errors.js\";\nimport { safeReadBody } from \"../lib/http.js\";\nimport { TrackingManager } from \"../TrackingManager.js\";\nimport type { EventTracker } from \"../types.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport { mapRecommendationsResponse } from \"./recommendationsMapper.js\";\nimport { transformRequest } from \"./recommendationsRequestMapper.js\";\n\n/**\n * Per-environment base URL for the internal/proxy backend — the legacy server\n * that orchestrates and forwards to the downstream services. Both the\n * recommendations and tracking endpoints sit under this origin, routed by path\n * (the client appends `/core/recommendations/…` and `/track/partners_event/`).\n */\nexport const INTERNAL_BASE_URL = {\n production: \"https://consumer.disconetwork.com\",\n staging: \"https://consumer.disconetwork-staging.com\",\n} as const satisfies Record<DiscoEnv, string>;\n\n/**\n * Authenticate with a scoped public API key. Sent as the `x-api-key`\n * header against the unified `/core/recommendations/` endpoint. Both\n * `disco_pk_live_…` and `disco_pk_sandbox_…` keys use production; there is\n * no separate `env` to set.\n *\n * Use this from partner apps and server-side code that hold a key.\n */\nexport type ApiKeyConfig = {\n apiKey: string;\n fetch?: typeof fetch;\n};\n\n/**\n * Authenticate by Shopify shop — for surfaces that must not embed a key,\n * notably the App-Store-deployed checkout extension. The request hits the\n * `/core/recommendations/shop_gid/<id>/` proxy with **no** API key; the\n * backend resolves the publisher from the shop and injects the key\n * server-side.\n *\n * `env` is required here to select the backend for shop-based authentication.\n * `shopGid` may be a full `gid://shopify/Shop/<id>` or the bare id.\n */\nexport type ShopGidConfig = {\n shopGid: string;\n env: DiscoEnv;\n fetch?: typeof fetch;\n};\n\nexport type DiscoClientConfig = ApiKeyConfig | ShopGidConfig;\n\nexport type GetRecommendationsOptions = {\n /** Forwarded to `fetch` so consumers can cancel in-flight requests. */\n signal?: AbortSignal;\n};\n\nexport type CreateTrackingManagerOptions = {\n /**\n * Override the fetch implementation used by the tracker. Defaults to the\n * same fetch implementation configured on the client.\n */\n fetch?: typeof fetch;\n};\n\n/**\n * Result of `getRecommendationsWithTracker`: the mapped recommendations\n * response plus a tracker already bound to its session.\n */\nexport type RecommendationsWithTracker = {\n /**\n * The mapped, denormalized recommendations response — the same friendly\n * camelCase shape `getRecommendations` returns.\n */\n data: RecommendationsResponse;\n /** Event tracker bound to this response's session. */\n tracker: EventTracker;\n};\n\n/**\n * Internal client for the legacy **proxy** recommendations endpoint\n * (`/core/recommendations/` on the backend), which orchestrates placement,\n * experiments, layout, and `publisher_customization` server-side and supports\n * `shopGid` auth for first-party surfaces (e.g. the Shopify checkout\n * extension).\n *\n * First-party / legacy only — exported from `@disconetwork/core/internal`.\n * External partners use the `DiscoClient` from the package root, which talks\n * directly to `disco-recommendations-api`.\n *\n * Renderer-agnostic: this class makes plain HTTP calls and has no React\n * dependency.\n */\nexport class InternalDiscoClient {\n readonly #env: DiscoEnv;\n readonly #url: string;\n readonly #headers: Record<string, string>;\n readonly #fetch: typeof fetch;\n\n get env(): DiscoEnv {\n return this.#env;\n }\n\n constructor(config: DiscoClientConfig) {\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (\"apiKey\" in config) {\n validatePublicApiKey(config.apiKey);\n this.#env = \"production\";\n this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/`;\n this.#headers = {\n \"x-api-key\": config.apiKey,\n \"Content-Type\": \"application/json\",\n };\n } else {\n this.#env = config.env;\n const shopId = stripShopGid(config.shopGid);\n this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;\n // No x-api-key: the backend resolves auth from the shop_gid.\n this.#headers = { \"Content-Type\": \"application/json\" };\n }\n }\n\n /**\n * Fetch recommendations for the given request.\n *\n * Validates and transforms the friendly camelCase `request` into the wire\n * body, POSTs it, then validates and denormalizes the response into the\n * friendly `RecommendationsResponse`. The snake_case wire format is fully\n * encapsulated — callers never see it.\n *\n * Throws `DiscoValidationError` if the request or response fails schema\n * validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`\n * if the request can't reach the server (an abort rejects with the native\n * `AbortError`). Parse failures propagate as-is.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RecommendationsResponse> => {\n // `transformRequest` validates the request and builds the wire body; its\n // `DiscoValidationError` must propagate, so it runs *before* the fetch try\n // (otherwise the catch below would mis-wrap it as a `DiscoNetworkError`).\n const body = JSON.stringify(transformRequest(request));\n let response: Response;\n try {\n response = await this.#fetch(this.#url, {\n method: \"POST\",\n headers: this.#headers,\n body,\n signal: options?.signal,\n });\n } catch (error) {\n // A cancellation propagates as-is; any other transport failure is wrapped.\n if (isAbortError(error)) throw error;\n throw new DiscoNetworkError(\n \"Recommendations request failed to reach the server\",\n error,\n );\n }\n\n if (!response.ok) {\n const body = await safeReadBody(response);\n throw new DiscoApiError(\n `Recommendations request failed: ${response.status} ${response.statusText}`,\n { status: response.status, statusText: response.statusText, body },\n );\n }\n\n return mapRecommendationsResponse(await response.json());\n };\n\n /**\n * Fetch recommendations and create a session-bound tracker in one call.\n *\n * Composition convenience over `getRecommendations` + `createTrackingManager`:\n * it derives the tracker's session from the response so callers don't have to\n * thread the session id through themselves (and can't bind a tracker to the\n * wrong session). The returned `data` is the mapped `RecommendationsResponse`.\n *\n * Throws `DiscoValidationError` / `DiscoApiError` the same as\n * `getRecommendations`.\n */\n getRecommendationsWithTracker = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions & CreateTrackingManagerOptions,\n ): Promise<RecommendationsWithTracker> => {\n const data = await this.getRecommendations(request, {\n signal: options?.signal,\n });\n const tracker = this.createTrackingManager(data.sessionId, {\n fetch: options?.fetch,\n });\n return { data, tracker };\n };\n\n /**\n * Create an event tracker bound to a recommendations session (the `sessionId`\n * from a `getRecommendations` response).\n *\n * The tracker uses the same environment as the recommendations call.\n * Both live and sandbox public keys use production.\n */\n createTrackingManager = (\n sessionId: string,\n options?: CreateTrackingManagerOptions,\n ): EventTracker =>\n new TrackingManager({\n sessionId,\n endpoint: `${INTERNAL_BASE_URL[this.#env]}/track/partners_event/`,\n fetch: options?.fetch ?? this.#fetch,\n });\n}\n\nfunction stripShopGid(shopGid: string): string {\n return shopGid.replace(\"gid://shopify/Shop/\", \"\");\n}\n"],"mappings":";;;;;;;;;;AAKA,eAAsB,aAAa,UAAsC;CACvE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,EAAE,KAAK;CACrC,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,SAAS,KAAK;EAC7B,QAAQ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  "description": "Core package for disco-js.",
5
5
  "license": "MIT",
6
6
  "repository": {