@disconetwork/core 0.0.6 → 0.0.8

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.
@@ -1,21 +1,5 @@
1
- import { C as OfferCtaDetails, S as OfferAsset, _ as ProductProperties, a as EventTracker, b as Footer, c as BrandClickInitiatingTarget, d as BrandVisibilityEventType, f as ElementClickInitiatingTarget, g as ProductEventType, h as ProductDisplayInitiatingTarget, i as DiscoValidationError, l as BrandDisplayInitiatingTarget, m as EventPlacementDetails, n as DiscoError, o as TrackingManager, p as EventPayload, r as DiscoNetworkError, s as TrackingManagerConfig, t as DiscoApiError, u as BrandProperties, v as WidgetEventType, w as OfferDisclosureDetails, x as Offer, y as Advertiser } from "./errors-C-xomnpl.js";
1
+ import { C as OfferMetadata, I as DiscoEnv, L as envFromApiKey, O as RecommendationsResponse$1, S as OfferDisclosureDetails, _ as Advertiser, a as BrandClickInitiatingTarget, b as OfferAsset, c as BrandVisibilityEventType, d as EventPlacementDetails, f as EventTracker, g as WidgetEventType, h as ProductProperties, i as DiscoValidationError, l as ElementClickInitiatingTarget, m as ProductEventType, n as DiscoError, o as BrandDisplayInitiatingTarget, p as ProductDisplayInitiatingTarget, r as DiscoNetworkError, s as BrandProperties, t as DiscoApiError, u as EventPayload, v as Footer, x as OfferCtaDetails, y as Offer } from "./errors-BygGBn_U.js";
2
2
 
3
- //#region src/env.d.ts
4
- type DiscoEnv = "production" | "staging";
5
- /**
6
- * Derive the environment from a Disco public API key.
7
- *
8
- * Public keys are prefixed `disco_pk_<env>_…`, where `<env>` is `live`
9
- * (→ production) or `sandbox` (→ staging). The key is the single source
10
- * of truth for which backend the SDK talks to — there is no separate
11
- * `env` to pass or keep in sync, and a `live` key can't be pointed at
12
- * staging (or vice versa).
13
- *
14
- * Throws on anything that isn't a recognized public key — including a
15
- * secret (`disco_sk_…`) key, which must never be used in browser code.
16
- */
17
- declare function envFromApiKey(apiKey: string): DiscoEnv;
18
- //#endregion
19
3
  //#region src/internal/recommendations.d.ts
