@disconetwork/core 0.0.1

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.
@@ -0,0 +1,384 @@
1
+ //#region src/env.d.ts
2
+ /**
3
+ * Disco backend environments. The SDK does not accept arbitrary URLs —
4
+ * consumers pick an environment and the SDK resolves the correct
5
+ * endpoints internally. This keeps partners from pointing the client or
6
+ * tracker at unintended hosts while still supporting staging.
7
+ */
8
+ type DiscoEnv = "production" | "staging";
9
+ /**
10
+ * Derive the environment from a Disco public API key.
11
+ *
12
+ * Public keys are prefixed `disco_pk_<env>_…`, where `<env>` is `live`
13
+ * (→ production) or `sandbox` (→ staging). The key is the single source
14
+ * of truth for which backend the SDK talks to — there is no separate
15
+ * `env` to pass or keep in sync, and a `live` key can't be pointed at
16
+ * staging (or vice versa).
17
+ *
18
+ * Throws on anything that isn't a recognized public key — including a
19
+ * secret (`disco_sk_…`) key, which must never be used in browser code.
20
+ */
21
+ declare function envFromApiKey(apiKey: string): DiscoEnv;
22
+ //#endregion
23
+ //#region src/types.d.ts
24
+ /**
25
+ * Targets for `BRAND_CLICK` events — where in the widget the click originated.
26
+ */
27
+ type BrandClickInitiatingTarget = "INLINE_ACTION_BUTTON" | "INLINE_ASSET_TILE" | "SCROLLABLE_SLOT_TILE";
28
+ /**
29
+ * Targets for `ELEMENT_CLICK` events — non-brand UI interactions.
30
+ */
31
+ type ElementClickInitiatingTarget = "INLINE_NAV_FORWARD" | "INLINE_NAV_BACKWARD" | "INLINE_FOOTER_DISCO" | "INLINE_FOOTER_PRIVACY" | "CLOSE_BUTTON" | "CLOSE_BACKDROP" | "OPEN_OVERLAY";
32
+ /**
33
+ * Targets for `BRAND_DISPLAY` / `BRAND_VIEW` events.
34
+ */
35
+ type BrandDisplayInitiatingTarget = "INLINE_SLOT" | "SCROLLABLE_SLOT";
36
+ /**
37
+ * Targets for `PRODUCT_DISPLAY` / `PRODUCT_VIEW` / `PRODUCT_CLICK` events.
38
+ */
39
+ type ProductDisplayInitiatingTarget = "INLINE_TILE";
40
+ /**
41
+ * Identifies a brand instance in the recommendations response.
42
+ *
43
+ * `insertionId` is the unique-per-render identifier and is what dedup keys
44
+ * are built from.
45
+ */
46
+ type BrandProperties = {
47
+ offerId: string;
48
+ advertiserId: string;
49
+ insertionId: string;
50
+ };
51
+ type ProductProperties = {
52
+ productId: string;
53
+ };
54
+ type WidgetEventType = "WIDGET_LOAD" | "WIDGET_DISPLAY" | "WIDGET_VIEW";
55
+ type BrandVisibilityEventType = "BRAND_DISPLAY" | "BRAND_VIEW";
56
+ type ProductEventType = "PRODUCT_DISPLAY" | "PRODUCT_VIEW" | "PRODUCT_CLICK";
57
+ /**
58
+ * Discriminated union of every event the SDK can emit.
59
+ *
60
+ * The shape of each variant matches what the partner-events backend
61
+ * expects after the `toBody` transformation applied inside the event tracker.
62
+ */
63
+ type EventPayload = {
64
+ type: WidgetEventType;
65
+ } | {
66
+ type: BrandVisibilityEventType;
67
+ brand: BrandProperties;
68
+ target: BrandDisplayInitiatingTarget;
69
+ } | {
70
+ type: "BRAND_CLICK";
71
+ brand: BrandProperties;
72
+ target: BrandClickInitiatingTarget;
73
+ assetId?: string;
74
+ } | {
75
+ type: "ELEMENT_CLICK";
76
+ target: ElementClickInitiatingTarget;
77
+ brand?: BrandProperties;
78
+ } | {
79
+ type: ProductEventType;
80
+ product: ProductProperties;
81
+ brand: BrandProperties;
82
+ target: ProductDisplayInitiatingTarget;
83
+ };
84
+ //#endregion
85
+ //#region src/TrackingManager.d.ts
86
+ type EventTracker = {
87
+ track: (event: EventPayload) => void;
88
+ };
89
+ //#endregion
90
+ //#region src/recommendations.d.ts
91
+ /**
92
+ * Public, camelCase types for the recommendations API request and response.
93
+ *
94
+ * The wire format uses snake_case; `DiscoClient` handles the translation
95
+ * in both directions so consumers never see snake_case keys — with one
96
+ * deliberate exception: keys inside `PublisherCustomization` are opaque
97
+ * server-defined identifiers (`widget_heading`, `widget_subheading`, …)
98
+ * and are passed through as-is.
99
+ */
100
+ type RecommendationsRequest = {
101
+ user?: UserDetails;
102
+ placement?: PlacementDetails;
103
+ order?: OrderDetails;
104
+ purchases?: Purchase[];
105
+ experiments?: RunningExperiment[];
106
+ attributes?: Record<string, unknown>;
107
+ /**
108
+ * Additional top-level fields passed through to the API unchanged.
109
+ * Use for platform-specific extensions (e.g. `shopify_checkout_token`).
110
+ * Keys here are not transformed — provide them in whatever case the
111
+ * backend expects.
112
+ */
113
+ extras?: Record<string, unknown>;
114
+ };
115
+ type UserDetails = {
116
+ email?: string;
117
+ firstName?: string;
118
+ lastName?: string;
119
+ phone?: string;
120
+ };
121
+ type PlacementDetails = {
122
+ /** e.g. `"INLINE"`. Open-ended — see backend for supported values. */displayMode?: string; /** e.g. `"THANK_YOU"`, `"ORDER_STATUS"`. Open-ended. */
123
+ view?: string;
124
+ };
125
+ type OrderDetails = {
126
+ id?: string;
127
+ amount?: number | string;
128
+ currencyCode?: string;
129
+ };
130
+ type Purchase = {
131
+ name?: string;
132
+ type?: string;
133
+ variant?: string;
134
+ quantity?: number;
135
+ productId?: string;
136
+ amount?: number;
137
+ currencyCode?: string;
138
+ };
139
+ type RunningExperiment = {
140
+ id: string;
141
+ variant: string;
142
+ };
143
+ type LayoutId = "SHOPIFY_NATIVE_LEAD_GEN" | "SHOPIFY_NATIVE_ESSENTIAL" | "SHOPIFY_NATIVE_COVER" | (string & {});
144
+ type RecommendationsResponse = {
145
+ sessionId: string;
146
+ layoutId: LayoutId;
147
+ recommendationGroups: RecommendationGroup[];
148
+ footer: Footer;
149
+ publisherCustomization: PublisherCustomization | null;
150
+ };
151
+ type RecommendationGroup = {
152
+ heading: string | null;
153
+ slotContext: "HERO" | "SCROLLABLE" | (string & {});
154
+ recommendations: Recommendation[];
155
+ };
156
+ type Recommendation = {
157
+ id: string;
158
+ insertionId: string;
159
+ advertiser: Advertiser;
160
+ offer: Offer;
161
+ };
162
+ type Advertiser = {
163
+ id: string;
164
+ name: string;
165
+ logoUrl: string;
166
+ description: string | null;
167
+ };
168
+ type Offer = {
169
+ id: string;
170
+ heading: string | null;
171
+ subheading: string | null;
172
+ jsonContent: Record<string, unknown> | null;
173
+ targetUrl: string;
174
+ ctaDetails: OfferCtaDetails;
175
+ assets: OfferAsset[];
176
+ metadata: Record<string, unknown> | null;
177
+ disclosureDetails: OfferDisclosureDetails | null;
178
+ };
179
+ type OfferCtaDetails = {
180
+ acceptCopy: string;
181
+ declineCopy: string;
182
+ transitionCopy: string | null;
183
+ };
184
+ type OfferAsset = {
185
+ id: string;
186
+ imageUrl: string;
187
+ targetUrl: string | null;
188
+ };
189
+ /**
190
+ * Server-defined disclosure copy / links for an offer. Shape is open;
191
+ * the SDK passes it through without inspection.
192
+ */
193
+ type OfferDisclosureDetails = Record<string, unknown>;
194
+ type Footer = {
195
+ attributionDetails: {
196
+ copy: string;
197
+ discoLogoUrl: string;
198
+ targetUrl: string;
199
+ };
200
+ privacyPolicy: {
201
+ copy: string;
202
+ targetUrl: string;
203
+ };
204
+ };
205
+ /**
206
+ * Publisher-configured copy / overrides. Keyed first by surface type
207
+ * (`checkout`, `upfront`, …) and then by opaque server-defined keys —
208
+ * see `applyCustomizationOrFallback` consumer-side helpers.
209
+ *
210
+ * Inner keys remain snake_case because they're identifiers, not
211
+ * JavaScript field names.
212
+ */
213
+ type PublisherCustomization = {
214
+ checkout?: Record<string, string>;
215
+ upfront?: Record<string, string>;
216
+ } & Record<string, Record<string, string> | undefined>;
217
+ //#endregion
218
+ //#region src/recommendationsMapper.d.ts
219
+ type RawRecommendationsResponse = {
220
+ session_id: string;
221
+ layout_id: string; /** Map of offer id → recommendation. */
222
+ recommendations?: Record<string, RawRecommendation> | null; /** Map of group key → ordered entry list referencing offer ids. */
223
+ recommendation_groups?: Record<string, RawGroupEntry[]> | null; /** Map of group key → group display properties. */
224
+ recommendation_group_properties?: Record<string, RawGroupProperties> | null;
225
+ footer: RawFooter;
226
+ publisher_customization?: RawPublisherCustomization | null;
227
+ is_using_cmos_recommendations?: boolean;
228
+ widget_type?: string;
229
+ widget_mode?: string;
230
+ widget_version?: string;
231
+ running_experiments?: unknown[];
232
+ };
233
+ type RawRecommendation = {
234
+ advertiser: RawAdvertiser;
235
+ offer: RawOffer;
236
+ };
237
+ type RawGroupEntry = {
238
+ insertion_order: number;
239
+ insertion_id: string;
240
+ offer_id: string;
241
+ advertiser_id: string;
242
+ };
243
+ type RawGroupProperties = {
244
+ heading?: string | null;
245
+ slot_context: string;
246
+ };
247
+ type RawAdvertiser = {
248
+ id: string;
249
+ name: string;
250
+ logo_url: string;
251
+ description?: string | null;
252
+ };
253
+ type RawOffer = {
254
+ id: string;
255
+ heading?: string | null;
256
+ subheading?: string | null;
257
+ json_content?: Record<string, unknown> | null;
258
+ target_url: string;
259
+ cta_details: RawOfferCtaDetails;
260
+ assets?: RawOfferAsset[] | null;
261
+ metadata?: Record<string, unknown> | null;
262
+ disclosure_details?: Record<string, unknown> | null;
263
+ };
264
+ type RawOfferCtaDetails = {
265
+ accept_copy: string;
266
+ decline_copy: string;
267
+ transition_copy?: string | null;
268
+ };
269
+ type RawOfferAsset = {
270
+ id: string;
271
+ image_url: string;
272
+ target_url?: string | null;
273
+ };
274
+ type RawFooter = {
275
+ attribution_details: {
276
+ copy: string;
277
+ disco_logo_url: string;
278
+ target_url: string;
279
+ };
280
+ privacy_policy: {
281
+ copy: string;
282
+ target_url: string;
283
+ };
284
+ };
285
+ type RawPublisherCustomization = Record<string, Record<string, string>>;
286
+ /**
287
+ * Denormalize a raw recommendations response into the public
288
+ * `RecommendationsResponse`: join group entries → recommendations by offer id,
289
+ * order groups by the numeric suffix of their key (group_0, group_1, …), and
290
+ * convert snake_case to camelCase.
291
+ *
292
+ * Pure and side-effect-free — call it on the result of
293
+ * `DiscoClient.getRecommendations` when you want the friendly shape.
294
+ */
295
+ declare function mapRecommendationsResponse(raw: RawRecommendationsResponse): RecommendationsResponse;
296
+ //#endregion
297
+ //#region src/DiscoClient.d.ts
298
+ /**
299
+ * Authenticate with a scoped public API key. Sent as the `x-api-key`
300
+ * header against the unified `/core/recommendations/` endpoint. The key
301
+ * prefix (`disco_pk_live_` / `disco_pk_sandbox_`) determines the
302
+ * environment, so there is no separate `env` to set.
303
+ *
304
+ * Use this from partner apps and server-side code that hold a key.
305
+ */
306
+ type ApiKeyConfig = {
307
+ apiKey: string;
308
+ fetch?: typeof fetch;
309
+ };
310
+ /**
311
+ * Authenticate by Shopify shop — for surfaces that must not embed a key,
312
+ * notably the App-Store-deployed checkout extension. The request hits the
313
+ * `/core/recommendations/shop_gid/<id>/` proxy with **no** API key; the
314
+ * backend resolves the publisher from the shop and injects the key
315
+ * server-side.
316
+ *
317
+ * `env` is required here because, unlike `ApiKeyConfig`, there is no key
318
+ * to derive it from. `shopGid` may be a full `gid://shopify/Shop/<id>` or
319
+ * the bare id.
320
+ */
321
+ type ShopGidConfig = {
322
+ shopGid: string;
323
+ env: DiscoEnv;
324
+ fetch?: typeof fetch;
325
+ };
326
+ type DiscoClientConfig = ApiKeyConfig | ShopGidConfig;
327
+ type GetRecommendationsOptions = {
328
+ /** Forwarded to `fetch` so consumers can cancel in-flight requests. */signal?: AbortSignal;
329
+ };
330
+ type CreateTrackingManagerOptions = {
331
+ /**
332
+ * Override the fetch implementation used by the tracker. Defaults to the
333
+ * same fetch implementation configured on the client.
334
+ */
335
+ fetch?: typeof fetch;
336
+ };
337
+ /**
338
+ * Thrown by `DiscoClient.getRecommendations` when the server returns a
339
+ * non-2xx status. The HTTP status and an optional parsed body are
340
+ * preserved for error UIs and retry logic.
341
+ */
342
+ declare class DiscoApiError extends Error {
343
+ readonly status: number;
344
+ readonly statusText: string;
345
+ readonly body: unknown;
346
+ constructor(message: string, info: {
347
+ status: number;
348
+ statusText: string;
349
+ body?: unknown;
350
+ });
351
+ }
352
+ /**
353
+ * Typed client for the Disco recommendations API.
354
+ *
355
+ * Renderer-agnostic: this class makes plain HTTP calls and has no
356
+ * React dependency. Wrap it in a Provider (`@disconetwork/react`'s
357
+ * `DiscoProvider`) for use from a React tree, or instantiate it
358
+ * directly from server code, scripts, or tests.
359
+ */
360
+ declare class DiscoClient {
361
+ #private;
362
+ constructor(config: DiscoClientConfig);
363
+ /**
364
+ * POST the recommendations endpoint and return the backend's response
365
+ * **verbatim** — this reflects `ExternalAPIRecommendationView` with no
366
+ * transformation. Pass the result through `mapRecommendationsResponse`
367
+ * if you want the friendly denormalized `RecommendationsResponse`.
368
+ *
369
+ * Throws `DiscoApiError` on non-2xx responses; other failures
370
+ * (network, parse) propagate as-is.
371
+ */
372
+ getRecommendations: (request: RecommendationsRequest, options?: GetRecommendationsOptions) => Promise<RawRecommendationsResponse>;
373
+ /**
374
+ * Create an event tracker for a recommendations response from this client.
375
+ *
376
+ * The tracker uses the same API-key-derived environment as the
377
+ * recommendations call, so sandbox recommendations cannot accidentally emit
378
+ * production tracking events.
379
+ */
380
+ createTrackingManager: (recommendations: Pick<RecommendationsResponse, "sessionId">, options?: CreateTrackingManagerOptions) => EventTracker;
381
+ }
382
+ //#endregion
383
+ export { type Advertiser, type ApiKeyConfig, type BrandClickInitiatingTarget, type BrandDisplayInitiatingTarget, type BrandProperties, type BrandVisibilityEventType, type CreateTrackingManagerOptions, DiscoApiError, DiscoClient, type DiscoClientConfig, type DiscoEnv, type ElementClickInitiatingTarget, type EventPayload, type EventTracker, type Footer, type GetRecommendationsOptions, 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 RawAdvertiser, type RawFooter, type RawGroupEntry, type RawGroupProperties, type RawOffer, type RawOfferAsset, type RawOfferCtaDetails, type RawPublisherCustomization, type RawRecommendation, type RawRecommendationsResponse, type Recommendation, type RecommendationGroup, type RecommendationsRequest, type RecommendationsResponse, type RunningExperiment, type ShopGidConfig, type UserDetails, type WidgetEventType, envFromApiKey, mapRecommendationsResponse };
384
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/env.ts","../src/types.ts","../src/TrackingManager.ts","../src/recommendations.ts","../src/recommendationsMapper.ts","../src/DiscoClient.ts"],"mappings":";;AAMA;;;;AAAoB;KAAR,QAAA;ACiBZ;;;;AAAwC;AAKxC;;;;AAA0C;AAQ1C;;AAbA,iBDkBgB,aAAA,CAAc,MAAA,WAAiB,QAAQ;;;;AAnCvD;;KCHY,0BAAA;;ADGQ;AAmCpB;KC9BY,4BAAA;;;AD8B2C;KClB3C,4BAAA;;;AApBZ;KAyBY,8BAAA;;;AAzB0B;AAQtC;;;KAyBY,eAAA;EACV,OAAA;EACA,YAAA;EACA,WAAA;AAAA;AAAA,KAGU,iBAAA;EACV,SAAS;AAAA;AAAA,KAGC,eAAA;AAAA,KAEA,wBAAA;AAAA,KAEA,gBAAA;AAtB8B;AAQ1C;;;;;AAR0C,KAiC9B,YAAA;EACN,IAAA,EAAM,eAAA;AAAA;EAEN,IAAA,EAAM,wBAAA;EACN,KAAA,EAAO,eAAA;EACP,MAAA,EAAQ,4BAAA;AAAA;EAGR,IAAA;EACA,KAAA,EAAO,eAAA;EACP,MAAA,EAAQ,0BAAA;EACR,OAAA;AAAA;EAGA,IAAA;EACA,MAAA,EAAQ,4BAAA;EACR,KAAA,GAAQ,eAAA;AAAA;EAGR,IAAA,EAAM,gBAAA;EACN,OAAA,EAAS,iBAAA;EACT,KAAA,EAAO,eAAA;EACP,MAAA,EAAQ,8BAAA;AAAA;;;KCtDF,YAAA;EACV,KAAA,GAAQ,KAAA,EAAO,YAAY;AAAA;;;;AFxB7B;;;;AAAoB;AAmCpB;;;KG7BY,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;;;AFfuB;AAQtC;;;EEcE,MA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;;;;AAAwC;AAYxC;;;KISY,aAAA;EACV,OAAA;EACA,GAAA,EAAK,QAAA;EACL,KAAA,UAAe,KAAK;AAAA;AAAA,KAGV,iBAAA,GAAoB,YAAA,GAAe,aAAa;AAAA,KAEhD,yBAAA;EJJA,uEIMV,MAAA,GAAS,WAAW;AAAA;AAAA,KAGV,4BAAA;EJRV;;;;EIaA,KAAA,UAAe,KAAK;AAAA;;;;AJPX;AAGX;cIYa,aAAA,SAAsB,KAAK;EAAA,SAC7B,MAAA;EAAA,SACA,UAAA;EAAA,SACA,IAAA;cAGP,OAAA,UACA,IAAA;IACE,MAAA;IACA,UAAA;IACA,IAAA;EAAA;AAAA;;;;AJlBsB;AAW5B;;;;cI0Ba,WAAA;EAAA;cAMC,MAAA,EAAQ,iBAAA;EJvBT;;;;;;;;;EImDX,kBAAA,GACE,OAAA,EAAS,sBAAA,EACT,OAAA,GAAU,yBAAA,KACT,OAAA,CAAQ,0BAAA;EJ9DP;;;;;;;EIwFJ,qBAAA,GACE,eAAA,EAAiB,IAAA,CAAK,uBAAA,gBACtB,OAAA,GAAU,4BAAA,KACT,YAAA;AAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,355 @@
1
+ //#region src/env.ts
2
+ const ENV_ENDPOINTS = {
3
+ production: {
4
+ apiBaseUrl: "https://consumer.disconetwork.com",
5
+ trackingEndpoint: "https://consumer.disconetwork.com/track/partners_event/"
6
+ },
7
+ staging: {
8
+ apiBaseUrl: "https://consumer.disconetwork-staging.com",
9
+ trackingEndpoint: "https://consumer.disconetwork-staging.com/track/partners_event/"
10
+ }
11
+ };
12
+ /**
13
+ * Derive the environment from a Disco public API key.
14
+ *
15
+ * Public keys are prefixed `disco_pk_<env>_…`, where `<env>` is `live`
16
+ * (→ production) or `sandbox` (→ staging). The key is the single source
17
+ * of truth for which backend the SDK talks to — there is no separate
18
+ * `env` to pass or keep in sync, and a `live` key can't be pointed at
19
+ * staging (or vice versa).
20
+ *
21
+ * Throws on anything that isn't a recognized public key — including a
22
+ * secret (`disco_sk_…`) key, which must never be used in browser code.
23
+ */
24
+ function envFromApiKey(apiKey) {
25
+ if (apiKey.startsWith("disco_pk_live_")) return "production";
26
+ if (apiKey.startsWith("disco_pk_sandbox_")) return "staging";
27
+ throw new Error("Invalid Disco API key: expected a public key prefixed \"disco_pk_live_\" (production) or \"disco_pk_sandbox_\" (staging).");
28
+ }
29
+ //#endregion
30
+ //#region src/TrackingManager.ts
31
+ /**
32
+ * Renderer-agnostic event tracker for Disco recommendation surfaces.
33
+ *
34
+ * Owns:
35
+ * - the dedup set (so repeated display/view events for the same brand
36
+ * don't get re-sent within a session)
37
+ * - the network call to the partner-events endpoint
38
+ * - payload formatting (snake_case keys, BE-friendly datetime)
39
+ *
40
+ * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s
41
+ * `DiscoProvider`) when consuming from a React tree, or instantiate it
42
+ * directly from any other JS environment.
43
+ *
44
+ * `track` is implemented as an instance-bound arrow function so consumers
45
+ * can safely destructure it without losing `this`.
46
+ */
47
+ var TrackingManager = class {
48
+ #endpoint;
49
+ #sessionId;
50
+ #fetch;
51
+ #dedupe = /* @__PURE__ */ new Set();
52
+ constructor(config) {
53
+ this.#endpoint = ENV_ENDPOINTS[config.env].trackingEndpoint;
54
+ this.#sessionId = config.sessionId;
55
+ this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
56
+ }
57
+ /**
58
+ * Send a tracking event. Fire-and-forget — never throws.
59
+ * Failures are logged via `console.error`.
60
+ *
61
+ * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and
62
+ * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).
63
+ */
64
+ track = (event) => {
65
+ if (this.#isDeduped(event)) return;
66
+ this.#fetch(this.#endpoint, {
67
+ method: "POST",
68
+ headers: { "Content-Type": "application/json" },
69
+ body: JSON.stringify(this.#toBody(event))
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
+ };
88
+ switch (event.type) {
89
+ case "BRAND_CLICK":
90
+ case "BRAND_DISPLAY":
91
+ case "BRAND_VIEW": return {
92
+ ...commonEventFields,
93
+ brand_properties: brandProperties(event.brand),
94
+ initiating_target: event.target
95
+ };
96
+ case "ELEMENT_CLICK": return {
97
+ ...commonEventFields,
98
+ brand_properties: event.brand ? brandProperties(event.brand) : void 0,
99
+ initiating_target: event.target
100
+ };
101
+ default: return commonEventFields;
102
+ }
103
+ }
104
+ };
105
+ function brandProperties(brand) {
106
+ return {
107
+ offer_id: brand.offerId,
108
+ advertiser_id: brand.advertiserId,
109
+ insertion_id: brand.insertionId
110
+ };
111
+ }
112
+ //#endregion
113
+ //#region src/DiscoClient.ts
114
+ /**
115
+ * Thrown by `DiscoClient.getRecommendations` when the server returns a
116
+ * non-2xx status. The HTTP status and an optional parsed body are
117
+ * preserved for error UIs and retry logic.
118
+ */
119
+ var DiscoApiError = class extends Error {
120
+ status;
121
+ statusText;
122
+ body;
123
+ constructor(message, info) {
124
+ super(message);
125
+ this.name = "DiscoApiError";
126
+ this.status = info.status;
127
+ this.statusText = info.statusText;
128
+ this.body = info.body;
129
+ }
130
+ };
131
+ /**
132
+ * Typed client for the Disco recommendations API.
133
+ *
134
+ * Renderer-agnostic: this class makes plain HTTP calls and has no
135
+ * React dependency. Wrap it in a Provider (`@disconetwork/react`'s
136
+ * `DiscoProvider`) for use from a React tree, or instantiate it
137
+ * directly from server code, scripts, or tests.
138
+ */
139
+ var DiscoClient = class {
140
+ #env;
141
+ #url;
142
+ #headers;
143
+ #fetch;
144
+ constructor(config) {
145
+ this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
146
+ if ("apiKey" in config) {
147
+ this.#env = envFromApiKey(config.apiKey);
148
+ this.#url = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/core/recommendations/`;
149
+ this.#headers = {
150
+ "x-api-key": config.apiKey,
151
+ "Content-Type": "application/json"
152
+ };
153
+ } else {
154
+ this.#env = config.env;
155
+ const shopId = stripShopGid(config.shopGid);
156
+ this.#url = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;
157
+ this.#headers = { "Content-Type": "application/json" };
158
+ }
159
+ }
160
+ /**
161
+ * POST the recommendations endpoint and return the backend's response
162
+ * **verbatim** — this reflects `ExternalAPIRecommendationView` with no
163
+ * transformation. Pass the result through `mapRecommendationsResponse`
164
+ * if you want the friendly denormalized `RecommendationsResponse`.
165
+ *
166
+ * Throws `DiscoApiError` on non-2xx responses; other failures
167
+ * (network, parse) propagate as-is.
168
+ */
169
+ getRecommendations = async (request, options) => {
170
+ const response = await this.#fetch(this.#url, {
171
+ method: "POST",
172
+ headers: this.#headers,
173
+ body: JSON.stringify(toRequestBody(request)),
174
+ signal: options?.signal
175
+ });
176
+ if (!response.ok) {
177
+ const body = await safeReadBody(response);
178
+ throw new DiscoApiError(`Recommendations request failed: ${response.status} ${response.statusText}`, {
179
+ status: response.status,
180
+ statusText: response.statusText,
181
+ body
182
+ });
183
+ }
184
+ return await response.json();
185
+ };
186
+ /**
187
+ * Create an event tracker for a recommendations response from this client.
188
+ *
189
+ * The tracker uses the same API-key-derived environment as the
190
+ * recommendations call, so sandbox recommendations cannot accidentally emit
191
+ * production tracking events.
192
+ */
193
+ createTrackingManager = (recommendations, options) => new TrackingManager({
194
+ sessionId: recommendations.sessionId,
195
+ env: this.#env,
196
+ fetch: options?.fetch ?? this.#fetch
197
+ });
198
+ };
199
+ function stripShopGid(shopGid) {
200
+ return shopGid.replace("gid://shopify/Shop/", "");
201
+ }
202
+ function toRequestBody(req) {
203
+ return {
204
+ recommendations_data: {
205
+ user_details: req.user && {
206
+ email: req.user.email,
207
+ first_name: req.user.firstName,
208
+ last_name: req.user.lastName,
209
+ phone: req.user.phone
210
+ },
211
+ placement_details: req.placement && {
212
+ display_mode: req.placement.displayMode,
213
+ view: req.placement.view
214
+ },
215
+ order_details: req.order && {
216
+ order_id: req.order.id,
217
+ cost_details: req.order.amount !== void 0 || req.order.currencyCode !== void 0 ? {
218
+ amount: req.order.amount,
219
+ currency_code: req.order.currencyCode
220
+ } : void 0
221
+ },
222
+ purchases: req.purchases?.map((p) => ({
223
+ name: p.name,
224
+ type: p.type,
225
+ variant: p.variant,
226
+ quantity: p.quantity,
227
+ product_id: p.productId,
228
+ cost_details: p.amount !== void 0 || p.currencyCode !== void 0 ? {
229
+ amount: p.amount,
230
+ currency_code: p.currencyCode
231
+ } : void 0
232
+ }))
233
+ },
234
+ running_experiments: req.experiments?.map((e) => ({
235
+ id: e.id,
236
+ variant: e.variant
237
+ })),
238
+ attributes: req.attributes,
239
+ ...req.extras
240
+ };
241
+ }
242
+ async function safeReadBody(response) {
243
+ try {
244
+ return await response.clone().json();
245
+ } catch {
246
+ try {
247
+ return await response.text();
248
+ } catch {
249
+ return;
250
+ }
251
+ }
252
+ }
253
+ //#endregion
254
+ //#region src/recommendationsMapper.ts
255
+ /**
256
+ * Denormalize a raw recommendations response into the public
257
+ * `RecommendationsResponse`: join group entries → recommendations by offer id,
258
+ * order groups by the numeric suffix of their key (group_0, group_1, …), and
259
+ * convert snake_case to camelCase.
260
+ *
261
+ * Pure and side-effect-free — call it on the result of
262
+ * `DiscoClient.getRecommendations` when you want the friendly shape.
263
+ */
264
+ function mapRecommendationsResponse(raw) {
265
+ const recommendations = raw.recommendations ?? {};
266
+ const groupEntries = raw.recommendation_groups ?? {};
267
+ const groupProps = raw.recommendation_group_properties ?? {};
268
+ const orderedKeys = Object.keys(groupEntries).sort((a, b) => numericSuffix(a) - numericSuffix(b));
269
+ const recommendationGroups = [];
270
+ for (const key of orderedKeys) {
271
+ const entries = groupEntries[key];
272
+ const props = groupProps[key];
273
+ if (!entries || !props) continue;
274
+ const recs = [];
275
+ for (const entry of entries) {
276
+ const rawRec = recommendations[entry.offer_id];
277
+ if (!rawRec) continue;
278
+ recs.push({
279
+ id: rawRec.offer.id,
280
+ insertionId: entry.insertion_id,
281
+ advertiser: mapAdvertiser(rawRec.advertiser),
282
+ offer: mapOffer(rawRec.offer)
283
+ });
284
+ }
285
+ recommendationGroups.push({
286
+ heading: props.heading ?? null,
287
+ slotContext: props.slot_context,
288
+ recommendations: recs
289
+ });
290
+ }
291
+ return {
292
+ sessionId: raw.session_id,
293
+ layoutId: raw.layout_id,
294
+ recommendationGroups,
295
+ footer: mapFooter(raw.footer),
296
+ publisherCustomization: raw.publisher_customization ?? null
297
+ };
298
+ }
299
+ function numericSuffix(value) {
300
+ const suffix = value.split("_").pop() ?? "";
301
+ const parsed = Number.parseInt(suffix, 10);
302
+ return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
303
+ }
304
+ function mapAdvertiser(raw) {
305
+ return {
306
+ id: raw.id,
307
+ name: raw.name,
308
+ logoUrl: raw.logo_url,
309
+ description: raw.description ?? null
310
+ };
311
+ }
312
+ function mapOffer(raw) {
313
+ return {
314
+ id: raw.id,
315
+ heading: raw.heading ?? null,
316
+ subheading: raw.subheading ?? null,
317
+ jsonContent: raw.json_content ?? null,
318
+ targetUrl: raw.target_url,
319
+ ctaDetails: mapCtaDetails(raw.cta_details),
320
+ assets: (raw.assets ?? []).map(mapAsset),
321
+ metadata: raw.metadata ?? null,
322
+ disclosureDetails: raw.disclosure_details ?? null
323
+ };
324
+ }
325
+ function mapCtaDetails(raw) {
326
+ return {
327
+ acceptCopy: raw.accept_copy,
328
+ declineCopy: raw.decline_copy,
329
+ transitionCopy: raw.transition_copy ?? null
330
+ };
331
+ }
332
+ function mapAsset(raw) {
333
+ return {
334
+ id: raw.id,
335
+ imageUrl: raw.image_url,
336
+ targetUrl: raw.target_url ?? null
337
+ };
338
+ }
339
+ function mapFooter(raw) {
340
+ return {
341
+ attributionDetails: {
342
+ copy: raw.attribution_details.copy,
343
+ discoLogoUrl: raw.attribution_details.disco_logo_url,
344
+ targetUrl: raw.attribution_details.target_url
345
+ },
346
+ privacyPolicy: {
347
+ copy: raw.privacy_policy.copy,
348
+ targetUrl: raw.privacy_policy.target_url
349
+ }
350
+ };
351
+ }
352
+ //#endregion
353
+ export { DiscoApiError, DiscoClient, envFromApiKey, mapRecommendationsResponse };
354
+
355
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["#endpoint","#sessionId","#fetch","#dedupe","#isDeduped","#toBody","#env","#url","#headers","#fetch"],"sources":["../src/env.ts","../src/TrackingManager.ts","../src/DiscoClient.ts","../src/recommendationsMapper.ts"],"sourcesContent":["/**\n * Disco backend environments. The SDK does not accept arbitrary URLs —\n * consumers pick an environment and the SDK resolves the correct\n * endpoints internally. This keeps partners from pointing the client or\n * tracker at unintended hosts while still supporting staging.\n */\nexport type DiscoEnv = \"production\" | \"staging\";\n\nexport type EnvEndpoints = {\n /** Base URL for the recommendations API (no trailing slash). */\n apiBaseUrl: string;\n /** Absolute URL events are POSTed to. */\n trackingEndpoint: string;\n};\n\nexport const ENV_ENDPOINTS = {\n production: {\n apiBaseUrl: \"https://consumer.disconetwork.com\",\n trackingEndpoint: \"https://consumer.disconetwork.com/track/partners_event/\",\n },\n staging: {\n apiBaseUrl: \"https://consumer.disconetwork-staging.com\",\n trackingEndpoint:\n \"https://consumer.disconetwork-staging.com/track/partners_event/\",\n },\n} as const satisfies Record<DiscoEnv, EnvEndpoints>;\n\nexport const DEFAULT_ENV: DiscoEnv = \"production\";\n\n/**\n * Derive the environment from a Disco public API key.\n *\n * Public keys are prefixed `disco_pk_<env>_…`, where `<env>` is `live`\n * (→ production) or `sandbox` (→ staging). The key is the single source\n * of truth for which backend the SDK talks to — there is no separate\n * `env` to pass or keep in sync, and a `live` key can't be pointed at\n * staging (or vice versa).\n *\n * Throws on anything that isn't a recognized public key — including a\n * secret (`disco_sk_…`) key, which must never be used in browser code.\n */\nexport function envFromApiKey(apiKey: string): DiscoEnv {\n if (apiKey.startsWith(\"disco_pk_live_\")) return \"production\";\n if (apiKey.startsWith(\"disco_pk_sandbox_\")) return \"staging\";\n throw new Error(\n 'Invalid Disco API key: expected a public key prefixed \"disco_pk_live_\" ' +\n '(production) or \"disco_pk_sandbox_\" (staging).',\n );\n}\n","import { ENV_ENDPOINTS, type DiscoEnv } from \"./env.js\";\nimport 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 * Which Disco environment to send events to. The endpoint URL is resolved\n * internally — it is not configurable.\n *\n * Prefer `DiscoClient#createTrackingManager` so tracking uses the same\n * API-key-derived environment as the recommendations call.\n */\n env: DiscoEnv;\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\nexport type EventTracker = {\n track: (event: EventPayload) => void;\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 #sessionId: string;\n readonly #fetch: typeof fetch;\n readonly #dedupe = new Set<string>();\n\n constructor(config: TrackingManagerConfig) {\n this.#endpoint = ENV_ENDPOINTS[config.env].trackingEndpoint;\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\" },\n body: JSON.stringify(this.#toBody(event)),\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 // BE validation can't parse the \"Z\" timezone suffix, so replace it\n // with \"+00:00\".\n event_datetime: new Date().toISOString().replace(\"Z\", \"+00:00\"),\n };\n\n switch (event.type) {\n case \"BRAND_CLICK\":\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 \"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","import { ENV_ENDPOINTS, envFromApiKey, type DiscoEnv } from \"./env.js\";\nimport { TrackingManager, type EventTracker } from \"./TrackingManager.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport type { RawRecommendationsResponse } from \"./recommendationsMapper.js\";\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 * Thrown by `DiscoClient.getRecommendations` when the server returns a\n * non-2xx status. The HTTP status and an optional parsed body are\n * preserved for error UIs and retry logic.\n */\nexport class DiscoApiError extends Error {\n readonly status: number;\n readonly statusText: string;\n readonly body: unknown;\n\n constructor(\n message: string,\n info: {\n status: number;\n statusText: string;\n body?: unknown;\n },\n ) {\n super(message);\n this.name = \"DiscoApiError\";\n this.status = info.status;\n this.statusText = info.statusText;\n this.body = info.body;\n }\n}\n\n/**\n * Typed client for the Disco recommendations API.\n *\n * Renderer-agnostic: this class makes plain HTTP calls and has no\n * React dependency. Wrap it in a Provider (`@disconetwork/react`'s\n * `DiscoProvider`) for use from a React tree, or instantiate it\n * directly from server code, scripts, or tests.\n */\nexport class DiscoClient {\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 = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/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 = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/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 * POST the recommendations endpoint and return the backend's response\n * **verbatim** — this reflects `ExternalAPIRecommendationView` with no\n * transformation. Pass the result through `mapRecommendationsResponse`\n * if you want the friendly denormalized `RecommendationsResponse`.\n *\n * Throws `DiscoApiError` on non-2xx responses; other failures\n * (network, parse) propagate as-is.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RawRecommendationsResponse> => {\n const response = await this.#fetch(this.#url, {\n method: \"POST\",\n headers: this.#headers,\n body: JSON.stringify(toRequestBody(request)),\n signal: options?.signal,\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 (await response.json()) as RawRecommendationsResponse;\n };\n\n /**\n * Create an event tracker for a recommendations response from this client.\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 recommendations: Pick<RecommendationsResponse, \"sessionId\">,\n options?: CreateTrackingManagerOptions,\n ): EventTracker =>\n new TrackingManager({\n sessionId: recommendations.sessionId,\n env: this.#env,\n fetch: options?.fetch ?? this.#fetch,\n });\n}\n\nfunction stripShopGid(shopGid: string): string {\n return shopGid.replace(\"gid://shopify/Shop/\", \"\");\n}\n\n// ─── Request transformation ────────────────────────────────────────────────\n\nfunction toRequestBody(req: RecommendationsRequest): Record<string, unknown> {\n return {\n recommendations_data: {\n user_details: req.user && {\n email: req.user.email,\n first_name: req.user.firstName,\n last_name: req.user.lastName,\n phone: req.user.phone,\n },\n placement_details: req.placement && {\n display_mode: req.placement.displayMode,\n view: req.placement.view,\n },\n order_details: req.order && {\n order_id: req.order.id,\n cost_details:\n req.order.amount !== undefined || req.order.currencyCode !== undefined\n ? {\n amount: req.order.amount,\n currency_code: req.order.currencyCode,\n }\n : undefined,\n },\n purchases: req.purchases?.map((p) => ({\n name: p.name,\n type: p.type,\n variant: p.variant,\n quantity: p.quantity,\n product_id: p.productId,\n cost_details:\n p.amount !== undefined || p.currencyCode !== undefined\n ? { amount: p.amount, currency_code: p.currencyCode }\n : undefined,\n })),\n },\n running_experiments: req.experiments?.map((e) => ({\n id: e.id,\n variant: e.variant,\n })),\n attributes: req.attributes,\n ...req.extras,\n };\n}\n\n// ─── Misc ──────────────────────────────────────────────────────────────────\n\nasync 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 * Raw wire types for the recommendations endpoint and the opt-in mapper\n * that denormalizes them into the public `RecommendationsResponse`.\n *\n * `DiscoClient.getRecommendations` returns `RawRecommendationsResponse`\n * verbatim — it reflects exactly what the backend's\n * `ExternalAPIRecommendationView` returns, with no transformation. Callers\n * that want the friendlier denormalized shape pass that raw value through\n * `mapRecommendationsResponse`. Keeping the two separate means the SDK's\n * transport contract is just \"the server's response\", and the (drift-prone)\n * mapping is an explicit, swappable step.\n */\n\nimport type {\n Advertiser,\n Footer,\n Offer,\n OfferAsset,\n OfferCtaDetails,\n Recommendation,\n RecommendationGroup,\n RecommendationsResponse,\n} from \"./recommendations.js\";\n\n// ─── Raw wire shape ──────────────────────────────────────────────────────────\n//\n// The endpoint returns a *normalized* payload: a flat map of recommendations\n// keyed by offer id, separate per-group entry lists that reference those offer\n// ids, and separate per-group properties. Plus assorted top-level fields the\n// proxy adds (widget_type, etc.) that the mapper doesn't need but that other\n// consumers (e.g. the script SDK) read directly off the raw response.\n\nexport type RawRecommendationsResponse = {\n session_id: string;\n layout_id: string;\n /** Map of offer id → recommendation. */\n recommendations?: Record<string, RawRecommendation> | null;\n /** Map of group key → ordered entry list referencing offer ids. */\n recommendation_groups?: Record<string, RawGroupEntry[]> | null;\n /** Map of group key → group display properties. */\n recommendation_group_properties?: Record<string, RawGroupProperties> | null;\n footer: RawFooter;\n publisher_customization?: RawPublisherCustomization | null;\n // Proxy-added top-level fields. Not used by the mapper; surfaced so raw\n // consumers can read them. Open-ended — see ExternalAPIRecommendationView.\n is_using_cmos_recommendations?: boolean;\n widget_type?: string;\n widget_mode?: string;\n widget_version?: string;\n running_experiments?: unknown[];\n};\n\nexport type RawRecommendation = {\n advertiser: RawAdvertiser;\n offer: RawOffer;\n};\n\nexport type RawGroupEntry = {\n insertion_order: number;\n insertion_id: string;\n offer_id: string;\n advertiser_id: string;\n};\n\nexport type RawGroupProperties = {\n heading?: string | null;\n slot_context: string;\n};\n\nexport type RawAdvertiser = {\n id: string;\n name: string;\n logo_url: string;\n description?: string | null;\n};\n\nexport type RawOffer = {\n id: string;\n heading?: string | null;\n subheading?: string | null;\n json_content?: Record<string, unknown> | null;\n target_url: string;\n cta_details: RawOfferCtaDetails;\n assets?: RawOfferAsset[] | null;\n metadata?: Record<string, unknown> | null;\n disclosure_details?: Record<string, unknown> | null;\n};\n\nexport type RawOfferCtaDetails = {\n accept_copy: string;\n decline_copy: string;\n transition_copy?: string | null;\n};\n\nexport type RawOfferAsset = {\n id: string;\n image_url: string;\n target_url?: string | null;\n};\n\nexport type RawFooter = {\n attribution_details: {\n copy: string;\n disco_logo_url: string;\n target_url: string;\n };\n privacy_policy: {\n copy: string;\n target_url: string;\n };\n};\n\nexport type RawPublisherCustomization = Record<string, Record<string, string>>;\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Denormalize a raw recommendations response into the public\n * `RecommendationsResponse`: join group entries → recommendations by offer id,\n * order groups by the numeric suffix of their key (group_0, group_1, …), and\n * convert snake_case to camelCase.\n *\n * Pure and side-effect-free — call it on the result of\n * `DiscoClient.getRecommendations` when you want the friendly shape.\n */\nexport function mapRecommendationsResponse(\n raw: RawRecommendationsResponse,\n): RecommendationsResponse {\n const recommendations = raw.recommendations ?? {};\n const groupEntries = raw.recommendation_groups ?? {};\n const groupProps = raw.recommendation_group_properties ?? {};\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 rawRec = recommendations[entry.offer_id];\n if (!rawRec) continue; // entry references an absent recommendation\n recs.push({\n id: rawRec.offer.id,\n insertionId: entry.insertion_id,\n advertiser: mapAdvertiser(rawRec.advertiser),\n offer: mapOffer(rawRec.offer),\n });\n }\n\n recommendationGroups.push({\n heading: props.heading ?? null,\n slotContext: props.slot_context,\n recommendations: recs,\n });\n }\n\n return {\n sessionId: raw.session_id,\n layoutId: raw.layout_id,\n recommendationGroups,\n footer: mapFooter(raw.footer),\n publisherCustomization: raw.publisher_customization ?? null,\n };\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\nfunction mapAdvertiser(raw: RawAdvertiser): Advertiser {\n return {\n id: raw.id,\n name: raw.name,\n logoUrl: raw.logo_url,\n description: raw.description ?? null,\n };\n}\n\nfunction mapOffer(raw: RawOffer): Offer {\n return {\n id: raw.id,\n heading: raw.heading ?? null,\n subheading: raw.subheading ?? null,\n jsonContent: raw.json_content ?? null,\n targetUrl: raw.target_url,\n ctaDetails: mapCtaDetails(raw.cta_details),\n assets: (raw.assets ?? []).map(mapAsset),\n metadata: raw.metadata ?? null,\n disclosureDetails: raw.disclosure_details ?? null,\n };\n}\n\nfunction mapCtaDetails(raw: RawOfferCtaDetails): OfferCtaDetails {\n return {\n acceptCopy: raw.accept_copy,\n declineCopy: raw.decline_copy,\n transitionCopy: raw.transition_copy ?? null,\n };\n}\n\nfunction mapAsset(raw: RawOfferAsset): OfferAsset {\n return {\n id: raw.id,\n imageUrl: raw.image_url,\n targetUrl: raw.target_url ?? null,\n };\n}\n\nfunction mapFooter(raw: RawFooter): Footer {\n return {\n attributionDetails: {\n copy: raw.attribution_details.copy,\n discoLogoUrl: raw.attribution_details.disco_logo_url,\n targetUrl: raw.attribution_details.target_url,\n },\n privacyPolicy: {\n copy: raw.privacy_policy.copy,\n targetUrl: raw.privacy_policy.target_url,\n },\n };\n}\n"],"mappings":";AAeA,MAAa,gBAAgB;CAC3B,YAAY;EACV,YAAY;EACZ,kBAAkB;CACpB;CACA,SAAS;EACP,YAAY;EACZ,kBACE;CACJ;AACF;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,QAA0B;CACtD,IAAI,OAAO,WAAW,gBAAgB,GAAG,OAAO;CAChD,IAAI,OAAO,WAAW,mBAAmB,GA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ACL,IAAI,IAAI;EACR,SAAS,IAAI,WAAW;EACxB,YAAY,IAAI,cAAc;EAC9B,aAAa,IAAI,gBAAgB;EACjC,WAAW,IAAI;EACf,YAAY,cAAc,IAAI,WAAW;EACzC,SAAS,IAAI,UAAU,CAAC,GAAG,IAAI,QAAQ;EACvC,UAAU,IAAI,YAAY;EAC1B,mBAAmB,IAAI,sBAAsB;CAC/C;AACF;AAEA,SAAS,cAAc,KAA0C;CAC/D,OAAO;EACL,YAAY,IAAI;EAChB,aAAa,IAAI;EACjB,gBAAgB,IAAI,mBAAmB;CACzC;AACF;AAEA,SAAS,SAAS,KAAgC;CAChD,OAAO;EACL,IAAI,IAAI;EACR,UAAU,IAAI;EACd,WAAW,IAAI,cAAc;CAC/B;AACF;AAEA,SAAS,UAAU,KAAwB;CACzC,OAAO;EACL,oBAAoB;GAClB,MAAM,IAAI,oBAAoB;GAC9B,cAAc,IAAI,oBAAoB;GACtC,WAAW,IAAI,oBAAoB;EACrC;EACA,eAAe;GACb,MAAM,IAAI,eAAe;GACzB,WAAW,IAAI,eAAe;EAChC;CACF;AACF"}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@disconetwork/core",
3
+ "version": "0.0.1",
4
+ "description": "Core package for disco-js.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "restricted"
21
+ },
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^22.15.3",
27
+ "eslint": "^9.39.1",
28
+ "tsdown": "^0.22.0",
29
+ "typescript": "5.9.2",
30
+ "vitest": "^4.1.7",
31
+ "@repo/eslint-config": "0.0.0",
32
+ "@repo/typescript-config": "0.0.0"
33
+ },
34
+ "scripts": {
35
+ "build": "tsdown",
36
+ "dev": "tsdown --watch",
37
+ "check-types": "tsc --noEmit",
38
+ "lint": "eslint . --max-warnings 0",
39
+ "test": "vitest run",
40
+ "test:watch": "vitest",
41
+ "clean": "rm -rf dist"
42
+ }
43
+ }