@disconetwork/core 0.0.16 → 0.0.18
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.
- package/README.md +14 -12
- package/dist/TrackingManager.d.ts +64 -0
- package/dist/TrackingManager.d.ts.map +1 -0
- package/dist/TrackingManager.js +114 -0
- package/dist/TrackingManager.js.map +1 -0
- package/dist/api/generated/events/client/client.gen.js +176 -0
- package/dist/api/generated/events/client/client.gen.js.map +1 -0
- package/dist/api/generated/events/client/utils.gen.js +179 -0
- package/dist/api/generated/events/client/utils.gen.js.map +1 -0
- package/dist/api/generated/events/client.gen.js +8 -0
- package/dist/api/generated/events/client.gen.js.map +1 -0
- package/dist/api/generated/events/core/auth.gen.js +12 -0
- package/dist/api/generated/events/core/auth.gen.js.map +1 -0
- package/dist/api/generated/events/core/bodySerializer.gen.js +6 -0
- package/dist/api/generated/events/core/bodySerializer.gen.js.map +1 -0
- package/dist/api/generated/events/core/pathSerializer.gen.js +82 -0
- package/dist/api/generated/events/core/pathSerializer.gen.js.map +1 -0
- package/dist/api/generated/events/core/serverSentEvents.gen.js +95 -0
- package/dist/api/generated/events/core/serverSentEvents.gen.js.map +1 -0
- package/dist/api/generated/events/core/utils.gen.js +78 -0
- package/dist/api/generated/events/core/utils.gen.js.map +1 -0
- package/dist/api/generated/events/sdk.gen.js +31 -0
- package/dist/api/generated/events/sdk.gen.js.map +1 -0
- package/dist/api/generated/events/zod.gen.js +197 -0
- package/dist/api/generated/events/zod.gen.js.map +1 -0
- package/dist/api/generated/recommendations/client/client.gen.js +176 -0
- package/dist/api/generated/recommendations/client/client.gen.js.map +1 -0
- package/dist/api/generated/recommendations/client/utils.gen.js +179 -0
- package/dist/api/generated/recommendations/client/utils.gen.js.map +1 -0
- package/dist/api/generated/recommendations/client.gen.js +8 -0
- package/dist/api/generated/recommendations/client.gen.js.map +1 -0
- package/dist/api/generated/recommendations/core/auth.gen.js +12 -0
- package/dist/api/generated/recommendations/core/auth.gen.js.map +1 -0
- package/dist/api/generated/recommendations/core/bodySerializer.gen.js +6 -0
- package/dist/api/generated/recommendations/core/bodySerializer.gen.js.map +1 -0
- package/dist/api/generated/recommendations/core/pathSerializer.gen.js +82 -0
- package/dist/api/generated/recommendations/core/pathSerializer.gen.js.map +1 -0
- package/dist/api/generated/recommendations/core/serverSentEvents.gen.js +95 -0
- package/dist/api/generated/recommendations/core/serverSentEvents.gen.js.map +1 -0
- package/dist/api/generated/recommendations/core/utils.gen.js +78 -0
- package/dist/api/generated/recommendations/core/utils.gen.js.map +1 -0
- package/dist/api/generated/recommendations/sdk.gen.js +35 -0
- package/dist/api/generated/recommendations/sdk.gen.js.map +1 -0
- package/dist/api/generated/recommendations/types.gen.d.ts +32 -0
- package/dist/api/generated/recommendations/types.gen.d.ts.map +1 -0
- package/dist/api/generated/recommendations/zod.gen.js +407 -0
- package/dist/api/generated/recommendations/zod.gen.js.map +1 -0
- package/dist/api/index.js +60 -0
- package/dist/api/index.js.map +1 -0
- package/dist/apiKey.js +13 -0
- package/dist/apiKey.js.map +1 -0
- package/dist/config.js +38 -0
- package/dist/config.js.map +1 -0
- package/dist/env.d.ts +5 -0
- package/dist/env.d.ts.map +1 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +76 -0
- package/dist/errors.js.map +1 -0
- package/dist/events/dedupe.d.ts +15 -0
- package/dist/events/dedupe.d.ts.map +1 -0
- package/dist/events/dedupe.js +34 -0
- package/dist/events/dedupe.js.map +1 -0
- package/dist/events/eventMapping.js +88 -0
- package/dist/events/eventMapping.js.map +1 -0
- package/dist/external/DiscoClient.d.ts +88 -0
- package/dist/external/DiscoClient.d.ts.map +1 -0
- package/dist/external/DiscoClient.js +122 -0
- package/dist/external/DiscoClient.js.map +1 -0
- package/dist/external/recommendations.d.ts +186 -0
- package/dist/external/recommendations.d.ts.map +1 -0
- package/dist/external/recommendationsTransforms.js +209 -0
- package/dist/external/recommendationsTransforms.js.map +1 -0
- package/dist/index.d.ts +8 -97
- package/dist/index.js +3 -1769
- package/dist/internal/InternalDiscoClient.d.ts +129 -0
- package/dist/internal/InternalDiscoClient.d.ts.map +1 -0
- package/dist/internal/InternalDiscoClient.js +137 -0
- package/dist/internal/InternalDiscoClient.js.map +1 -0
- package/dist/internal/denormalize.d.ts +18 -0
- package/dist/internal/denormalize.d.ts.map +1 -0
- package/dist/internal/denormalize.js +49 -0
- package/dist/internal/denormalize.js.map +1 -0
- package/dist/internal/recommendations.d.ts +88 -0
- package/dist/internal/recommendations.d.ts.map +1 -0
- package/dist/internal/recommendationsMapper.js +68 -0
- package/dist/internal/recommendationsMapper.js.map +1 -0
- package/dist/internal/recommendationsRequestMapper.js +114 -0
- package/dist/internal/recommendationsRequestMapper.js.map +1 -0
- package/dist/internal/screens.d.ts +77 -0
- package/dist/internal/screens.d.ts.map +1 -0
- package/dist/internal/screens.js +79 -0
- package/dist/internal/screens.js.map +1 -0
- package/dist/internal.d.ts +11 -399
- package/dist/internal.js +5 -560
- package/dist/lib/case.js +26 -0
- package/dist/lib/case.js.map +1 -0
- package/dist/lib/http.js +21 -0
- package/dist/lib/http.js.map +1 -0
- package/dist/lib/primitives.js +23 -0
- package/dist/lib/primitives.js.map +1 -0
- package/dist/lib/schemas.js +25 -0
- package/dist/lib/schemas.js.map +1 -0
- package/dist/package.js +7 -0
- package/dist/package.js.map +1 -0
- package/dist/sdkIdentity.d.ts +9 -0
- package/dist/sdkIdentity.d.ts.map +1 -0
- package/dist/sdkIdentity.js +16 -0
- package/dist/sdkIdentity.js.map +1 -0
- package/dist/types.d.ts +91 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +3 -3
- package/dist/errors-DpKOKpT8.d.ts +0 -363
- package/dist/errors-DpKOKpT8.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/internal.d.ts.map +0 -1
- package/dist/internal.js.map +0 -1
- package/dist/recommendationsTransforms-O4CTnnnS.js +0 -748
- package/dist/recommendationsTransforms-O4CTnnnS.js.map +0 -1
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { SdkIdentity } from "../sdkIdentity.js";
|
|
2
|
+
import { EventTracker } from "../types.js";
|
|
3
|
+
import { DiscoEnv } from "../env.js";
|
|
4
|
+
import { RecommendationsRequest, RecommendationsResponse } from "./recommendations.js";
|
|
5
|
+
|
|
6
|
+
//#region src/internal/InternalDiscoClient.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Per-environment base URL for the internal/proxy backend — the legacy server
|
|
9
|
+
* that orchestrates and forwards to the downstream services. Both the
|
|
10
|
+
* recommendations and tracking endpoints sit under this origin, routed by path
|
|
11
|
+
* (the client appends `/core/recommendations/…` and `/track/partners_event/`).
|
|
12
|
+
*/
|
|
13
|
+
declare const INTERNAL_BASE_URL: {
|
|
14
|
+
readonly production: "https://consumer.disconetwork.com";
|
|
15
|
+
readonly staging: "https://consumer.disconetwork-staging.com";
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Authenticate with a scoped public API key. Sent as the `x-api-key`
|
|
19
|
+
* header against the unified `/core/recommendations/` endpoint. Both
|
|
20
|
+
* `disco_pk_live_…` and `disco_pk_sandbox_…` keys use production; there is
|
|
21
|
+
* no separate `env` to set.
|
|
22
|
+
*
|
|
23
|
+
* Use this from partner apps and server-side code that hold a key.
|
|
24
|
+
*
|
|
25
|
+
* Set `surface: "shopify"` from a Shopify UI extension to send the request to
|
|
26
|
+
* the `/core/recommendations/shopify/` route instead. The route marks the
|
|
27
|
+
* request as coming from an extension; the channel still comes from the key.
|
|
28
|
+
*/
|
|
29
|
+
type ApiKeyConfig = {
|
|
30
|
+
apiKey: string;
|
|
31
|
+
surface?: "shopify";
|
|
32
|
+
fetch?: typeof fetch;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Authenticate by Shopify shop — for surfaces that must not embed a key,
|
|
36
|
+
* notably the App-Store-deployed checkout extension. The request hits the
|
|
37
|
+
* `/core/recommendations/shop_gid/<id>/` proxy with **no** API key; the
|
|
38
|
+
* backend resolves the publisher from the shop and injects the key
|
|
39
|
+
* server-side.
|
|
40
|
+
*
|
|
41
|
+
* `env` is required here to select the backend for shop-based authentication.
|
|
42
|
+
* `shopGid` may be a full `gid://shopify/Shop/<id>` or the bare id.
|
|
43
|
+
*/
|
|
44
|
+
type ShopGidConfig = {
|
|
45
|
+
shopGid: string;
|
|
46
|
+
env: DiscoEnv;
|
|
47
|
+
fetch?: typeof fetch;
|
|
48
|
+
};
|
|
49
|
+
type DiscoClientConfig = (ApiKeyConfig | ShopGidConfig) & {
|
|
50
|
+
sdk?: SdkIdentity;
|
|
51
|
+
};
|
|
52
|
+
type GetRecommendationsOptions = {
|
|
53
|
+
/** Forwarded to `fetch` so consumers can cancel in-flight requests. */signal?: AbortSignal;
|
|
54
|
+
};
|
|
55
|
+
type CreateTrackingManagerOptions = {
|
|
56
|
+
/**
|
|
57
|
+
* Override the fetch implementation used by the tracker. Defaults to the
|
|
58
|
+
* same fetch implementation configured on the client.
|
|
59
|
+
*/
|
|
60
|
+
fetch?: typeof fetch;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Result of `getRecommendationsWithTracker`: the mapped recommendations
|
|
64
|
+
* response plus a tracker already bound to its session.
|
|
65
|
+
*/
|
|
66
|
+
type RecommendationsWithTracker = {
|
|
67
|
+
/**
|
|
68
|
+
* The mapped, denormalized recommendations response — the same friendly
|
|
69
|
+
* camelCase shape `getRecommendations` returns.
|
|
70
|
+
*/
|
|
71
|
+
data: RecommendationsResponse; /** Event tracker bound to this response's session. */
|
|
72
|
+
tracker: EventTracker;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Internal client for the legacy **proxy** recommendations endpoint
|
|
76
|
+
* (`/core/recommendations/` on the backend), which orchestrates placement,
|
|
77
|
+
* experiments, layout, and `publisher_customization` server-side and supports
|
|
78
|
+
* `shopGid` auth for first-party surfaces (e.g. the Shopify checkout
|
|
79
|
+
* extension).
|
|
80
|
+
*
|
|
81
|
+
* First-party / legacy only — exported from `@disconetwork/core/internal`.
|
|
82
|
+
* External partners use the `DiscoClient` from the package root, which talks
|
|
83
|
+
* directly to `disco-recommendations-api`.
|
|
84
|
+
*
|
|
85
|
+
* Renderer-agnostic: this class makes plain HTTP calls and has no React
|
|
86
|
+
* dependency.
|
|
87
|
+
*/
|
|
88
|
+
declare class InternalDiscoClient {
|
|
89
|
+
#private;
|
|
90
|
+
get env(): DiscoEnv;
|
|
91
|
+
constructor(config: DiscoClientConfig);
|
|
92
|
+
/**
|
|
93
|
+
* Fetch recommendations for the given request.
|
|
94
|
+
*
|
|
95
|
+
* Validates and transforms the friendly camelCase `request` into the wire
|
|
96
|
+
* body, POSTs it, then validates and denormalizes the response into the
|
|
97
|
+
* friendly `RecommendationsResponse`. The snake_case wire format is fully
|
|
98
|
+
* encapsulated — callers never see it.
|
|
99
|
+
*
|
|
100
|
+
* Throws `DiscoValidationError` if the request or response fails schema
|
|
101
|
+
* validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`
|
|
102
|
+
* if the request can't reach the server (an abort rejects with the native
|
|
103
|
+
* `AbortError`). Parse failures propagate as-is.
|
|
104
|
+
*/
|
|
105
|
+
getRecommendations: (request: RecommendationsRequest, options?: GetRecommendationsOptions) => Promise<RecommendationsResponse>;
|
|
106
|
+
/**
|
|
107
|
+
* Fetch recommendations and create a session-bound tracker in one call.
|
|
108
|
+
*
|
|
109
|
+
* Composition convenience over `getRecommendations` + `createTrackingManager`:
|
|
110
|
+
* it derives the tracker's session from the response so callers don't have to
|
|
111
|
+
* thread the session id through themselves (and can't bind a tracker to the
|
|
112
|
+
* wrong session). The returned `data` is the mapped `RecommendationsResponse`.
|
|
113
|
+
*
|
|
114
|
+
* Throws `DiscoValidationError` / `DiscoApiError` the same as
|
|
115
|
+
* `getRecommendations`.
|
|
116
|
+
*/
|
|
117
|
+
getRecommendationsWithTracker: (request: RecommendationsRequest, options?: GetRecommendationsOptions & CreateTrackingManagerOptions) => Promise<RecommendationsWithTracker>;
|
|
118
|
+
/**
|
|
119
|
+
* Create an event tracker bound to a recommendations session (the `sessionId`
|
|
120
|
+
* from a `getRecommendations` response).
|
|
121
|
+
*
|
|
122
|
+
* The tracker uses the same environment as the recommendations call.
|
|
123
|
+
* Both live and sandbox public keys use production.
|
|
124
|
+
*/
|
|
125
|
+
createTrackingManager: (sessionId: string, options?: CreateTrackingManagerOptions) => EventTracker;
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
export { ApiKeyConfig, CreateTrackingManagerOptions, DiscoClientConfig, GetRecommendationsOptions, INTERNAL_BASE_URL, InternalDiscoClient, RecommendationsWithTracker, ShopGidConfig };
|
|
129
|
+
//# sourceMappingURL=InternalDiscoClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InternalDiscoClient.d.ts","names":[],"sources":["../../src/internal/InternalDiscoClient.ts"],"mappings":";;;;;;;;AAoBA;;;;cAAa,iBAAA;EAAA,SAGgC,UAAA;EAAA,SAAA,OAAA;AAAA;;;;;;;AAiBvB;AAatB;;;;;KAhBY,YAAA;EACV,MAAA;EACA,OAAA;EACA,KAAA,UAAe,KAAK;AAAA;AAgBA;AAGtB;;;;;;;;;AAHsB,KAHV,aAAA;EACV,OAAA;EACA,GAAA,EAAK,QAAA;EACL,KAAA,UAAe,KAAK;AAAA;AAAA,KAGV,iBAAA,IAAqB,YAAA,GAAe,aAAA;EAC9C,GAAA,GAAM,WAAA;AAAA;AAAA,KAGI,yBAAA;EAEU,uEAApB,MAAA,GAAS,WAAW;AAAA;AAAA,KAGV,4BAAA;EAKV;AAAoB;AAOtB;;EAPE,KAAA,UAAe,KAAK;AAAA;;;;;KAOV,0BAAA;EAOW;AAiBvB;;;EAnBE,IAAA,EAAM,uBAAA,EA8Bc;EA5BpB,OAAA,EAAS,YAAY;AAAA;;;;;;;;;;;;;;;cAiBV,mBAAA;EAAA;MAOP,GAAA,CAAA,GAAO,QAAA;cAIC,MAAA,EAAQ,iBAAA;EAqCT;;;;;;;;;;;;;EADX,kBAAA,GACE,OAAA,EAAS,sBAAA,EACT,OAAA,GAAU,yBAAA,KACT,OAAA,CAAQ,uBAAA;EAgEX;;;;;;AAGe;;;;;EAvBf,6BAAA,GACE,OAAA,EAAS,sBAAA,EACT,OAAA,GAAU,yBAAA,GAA4B,4BAAA,KACrC,OAAA,CAAQ,0BAAA;;;;;;;;EAiBX,qBAAA,GACE,SAAA,UACA,OAAA,GAAU,4BAAA,KACT,YAAA;AAAA"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { getSdkHeaders } from "../sdkIdentity.js";
|
|
2
|
+
import { validatePublicApiKey } from "../apiKey.js";
|
|
3
|
+
import { DiscoApiError, DiscoNetworkError, isAbortError } from "../errors.js";
|
|
4
|
+
import { safeReadBody } from "../lib/http.js";
|
|
5
|
+
import { TrackingManager } from "../TrackingManager.js";
|
|
6
|
+
import { mapRecommendationsResponse } from "./recommendationsMapper.js";
|
|
7
|
+
import { transformRequest } from "./recommendationsRequestMapper.js";
|
|
8
|
+
//#region src/internal/InternalDiscoClient.ts
|
|
9
|
+
/**
|
|
10
|
+
* Per-environment base URL for the internal/proxy backend — the legacy server
|
|
11
|
+
* that orchestrates and forwards to the downstream services. Both the
|
|
12
|
+
* recommendations and tracking endpoints sit under this origin, routed by path
|
|
13
|
+
* (the client appends `/core/recommendations/…` and `/track/partners_event/`).
|
|
14
|
+
*/
|
|
15
|
+
const INTERNAL_BASE_URL = {
|
|
16
|
+
production: "https://consumer.disconetwork.com",
|
|
17
|
+
staging: "https://consumer.disconetwork-staging.com"
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Internal client for the legacy **proxy** recommendations endpoint
|
|
21
|
+
* (`/core/recommendations/` on the backend), which orchestrates placement,
|
|
22
|
+
* experiments, layout, and `publisher_customization` server-side and supports
|
|
23
|
+
* `shopGid` auth for first-party surfaces (e.g. the Shopify checkout
|
|
24
|
+
* extension).
|
|
25
|
+
*
|
|
26
|
+
* First-party / legacy only — exported from `@disconetwork/core/internal`.
|
|
27
|
+
* External partners use the `DiscoClient` from the package root, which talks
|
|
28
|
+
* directly to `disco-recommendations-api`.
|
|
29
|
+
*
|
|
30
|
+
* Renderer-agnostic: this class makes plain HTTP calls and has no React
|
|
31
|
+
* dependency.
|
|
32
|
+
*/
|
|
33
|
+
var InternalDiscoClient = class {
|
|
34
|
+
#env;
|
|
35
|
+
#url;
|
|
36
|
+
#headers;
|
|
37
|
+
#sdk;
|
|
38
|
+
#fetch;
|
|
39
|
+
get env() {
|
|
40
|
+
return this.#env;
|
|
41
|
+
}
|
|
42
|
+
constructor(config) {
|
|
43
|
+
this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
44
|
+
this.#sdk = config.sdk ? { ...config.sdk } : void 0;
|
|
45
|
+
if ("apiKey" in config) {
|
|
46
|
+
validatePublicApiKey(config.apiKey);
|
|
47
|
+
this.#env = "production";
|
|
48
|
+
const path = config.surface === "shopify" ? "shopify/" : "";
|
|
49
|
+
this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/${path}`;
|
|
50
|
+
this.#headers = {
|
|
51
|
+
"x-api-key": config.apiKey,
|
|
52
|
+
"Content-Type": "application/json"
|
|
53
|
+
};
|
|
54
|
+
} else {
|
|
55
|
+
this.#env = config.env;
|
|
56
|
+
const shopId = stripShopGid(config.shopGid);
|
|
57
|
+
this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;
|
|
58
|
+
this.#headers = { "Content-Type": "application/json" };
|
|
59
|
+
}
|
|
60
|
+
Object.assign(this.#headers, getSdkHeaders(this.#sdk));
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Fetch recommendations for the given request.
|
|
64
|
+
*
|
|
65
|
+
* Validates and transforms the friendly camelCase `request` into the wire
|
|
66
|
+
* body, POSTs it, then validates and denormalizes the response into the
|
|
67
|
+
* friendly `RecommendationsResponse`. The snake_case wire format is fully
|
|
68
|
+
* encapsulated — callers never see it.
|
|
69
|
+
*
|
|
70
|
+
* Throws `DiscoValidationError` if the request or response fails schema
|
|
71
|
+
* validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`
|
|
72
|
+
* if the request can't reach the server (an abort rejects with the native
|
|
73
|
+
* `AbortError`). Parse failures propagate as-is.
|
|
74
|
+
*/
|
|
75
|
+
getRecommendations = async (request, options) => {
|
|
76
|
+
const body = JSON.stringify(transformRequest(request));
|
|
77
|
+
let response;
|
|
78
|
+
try {
|
|
79
|
+
response = await this.#fetch(this.#url, {
|
|
80
|
+
method: "POST",
|
|
81
|
+
headers: this.#headers,
|
|
82
|
+
body,
|
|
83
|
+
signal: options?.signal
|
|
84
|
+
});
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (isAbortError(error)) throw error;
|
|
87
|
+
throw new DiscoNetworkError("Recommendations request failed to reach the server", error);
|
|
88
|
+
}
|
|
89
|
+
if (!response.ok) {
|
|
90
|
+
const body = await safeReadBody(response);
|
|
91
|
+
throw new DiscoApiError(`Recommendations request failed: ${response.status} ${response.statusText}`, {
|
|
92
|
+
status: response.status,
|
|
93
|
+
statusText: response.statusText,
|
|
94
|
+
body
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return mapRecommendationsResponse(await response.json());
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Fetch recommendations and create a session-bound tracker in one call.
|
|
101
|
+
*
|
|
102
|
+
* Composition convenience over `getRecommendations` + `createTrackingManager`:
|
|
103
|
+
* it derives the tracker's session from the response so callers don't have to
|
|
104
|
+
* thread the session id through themselves (and can't bind a tracker to the
|
|
105
|
+
* wrong session). The returned `data` is the mapped `RecommendationsResponse`.
|
|
106
|
+
*
|
|
107
|
+
* Throws `DiscoValidationError` / `DiscoApiError` the same as
|
|
108
|
+
* `getRecommendations`.
|
|
109
|
+
*/
|
|
110
|
+
getRecommendationsWithTracker = async (request, options) => {
|
|
111
|
+
const data = await this.getRecommendations(request, { signal: options?.signal });
|
|
112
|
+
return {
|
|
113
|
+
data,
|
|
114
|
+
tracker: this.createTrackingManager(data.sessionId, { fetch: options?.fetch })
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* Create an event tracker bound to a recommendations session (the `sessionId`
|
|
119
|
+
* from a `getRecommendations` response).
|
|
120
|
+
*
|
|
121
|
+
* The tracker uses the same environment as the recommendations call.
|
|
122
|
+
* Both live and sandbox public keys use production.
|
|
123
|
+
*/
|
|
124
|
+
createTrackingManager = (sessionId, options) => new TrackingManager({
|
|
125
|
+
sessionId,
|
|
126
|
+
endpoint: `${INTERNAL_BASE_URL[this.#env]}/track/partners_event/`,
|
|
127
|
+
fetch: options?.fetch ?? this.#fetch,
|
|
128
|
+
sdk: this.#sdk
|
|
129
|
+
});
|
|
130
|
+
};
|
|
131
|
+
function stripShopGid(shopGid) {
|
|
132
|
+
return shopGid.replace("gid://shopify/Shop/", "");
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
export { INTERNAL_BASE_URL, InternalDiscoClient };
|
|
136
|
+
|
|
137
|
+
//# sourceMappingURL=InternalDiscoClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InternalDiscoClient.js","names":["#env","#url","#headers","#sdk","#fetch"],"sources":["../../src/internal/InternalDiscoClient.ts"],"sourcesContent":["import { validatePublicApiKey } from \"../apiKey.js\";\nimport type { DiscoEnv } from \"../env.js\";\nimport { DiscoApiError, DiscoNetworkError, isAbortError } from \"../errors.js\";\nimport { safeReadBody } from \"../lib/http.js\";\nimport { TrackingManager } from \"../TrackingManager.js\";\nimport { getSdkHeaders, type SdkIdentity } from \"../sdkIdentity.js\";\nimport type { EventTracker } from \"../types.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport { mapRecommendationsResponse } from \"./recommendationsMapper.js\";\nimport { transformRequest } from \"./recommendationsRequestMapper.js\";\n\n/**\n * Per-environment base URL for the internal/proxy backend — the legacy server\n * that orchestrates and forwards to the downstream services. Both the\n * recommendations and tracking endpoints sit under this origin, routed by path\n * (the client appends `/core/recommendations/…` and `/track/partners_event/`).\n */\nexport const INTERNAL_BASE_URL = {\n production: \"https://consumer.disconetwork.com\",\n staging: \"https://consumer.disconetwork-staging.com\",\n} as const satisfies Record<DiscoEnv, string>;\n\n/**\n * Authenticate with a scoped public API key. Sent as the `x-api-key`\n * header against the unified `/core/recommendations/` endpoint. Both\n * `disco_pk_live_…` and `disco_pk_sandbox_…` keys use production; there is\n * no separate `env` to set.\n *\n * Use this from partner apps and server-side code that hold a key.\n *\n * Set `surface: \"shopify\"` from a Shopify UI extension to send the request to\n * the `/core/recommendations/shopify/` route instead. The route marks the\n * request as coming from an extension; the channel still comes from the key.\n */\nexport type ApiKeyConfig = {\n apiKey: string;\n surface?: \"shopify\";\n fetch?: typeof fetch;\n};\n\n/**\n * Authenticate by Shopify shop — for surfaces that must not embed a key,\n * notably the App-Store-deployed checkout extension. The request hits the\n * `/core/recommendations/shop_gid/<id>/` proxy with **no** API key; the\n * backend resolves the publisher from the shop and injects the key\n * server-side.\n *\n * `env` is required here to select the backend for shop-based authentication.\n * `shopGid` may be a full `gid://shopify/Shop/<id>` or the bare id.\n */\nexport type ShopGidConfig = {\n shopGid: string;\n env: DiscoEnv;\n fetch?: typeof fetch;\n};\n\nexport type DiscoClientConfig = (ApiKeyConfig | ShopGidConfig) & {\n sdk?: SdkIdentity;\n};\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 #sdk: SdkIdentity | undefined;\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 this.#sdk = config.sdk ? { ...config.sdk } : undefined;\n\n if (\"apiKey\" in config) {\n validatePublicApiKey(config.apiKey);\n this.#env = \"production\";\n const path = config.surface === \"shopify\" ? \"shopify/\" : \"\";\n this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/${path}`;\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 Object.assign(this.#headers, getSdkHeaders(this.#sdk));\n }\n\n /**\n * Fetch recommendations for the given request.\n *\n * Validates and transforms the friendly camelCase `request` into the wire\n * body, POSTs it, then validates and denormalizes the response into the\n * friendly `RecommendationsResponse`. The snake_case wire format is fully\n * encapsulated — callers never see it.\n *\n * Throws `DiscoValidationError` if the request or response fails schema\n * validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`\n * if the request can't reach the server (an abort rejects with the native\n * `AbortError`). Parse failures propagate as-is.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RecommendationsResponse> => {\n // `transformRequest` validates the request and builds the wire body; its\n // `DiscoValidationError` must propagate, so it runs *before* the fetch try\n // (otherwise the catch below would mis-wrap it as a `DiscoNetworkError`).\n const body = JSON.stringify(transformRequest(request));\n let response: Response;\n try {\n response = await this.#fetch(this.#url, {\n method: \"POST\",\n headers: this.#headers,\n body,\n signal: options?.signal,\n });\n } catch (error) {\n // A cancellation propagates as-is; any other transport failure is wrapped.\n if (isAbortError(error)) throw error;\n throw new DiscoNetworkError(\n \"Recommendations request failed to reach the server\",\n error,\n );\n }\n\n if (!response.ok) {\n const body = await safeReadBody(response);\n throw new DiscoApiError(\n `Recommendations request failed: ${response.status} ${response.statusText}`,\n { status: response.status, statusText: response.statusText, body },\n );\n }\n\n return mapRecommendationsResponse(await response.json());\n };\n\n /**\n * Fetch recommendations and create a session-bound tracker in one call.\n *\n * Composition convenience over `getRecommendations` + `createTrackingManager`:\n * it derives the tracker's session from the response so callers don't have to\n * thread the session id through themselves (and can't bind a tracker to the\n * wrong session). The returned `data` is the mapped `RecommendationsResponse`.\n *\n * Throws `DiscoValidationError` / `DiscoApiError` the same as\n * `getRecommendations`.\n */\n getRecommendationsWithTracker = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions & CreateTrackingManagerOptions,\n ): Promise<RecommendationsWithTracker> => {\n const data = await this.getRecommendations(request, {\n signal: options?.signal,\n });\n const tracker = this.createTrackingManager(data.sessionId, {\n fetch: options?.fetch,\n });\n return { data, tracker };\n };\n\n /**\n * Create an event tracker bound to a recommendations session (the `sessionId`\n * from a `getRecommendations` response).\n *\n * The tracker uses the same environment as the recommendations call.\n * Both live and sandbox public keys use production.\n */\n createTrackingManager = (\n sessionId: string,\n options?: CreateTrackingManagerOptions,\n ): EventTracker =>\n new TrackingManager({\n sessionId,\n endpoint: `${INTERNAL_BASE_URL[this.#env]}/track/partners_event/`,\n fetch: options?.fetch ?? this.#fetch,\n sdk: this.#sdk,\n });\n}\n\nfunction stripShopGid(shopGid: string): string {\n return shopGid.replace(\"gid://shopify/Shop/\", \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;AAoBA,MAAa,oBAAoB;CAC/B,YAAY;CACZ,SAAS;AACX;;;;;;;;;;;;;;;AAiFA,IAAa,sBAAb,MAAiC;CAC/B;CACA;CACA;CACA;CACA;CAEA,IAAI,MAAgB;EAClB,OAAO,KAAKA;CACd;CAEA,YAAY,QAA2B;EACrC,KAAKI,SAAS,OAAO,SAAS,WAAW,MAAM,KAAK,UAAU;EAC9D,KAAKD,OAAO,OAAO,MAAM,EAAE,GAAG,OAAO,IAAI,IAAI,KAAA;EAE7C,IAAI,YAAY,QAAQ;GACtB,qBAAqB,OAAO,MAAM;GAClC,KAAKH,OAAO;GACZ,MAAM,OAAO,OAAO,YAAY,YAAY,aAAa;GACzD,KAAKC,OAAO,GAAG,kBAAkB,KAAKD,MAAM,wBAAwB;GACpE,KAAKE,WAAW;IACd,aAAa,OAAO;IACpB,gBAAgB;GAClB;EACF,OAAO;GACL,KAAKF,OAAO,OAAO;GACnB,MAAM,SAAS,aAAa,OAAO,OAAO;GAC1C,KAAKC,OAAO,GAAG,kBAAkB,KAAKD,MAAM,iCAAiC,mBAAmB,MAAM,EAAE;GAExG,KAAKE,WAAW,EAAE,gBAAgB,mBAAmB;EACvD;EACA,OAAO,OAAO,KAAKA,UAAU,cAAc,KAAKC,IAAI,CAAC;CACvD;;;;;;;;;;;;;;CAeA,qBAAqB,OACnB,SACA,YACqC;EAIrC,MAAM,OAAO,KAAK,UAAU,iBAAiB,OAAO,CAAC;EACrD,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,KAAKC,OAAO,KAAKH,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;;;;;;;;CASA,yBACE,WACA,YAEA,IAAI,gBAAgB;EAClB;EACA,UAAU,GAAG,kBAAkB,KAAKF,MAAM;EAC1C,OAAO,SAAS,SAAS,KAAKI;EAC9B,KAAK,KAAKD;CACZ,CAAC;AACL;AAEA,SAAS,aAAa,SAAyB;CAC7C,OAAO,QAAQ,QAAQ,uBAAuB,EAAE;AAClD"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { RecommendationsResponse } from "../external/recommendations.js";
|
|
2
|
+
import { RecommendationGroup } from "./recommendations.js";
|
|
3
|
+
|
|
4
|
+
//#region src/internal/denormalize.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Join the normalized response maps into ordered `RecommendationGroup[]`.
|
|
7
|
+
*
|
|
8
|
+
* Groups are ordered by the numeric suffix of their key (`group_0` before
|
|
9
|
+
* `group_10`); within each group, entries are ordered by `insertionOrder`.
|
|
10
|
+
* Groups missing their entry list or display properties are skipped, as are
|
|
11
|
+
* entries whose `offerId` is absent from the recommendations map. Each result
|
|
12
|
+
* recommendation's `id` is the offer's id and its `insertionId` comes from the
|
|
13
|
+
* group entry.
|
|
14
|
+
*/
|
|
15
|
+
declare function denormalize(response: RecommendationsResponse): RecommendationGroup[];
|
|
16
|
+
//#endregion
|
|
17
|
+
export { denormalize };
|
|
18
|
+
//# sourceMappingURL=denormalize.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"denormalize.d.ts","names":[],"sources":["../../src/internal/denormalize.ts"],"mappings":";;;;;;;;;;;;;;iBA4BgB,WAAA,CACd,QAAA,EAAU,uBAAA,GACT,mBAAmB"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
//#region src/internal/denormalize.ts
|
|
2
|
+
/**
|
|
3
|
+
* Join the normalized response maps into ordered `RecommendationGroup[]`.
|
|
4
|
+
*
|
|
5
|
+
* Groups are ordered by the numeric suffix of their key (`group_0` before
|
|
6
|
+
* `group_10`); within each group, entries are ordered by `insertionOrder`.
|
|
7
|
+
* Groups missing their entry list or display properties are skipped, as are
|
|
8
|
+
* entries whose `offerId` is absent from the recommendations map. Each result
|
|
9
|
+
* recommendation's `id` is the offer's id and its `insertionId` comes from the
|
|
10
|
+
* group entry.
|
|
11
|
+
*/
|
|
12
|
+
function denormalize(response) {
|
|
13
|
+
const recommendations = response.recommendations;
|
|
14
|
+
const groupEntries = response.recommendationGroups;
|
|
15
|
+
const groupProps = response.recommendationGroupProperties ?? {};
|
|
16
|
+
const orderedKeys = Object.keys(groupEntries).sort((a, b) => numericSuffix(a) - numericSuffix(b));
|
|
17
|
+
const recommendationGroups = [];
|
|
18
|
+
for (const key of orderedKeys) {
|
|
19
|
+
const entries = groupEntries[key];
|
|
20
|
+
const props = groupProps[key];
|
|
21
|
+
if (!entries || !props) continue;
|
|
22
|
+
const recs = [];
|
|
23
|
+
for (const entry of entries) {
|
|
24
|
+
const rec = recommendations[entry.offerId];
|
|
25
|
+
if (!rec) continue;
|
|
26
|
+
recs.push({
|
|
27
|
+
id: rec.offer.id,
|
|
28
|
+
insertionId: entry.insertionId,
|
|
29
|
+
advertiser: rec.advertiser,
|
|
30
|
+
offer: rec.offer
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
recommendationGroups.push({
|
|
34
|
+
heading: props.heading ?? null,
|
|
35
|
+
slotContext: props.slotContext,
|
|
36
|
+
recommendations: recs
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return recommendationGroups;
|
|
40
|
+
}
|
|
41
|
+
function numericSuffix(value) {
|
|
42
|
+
const suffix = value.split("_").pop() ?? "";
|
|
43
|
+
const parsed = Number.parseInt(suffix, 10);
|
|
44
|
+
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { denormalize };
|
|
48
|
+
|
|
49
|
+
//# sourceMappingURL=denormalize.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"denormalize.js","names":[],"sources":["../../src/internal/denormalize.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;AA4BA,SAAgB,YACd,UACuB;CACvB,MAAM,kBAAkB,SAAS;CACjC,MAAM,eAAe,SAAS;CAC9B,MAAM,aAAa,SAAS,iCAAiC,CAAC;CAE9D,MAAM,cAAc,OAAO,KAAK,YAAY,EAAE,MAC3C,GAAG,MAAM,cAAc,CAAC,IAAI,cAAc,CAAC,CAC9C;CAEA,MAAM,uBAA8C,CAAC;CACrD,KAAK,MAAM,OAAO,aAAa;EAC7B,MAAM,UAAU,aAAa;EAC7B,MAAM,QAAQ,WAAW;EAEzB,IAAI,CAAC,WAAW,CAAC,OAAO;EAExB,MAAM,OAAyB,CAAC;EAChC,KAAK,MAAM,SAAS,SAAS;GAI3B,MAAM,MAAM,gBAAgB,MAAM;GAClC,IAAI,CAAC,KAAK;GACV,KAAK,KAAK;IACR,IAAI,IAAI,MAAM;IACd,aAAa,MAAM;IACnB,YAAY,IAAI;IAChB,OAAO,IAAI;GACb,CAAC;EACH;EAEA,qBAAqB,KAAK;GACxB,SAAS,MAAM,WAAW;GAC1B,aAAa,MAAM;GACnB,iBAAiB;EACnB,CAAC;CACH;CAEA,OAAO;AACT;AAEA,SAAS,cAAc,OAAuB;CAC5C,MAAM,SAAS,MAAM,MAAM,GAAG,EAAE,IAAI,KAAK;CACzC,MAAM,SAAS,OAAO,SAAS,QAAQ,EAAE;CACzC,OAAO,OAAO,MAAM,MAAM,IAAI,OAAO,oBAAoB;AAC3D"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Advertiser, Footer, Offer, OfferAsset, OfferCtaDetails, OfferDisclosureDetails, OfferMetadata } from "../external/recommendations.js";
|
|
2
|
+
|
|
3
|
+
//#region src/internal/recommendations.d.ts
|
|
4
|
+
type RecommendationsRequest = {
|
|
5
|
+
user?: UserDetails;
|
|
6
|
+
placement?: PlacementDetails;
|
|
7
|
+
order?: OrderDetails;
|
|
8
|
+
purchases?: Purchase[];
|
|
9
|
+
experiments?: RunningExperiment[];
|
|
10
|
+
attributes?: Record<string, unknown>;
|
|
11
|
+
/**
|
|
12
|
+
* Additional top-level fields passed through to the API unchanged.
|
|
13
|
+
* Use for platform-specific extensions (e.g. `shopify_checkout_token`).
|
|
14
|
+
* Keys here are not transformed — provide them in whatever case the
|
|
15
|
+
* backend expects.
|
|
16
|
+
*/
|
|
17
|
+
extras?: Record<string, unknown>;
|
|
18
|
+
};
|
|
19
|
+
type UserDetails = {
|
|
20
|
+
email?: string;
|
|
21
|
+
emailHash?: string;
|
|
22
|
+
firstName?: string;
|
|
23
|
+
lastName?: string;
|
|
24
|
+
phone?: string;
|
|
25
|
+
};
|
|
26
|
+
type PlacementDetails = {
|
|
27
|
+
/** Configured widget ID on the requested page (1-64 characters). */widgetId?: string; /** e.g. `"INLINE"`. Open-ended — see backend for supported values. */
|
|
28
|
+
displayMode?: string; /** e.g. `"THANK_YOU"`, `"ORDER_STATUS"`. Open-ended. */
|
|
29
|
+
view?: string;
|
|
30
|
+
};
|
|
31
|
+
type OrderDetails = {
|
|
32
|
+
id?: string;
|
|
33
|
+
amount?: number | string;
|
|
34
|
+
currencyCode?: string;
|
|
35
|
+
};
|
|
36
|
+
type Purchase = {
|
|
37
|
+
name?: string;
|
|
38
|
+
type?: string;
|
|
39
|
+
variant?: string;
|
|
40
|
+
quantity?: number;
|
|
41
|
+
productId?: string;
|
|
42
|
+
amount?: number;
|
|
43
|
+
currencyCode?: string;
|
|
44
|
+
};
|
|
45
|
+
type RunningExperiment = {
|
|
46
|
+
id: string;
|
|
47
|
+
variant: string;
|
|
48
|
+
};
|
|
49
|
+
type LayoutId = "SHOPIFY_NATIVE_LEAD_GEN" | "SHOPIFY_NATIVE_ESSENTIAL" | "SHOPIFY_NATIVE_COVER" | (string & {});
|
|
50
|
+
type RecommendationsResponse = {
|
|
51
|
+
sessionId: string;
|
|
52
|
+
layoutId: LayoutId;
|
|
53
|
+
recommendationGroups: RecommendationGroup[];
|
|
54
|
+
footer: Footer;
|
|
55
|
+
publisherCustomization: PublisherCustomization | null;
|
|
56
|
+
};
|
|
57
|
+
type RecommendationGroup = {
|
|
58
|
+
heading: string | null;
|
|
59
|
+
slotContext: "HERO" | "SCROLLABLE" | (string & {});
|
|
60
|
+
recommendations: Recommendation[];
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* A single recommendation within a denormalized group. Differs from the
|
|
64
|
+
* external `Recommendation` (`{ advertiser, offer }`): the internal one is the
|
|
65
|
+
* join result, so it also carries the offer-derived `id` and the group entry's
|
|
66
|
+
* `insertionId`. The `advertiser` / `offer` leaves are the external types.
|
|
67
|
+
*/
|
|
68
|
+
type Recommendation = {
|
|
69
|
+
id: string;
|
|
70
|
+
insertionId: string;
|
|
71
|
+
advertiser: Advertiser;
|
|
72
|
+
offer: Offer;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Publisher-configured copy, boolean flags, and overrides. Keyed first by surface type
|
|
76
|
+
* (`checkout`, `upfront`, …) and then by opaque server-defined keys —
|
|
77
|
+
* see `applyCustomizationOrFallback` consumer-side helpers.
|
|
78
|
+
*
|
|
79
|
+
* Inner keys remain snake_case because they're identifiers, not
|
|
80
|
+
* JavaScript field names.
|
|
81
|
+
*/
|
|
82
|
+
type PublisherCustomization = {
|
|
83
|
+
checkout?: Record<string, string | boolean>;
|
|
84
|
+
upfront?: Record<string, string | boolean>;
|
|
85
|
+
} & Record<string, Record<string, string | boolean> | undefined>;
|
|
86
|
+
//#endregion
|
|
87
|
+
export { LayoutId, OrderDetails, PlacementDetails, PublisherCustomization, Purchase, Recommendation, RecommendationGroup, RecommendationsRequest, RecommendationsResponse, RunningExperiment, UserDetails };
|
|
88
|
+
//# sourceMappingURL=recommendations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recommendations.d.ts","names":[],"sources":["../../src/internal/recommendations.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,SAAA;EACA,QAAA;EACA,KAAA;AAAA;AAAA,KAGU,gBAAA;EAHL,oEAKL,QAAA,WAFU;EAIV,WAAA;EAEA,IAAA;AAAA;AAAA,KAGU,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,EAAA;EACA,OAAO;AAAA;AAAA,KAKG,QAAA;AAAA,KAOA,uBAAA;EACV,SAAA;EACA,QAAA,EAAU,QAAA;EACV,oBAAA,EAAsB,mBAAA;EACtB,MAAA,EAAQ,MAAA;EACR,sBAAA,EAAwB,sBAAA;AAAA;AAAA,KAGd,mBAAA;EACV,OAAA;EACA,WAAA;EACA,eAAA,EAAiB,cAAc;AAAA;AAlBjC;;;;AAAoB;AAOpB;AAPA,KA2BY,cAAA;EACV,EAAA;EACA,WAAA;EACA,UAAA,EAAY,UAAA;EACZ,KAAA,EAAO,KAAK;AAAA;;;;;;;;;KAWF,sBAAA;EACV,QAAA,GAAW,MAAA;EACX,OAAA,GAAU,MAAA;AAAA,IACR,MAAA,SAAe,MAAA"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { zRecommendationsResponse2 } from "../api/generated/recommendations/zod.gen.js";
|
|
2
|
+
import { DiscoValidationError } from "../errors.js";
|
|
3
|
+
import { transformResponse } from "../external/recommendationsTransforms.js";
|
|
4
|
+
import { denormalize } from "./denormalize.js";
|
|
5
|
+
import { $ZodError } from "zod/v4/core";
|
|
6
|
+
import * as z from "zod/v4-mini";
|
|
7
|
+
//#region src/internal/recommendationsMapper.ts
|
|
8
|
+
/**
|
|
9
|
+
* Maps the proxy `/recommendations` response into the public, denormalized
|
|
10
|
+
* `RecommendationsResponse` (`mapRecommendationsResponse`).
|
|
11
|
+
*
|
|
12
|
+
* The proxy response is the external `/recommendations` response **verbatim plus
|
|
13
|
+
* a few extra top-level fields** (`layout_id`, `publisher_customization`, the
|
|
14
|
+
* `widget_*` markers, …). So this reuses the external machinery — the generated
|
|
15
|
+
* zod validator (`zRecommendationsResponse2`) and the external `transformResponse`
|
|
16
|
+
* mapper — and only layers on the denormalization (the join into
|
|
17
|
+
* `RecommendationGroup[]`) and the proxy extras.
|
|
18
|
+
*
|
|
19
|
+
* Validation is zod-backed: the external-wire part is validated by the generated
|
|
20
|
+
* `zRecommendationsResponse2` and the proxy extras by a small local schema, so a
|
|
21
|
+
* malformed server response surfaces as a `DiscoValidationError` rather than an
|
|
22
|
+
* opaque `undefined`-access crash deep in the join.
|
|
23
|
+
*/
|
|
24
|
+
const zProxyExtras = z.object({
|
|
25
|
+
layout_id: z.optional(z.string()),
|
|
26
|
+
publisher_customization: z.nullish(z.record(z.string(), z.record(z.string(), z.union([z.string(), z.boolean()]))))
|
|
27
|
+
});
|
|
28
|
+
/**
|
|
29
|
+
* Validate the proxy recommendations response and denormalize it into the
|
|
30
|
+
* public `RecommendationsResponse`.
|
|
31
|
+
*
|
|
32
|
+
* The proxy payload is the external wire response plus extras, so this reuses
|
|
33
|
+
* the external machinery: validate the wire part with the generated
|
|
34
|
+
* `zRecommendationsResponse2` and the extras with `zProxyExtras`, recase via
|
|
35
|
+
* the external `transformResponse`, then denormalize the resulting maps into
|
|
36
|
+
* `RecommendationGroup[]` (the internal value-add) and assemble the response
|
|
37
|
+
* with the proxy extras layered on.
|
|
38
|
+
*
|
|
39
|
+
* Throws `DiscoValidationError` if the server payload doesn't match the
|
|
40
|
+
* expected shape.
|
|
41
|
+
*
|
|
42
|
+
* @internal Built into `InternalDiscoClient.getRecommendations`; not part of
|
|
43
|
+
* the public API. The wire shape is encapsulated by the client on purpose.
|
|
44
|
+
*/
|
|
45
|
+
function mapRecommendationsResponse(raw) {
|
|
46
|
+
let wire;
|
|
47
|
+
let extras;
|
|
48
|
+
try {
|
|
49
|
+
wire = zRecommendationsResponse2.parse(raw);
|
|
50
|
+
extras = zProxyExtras.parse(raw);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (error instanceof $ZodError) throw new DiscoValidationError("Failed to validate recommendations response", error, raw);
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
const normalized = transformResponse(wire);
|
|
56
|
+
const recommendationGroups = denormalize(normalized);
|
|
57
|
+
return {
|
|
58
|
+
sessionId: normalized.sessionId,
|
|
59
|
+
layoutId: extras.layout_id ?? "SHOPIFY_NATIVE_ESSENTIAL",
|
|
60
|
+
recommendationGroups,
|
|
61
|
+
footer: normalized.footer,
|
|
62
|
+
publisherCustomization: extras.publisher_customization ?? null
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
export { mapRecommendationsResponse };
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=recommendationsMapper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recommendationsMapper.js","names":[],"sources":["../../src/internal/recommendationsMapper.ts"],"sourcesContent":["/**\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/core\";\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-mini\";\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-mini` — to match the\n// generated validator and keep the bundle small (see `lib/schemas.ts`).\nconst zProxyExtras = z.object({\n layout_id: z.optional(z.string()),\n publisher_customization: z.nullish(\n z.record(\n z.string(),\n z.record(z.string(), z.union([z.string(), z.boolean()])),\n ),\n ),\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,eAAe,EAAE,OAAO;CAC5B,WAAW,EAAE,SAAS,EAAE,OAAO,CAAC;CAChC,yBAAyB,EAAE,QACzB,EAAE,OACA,EAAE,OAAO,GACT,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,CACzD,CACF;AACF,CAAC;;;;;;;;;;;;;;;;;;AAqBD,SAAgB,2BACd,KACyB;CACzB,IAAI;CACJ,IAAI;CACJ,IAAI;EAIF,OAAO,0BAA0B,MAAM,GAAG;EAC1C,SAAS,aAAa,MAAM,GAAG;CACjC,SAAS,OAAO;EACd,IAAI,iBAAiB,WACnB,MAAM,IAAI,qBACR,+CACA,OACA,GACF;EAEF,MAAM;CACR;CAKA,MAAM,aAAa,kBAAkB,IAAI;CACzC,MAAM,uBAAuB,YAAY,UAAU;CAEnD,OAAO;EACL,WAAW,WAAW;EACtB,UAAU,OAAO,aAAa;EAC9B;EACA,QAAQ,WAAW;EACnB,wBACG,OAAO,2BAA6D;CACzE;AACF"}
|