20
4
  type RecommendationsRequest = {
21
5
  user?: UserDetails;
@@ -99,6 +83,16 @@ type PublisherCustomization = {
99
83
  } & Record<string, Record<string, string> | undefined>;
100
84
  //#endregion
101
85
  //#region src/internal/InternalDiscoClient.d.ts
86
+ /**
87
+ * Per-environment base URL for the internal/proxy backend — the legacy server
88
+ * that orchestrates and forwards to the downstream services. Both the
89
+ * recommendations and tracking endpoints sit under this origin, routed by path
90
+ * (the client appends `/core/recommendations/…` and `/track/partners_event/`).
91
+ */
92
+ declare const INTERNAL_BASE_URL: {
93
+ readonly production: "https://consumer.disconetwork.com";
94
+ readonly staging: "https://consumer.disconetwork-staging.com";
95
+ };
102
96
  /**
103
97
  * Authenticate with a scoped public API key. Sent as the `x-api-key`
104
98
  * header against the unified `/core/recommendations/` endpoint. The key
@@ -166,6 +160,7 @@ type RecommendationsWithTracker = {
166
160
  */
167
161
  declare class InternalDiscoClient {
168
162
  #private;
163
+ get env(): DiscoEnv;
169
164
  constructor(config: DiscoClientConfig);
170
165
  /**
171
166
  * Fetch recommendations for the given request.
@@ -204,5 +199,76 @@ declare class InternalDiscoClient {
204
199
  createTrackingManager: (sessionId: string, options?: CreateTrackingManagerOptions) => EventTracker;
205
200
  }
206
201
  //#endregion
207
- export { type Advertiser, type ApiKeyConfig, type BrandClickInitiatingTarget, type BrandDisplayInitiatingTarget, type BrandProperties, type BrandVisibilityEventType, type CreateTrackingManagerOptions, DiscoApiError, type DiscoClientConfig, type DiscoEnv, DiscoError, DiscoNetworkError, DiscoValidationError, type ElementClickInitiatingTarget, type EventPayload, type EventPlacementDetails, type EventTracker, type Footer, type GetRecommendationsOptions, InternalDiscoClient, type LayoutId, type Offer, type OfferAsset, type OfferCtaDetails, type OfferDisclosureDetails, type OrderDetails, type PlacementDetails, type ProductDisplayInitiatingTarget, type ProductEventType, type ProductProperties, type PublisherCustomization, type Purchase, type Recommendation, type RecommendationGroup, type RecommendationsRequest, type RecommendationsResponse, type RecommendationsWithTracker, type RunningExperiment, type ShopGidConfig, TrackingManager, type TrackingManagerConfig, type UserDetails, type WidgetEventType, envFromApiKey };
202
+ //#region src/TrackingManager.d.ts
203
+ type TrackingManagerConfig = {
204
+ /**
205
+ * Session identifier returned by the recommendations API. Stamped onto
206
+ * every emitted event as `session_id`. A tracker is meaningless without
207
+ * a session, so this is required — instantiate the manager only after
208
+ * the recommendations response is in hand.
209
+ */
210
+ sessionId: string;
211
+ /**
212
+ * Absolute URL events are POSTed to. The external client points this at the
213
+ * events service (`/events`); the internal client at the proxy
214
+ * (`/track/partners_event/`). Prefer a client's `createTrackingManager` over
215
+ * constructing this directly, so the endpoint and auth stay consistent with
216
+ * the recommendations call.
217
+ */
218
+ endpoint: string;
219
+ /**
220
+ * Extra request headers — e.g. `{ "x-api-key": key }` for the external
221
+ * events service. `Content-Type: application/json` is always sent.
222
+ */
223
+ headers?: Record<string, string>;
224
+ /**
225
+ * Override the global `fetch`. Primarily useful in tests and in runtimes
226
+ * that provide a non-standard fetch implementation. Defaults to
227
+ * `globalThis.fetch`.
228
+ */
229
+ fetch?: typeof fetch;
230
+ };
231
+ /**
232
+ * Renderer-agnostic event tracker for Disco recommendation surfaces.
233
+ *
234
+ * Owns:
235
+ * - the dedup set (so repeated display/view events for the same brand
236
+ * don't get re-sent within a session)
237
+ * - the network call to the partner-events endpoint
238
+ * - payload formatting (snake_case keys, BE-friendly datetime)
239
+ *
240
+ * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s
241
+ * `DiscoProvider`) when consuming from a React tree, or instantiate it
242
+ * directly from any other JS environment.
243
+ *
244
+ * `track` is implemented as an instance-bound arrow function so consumers
245
+ * can safely destructure it without losing `this`.
246
+ */
247
+ declare class TrackingManager {
248
+ #private;
249
+ constructor(config: TrackingManagerConfig);
250
+ /**
251
+ * Send a tracking event. Fire-and-forget — never throws.
252
+ * Failures are logged via `console.error`.
253
+ *
254
+ * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and
255
+ * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).
256
+ */
257
+ track: (event: EventPayload) => void;
258
+ }
259
+ //#endregion
260
+ //#region src/internal/denormalize.d.ts
261
+ /**
262
+ * Join the normalized response maps into ordered `RecommendationGroup[]`.
263
+ *
264
+ * Groups are ordered by the numeric suffix of their key (`group_0` before
265
+ * `group_10`); within each group, entries are ordered by `insertionOrder`.
266
+ * Groups missing their entry list or display properties are skipped, as are
267
+ * entries whose `offerId` is absent from the recommendations map. Each result
268
+ * recommendation's `id` is the offer's id and its `insertionId` comes from the
269
+ * group entry.
270
+ */
271
+ declare function denormalize(response: RecommendationsResponse$1): RecommendationGroup[];
272
+ //#endregion
273
+ export { type Advertiser, type ApiKeyConfig, type BrandClickInitiatingTarget, type BrandDisplayInitiatingTarget, type BrandProperties, type BrandVisibilityEventType, type CreateTrackingManagerOptions, DiscoApiError, type DiscoClientConfig, type DiscoEnv, DiscoError, DiscoNetworkError, DiscoValidationError, type ElementClickInitiatingTarget, type EventPayload, type EventPlacementDetails, type EventTracker, type Footer, type GetRecommendationsOptions, INTERNAL_BASE_URL, InternalDiscoClient, type LayoutId, type Offer, type OfferAsset, type OfferCtaDetails, type OfferDisclosureDetails, type OfferMetadata, type OrderDetails, type PlacementDetails, type ProductDisplayInitiatingTarget, type ProductEventType, type ProductProperties, type PublisherCustomization, type Purchase, type Recommendation, type RecommendationGroup, type RecommendationsRequest, type RecommendationsResponse, type RecommendationsWithTracker, type RunningExperiment, type ShopGidConfig, TrackingManager, type TrackingManagerConfig, type UserDetails, type WidgetEventType, denormalize, envFromApiKey };
208
274
  //# sourceMappingURL=internal.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal.d.ts","names":[],"sources":["../src/env.ts","../src/internal/recommendations.ts","../src/internal/InternalDiscoClient.ts"],"mappings":";;;KAAY,QAAA;;;AAAZ;;;;AAAoB;AAcpB;;;;AAAuD;iBAAvC,aAAA,CAAc,MAAA,WAAiB,QAA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AW;AAAA;AAAA,KAGV,4BAAA;EDFW;;;;ECOrB,KAAA,UAAe,KAAK;AAAA;ADHf;AAGP;;;AAHO,KCUK,0BAAA;EDHN;AAGN;;;ECKE,IAAA,EAAM,uBAAA,EDJN;ECMA,OAAA,EAAS,YAAY;AAAA;;ADJT;AAGd;;;;;;;;;;;;cCkBa,mBAAA;EAAA;cAMC,MAAA,EAAQ,iBAAA;;;ADZb;AAKT;;;;AAAoB;AAOpB;;;;;ECgCE,kBAAA,GACE,OAAA,EAAS,sBAAA,EACT,OAAA,GAAU,yBAAA,KACT,OAAA,CAAQ,uBAAA;ED9Ba;;;;;;;;;;;EC0ExB,6BAAA,GACE,OAAA,EAAS,sBAAA,EACT,OAAA,GAAU,yBAAA,GAA4B,4BAAA,KACrC,OAAA,CAAQ,0BAAA;ED7EmC;AAAA;AAGhD;;;;;;EC4FE,qBAAA,GACE,SAAA,UACA,OAAA,GAAU,4BAAA,KACT,YAAA;AAAA"}
1
+ {"version":3,"file":"internal.d.ts","names":[],"sources":["../src/internal/recommendations.ts","../src/internal/InternalDiscoClient.ts","../src/TrackingManager.ts","../src/internal/denormalize.ts"],"mappings":";;;KAyCY,sBAAA;EACV,IAAA,GAAO,WAAA;EACP,SAAA,GAAY,gBAAA;EACZ,KAAA,GAAQ,YAAA;EACR,SAAA,GAAY,QAAA;EACZ,WAAA,GAAc,iBAAA;EACd,UAAA,GAAa,MAAA;EADC;;;;;;EAQd,MAAA,GAAS,MAAA;AAAA;AAAA,KAGC,WAAA;EACV,KAAA;EACA,SAAA;EACA,QAAA;EACA,KAAA;AAAA;AAAA,KAGU,gBAAA;EAHL,sEAKL,WAAA,WAFU;EAIV,IAAI;AAAA;AAAA,KAGM,YAAA;EACV,EAAA;EACA,MAAA;EACA,YAAA;AAAA;AAAA,KAGU,QAAA;EACV,IAAA;EACA,IAAA;EACA,OAAA;EACA,QAAA;EACA,SAAA;EACA,MAAA;EACA,YAAA;AAAA;AAAA,KAGU,iBAAA;EACV,EAA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OAAA,EAAS,sBAAA,EACT,OAAA,GAAU,yBAAA,GAA4B,4BAAA,KACrC,OAAA,CAAQ,0BAAA;;;;;;;;;EAkBX,qBAAA,GACE,SAAA,UACA,OAAA,GAAU,4BAAA,KACT,YAAA;AAAA;;;KC/MO,qBAAA;;AFuCZ;;;;;EEhCE,SAAA;EFoCY;;;;;;;EE3BZ,QAAA;EFyBA;;;;EEnBA,OAAA,GAAU,MAAA;EFqBE;;;;;EEdZ,KAAA,UAAe,KAAK;AAAA;;AFuBL;AAGjB;;;;;;;;;AAIO;AAGP;;;;cEda,eAAA;EAAA;cAOC,MAAA,EAAQ,qBAAA;;;;;;;AFiBR;EEHZ,KAAA,GAAS,KAAA,EAAO,YAAY;AAAA;;;;;;;;;;;;;iBC3Cd,WAAA,CACd,QAAA,EAAU,yBAAA,GACT,mBAAmB"}
package/dist/internal.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { a as DiscoApiError, c as DiscoValidationError, f as zRecommendationsResponse2, i as remap, l as isAbortError, o as DiscoError, r as transformResponse, s as DiscoNetworkError, t as TrackingManager, u as envFromApiKey } from "./TrackingManager-_IENEPuL.js";
2
+ import { a as DiscoError, c as isAbortError, d as zRecommendationsResponse2, i as DiscoApiError, l as envFromApiKey, n as transformResponse, o as DiscoNetworkError, r as remap, s as DiscoValidationError } from "./recommendationsTransforms-BDrxhOzv.js";
3
3
  import * as z$1 from "zod/v4";
4
4
  import { ZodError } from "zod/v4";
5
5
  import * as z from "zod/v3";
@@ -21,6 +21,159 @@ async function safeReadBody(response) {
21
21
  }
22
22
  }
