@disconetwork/core 0.0.17 → 0.0.19
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 +216 -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 +90 -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 +121 -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 -400
- package/dist/internal.js +5 -564
- 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 +4 -4
- 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-D_E4xU1d.js +0 -748
- package/dist/recommendationsTransforms-D_E4xU1d.js.map +0 -1
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { recommendations } from "../api/generated/recommendations/sdk.gen.js";
|
|
2
|
+
import { createEventsClient, createRecommendationsClient } from "../api/index.js";
|
|
3
|
+
import { eventsPost } from "../api/generated/events/sdk.gen.js";
|
|
4
|
+
import { authHeaders, resolveGatewayBaseUrl } from "../config.js";
|
|
5
|
+
import { getSdkHeaders } from "../sdkIdentity.js";
|
|
6
|
+
import { validatePublicApiKey } from "../apiKey.js";
|
|
7
|
+
import { DiscoApiError, DiscoNetworkError, DiscoValidationError, isAbortError } from "../errors.js";
|
|
8
|
+
import { transformRequest, transformResponse } from "./recommendationsTransforms.js";
|
|
9
|
+
import { toEventRequest } from "../events/eventMapping.js";
|
|
10
|
+
import { $ZodError } from "zod/v4/core";
|
|
11
|
+
//#region src/external/DiscoClient.ts
|
|
12
|
+
/**
|
|
13
|
+
* Typed client for the Disco recommendations API — calls
|
|
14
|
+
* `disco-recommendations-api` **directly** (no proxy) at
|
|
15
|
+
* `/recommendations` on the configured gateway (production by default).
|
|
16
|
+
*
|
|
17
|
+
* This is the recommended, partner-facing client. It maps the friendly
|
|
18
|
+
* camelCase request into the rec-api wire body (sending `x-api-key` +
|
|
19
|
+
* `X-API-Version`) and recases the response into camelCase.
|
|
20
|
+
* Validation is performed by the generated SDK. The wire
|
|
21
|
+
* format is fully encapsulated.
|
|
22
|
+
*
|
|
23
|
+
* Renderer-agnostic: plain HTTP, no React dependency.
|
|
24
|
+
*/
|
|
25
|
+
var DiscoClient = class {
|
|
26
|
+
#recommendationsClient;
|
|
27
|
+
#eventsClient;
|
|
28
|
+
#fetch;
|
|
29
|
+
#baseUrl;
|
|
30
|
+
get baseUrl() {
|
|
31
|
+
return this.#baseUrl;
|
|
32
|
+
}
|
|
33
|
+
constructor(config) {
|
|
34
|
+
validatePublicApiKey(config.apiKey);
|
|
35
|
+
this.#baseUrl = resolveGatewayBaseUrl(config.baseUrl);
|
|
36
|
+
this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
37
|
+
const sdkHeaders = getSdkHeaders(config.sdk);
|
|
38
|
+
this.#recommendationsClient = createRecommendationsClient({
|
|
39
|
+
baseUrl: this.#baseUrl,
|
|
40
|
+
headers: {
|
|
41
|
+
...authHeaders(config),
|
|
42
|
+
...sdkHeaders
|
|
43
|
+
},
|
|
44
|
+
fetch: this.#fetch
|
|
45
|
+
});
|
|
46
|
+
this.#eventsClient = createEventsClient({
|
|
47
|
+
baseUrl: `${this.#baseUrl}/events`,
|
|
48
|
+
headers: {
|
|
49
|
+
"x-api-key": config.apiKey,
|
|
50
|
+
...sdkHeaders
|
|
51
|
+
},
|
|
52
|
+
fetch: this.#fetch
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Fetch recommendations for the given request.
|
|
57
|
+
*
|
|
58
|
+
* Maps the request to the wire body, POSTs it, then recases the response to
|
|
59
|
+
* camelCase (keeping the API's normalized shape). The generated SDK validates
|
|
60
|
+
* both sides. Throws `DiscoValidationError` on a request/response schema
|
|
61
|
+
* failure, `DiscoApiError` on a non-2xx response, and `DiscoNetworkError` if
|
|
62
|
+
* the request can't reach the server. An aborted request rejects with the
|
|
63
|
+
* native `AbortError`.
|
|
64
|
+
*/
|
|
65
|
+
getRecommendations = async (request, options) => {
|
|
66
|
+
const result = await recommendations({
|
|
67
|
+
client: this.#recommendationsClient,
|
|
68
|
+
body: transformRequest(request),
|
|
69
|
+
signal: options?.signal
|
|
70
|
+
});
|
|
71
|
+
if (result.response && !result.response.ok) throw new DiscoApiError(`Recommendations request failed: ${result.response.status} ${result.response.statusText}`, {
|
|
72
|
+
status: result.response.status,
|
|
73
|
+
statusText: result.response.statusText,
|
|
74
|
+
body: result.error
|
|
75
|
+
});
|
|
76
|
+
if (result.error) {
|
|
77
|
+
if (result.error instanceof $ZodError) throw new DiscoValidationError("Failed to validate recommendations payload", result.error, result.data);
|
|
78
|
+
if (isAbortError(result.error)) throw result.error;
|
|
79
|
+
throw new DiscoNetworkError("Recommendations request failed to reach the server", result.error);
|
|
80
|
+
}
|
|
81
|
+
return transformResponse(result.data);
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Fetch recommendations and create a session-bound events tracker in one
|
|
85
|
+
* call. The tracker inherits this client's API key and base URL.
|
|
86
|
+
*/
|
|
87
|
+
getRecommendationsWithTracker = async (request, options) => {
|
|
88
|
+
const data = await this.getRecommendations(request, { signal: options?.signal });
|
|
89
|
+
return {
|
|
90
|
+
data,
|
|
91
|
+
tracker: this.createTrackingManager(data.sessionId, { fetch: options?.fetch })
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Create an events tracker bound to a recommendations session (the
|
|
96
|
+
* `sessionId` from a `getRecommendations` response). Posts to the external
|
|
97
|
+
* `/events` endpoint with this client's `x-api-key`, via the generated events
|
|
98
|
+
* SDK (`eventsPost`).
|
|
99
|
+
*
|
|
100
|
+
* This is the **raw** tracker — it sends every call, fire-and-forget (never
|
|
101
|
+
* throws; failures are logged). Impression dedup is a render-lifecycle policy
|
|
102
|
+
* applied a layer up (the React layer wraps this with `withImpressionDedupe`),
|
|
103
|
+
* not baked into the core client.
|
|
104
|
+
*/
|
|
105
|
+
createTrackingManager = (sessionId, options) => {
|
|
106
|
+
const fetchOverride = options?.fetch;
|
|
107
|
+
return { track: (event) => {
|
|
108
|
+
eventsPost({
|
|
109
|
+
client: this.#eventsClient,
|
|
110
|
+
body: toEventRequest(event, { sessionId }),
|
|
111
|
+
keepalive: true,
|
|
112
|
+
...fetchOverride ? { fetch: fetchOverride } : {}
|
|
113
|
+
}).then((result) => {
|
|
114
|
+
if (result.error) console.error("Event tracking failed:", result.error);
|
|
115
|
+
});
|
|
116
|
+
} };
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
//#endregion
|
|
120
|
+
export { DiscoClient };
|
|
121
|
+
|
|
122
|
+
//# sourceMappingURL=DiscoClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DiscoClient.js","names":["#recommendationsClient","#eventsClient","#fetch","#baseUrl"],"sources":["../../src/external/DiscoClient.ts"],"sourcesContent":["import { $ZodError } from \"zod/v4/core\";\nimport { recommendations } from \"../api/generated/recommendations/index.js\";\nimport type { Client } from \"../api/generated/recommendations/client/index.js\";\nimport {\n createEventsClient,\n createRecommendationsClient,\n} from \"../api/index.js\";\nimport { eventsPost } from \"../api/generated/events/index.js\";\nimport type { Client as EventsClient } from \"../api/generated/events/client/index.js\";\nimport { authHeaders, resolveGatewayBaseUrl } from \"../config.js\";\nimport { getSdkHeaders, type SdkIdentity } from \"../sdkIdentity.js\";\nimport { validatePublicApiKey } from \"../apiKey.js\";\nimport {\n DiscoApiError,\n DiscoNetworkError,\n DiscoValidationError,\n isAbortError,\n} from \"../errors.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport {\n transformRequest,\n transformResponse,\n} from \"./recommendationsTransforms.js\";\nimport type { EventPayload, EventTracker } from \"../types.js\";\nimport { toEventRequest } from \"../events/eventMapping.js\";\n\n/**\n * Authenticate with a scoped public API key (`disco_pk_live_…` /\n * `disco_pk_sandbox_…`). Both prefixes default to production. Use `baseUrl`\n * to override the gateway for recommendations and events.\n */\nexport type DiscoClientConfig = {\n apiKey: string;\n /**\n * Absolute HTTP(S) gateway root, without a query or fragment. The SDK appends\n * `/recommendations` and `/events`. Defaults to `https://partners.disconetwork.com`.\n */\n baseUrl?: string;\n /**\n * Value for the required `X-API-Version` header. Defaults to\n * `DEFAULT_API_VERSION` (see `config.ts`).\n */\n apiVersion?: string;\n fetch?: typeof fetch;\n /** SDK/renderer identity. Defaults to this core package's name and version. */\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 /** Override the fetch used by the tracker. Defaults to the client's fetch. */\n fetch?: typeof fetch;\n};\n\n/**\n * Result of `getRecommendationsWithTracker`: the mapped response plus a tracker\n * already bound to its session.\n */\nexport type RecommendationsWithTracker = {\n data: RecommendationsResponse;\n tracker: EventTracker;\n};\n\n/**\n * Typed client for the Disco recommendations API — calls\n * `disco-recommendations-api` **directly** (no proxy) at\n * `/recommendations` on the configured gateway (production by default).\n *\n * This is the recommended, partner-facing client. It maps the friendly\n * camelCase request into the rec-api wire body (sending `x-api-key` +\n * `X-API-Version`) and recases the response into camelCase.\n * Validation is performed by the generated SDK. The wire\n * format is fully encapsulated.\n *\n * Renderer-agnostic: plain HTTP, no React dependency.\n */\nexport class DiscoClient {\n readonly #recommendationsClient: Client;\n readonly #eventsClient: EventsClient;\n readonly #fetch: typeof fetch;\n readonly #baseUrl: string;\n\n get baseUrl(): string {\n return this.#baseUrl;\n }\n\n constructor(config: DiscoClientConfig) {\n validatePublicApiKey(config.apiKey);\n this.#baseUrl = resolveGatewayBaseUrl(config.baseUrl);\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n const sdkHeaders = getSdkHeaders(config.sdk);\n this.#recommendationsClient = createRecommendationsClient({\n baseUrl: this.#baseUrl,\n headers: { ...authHeaders(config), ...sdkHeaders },\n fetch: this.#fetch,\n });\n // Built once and shared by every tracker (only the session id varies),\n // mirroring the recommendations client. The events SDK posts to `/`, so the\n // base URL is the full `/events` URL.\n this.#eventsClient = createEventsClient({\n baseUrl: `${this.#baseUrl}/events`,\n headers: { \"x-api-key\": config.apiKey, ...sdkHeaders },\n fetch: this.#fetch,\n });\n }\n\n /**\n * Fetch recommendations for the given request.\n *\n * Maps the request to the wire body, POSTs it, then recases the response to\n * camelCase (keeping the API's normalized shape). The generated SDK validates\n * both sides. Throws `DiscoValidationError` on a request/response schema\n * failure, `DiscoApiError` on a non-2xx response, and `DiscoNetworkError` if\n * the request can't reach the server. An aborted request rejects with the\n * native `AbortError`.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RecommendationsResponse> => {\n // `transformRequest` maps the camelCase request to the wire body; the\n // generated SDK validates both request and response.\n // Not destructured: the result is a discriminated union on `error`, so\n // accessing fields off `result` lets TS narrow `result.data` to a defined\n // response once the error/non-2xx branches have thrown.\n const result = await recommendations({\n client: this.#recommendationsClient,\n body: transformRequest(request),\n signal: options?.signal,\n });\n\n if (result.response && !result.response.ok) {\n throw new DiscoApiError(\n `Recommendations request failed: ${result.response.status} ${result.response.statusText}`,\n {\n status: result.response.status,\n statusText: result.response.statusText,\n body: result.error,\n },\n );\n }\n\n if (result.error) {\n // A `$ZodError` means the generated validator rejected the request or\n // response.\n if (result.error instanceof $ZodError) {\n throw new DiscoValidationError(\n \"Failed to validate recommendations payload\",\n result.error,\n result.data,\n );\n }\n // A cancellation propagates as-is; any other transport failure (network,\n // DNS, timeout) is wrapped so it's catchable as a `DiscoError`.\n if (isAbortError(result.error)) throw result.error;\n throw new DiscoNetworkError(\n \"Recommendations request failed to reach the server\",\n result.error,\n );\n }\n\n return transformResponse(result.data);\n };\n\n /**\n * Fetch recommendations and create a session-bound events tracker in one\n * call. The tracker inherits this client's API key and base URL.\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 events tracker bound to a recommendations session (the\n * `sessionId` from a `getRecommendations` response). Posts to the external\n * `/events` endpoint with this client's `x-api-key`, via the generated events\n * SDK (`eventsPost`).\n *\n * This is the **raw** tracker — it sends every call, fire-and-forget (never\n * throws; failures are logged). Impression dedup is a render-lifecycle policy\n * applied a layer up (the React layer wraps this with `withImpressionDedupe`),\n * not baked into the core client.\n */\n createTrackingManager = (\n sessionId: string,\n options?: CreateTrackingManagerOptions,\n ): EventTracker => {\n const fetchOverride = options?.fetch;\n return {\n track: (event: EventPayload): void => {\n // `throwOnError` defaults to false, so this resolves to a result object\n // (never rejects); validation/transport failures surface in `error`.\n void eventsPost({\n client: this.#eventsClient,\n body: toEventRequest(event, { sessionId }),\n keepalive: true,\n ...(fetchOverride ? { fetch: fetchOverride } : {}),\n }).then((result) => {\n if (result.error) {\n console.error(\"Event tracking failed:\", result.error);\n }\n });\n },\n };\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmFA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CAEA,IAAI,UAAkB;EACpB,OAAO,KAAKG;CACd;CAEA,YAAY,QAA2B;EACrC,qBAAqB,OAAO,MAAM;EAClC,KAAKA,WAAW,sBAAsB,OAAO,OAAO;EACpD,KAAKD,SAAS,OAAO,SAAS,WAAW,MAAM,KAAK,UAAU;EAC9D,MAAM,aAAa,cAAc,OAAO,GAAG;EAC3C,KAAKF,yBAAyB,4BAA4B;GACxD,SAAS,KAAKG;GACd,SAAS;IAAE,GAAG,YAAY,MAAM;IAAG,GAAG;GAAW;GACjD,OAAO,KAAKD;EACd,CAAC;EAID,KAAKD,gBAAgB,mBAAmB;GACtC,SAAS,GAAG,KAAKE,SAAS;GAC1B,SAAS;IAAE,aAAa,OAAO;IAAQ,GAAG;GAAW;GACrD,OAAO,KAAKD;EACd,CAAC;CACH;;;;;;;;;;;CAYA,qBAAqB,OACnB,SACA,YACqC;EAMrC,MAAM,SAAS,MAAM,gBAAgB;GACnC,QAAQ,KAAKF;GACb,MAAM,iBAAiB,OAAO;GAC9B,QAAQ,SAAS;EACnB,CAAC;EAED,IAAI,OAAO,YAAY,CAAC,OAAO,SAAS,IACtC,MAAM,IAAI,cACR,mCAAmC,OAAO,SAAS,OAAO,GAAG,OAAO,SAAS,cAC7E;GACE,QAAQ,OAAO,SAAS;GACxB,YAAY,OAAO,SAAS;GAC5B,MAAM,OAAO;EACf,CACF;EAGF,IAAI,OAAO,OAAO;GAGhB,IAAI,OAAO,iBAAiB,WAC1B,MAAM,IAAI,qBACR,8CACA,OAAO,OACP,OAAO,IACT;GAIF,IAAI,aAAa,OAAO,KAAK,GAAG,MAAM,OAAO;GAC7C,MAAM,IAAI,kBACR,sDACA,OAAO,KACT;EACF;EAEA,OAAO,kBAAkB,OAAO,IAAI;CACtC;;;;;CAMA,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;;;;;;;;;;;;CAaA,yBACE,WACA,YACiB;EACjB,MAAM,gBAAgB,SAAS;EAC/B,OAAO,EACL,QAAQ,UAA8B;GAGpC,WAAgB;IACd,QAAQ,KAAKC;IACb,MAAM,eAAe,OAAO,EAAE,UAAU,CAAC;IACzC,WAAW;IACX,GAAI,gBAAgB,EAAE,OAAO,cAAc,IAAI,CAAC;GAClD,CAAC,EAAE,MAAM,WAAW;IAClB,IAAI,OAAO,OACT,QAAQ,MAAM,0BAA0B,OAAO,KAAK;GAExD,CAAC;EACH,EACF;CACF;AACF"}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { DisplayMode, Gender, PlatformType, SubView, Title, View } from "../api/generated/recommendations/types.gen.js";
|
|
2
|
+
|
|
3
|
+
//#region src/external/recommendations.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* A running experiment — shared by the request (input) and the response
|
|
6
|
+
* (echoed back). Declared here (not inferred) because the response references
|
|
7
|
+
* it; the request schema validates the identical `{ name, version }` shape.
|
|
8
|
+
*/
|
|
9
|
+
type RunningExperiment = {
|
|
10
|
+
name: string; /** 0 .. 999. */
|
|
11
|
+
version: number;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Structured device/session attributes. Only these fields are recognized by the
|
|
15
|
+
* backend (`disco_shared` `Attributes`); unknown keys are dropped server-side.
|
|
16
|
+
*/
|
|
17
|
+
type Attributes = {
|
|
18
|
+
userAgent?: string;
|
|
19
|
+
operatingSystem?: string;
|
|
20
|
+
operatingSystemVersion?: string;
|
|
21
|
+
ipAddress?: string;
|
|
22
|
+
ipAddressHash?: string;
|
|
23
|
+
platformType?: PlatformType; /** ISO-639 language code. */
|
|
24
|
+
language?: string;
|
|
25
|
+
deviceType?: string;
|
|
26
|
+
};
|
|
27
|
+
type UserProfile = {
|
|
28
|
+
title?: Title;
|
|
29
|
+
firstName?: string;
|
|
30
|
+
lastName?: string;
|
|
31
|
+
phone?: string;
|
|
32
|
+
gender?: Gender; /** Date of birth, `YYYY-MM-DD`. */
|
|
33
|
+
dob?: string; /** Non-negative. */
|
|
34
|
+
age?: number;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* User details must carry at least one identifier — email, email hash, external
|
|
38
|
+
* GUID, or phone. (Enforced by the generated SDK's request validator, not the
|
|
39
|
+
* type.)
|
|
40
|
+
*/
|
|
41
|
+
type UserDetails = (UserProfile & {
|
|
42
|
+
email: string;
|
|
43
|
+
}) | (UserProfile & {
|
|
44
|
+
emailHash: string;
|
|
45
|
+
}) | (UserProfile & {
|
|
46
|
+
externalGuid: string;
|
|
47
|
+
}) | (UserProfile & {
|
|
48
|
+
phone: string;
|
|
49
|
+
});
|
|
50
|
+
type CostDetails = {
|
|
51
|
+
amount?: number; /** ISO-4217 currency code. */
|
|
52
|
+
currencyCode?: string;
|
|
53
|
+
};
|
|
54
|
+
type PlacementDetails = {
|
|
55
|
+
displayMode: DisplayMode;
|
|
56
|
+
view: View;
|
|
57
|
+
subView?: SubView;
|
|
58
|
+
layoutId?: string;
|
|
59
|
+
};
|
|
60
|
+
type OrderDetails = {
|
|
61
|
+
orderId?: string;
|
|
62
|
+
paymentType?: string;
|
|
63
|
+
costDetails?: CostDetails;
|
|
64
|
+
};
|
|
65
|
+
type PurchaseAttributes = {
|
|
66
|
+
isClearance?: boolean;
|
|
67
|
+
isGift?: boolean;
|
|
68
|
+
};
|
|
69
|
+
type Purchase = {
|
|
70
|
+
name?: string;
|
|
71
|
+
type?: string; /** A string, or a data-keyed map passed through to the wire verbatim. */
|
|
72
|
+
variant?: string | Record<string, string>;
|
|
73
|
+
quantity?: number;
|
|
74
|
+
description?: string;
|
|
75
|
+
productId?: string;
|
|
76
|
+
costDetails?: CostDetails;
|
|
77
|
+
attributes?: PurchaseAttributes;
|
|
78
|
+
};
|
|
79
|
+
type Address = {
|
|
80
|
+
addressLine1?: string;
|
|
81
|
+
addressLine2?: string;
|
|
82
|
+
city?: string;
|
|
83
|
+
state?: string;
|
|
84
|
+
zip?: string;
|
|
85
|
+
phone?: string;
|
|
86
|
+
countryCode?: string;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Free-form custom metadata. Untyped on purpose: the backend `CustomMetadata`
|
|
90
|
+
* model has many fields and churns; keys are recased camelCase → snake_case on
|
|
91
|
+
* the way out so callers can stay in the camelCase idiom.
|
|
92
|
+
*/
|
|
93
|
+
type CustomMetadata = Record<string, unknown>;
|
|
94
|
+
type RecommendationsRequest = {
|
|
95
|
+
userDetails: UserDetails;
|
|
96
|
+
placementDetails: PlacementDetails;
|
|
97
|
+
orderDetails?: OrderDetails;
|
|
98
|
+
purchases?: Purchase[];
|
|
99
|
+
attributes?: Attributes;
|
|
100
|
+
customMetadata?: CustomMetadata;
|
|
101
|
+
shipping?: Address;
|
|
102
|
+
billing?: Address;
|
|
103
|
+
runningExperiments?: RunningExperiment[];
|
|
104
|
+
};
|
|
105
|
+
type RecommendationsResponse = {
|
|
106
|
+
sessionId: string; /** Offer id → recommendation. */
|
|
107
|
+
recommendations: Record<string, Recommendation>; /** Group key → ordered entry list referencing offer ids. */
|
|
108
|
+
recommendationGroups: Record<string, RecommendationGroupEntry[]>; /** Group key → display properties. */
|
|
109
|
+
recommendationGroupProperties?: Record<string, RecommendationGroupProperty>;
|
|
110
|
+
runningExperiments?: RunningExperiment[];
|
|
111
|
+
footer: Footer;
|
|
112
|
+
};
|
|
113
|
+
type Recommendation = {
|
|
114
|
+
advertiser: Advertiser;
|
|
115
|
+
offer: Offer;
|
|
116
|
+
};
|
|
117
|
+
type RecommendationGroupEntry = {
|
|
118
|
+
insertionOrder: number;
|
|
119
|
+
insertionId: string;
|
|
120
|
+
offerId: string;
|
|
121
|
+
advertiserId: string;
|
|
122
|
+
};
|
|
123
|
+
type RecommendationGroupProperty = {
|
|
124
|
+
heading: string | null;
|
|
125
|
+
slotContext: string;
|
|
126
|
+
};
|
|
127
|
+
type Advertiser = {
|
|
128
|
+
id: string;
|
|
129
|
+
name: string;
|
|
130
|
+
logoUrl: string;
|
|
131
|
+
description: string | null;
|
|
132
|
+
};
|
|
133
|
+
type Offer = {
|
|
134
|
+
id: string;
|
|
135
|
+
heading: string;
|
|
136
|
+
subheading: string | null;
|
|
137
|
+
jsonContent: Record<string, unknown> | null;
|
|
138
|
+
targetUrl: string;
|
|
139
|
+
ctaDetails: OfferCtaDetails;
|
|
140
|
+
assets: OfferAsset[];
|
|
141
|
+
metadata: OfferMetadata;
|
|
142
|
+
disclosureDetails: OfferDisclosureDetails | null;
|
|
143
|
+
};
|
|
144
|
+
type OfferCtaDetails = {
|
|
145
|
+
acceptCopy: string;
|
|
146
|
+
declineCopy: string;
|
|
147
|
+
transitionCopy: string | null;
|
|
148
|
+
claimedAcceptCopy: string | null;
|
|
149
|
+
claimedDeclineCopy: string | null;
|
|
150
|
+
};
|
|
151
|
+
type OfferAsset = {
|
|
152
|
+
/** Server-defined asset type (e.g. `PRODUCT`). Open-ended. */assetType: string;
|
|
153
|
+
imageUrl: string;
|
|
154
|
+
insertionOrder: number;
|
|
155
|
+
id: string | null;
|
|
156
|
+
targetUrl: string | null;
|
|
157
|
+
shouldTriggerClaimFlow: boolean;
|
|
158
|
+
};
|
|
159
|
+
/** Discriminated on `type`. `layoutType` is a server-defined display format. */
|
|
160
|
+
type OfferMetadata = {
|
|
161
|
+
type: "PROMO_CODE";
|
|
162
|
+
code: string;
|
|
163
|
+
layoutType: string;
|
|
164
|
+
} | {
|
|
165
|
+
type: "NO_PROMO_CODE";
|
|
166
|
+
layoutType: string;
|
|
167
|
+
};
|
|
168
|
+
type OfferDisclosureDetails = {
|
|
169
|
+
copy: string;
|
|
170
|
+
targetUrl: string | null;
|
|
171
|
+
content: string | null;
|
|
172
|
+
};
|
|
173
|
+
type Footer = {
|
|
174
|
+
attributionDetails: {
|
|
175
|
+
copy: string;
|
|
176
|
+
discoLogoUrl: string;
|
|
177
|
+
targetUrl: string;
|
|
178
|
+
};
|
|
179
|
+
privacyPolicy: {
|
|
180
|
+
copy: string;
|
|
181
|
+
targetUrl: string;
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
//#endregion
|
|
185
|
+
export { Address, Advertiser, Footer, Offer, OfferAsset, OfferCtaDetails, OfferDisclosureDetails, OfferMetadata, Recommendation, RecommendationGroupEntry, RecommendationGroupProperty, RecommendationsRequest, RecommendationsResponse, RunningExperiment };
|
|
186
|
+
//# sourceMappingURL=recommendations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recommendations.d.ts","names":[],"sources":["../../src/external/recommendations.ts"],"mappings":";;;;;;;;KA8BY,iBAAA;EACV,IAAA,UA4BA;EA1BA,OAAO;AAAA;;;;;KAiBJ,UAAA;EACH,SAAA;EACA,eAAA;EACA,sBAAA;EACA,SAAA;EACA,aAAA;EACA,YAAA,GAAe,YAAY,EAe3B;EAbA,QAAA;EACA,UAAA;AAAA;AAAA,KAGG,WAAA;EACH,KAAA,GAAQ,KAAA;EACR,SAAA;EACA,QAAA;EACA,KAAA;EACA,MAAA,GAAS,MAAM,EAgBD;EAdd,GAAA,WAWG;EATH,GAAA;AAAA;;;;;;KAQG,WAAA,IACA,WAAA;EAAgB,KAAA;AAAA,MAChB,WAAA;EAAgB,SA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AA;EACA,YAAA;AAAA;AAAA,KAGU,2BAAA;EACV,OAAA;EACA,WAAW;AAAA;AAAA,KAGD,UAAA;EACV,EAAA;EACA,IAAA;EACA,OAAA;EACA,WAAA;AAAA;AAAA,KAGU,KAAA;EACV,EAAA;EACA,OAAA;EACA,UAAA;EACA,WAAA,EAAa,MAAA;EACb,SAAA;EACA,UAAA,EAAY,eAAA;EACZ,MAAA,EAAQ,UAAA;EACR,QAAA,EAAU,aAAA;EACV,iBAAA,EAAmB,sBAAA;AAAA;AAAA,KAGT,eAAA;EACV,UAAA;EACA,WAAA;EACA,cAAA;EACA,iBAAA;EACA,kBAAA;AAAA;AAAA,KAGU,UAAA;EArDO,8DAuDjB,SAAA;EACA,QAAA;EACA,cAAA;EACA,EAAA;EACA,SAAA;EACA,sBAAA;AAAA;;KAIU,aAAA;EACN,IAAA;EAAoB,IAAA;EAAc,UAAA;AAAA;EAClC,IAAA;EAAuB,UAAA;AAAA;AAAA,KAEjB,sBAAA;EACV,IAAA;EACA,SAAA;EACA,OAAA;AAAA;AAAA,KAGU,MAAA;EACV,kBAAA;IACE,IAAA;IACA,YAAA;IACA,SAAA;EAAA;EAEF,aAAA;IACE,IAAA;IACA,SAAA;EAAA;AAAA"}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { remap } from "../lib/primitives.js";
|
|
2
|
+
import { toSnakeKeys } from "../lib/case.js";
|
|
3
|
+
//#region src/external/recommendationsTransforms.ts
|
|
4
|
+
/**
|
|
5
|
+
* Zod schemas + casing transforms for the **external** recommendations contract.
|
|
6
|
+
*
|
|
7
|
+
* The public types mirror the endpoint 1:1 in structure, so the only
|
|
8
|
+
* transformation is snake_case ↔ camelCase:
|
|
9
|
+
* - Request: validate the camelCase input, then build the wire body with
|
|
10
|
+
* explicit per-field `remap`s (the same mechanism Speakeasy-generated SDKs
|
|
11
|
+
* use). Named fields are renamed deterministically; genuinely data-keyed
|
|
12
|
+
* values — `variant`'s map, `customMetadata` — are handled explicitly so a
|
|
13
|
+
* blind recaser can't corrupt them.
|
|
14
|
+
* - Response: validate the snake_case wire, then recase to camelCase
|
|
15
|
+
* **preserving map keys** (offer ids / group keys are data, not field names).
|
|
16
|
+
*
|
|
17
|
+
* @internal Built into the external `DiscoClient`; not part of the public API.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Build the snake_case wire body from the public request via explicit per-field
|
|
21
|
+
* `remap`s. Transform-only: validation is performed by the generated SDK's
|
|
22
|
+
* request validator (which surfaces as `DiscoValidationError` from
|
|
23
|
+
* `DiscoClient`), so this does not parse or throw on bad input.
|
|
24
|
+
*/
|
|
25
|
+
function transformRequest(request) {
|
|
26
|
+
const v = request;
|
|
27
|
+
return compact({
|
|
28
|
+
user_details: remap(v.userDetails, {
|
|
29
|
+
firstName: "first_name",
|
|
30
|
+
lastName: "last_name",
|
|
31
|
+
emailHash: "email_hash",
|
|
32
|
+
externalGuid: "external_guid"
|
|
33
|
+
}),
|
|
34
|
+
placement_details: remap(v.placementDetails, {
|
|
35
|
+
displayMode: "display_mode",
|
|
36
|
+
subView: "sub_view",
|
|
37
|
+
layoutId: "layout_id"
|
|
38
|
+
}),
|
|
39
|
+
order_details: v.orderDetails && wireOrderDetails(v.orderDetails),
|
|
40
|
+
purchases: v.purchases?.map(wirePurchase),
|
|
41
|
+
attributes: v.attributes && remap(v.attributes, attributesKeyMap),
|
|
42
|
+
custom_metadata: v.customMetadata && toSnakeKeys(v.customMetadata),
|
|
43
|
+
shipping: v.shipping && wireAddress(v.shipping),
|
|
44
|
+
billing: v.billing && wireAddress(v.billing),
|
|
45
|
+
running_experiments: v.runningExperiments
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const attributesKeyMap = {
|
|
49
|
+
userAgent: "user_agent",
|
|
50
|
+
operatingSystem: "operating_system",
|
|
51
|
+
operatingSystemVersion: "operating_system_version",
|
|
52
|
+
ipAddress: "ip_address",
|
|
53
|
+
ipAddressHash: "ip_address_hash",
|
|
54
|
+
platformType: "platform_type",
|
|
55
|
+
deviceType: "device_type"
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Map an `Address` to its wire shape. Also used by the internal (proxy) request
|
|
59
|
+
* mapper: the proxy forwards addresses to this API untouched, so both clients
|
|
60
|
+
* send the same shape.
|
|
61
|
+
*/
|
|
62
|
+
function wireAddress(a) {
|
|
63
|
+
return remap(a, {
|
|
64
|
+
addressLine1: "address_line_1",
|
|
65
|
+
addressLine2: "address_line_2",
|
|
66
|
+
countryCode: "country_code"
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function wireCostDetails(c) {
|
|
70
|
+
return remap(c, { currencyCode: "currency_code" });
|
|
71
|
+
}
|
|
72
|
+
function wireOrderDetails(o) {
|
|
73
|
+
return {
|
|
74
|
+
...remap(o, {
|
|
75
|
+
orderId: "order_id",
|
|
76
|
+
paymentType: "payment_type",
|
|
77
|
+
costDetails: null
|
|
78
|
+
}),
|
|
79
|
+
...o.costDetails && { cost_details: wireCostDetails(o.costDetails) }
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function wirePurchase(p) {
|
|
83
|
+
return {
|
|
84
|
+
...remap(p, {
|
|
85
|
+
productId: "product_id",
|
|
86
|
+
costDetails: null,
|
|
87
|
+
attributes: null
|
|
88
|
+
}),
|
|
89
|
+
...p.costDetails && { cost_details: wireCostDetails(p.costDetails) },
|
|
90
|
+
...p.attributes && { attributes: remap(p.attributes, {
|
|
91
|
+
isClearance: "is_clearance",
|
|
92
|
+
isGift: "is_gift"
|
|
93
|
+
}) }
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/** Drop keys whose value is `undefined` so absent optionals leave no trace. */
|
|
97
|
+
function compact(obj) {
|
|
98
|
+
const out = {};
|
|
99
|
+
for (const [k, val] of Object.entries(obj)) if (val !== void 0) out[k] = val;
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Recase the rec-api wire response into the friendly camelCase shape, keeping
|
|
104
|
+
* the normalized maps intact. Transform-only: the generated SDK validates the
|
|
105
|
+
* response before this runs, so it neither parses nor throws.
|
|
106
|
+
*/
|
|
107
|
+
function transformResponse(raw) {
|
|
108
|
+
return {
|
|
109
|
+
sessionId: raw.session_id,
|
|
110
|
+
recommendations: mapValues(raw.recommendations ?? {}, mapRecommendation),
|
|
111
|
+
recommendationGroups: mapValues(raw.recommendation_groups ?? {}, (entries) => entries.map(mapGroupEntry)),
|
|
112
|
+
recommendationGroupProperties: raw.recommendation_group_properties ? mapValues(raw.recommendation_group_properties, mapGroupProperty) : void 0,
|
|
113
|
+
runningExperiments: raw.running_experiments?.map((e) => ({
|
|
114
|
+
name: e.name,
|
|
115
|
+
version: e.version
|
|
116
|
+
})),
|
|
117
|
+
footer: mapFooter(raw.footer)
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Map a dictionary's values while preserving its (data) keys. */
|
|
121
|
+
function mapValues(obj, fn) {
|
|
122
|
+
const out = {};
|
|
123
|
+
for (const [key, value] of Object.entries(obj)) out[key] = fn(value);
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
function mapRecommendation(raw) {
|
|
127
|
+
return {
|
|
128
|
+
advertiser: mapAdvertiser(raw.advertiser),
|
|
129
|
+
offer: mapOffer(raw.offer)
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function mapGroupEntry(raw) {
|
|
133
|
+
return {
|
|
134
|
+
insertionOrder: raw.insertion_order,
|
|
135
|
+
insertionId: raw.insertion_id,
|
|
136
|
+
offerId: raw.offer_id,
|
|
137
|
+
advertiserId: raw.advertiser_id
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function mapGroupProperty(raw) {
|
|
141
|
+
return {
|
|
142
|
+
heading: raw.heading ?? null,
|
|
143
|
+
slotContext: raw.slot_context
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function mapAdvertiser(raw) {
|
|
147
|
+
return {
|
|
148
|
+
id: raw.id,
|
|
149
|
+
name: raw.name,
|
|
150
|
+
logoUrl: raw.logo_url,
|
|
151
|
+
description: raw.description ?? null
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
function mapOffer(raw) {
|
|
155
|
+
return {
|
|
156
|
+
id: raw.id,
|
|
157
|
+
heading: raw.heading,
|
|
158
|
+
subheading: raw.subheading ?? null,
|
|
159
|
+
jsonContent: raw.json_content ?? null,
|
|
160
|
+
targetUrl: raw.target_url,
|
|
161
|
+
ctaDetails: mapCtaDetails(raw.cta_details),
|
|
162
|
+
assets: (raw.assets ?? []).map(mapAsset),
|
|
163
|
+
metadata: mapMetadata(raw.metadata),
|
|
164
|
+
disclosureDetails: raw.disclosure_details ? {
|
|
165
|
+
copy: raw.disclosure_details.copy,
|
|
166
|
+
targetUrl: raw.disclosure_details.target_url ?? null,
|
|
167
|
+
content: raw.disclosure_details.content ?? null
|
|
168
|
+
} : null
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function mapCtaDetails(raw) {
|
|
172
|
+
return {
|
|
173
|
+
acceptCopy: raw.accept_copy,
|
|
174
|
+
declineCopy: raw.decline_copy,
|
|
175
|
+
transitionCopy: raw.transition_copy ?? null,
|
|
176
|
+
claimedAcceptCopy: raw.claimed_accept_copy ?? null,
|
|
177
|
+
claimedDeclineCopy: raw.claimed_decline_copy ?? null
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
function mapAsset(raw) {
|
|
181
|
+
return {
|
|
182
|
+
assetType: raw.asset_type,
|
|
183
|
+
imageUrl: raw.image_url,
|
|
184
|
+
insertionOrder: raw.insertion_order,
|
|
185
|
+
id: raw.id ?? null,
|
|
186
|
+
targetUrl: raw.target_url ?? null,
|
|
187
|
+
shouldTriggerClaimFlow: raw.should_trigger_claim_flow ?? false
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function mapMetadata(raw) {
|
|
191
|
+
return raw.type === "PROMO_CODE" ? {
|
|
192
|
+
type: "PROMO_CODE",
|
|
193
|
+
code: raw.code,
|
|
194
|
+
layoutType: raw.layout_type
|
|
195
|
+
} : {
|
|
196
|
+
type: "NO_PROMO_CODE",
|
|
197
|
+
layoutType: raw.layout_type
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function mapFooter(raw) {
|
|
201
|
+
return {
|
|
202
|
+
attributionDetails: {
|
|
203
|
+
copy: raw.attribution_details.copy,
|
|
204
|
+
discoLogoUrl: raw.attribution_details.disco_logo_url,
|
|
205
|
+
targetUrl: raw.attribution_details.target_url
|
|
206
|
+
},
|
|
207
|
+
privacyPolicy: {
|
|
208
|
+
copy: raw.privacy_policy.copy,
|
|
209
|
+
targetUrl: raw.privacy_policy.target_url
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
//#endregion
|
|
214
|
+
export { transformRequest, transformResponse, wireAddress };
|
|
215
|
+
|
|
216
|
+
//# sourceMappingURL=recommendationsTransforms.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recommendationsTransforms.js","names":[],"sources":["../../src/external/recommendationsTransforms.ts"],"sourcesContent":["/**\n * Zod schemas + casing transforms for the **external** recommendations contract.\n *\n * The public types mirror the endpoint 1:1 in structure, so the only\n * transformation is snake_case ↔ camelCase:\n * - Request: validate the camelCase input, then build the wire body with\n * explicit per-field `remap`s (the same mechanism Speakeasy-generated SDKs\n * use). Named fields are renamed deterministically; genuinely data-keyed\n * values — `variant`'s map, `customMetadata` — are handled explicitly so a\n * blind recaser can't corrupt them.\n * - Response: validate the snake_case wire, then recase to camelCase\n * **preserving map keys** (offer ids / group keys are data, not field names).\n *\n * @internal Built into the external `DiscoClient`; not part of the public API.\n */\n\nimport { remap } from \"../lib/primitives.js\";\nimport { toSnakeKeys } from \"../lib/case.js\";\n// The wire types the generated SDK returns (and has already validated). Aliased\n// with a `Wire` suffix to avoid clashing with the public camelCase domain types\n// imported above.\nimport type {\n Address as AddressWire,\n Advertiser as AdvertiserWire,\n Asset as AssetWire,\n CtaDetails as CtaDetailsWire,\n Footer as FooterWire,\n Offer as OfferWire,\n Recommendation as RecommendationWire,\n RecommendationGroupEntry as RecommendationGroupEntryWire,\n RecommendationGroupProperty as RecommendationGroupPropertyWire,\n RecommendationsRequest as RecommendationsWireRequest,\n RecommendationsResponse as RecommendationsWireResponse,\n} from \"../api/generated/recommendations/types.gen.js\";\nimport type {\n Address,\n Advertiser,\n CostDetails,\n Offer,\n OfferAsset,\n OfferCtaDetails,\n OfferMetadata,\n OrderDetails,\n Purchase,\n Recommendation,\n RecommendationGroupEntry,\n RecommendationGroupProperty,\n RecommendationsRequest,\n RecommendationsResponse,\n RunningExperiment,\n} from \"./recommendations.js\";\n\n/**\n * Build the snake_case wire body from the public request via explicit per-field\n * `remap`s. Transform-only: validation is performed by the generated SDK's\n * request validator (which surfaces as `DiscoValidationError` from\n * `DiscoClient`), so this does not parse or throw on bad input.\n */\nexport function transformRequest(\n request: RecommendationsRequest,\n): RecommendationsWireRequest {\n const v = request;\n // `compact` erases field types, so this cast is the request-side seam between\n // the domain shape and the wire shape. The generated SDK validates the result\n // at runtime; a full compile-time check would require a typed builder.\n return compact({\n user_details: remap(v.userDetails, {\n firstName: \"first_name\",\n lastName: \"last_name\",\n emailHash: \"email_hash\",\n externalGuid: \"external_guid\",\n }),\n placement_details: remap(v.placementDetails, {\n displayMode: \"display_mode\",\n subView: \"sub_view\",\n layoutId: \"layout_id\",\n }),\n order_details: v.orderDetails && wireOrderDetails(v.orderDetails),\n purchases: v.purchases?.map(wirePurchase),\n attributes: v.attributes && remap(v.attributes, attributesKeyMap),\n // Untyped map: recase keys algorithmically rather than field-by-field.\n custom_metadata: v.customMetadata && toSnakeKeys(v.customMetadata),\n shipping: v.shipping && wireAddress(v.shipping),\n billing: v.billing && wireAddress(v.billing),\n // `name` / `version` are already snake-safe; left as-is.\n running_experiments: v.runningExperiments,\n }) as unknown as RecommendationsWireRequest;\n}\n\nconst attributesKeyMap = {\n userAgent: \"user_agent\",\n operatingSystem: \"operating_system\",\n operatingSystemVersion: \"operating_system_version\",\n ipAddress: \"ip_address\",\n ipAddressHash: \"ip_address_hash\",\n platformType: \"platform_type\",\n deviceType: \"device_type\",\n} as const;\n\n/**\n * Map an `Address` to its wire shape. Also used by the internal (proxy) request\n * mapper: the proxy forwards addresses to this API untouched, so both clients\n * send the same shape.\n */\nexport function wireAddress(a: Address): AddressWire {\n return remap(a, {\n addressLine1: \"address_line_1\",\n addressLine2: \"address_line_2\",\n countryCode: \"country_code\",\n });\n}\n\nfunction wireCostDetails(c: CostDetails): Record<string, unknown> {\n return remap(c, { currencyCode: \"currency_code\" });\n}\n\nfunction wireOrderDetails(o: OrderDetails): Record<string, unknown> {\n return {\n ...remap(o, {\n orderId: \"order_id\",\n paymentType: \"payment_type\",\n costDetails: null,\n }),\n ...(o.costDetails && { cost_details: wireCostDetails(o.costDetails) }),\n };\n}\n\nfunction wirePurchase(p: Purchase): Record<string, unknown> {\n return {\n // `variant` is unmapped, so its value — string or data-keyed map — passes\n // through verbatim; recasing its keys would corrupt advertiser data.\n ...remap(p, {\n productId: \"product_id\",\n costDetails: null,\n attributes: null,\n }),\n ...(p.costDetails && { cost_details: wireCostDetails(p.costDetails) }),\n ...(p.attributes && {\n attributes: remap(p.attributes, {\n isClearance: \"is_clearance\",\n isGift: \"is_gift\",\n }),\n }),\n };\n}\n\n/** Drop keys whose value is `undefined` so absent optionals leave no trace. */\nfunction compact(obj: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, val] of Object.entries(obj)) {\n if (val !== undefined) out[k] = val;\n }\n return out;\n}\n\n// ─── Response: recase the generated wire response, preserving map keys ──────\n// Validation lives in the generated SDK; this is pure transformation over its\n// already-validated wire types (the `*Wire` aliases).\n\n/**\n * Recase the rec-api wire response into the friendly camelCase shape, keeping\n * the normalized maps intact. Transform-only: the generated SDK validates the\n * response before this runs, so it neither parses nor throws.\n */\nexport function transformResponse(\n raw: RecommendationsWireResponse,\n): RecommendationsResponse {\n return {\n sessionId: raw.session_id,\n recommendations: mapValues(raw.recommendations ?? {}, mapRecommendation),\n recommendationGroups: mapValues(\n raw.recommendation_groups ?? {},\n (entries) => entries.map(mapGroupEntry),\n ),\n recommendationGroupProperties: raw.recommendation_group_properties\n ? mapValues(raw.recommendation_group_properties, mapGroupProperty)\n : undefined,\n runningExperiments: raw.running_experiments?.map(\n (e): RunningExperiment => ({ name: e.name, version: e.version }),\n ),\n footer: mapFooter(raw.footer),\n };\n}\n\n/** Map a dictionary's values while preserving its (data) keys. */\nfunction mapValues<T, U>(\n obj: Record<string, T>,\n fn: (value: T) => U,\n): Record<string, U> {\n const out: Record<string, U> = {};\n for (const [key, value] of Object.entries(obj)) {\n out[key] = fn(value);\n }\n return out;\n}\n\nfunction mapRecommendation(raw: RecommendationWire): Recommendation {\n return {\n advertiser: mapAdvertiser(raw.advertiser),\n offer: mapOffer(raw.offer),\n };\n}\n\nfunction mapGroupEntry(\n raw: RecommendationGroupEntryWire,\n): RecommendationGroupEntry {\n return {\n insertionOrder: raw.insertion_order,\n insertionId: raw.insertion_id,\n offerId: raw.offer_id,\n advertiserId: raw.advertiser_id,\n };\n}\n\nfunction mapGroupProperty(\n raw: RecommendationGroupPropertyWire,\n): RecommendationGroupProperty {\n return { heading: raw.heading ?? null, slotContext: raw.slot_context };\n}\n\nfunction mapAdvertiser(raw: AdvertiserWire): 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: OfferWire): Offer {\n return {\n id: raw.id,\n heading: raw.heading,\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: mapMetadata(raw.metadata),\n disclosureDetails: raw.disclosure_details\n ? {\n copy: raw.disclosure_details.copy,\n targetUrl: raw.disclosure_details.target_url ?? null,\n content: raw.disclosure_details.content ?? null,\n }\n : null,\n };\n}\n\nfunction mapCtaDetails(raw: CtaDetailsWire): OfferCtaDetails {\n return {\n acceptCopy: raw.accept_copy,\n declineCopy: raw.decline_copy,\n transitionCopy: raw.transition_copy ?? null,\n claimedAcceptCopy: raw.claimed_accept_copy ?? null,\n claimedDeclineCopy: raw.claimed_decline_copy ?? null,\n };\n}\n\nfunction mapAsset(raw: AssetWire): OfferAsset {\n return {\n assetType: raw.asset_type,\n imageUrl: raw.image_url,\n insertionOrder: raw.insertion_order,\n id: raw.id ?? null,\n targetUrl: raw.target_url ?? null,\n // Spec marks this optional; default to `false` to keep the public type's\n // required boolean.\n shouldTriggerClaimFlow: raw.should_trigger_claim_flow ?? false,\n };\n}\n\nfunction mapMetadata(raw: OfferWire[\"metadata\"]): OfferMetadata {\n return raw.type === \"PROMO_CODE\"\n ? { type: \"PROMO_CODE\", code: raw.code, layoutType: raw.layout_type }\n : { type: \"NO_PROMO_CODE\", layoutType: raw.layout_type };\n}\n\nfunction mapFooter(raw: FooterWire): RecommendationsResponse[\"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":";;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,iBACd,SAC4B;CAC5B,MAAM,IAAI;CAIV,OAAO,QAAQ;EACb,cAAc,MAAM,EAAE,aAAa;GACjC,WAAW;GACX,UAAU;GACV,WAAW;GACX,cAAc;EAChB,CAAC;EACD,mBAAmB,MAAM,EAAE,kBAAkB;GAC3C,aAAa;GACb,SAAS;GACT,UAAU;EACZ,CAAC;EACD,eAAe,EAAE,gBAAgB,iBAAiB,EAAE,YAAY;EAChE,WAAW,EAAE,WAAW,IAAI,YAAY;EACxC,YAAY,EAAE,cAAc,MAAM,E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