23
23
  //#endregion
24
+ //#region src/TrackingManager.ts
25
+ /**
26
+ * Renderer-agnostic event tracker for Disco recommendation surfaces.
27
+ *
28
+ * Owns:
29
+ * - the dedup set (so repeated display/view events for the same brand
30
+ * don't get re-sent within a session)
31
+ * - the network call to the partner-events endpoint
32
+ * - payload formatting (snake_case keys, BE-friendly datetime)
33
+ *
34
+ * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s
35
+ * `DiscoProvider`) when consuming from a React tree, or instantiate it
36
+ * directly from any other JS environment.
37
+ *
38
+ * `track` is implemented as an instance-bound arrow function so consumers
39
+ * can safely destructure it without losing `this`.
40
+ */
41
+ var TrackingManager = class {
42
+ #endpoint;
43
+ #headers;
44
+ #sessionId;
45
+ #fetch;
46
+ #dedupe = /* @__PURE__ */ new Set();
47
+ constructor(config) {
48
+ this.#endpoint = config.endpoint;
49
+ this.#headers = config.headers ?? {};
50
+ this.#sessionId = config.sessionId;
51
+ this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
52
+ }
53
+ /**
54
+ * Send a tracking event. Fire-and-forget — never throws.
55
+ * Failures are logged via `console.error`.
56
+ *
57
+ * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and
58
+ * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).
59
+ */
60
+ track = (event) => {
61
+ if (this.#isDeduped(event)) return;
62
+ this.#fetch(this.#endpoint, {
63
+ method: "POST",
64
+ headers: {
65
+ "Content-Type": "application/json",
66
+ ...this.#headers
67
+ },
68
+ body: JSON.stringify(this.#toBody(event)),
69
+ keepalive: true
70
+ }).catch((error) => {
71
+ console.error("Event tracking failed:", error);
72
+ });
73
+ };
74
+ #isDeduped(event) {
75
+ if (event.type === "WIDGET_DISPLAY" || event.type === "WIDGET_VIEW" || event.type === "BRAND_DISPLAY" || event.type === "BRAND_VIEW") {
76
+ const key = event.type + ("brand" in event ? event.brand.insertionId : "widget");
77
+ if (this.#dedupe.has(key)) return true;
78
+ this.#dedupe.add(key);
79
+ }
80
+ return false;
81
+ }
82
+ #toBody(event) {
83
+ const commonEventFields = {
84
+ session_id: this.#sessionId,
85
+ event_name: event.type,
86
+ event_datetime: (/* @__PURE__ */ new Date()).toISOString().replace("Z", "+00:00"),
87
+ placement_details: event.placement ? {
88
+ display_mode: event.placement.displayMode,
89
+ view: event.placement.view,
90
+ layout_id: event.placement.layoutId
91
+ } : void 0
92
+ };
93
+ switch (event.type) {
94
+ case "BRAND_CLICK": return {
95
+ ...commonEventFields,
96
+ brand_properties: brandProperties(event.brand),
97
+ initiating_target: event.target,
98
+ asset_id: event.assetId
99
+ };
100
+ case "BRAND_DISPLAY":
101
+ case "BRAND_VIEW": return {
102
+ ...commonEventFields,
103
+ brand_properties: brandProperties(event.brand),
104
+ initiating_target: event.target
105
+ };
106
+ case "PRODUCT_DISPLAY":
107
+ case "PRODUCT_VIEW":
108
+ case "PRODUCT_CLICK": return {
109
+ ...commonEventFields,
110
+ brand_properties: brandProperties(event.brand),
111
+ product_properties: { product_id: event.product.productId },
112
+ initiating_target: event.target
113
+ };
114
+ case "ELEMENT_CLICK": return {
115
+ ...commonEventFields,
116
+ brand_properties: event.brand ? brandProperties(event.brand) : void 0,
117
+ initiating_target: event.target
118
+ };
119
+ default: return commonEventFields;
120
+ }
121
+ }
122
+ };
123
+ function brandProperties(brand) {
124
+ return {
125
+ offer_id: brand.offerId,
126
+ advertiser_id: brand.advertiserId,
127
+ insertion_id: brand.insertionId
128
+ };
129
+ }
130
+ //#endregion
131
+ //#region src/internal/denormalize.ts
132
+ /**
133
+ * Join the normalized response maps into ordered `RecommendationGroup[]`.
134
+ *
135
+ * Groups are ordered by the numeric suffix of their key (`group_0` before
136
+ * `group_10`); within each group, entries are ordered by `insertionOrder`.
137
+ * Groups missing their entry list or display properties are skipped, as are
138
+ * entries whose `offerId` is absent from the recommendations map. Each result
139
+ * recommendation's `id` is the offer's id and its `insertionId` comes from the
140
+ * group entry.
141
+ */
142
+ function denormalize(response) {
143
+ const recommendations = response.recommendations;
144
+ const groupEntries = response.recommendationGroups;
145
+ const groupProps = response.recommendationGroupProperties ?? {};
146
+ const orderedKeys = Object.keys(groupEntries).sort((a, b) => numericSuffix(a) - numericSuffix(b));
147
+ const recommendationGroups = [];
148
+ for (const key of orderedKeys) {
149
+ const entries = groupEntries[key];
150
+ const props = groupProps[key];
151
+ if (!entries || !props) continue;
152
+ const recs = [];
153
+ for (const entry of entries) {
154
+ const rec = recommendations[entry.offerId];
155
+ if (!rec) continue;
156
+ recs.push({
157
+ id: rec.offer.id,
158
+ insertionId: entry.insertionId,
159
+ advertiser: rec.advertiser,
160
+ offer: rec.offer
161
+ });
162
+ }
163
+ recommendationGroups.push({
164
+ heading: props.heading ?? null,
165
+ slotContext: props.slotContext,
166
+ recommendations: recs
167
+ });
168
+ }
169
+ return recommendationGroups;
170
+ }
171
+ function numericSuffix(value) {
172
+ const suffix = value.split("_").pop() ?? "";
173
+ const parsed = Number.parseInt(suffix, 10);
174
+ return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
175
+ }
176
+ //#endregion
24
177
  //#region src/internal/recommendationsMapper.ts
25
178
  /**
26
179
  * Maps the proxy `/recommendations` response into the public, denormalized
@@ -79,49 +232,6 @@ function mapRecommendationsResponse(raw) {
79
232
  publisherCustomization: extras.publisher_customization ?? null
80
233
  };
81
234
  }
82
- /**
83
- * Join the external normalized maps into ordered `RecommendationGroup[]`.
84
- *
85
- * Preserves the original denormalization semantics: order groups by the numeric
86
- * suffix of their key (`group_0` before `group_10`), skip groups missing their
87
- * entry list or display properties, skip entries whose `offerId` isn't in the
88
- * recommendations map, and set each `Recommendation.id` to the offer's id and
89
- * `insertionId` from the group entry.
90
- */
91
- function denormalize(normalized) {
92
- const recommendations = normalized.recommendations;
93
- const groupEntries = normalized.recommendationGroups;
94
- const groupProps = normalized.recommendationGroupProperties ?? {};
95
- const orderedKeys = Object.keys(groupEntries).sort((a, b) => numericSuffix(a) - numericSuffix(b));
96
- const recommendationGroups = [];
97
- for (const key of orderedKeys) {
98
- const entries = groupEntries[key];
99
- const props = groupProps[key];
100
- if (!entries || !props) continue;
101
- const recs = [];
102
- for (const entry of entries) {
103
- const rec = recommendations[entry.offerId];
104
- if (!rec) continue;
105
- recs.push({
106
- id: rec.offer.id,
107
- insertionId: entry.insertionId,
108
- advertiser: rec.advertiser,
109
- offer: rec.offer
110
- });
111
- }
112
- recommendationGroups.push({
113
- heading: props.heading ?? null,
114
- slotContext: props.slotContext,
115
- recommendations: recs
116
- });
117
- }
118
- return recommendationGroups;
119
- }
120
- function numericSuffix(value) {
121
- const suffix = value.split("_").pop() ?? "";
122
- const parsed = Number.parseInt(suffix, 10);
123
- return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
124
- }
125
235
  //#endregion
126
236
  //#region src/lib/schemas.ts
127
237
  /**
@@ -275,6 +385,9 @@ var InternalDiscoClient = class {
275
385
  #url;
276
386
  #headers;
277
387
  #fetch;
388
+ get env() {
389
+ return this.#env;
390
+ }
278
391
  constructor(config) {
279
392
  this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
280
393
  if ("apiKey" in config) {
@@ -364,6 +477,6 @@ function stripShopGid(shopGid) {
364
477
  return shopGid.replace("gid://shopify/Shop/", "");
365
478
  }
366
479
  //#endregion
367
- export { DiscoApiError, DiscoError, DiscoNetworkError, DiscoValidationError, InternalDiscoClient, TrackingManager, envFromApiKey };
480
+ export { DiscoApiError, DiscoError, DiscoNetworkError, DiscoValidationError, INTERNAL_BASE_URL, InternalDiscoClient, TrackingManager, denormalize, envFromApiKey };
368
481
 
369
482
  //# sourceMappingURL=internal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal.js","names":["z","#env","#url","#headers","#fetch"],"sources":["../src/lib/http.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","/**\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 { DiscoValidationError } from \"../errors.js\";\nimport * as z from \"zod/v4\";\nimport type {\n Recommendation,\n RecommendationGroup,\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 (the internal value-add).\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/**\n * Join the external normalized maps into ordered `RecommendationGroup[]`.\n *\n * Preserves the original denormalization semantics: order groups by the numeric\n * suffix of their key (`group_0` before `group_10`), skip groups missing their\n * entry list or display properties, skip entries whose `offerId` isn't in the\n * recommendations map, and set each `Recommendation.id` to the offer's id and\n * `insertionId` from the group entry.\n */\nfunction denormalize(\n normalized: ReturnType<typeof transformResponse>,\n): RecommendationGroup[] {\n const recommendations = normalized.recommendations;\n const groupEntries = normalized.recommendationGroups;\n const groupProps = normalized.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 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 * 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/v3\";\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/v3\";\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, ZodTypeDef, PublicX>` annotation pins input and output types\n// to the hand-written shapes so they can't drift.\n\nconst UserDetails$outboundSchema: z.ZodType<\n RawUserDetails,\n z.ZodTypeDef,\n UserDetails\n> = 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 z.ZodTypeDef,\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<\n RawOrderDetails,\n z.ZodTypeDef,\n OrderDetails\n> = 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, z.ZodTypeDef, Purchase> =\n 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 z.ZodTypeDef,\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 z.ZodTypeDef,\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.unknown()).optional(),\n extras: z.record(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 { envFromApiKey, type DiscoEnv } from \"../env.js\";\nimport { DiscoApiError, DiscoNetworkError, isAbortError } from \"../errors.js\";\nimport { safeReadBody } from \"../lib/http.js\";\nimport { TrackingManager, type EventTracker } from \"../TrackingManager.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. The key\n * prefix (`disco_pk_live_` / `disco_pk_sandbox_`) determines the\n * environment, so there is 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 because, unlike `ApiKeyConfig`, there is no key\n * to derive it from. `shopGid` may be a full `gid://shopify/Shop/<id>` or\n * 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 constructor(config: DiscoClientConfig) {\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (\"apiKey\" in config) {\n this.#env = envFromApiKey(config.apiKey);\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 API-key-derived environment as the\n * recommendations call, so sandbox recommendations cannot accidentally emit\n * production tracking events.\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;;;;;;;;;;;;;;;;;;;ACsBA,MAAM,eAAeA,IAAE,OAAO;CAC5B,WAAWA,IAAE,OAAO,EAAE,SAAS;CAC/B,yBAAyBA,IACtB,OAAOA,IAAE,OAAO,GAAGA,IAAE,OAAOA,IAAE,OAAO,GAAGA,IAAE,OAAO,CAAC,CAA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;EAAE;CACzB;;;;;;;;;CAUA,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","z","#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/v3\";\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/v3\";\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, ZodTypeDef, PublicX>` annotation pins input and output types\n// to the hand-written shapes so they can't drift.\n\nconst UserDetails$outboundSchema: z.ZodType<\n RawUserDetails,\n z.ZodTypeDef,\n UserDetails\n> = 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 z.ZodTypeDef,\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<\n RawOrderDetails,\n z.ZodTypeDef,\n OrderDetails\n> = 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, z.ZodTypeDef, Purchase> =\n 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 z.ZodTypeDef,\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 z.ZodTypeDef,\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.unknown()).optional(),\n extras: z.record(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 { envFromApiKey, 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. The key\n * prefix (`disco_pk_live_` / `disco_pk_sandbox_`) determines the\n * environment, so there is 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 because, unlike `ApiKeyConfig`, there is no key\n * to derive it from. `shopGid` may be a full `gid://shopify/Shop/<id>` or\n * 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 this.#env = envFromApiKey(config.apiKey);\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 API-key-derived environment as the\n * recommendations call, so sandbox recommendations cannot accidentally emit\n * production tracking events.\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;;;;;;;;;;;;;;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;;;;;;;;;;;;;CAeA,qBAAqB,OACnB,SACA,YACqC;EAIrC,MAAM,OAAO,KAAK,UAAU,iBAAiB,OAAO,CAAC;EACrD,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,KAAKC,OAAO,KAAKF,MAAM;IACtC,QAAQ;IACR,SAAS,KAAKC;IACd;IACA,QAAQ,SAAS;GACnB,CAAC;EACH,SAAS,OAAO;GAEd,IAAI,aAAa,KAAK,GAAG,MAAM;GAC/B,MAAM,IAAI,kBACR,sDACA,KACF;EACF;EAEA,IAAI,CAAC,SAAS,IAAI;GAChB,MAAM,OAAO,MAAM,aAAa,QAAQ;GACxC,MAAM,IAAI,cACR,mCAAmC,SAAS,OAAO,GAAG,SAAS,cAC/D;IAAE,QAAQ,SAAS;IAAQ,YAAY,SAAS;IAAY;GAAK,CACnE;EACF;EAEA,OAAO,2BAA2B,MAAM,SAAS,KAAK,CAAC;CACzD;;;;;;;;;;;;CAaA,gCAAgC,OAC9B,SACA,YACwC;EACxC,MAAM,OAAO,MAAM,KAAK,mBAAmB,SAAS,EAClD,QAAQ,SAAS,OACnB,CAAC;EAID,OAAO;GAAE;GAAM,SAHC,KAAK,sBAAsB,KAAK,WAAW,EACzD,OAAO,SAAS,MAClB,CACqB;EAAE;CACzB;;;;;;;;;CAUA,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"}
@@ -740,113 +740,6 @@ function mapFooter(raw) {
740
740
  };
741
741
  }
742
742
  //#endregion
743
- //#region src/TrackingManager.ts
744
- /**
745
- * Renderer-agnostic event tracker for Disco recommendation surfaces.
746
- *
747
- * Owns:
748
- * - the dedup set (so repeated display/view events for the same brand
749
- * don't get re-sent within a session)
750
- * - the network call to the partner-events endpoint
751
- * - payload formatting (snake_case keys, BE-friendly datetime)
752
- *
753
- * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s
754
- * `DiscoProvider`) when consuming from a React tree, or instantiate it
755
- * directly from any other JS environment.
756
- *
757
- * `track` is implemented as an instance-bound arrow function so consumers
758
- * can safely destructure it without losing `this`.
759
- */
760
- var TrackingManager = class {
761
- #endpoint;
762
- #headers;
763
- #sessionId;
764
- #fetch;
765
- #dedupe = /* @__PURE__ */ new Set();
766
- constructor(config) {
767
- this.#endpoint = config.endpoint;
768
- this.#headers = config.headers ?? {};
769
- this.#sessionId = config.sessionId;
770
- this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
771
- }
772
- /**
773
- * Send a tracking event. Fire-and-forget — never throws.
774
- * Failures are logged via `console.error`.
775
- *
776
- * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and
777
- * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).
778
- */
779
- track = (event) => {
780
- if (this.#isDeduped(event)) return;
781
- this.#fetch(this.#endpoint, {
782
- method: "POST",
783
- headers: {
784
- "Content-Type": "application/json",
785
- ...this.#headers
786
- },
787
- body: JSON.stringify(this.#toBody(event)),
788
- keepalive: true
789
- }).catch((error) => {
790
- console.error("Event tracking failed:", error);
791
- });
792
- };
793
- #isDeduped(event) {
794
- if (event.type === "WIDGET_DISPLAY" || event.type === "WIDGET_VIEW" || event.type === "BRAND_DISPLAY" || event.type === "BRAND_VIEW") {
795
- const key = event.type + ("brand" in event ? event.brand.insertionId : "widget");
796
- if (this.#dedupe.has(key)) return true;
797
- this.#dedupe.add(key);
798
- }
799
- return false;
800
- }
801
- #toBody(event) {
802
- const commonEventFields = {
803
- session_id: this.#sessionId,
804
- event_name: event.type,
805
- event_datetime: (/* @__PURE__ */ new Date()).toISOString().replace("Z", "+00:00"),
806
- placement_details: event.placement ? {
807
- display_mode: event.placement.displayMode,
808
- view: event.placement.view,
809
- layout_id: event.placement.layoutId
810
- } : void 0
811
- };
812
- switch (event.type) {
813
- case "BRAND_CLICK": return {
814
- ...commonEventFields,
815
- brand_properties: brandProperties(event.brand),
816
- initiating_target: event.target,
817
- asset_id: event.assetId
818
- };
819
- case "BRAND_DISPLAY":
820
- case "BRAND_VIEW": return {
821
- ...commonEventFields,
822
- brand_properties: brandProperties(event.brand),
823
- initiating_target: event.target
824
- };
825
- case "PRODUCT_DISPLAY":
826
- case "PRODUCT_VIEW":
827
- case "PRODUCT_CLICK": return {
828
- ...commonEventFields,
829
- brand_properties: brandProperties(event.brand),
830
- product_properties: { product_id: event.product.productId },
831
- initiating_target: event.target
832
- };
833
- case "ELEMENT_CLICK": return {
834
- ...commonEventFields,
835
- brand_properties: event.brand ? brandProperties(event.brand) : void 0,
836
- initiating_target: event.target
837
- };
838
- default: return commonEventFields;
839
- }
840
- }
841
- };
842
- function brandProperties(brand) {
843
- return {
844
- offer_id: brand.offerId,
845
- advertiser_id: brand.advertiserId,
846
- insertion_id: brand.insertionId
847
- };
848
- }
849
- //#endregion
850
- export { DiscoApiError as a, DiscoValidationError as c, zRecommendationsBody as d, zRecommendationsResponse2 as f, remap as i, isAbortError as l, transformRequest as n, DiscoError as o, transformResponse as r, DiscoNetworkError as s, TrackingManager as t, envFromApiKey as u };
743
+ export { DiscoError as a, isAbortError as c, zRecommendationsResponse2 as d, DiscoApiError as i, envFromApiKey as l, transformResponse as n, DiscoNetworkError as o, remap as r, DiscoValidationError as s, transformRequest as t, zRecommendationsBody as u };
851
744
 
852
- //# sourceMappingURL=TrackingManager-_IENEPuL.js.map
745
+ //# sourceMappingURL=recommendationsTransforms-BDrxhOzv.js.map