@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
package/dist/internal.js
CHANGED
|
@@ -1,562 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
* Best-effort read of a non-2xx response body: try JSON, fall back to text,
|
|
8
|
-
* then give up with `undefined`. Used by both clients to populate
|
|
9
|
-
* `DiscoApiError.body` without ever throwing from the error path.
|
|
10
|
-
*/
|
|
11
|
-
async function safeReadBody(response) {
|
|
12
|
-
try {
|
|
13
|
-
return await response.clone().json();
|
|
14
|
-
} catch {
|
|
15
|
-
try {
|
|
16
|
-
return await response.text();
|
|
17
|
-
} catch {
|
|
18
|
-
return;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
//#endregion
|
|
23
|
-
//#region src/TrackingManager.ts
|
|
24
|
-
/**
|
|
25
|
-
* Renderer-agnostic event tracker for Disco recommendation surfaces.
|
|
26
|
-
*
|
|
27
|
-
* Owns:
|
|
28
|
-
* - the dedup set (so repeated display/view events for the same brand
|
|
29
|
-
* don't get re-sent within a session)
|
|
30
|
-
* - the network call to the partner-events endpoint
|
|
31
|
-
* - payload formatting (snake_case keys, BE-friendly datetime)
|
|
32
|
-
*
|
|
33
|
-
* Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s
|
|
34
|
-
* `DiscoProvider`) when consuming from a React tree, or instantiate it
|
|
35
|
-
* directly from any other JS environment.
|
|
36
|
-
*
|
|
37
|
-
* `track` is implemented as an instance-bound arrow function so consumers
|
|
38
|
-
* can safely destructure it without losing `this`.
|
|
39
|
-
*/
|
|
40
|
-
var TrackingManager = class {
|
|
41
|
-
#endpoint;
|
|
42
|
-
#headers;
|
|
43
|
-
#sessionId;
|
|
44
|
-
#fetch;
|
|
45
|
-
#dedupe = /* @__PURE__ */ new Set();
|
|
46
|
-
constructor(config) {
|
|
47
|
-
this.#endpoint = config.endpoint;
|
|
48
|
-
this.#headers = {
|
|
49
|
-
...config.headers,
|
|
50
|
-
...getSdkHeaders(config.sdk)
|
|
51
|
-
};
|
|
52
|
-
this.#sessionId = config.sessionId;
|
|
53
|
-
this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Send a tracking event. Fire-and-forget — never throws.
|
|
57
|
-
* Failures are logged via `console.error`.
|
|
58
|
-
*
|
|
59
|
-
* Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and
|
|
60
|
-
* `BRAND_VIEW` are deduped per-instance by (event type, insertionId).
|
|
61
|
-
*/
|
|
62
|
-
track = (event) => {
|
|
63
|
-
if (this.#isDeduped(event)) return;
|
|
64
|
-
this.#fetch(this.#endpoint, {
|
|
65
|
-
method: "POST",
|
|
66
|
-
headers: {
|
|
67
|
-
"Content-Type": "application/json",
|
|
68
|
-
...this.#headers
|
|
69
|
-
},
|
|
70
|
-
body: JSON.stringify(this.#toBody(event)),
|
|
71
|
-
keepalive: true
|
|
72
|
-
}).catch((error) => {
|
|
73
|
-
console.error("Event tracking failed:", error);
|
|
74
|
-
});
|
|
75
|
-
};
|
|
76
|
-
#isDeduped(event) {
|
|
77
|
-
if (event.type === "WIDGET_DISPLAY" || event.type === "WIDGET_VIEW" || event.type === "BRAND_DISPLAY" || event.type === "BRAND_VIEW") {
|
|
78
|
-
const key = event.type + ("brand" in event ? event.brand.insertionId : "widget");
|
|
79
|
-
if (this.#dedupe.has(key)) return true;
|
|
80
|
-
this.#dedupe.add(key);
|
|
81
|
-
}
|
|
82
|
-
return false;
|
|
83
|
-
}
|
|
84
|
-
#toBody(event) {
|
|
85
|
-
const commonEventFields = {
|
|
86
|
-
session_id: this.#sessionId,
|
|
87
|
-
event_name: event.type,
|
|
88
|
-
event_datetime: (/* @__PURE__ */ new Date()).toISOString().replace("Z", "+00:00"),
|
|
89
|
-
placement_details: event.placement ? {
|
|
90
|
-
display_mode: event.placement.displayMode,
|
|
91
|
-
view: event.placement.view,
|
|
92
|
-
layout_id: event.placement.layoutId
|
|
93
|
-
} : void 0
|
|
94
|
-
};
|
|
95
|
-
switch (event.type) {
|
|
96
|
-
case "BRAND_CLICK": return {
|
|
97
|
-
...commonEventFields,
|
|
98
|
-
brand_properties: brandProperties(event.brand),
|
|
99
|
-
initiating_target: event.target,
|
|
100
|
-
asset_id: event.assetId
|
|
101
|
-
};
|
|
102
|
-
case "BRAND_DISPLAY":
|
|
103
|
-
case "BRAND_VIEW": return {
|
|
104
|
-
...commonEventFields,
|
|
105
|
-
brand_properties: brandProperties(event.brand),
|
|
106
|
-
initiating_target: event.target
|
|
107
|
-
};
|
|
108
|
-
case "PRODUCT_DISPLAY":
|
|
109
|
-
case "PRODUCT_VIEW":
|
|
110
|
-
case "PRODUCT_CLICK": return {
|
|
111
|
-
...commonEventFields,
|
|
112
|
-
brand_properties: brandProperties(event.brand),
|
|
113
|
-
product_properties: { product_id: event.product.productId },
|
|
114
|
-
initiating_target: event.target
|
|
115
|
-
};
|
|
116
|
-
case "ELEMENT_CLICK": return {
|
|
117
|
-
...commonEventFields,
|
|
118
|
-
brand_properties: event.brand ? brandProperties(event.brand) : void 0,
|
|
119
|
-
initiating_target: event.target
|
|
120
|
-
};
|
|
121
|
-
default: return commonEventFields;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
};
|
|
125
|
-
function brandProperties(brand) {
|
|
126
|
-
return {
|
|
127
|
-
offer_id: brand.offerId,
|
|
128
|
-
advertiser_id: brand.advertiserId,
|
|
129
|
-
insertion_id: brand.insertionId
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
//#endregion
|
|
133
|
-
//#region src/internal/denormalize.ts
|
|
134
|
-
/**
|
|
135
|
-
* Join the normalized response maps into ordered `RecommendationGroup[]`.
|
|
136
|
-
*
|
|
137
|
-
* Groups are ordered by the numeric suffix of their key (`group_0` before
|
|
138
|
-
* `group_10`); within each group, entries are ordered by `insertionOrder`.
|
|
139
|
-
* Groups missing their entry list or display properties are skipped, as are
|
|
140
|
-
* entries whose `offerId` is absent from the recommendations map. Each result
|
|
141
|
-
* recommendation's `id` is the offer's id and its `insertionId` comes from the
|
|
142
|
-
* group entry.
|
|
143
|
-
*/
|
|
144
|
-
function denormalize(response) {
|
|
145
|
-
const recommendations = response.recommendations;
|
|
146
|
-
const groupEntries = response.recommendationGroups;
|
|
147
|
-
const groupProps = response.recommendationGroupProperties ?? {};
|
|
148
|
-
const orderedKeys = Object.keys(groupEntries).sort((a, b) => numericSuffix(a) - numericSuffix(b));
|
|
149
|
-
const recommendationGroups = [];
|
|
150
|
-
for (const key of orderedKeys) {
|
|
151
|
-
const entries = groupEntries[key];
|
|
152
|
-
const props = groupProps[key];
|
|
153
|
-
if (!entries || !props) continue;
|
|
154
|
-
const recs = [];
|
|
155
|
-
for (const entry of entries) {
|
|
156
|
-
const rec = recommendations[entry.offerId];
|
|
157
|
-
if (!rec) continue;
|
|
158
|
-
recs.push({
|
|
159
|
-
id: rec.offer.id,
|
|
160
|
-
insertionId: entry.insertionId,
|
|
161
|
-
advertiser: rec.advertiser,
|
|
162
|
-
offer: rec.offer
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
recommendationGroups.push({
|
|
166
|
-
heading: props.heading ?? null,
|
|
167
|
-
slotContext: props.slotContext,
|
|
168
|
-
recommendations: recs
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
return recommendationGroups;
|
|
172
|
-
}
|
|
173
|
-
function numericSuffix(value) {
|
|
174
|
-
const suffix = value.split("_").pop() ?? "";
|
|
175
|
-
const parsed = Number.parseInt(suffix, 10);
|
|
176
|
-
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
|
177
|
-
}
|
|
178
|
-
//#endregion
|
|
179
|
-
//#region src/internal/recommendationsMapper.ts
|
|
180
|
-
/**
|
|
181
|
-
* Maps the proxy `/recommendations` response into the public, denormalized
|
|
182
|
-
* `RecommendationsResponse` (`mapRecommendationsResponse`).
|
|
183
|
-
*
|
|
184
|
-
* The proxy response is the external `/recommendations` response **verbatim plus
|
|
185
|
-
* a few extra top-level fields** (`layout_id`, `publisher_customization`, the
|
|
186
|
-
* `widget_*` markers, …). So this reuses the external machinery — the generated
|
|
187
|
-
* zod validator (`zRecommendationsResponse2`) and the external `transformResponse`
|
|
188
|
-
* mapper — and only layers on the denormalization (the join into
|
|
189
|
-
* `RecommendationGroup[]`) and the proxy extras.
|
|
190
|
-
*
|
|
191
|
-
* Validation is zod-backed: the external-wire part is validated by the generated
|
|
192
|
-
* `zRecommendationsResponse2` and the proxy extras by a small local schema, so a
|
|
193
|
-
* malformed server response surfaces as a `DiscoValidationError` rather than an
|
|
194
|
-
* opaque `undefined`-access crash deep in the join.
|
|
195
|
-
*/
|
|
196
|
-
const zProxyExtras = z.object({
|
|
197
|
-
layout_id: z.string().optional(),
|
|
198
|
-
publisher_customization: z.record(z.string(), z.record(z.string(), z.union([z.string(), z.boolean()]))).nullish()
|
|
199
|
-
});
|
|
200
|
-
/**
|
|
201
|
-
* Validate the proxy recommendations response and denormalize it into the
|
|
202
|
-
* public `RecommendationsResponse`.
|
|
203
|
-
*
|
|
204
|
-
* The proxy payload is the external wire response plus extras, so this reuses
|
|
205
|
-
* the external machinery: validate the wire part with the generated
|
|
206
|
-
* `zRecommendationsResponse2` and the extras with `zProxyExtras`, recase via
|
|
207
|
-
* the external `transformResponse`, then denormalize the resulting maps into
|
|
208
|
-
* `RecommendationGroup[]` (the internal value-add) and assemble the response
|
|
209
|
-
* with the proxy extras layered on.
|
|
210
|
-
*
|
|
211
|
-
* Throws `DiscoValidationError` if the server payload doesn't match the
|
|
212
|
-
* expected shape.
|
|
213
|
-
*
|
|
214
|
-
* @internal Built into `InternalDiscoClient.getRecommendations`; not part of
|
|
215
|
-
* the public API. The wire shape is encapsulated by the client on purpose.
|
|
216
|
-
*/
|
|
217
|
-
function mapRecommendationsResponse(raw) {
|
|
218
|
-
let wire;
|
|
219
|
-
let extras;
|
|
220
|
-
try {
|
|
221
|
-
wire = zRecommendationsResponse2.parse(raw);
|
|
222
|
-
extras = zProxyExtras.parse(raw);
|
|
223
|
-
} catch (error) {
|
|
224
|
-
if (error instanceof ZodError) throw new DiscoValidationError("Failed to validate recommendations response", error, raw);
|
|
225
|
-
throw error;
|
|
226
|
-
}
|
|
227
|
-
const normalized = transformResponse(wire);
|
|
228
|
-
const recommendationGroups = denormalize(normalized);
|
|
229
|
-
return {
|
|
230
|
-
sessionId: normalized.sessionId,
|
|
231
|
-
layoutId: extras.layout_id ?? "SHOPIFY_NATIVE_ESSENTIAL",
|
|
232
|
-
recommendationGroups,
|
|
233
|
-
footer: normalized.footer,
|
|
234
|
-
publisherCustomization: extras.publisher_customization ?? null
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
//#endregion
|
|
238
|
-
//#region src/lib/schemas.ts
|
|
239
|
-
/**
|
|
240
|
-
* Thin wrappers around Zod parsing that convert a thrown `ZodError` into a
|
|
241
|
-
* `DiscoValidationError`, so validation failures surface as a Disco error type
|
|
242
|
-
* rather than leaking Zod's internals to consumers. Modeled on the equivalent
|
|
243
|
-
* helpers in Speakeasy-generated SDKs.
|
|
244
|
-
*/
|
|
245
|
-
/**
|
|
246
|
-
* Run `fn` (typically a `schema.parse`) and, if it throws a `ZodError`, rethrow
|
|
247
|
-
* it as a `DiscoValidationError`. Any non-Zod error propagates untouched.
|
|
248
|
-
*/
|
|
249
|
-
function parse(rawValue, fn, errorMessage) {
|
|
250
|
-
try {
|
|
251
|
-
return fn(rawValue);
|
|
252
|
-
} catch (err) {
|
|
253
|
-
if (err instanceof z.ZodError) throw new DiscoValidationError(errorMessage, err, rawValue);
|
|
254
|
-
throw err;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
//#endregion
|
|
258
|
-
//#region src/internal/recommendationsRequestMapper.ts
|
|
259
|
-
/**
|
|
260
|
-
* Wire types for the recommendations *request* and `transformRequest`, which
|
|
261
|
-
* builds the snake_case wire body from the public `RecommendationsRequest`.
|
|
262
|
-
*
|
|
263
|
-
* `InternalDiscoClient.getRecommendations` calls `transformRequest` to map the
|
|
264
|
-
* camelCase request into the wire body before POSTing it.
|
|
265
|
-
*
|
|
266
|
-
* The mapping is Zod-backed: `RecommendationsRequest$outboundSchema` validates
|
|
267
|
-
* the public request before the `.transform()` reshapes it into the wire body,
|
|
268
|
-
* so a malformed request surfaces as a `DiscoValidationError` *before* it hits
|
|
269
|
-
* the network. This mirrors how Speakeasy-generated SDKs use an
|
|
270
|
-
* `$outboundSchema` per model.
|
|
271
|
-
*/
|
|
272
|
-
const UserDetails$outboundSchema = z.object({
|
|
273
|
-
email: z.string().optional(),
|
|
274
|
-
firstName: z.string().optional(),
|
|
275
|
-
lastName: z.string().optional(),
|
|
276
|
-
phone: z.string().optional()
|
|
277
|
-
}).transform((v) => remap(v, {
|
|
278
|
-
firstName: "first_name",
|
|
279
|
-
lastName: "last_name"
|
|
280
|
-
}));
|
|
281
|
-
const PlacementDetails$outboundSchema = z.object({
|
|
282
|
-
displayMode: z.string().optional(),
|
|
283
|
-
view: z.string().optional()
|
|
284
|
-
}).transform((v) => remap(v, { displayMode: "display_mode" }));
|
|
285
|
-
const OrderDetails$outboundSchema = z.object({
|
|
286
|
-
id: z.string().optional(),
|
|
287
|
-
amount: z.union([z.number(), z.string()]).optional(),
|
|
288
|
-
currencyCode: z.string().optional()
|
|
289
|
-
}).transform((v) => ({
|
|
290
|
-
order_id: v.id,
|
|
291
|
-
cost_details: v.amount !== void 0 || v.currencyCode !== void 0 ? {
|
|
292
|
-
amount: v.amount,
|
|
293
|
-
currency_code: v.currencyCode
|
|
294
|
-
} : void 0
|
|
295
|
-
}));
|
|
296
|
-
const Purchase$outboundSchema = z.object({
|
|
297
|
-
name: z.string().optional(),
|
|
298
|
-
type: z.string().optional(),
|
|
299
|
-
variant: z.string().optional(),
|
|
300
|
-
quantity: z.number().optional(),
|
|
301
|
-
productId: z.string().optional(),
|
|
302
|
-
amount: z.number().optional(),
|
|
303
|
-
currencyCode: z.string().optional()
|
|
304
|
-
}).transform((v) => ({
|
|
305
|
-
name: v.name,
|
|
306
|
-
type: v.type,
|
|
307
|
-
variant: v.variant,
|
|
308
|
-
quantity: v.quantity,
|
|
309
|
-
product_id: v.productId,
|
|
310
|
-
cost_details: v.amount !== void 0 || v.currencyCode !== void 0 ? {
|
|
311
|
-
amount: v.amount,
|
|
312
|
-
currency_code: v.currencyCode
|
|
313
|
-
} : void 0
|
|
314
|
-
}));
|
|
315
|
-
const RunningExperiment$outboundSchema = z.object({
|
|
316
|
-
id: z.string(),
|
|
317
|
-
variant: z.string()
|
|
318
|
-
});
|
|
319
|
-
/**
|
|
320
|
-
* Validates the public request and reshapes it into the raw wire body: nest
|
|
321
|
-
* fields under `recommendations_data`, fold monetary fields into `cost_details`,
|
|
322
|
-
* convert camelCase to snake_case, and spread `extras` at the top level
|
|
323
|
-
* untransformed.
|
|
324
|
-
*/
|
|
325
|
-
const RecommendationsRequest$outboundSchema = z.object({
|
|
326
|
-
user: UserDetails$outboundSchema.optional(),
|
|
327
|
-
placement: PlacementDetails$outboundSchema.optional(),
|
|
328
|
-
order: OrderDetails$outboundSchema.optional(),
|
|
329
|
-
purchases: z.array(Purchase$outboundSchema).optional(),
|
|
330
|
-
experiments: z.array(RunningExperiment$outboundSchema).optional(),
|
|
331
|
-
attributes: z.record(z.string(), z.unknown()).optional(),
|
|
332
|
-
extras: z.record(z.string(), z.unknown()).optional()
|
|
333
|
-
}).transform((v) => ({
|
|
334
|
-
recommendations_data: {
|
|
335
|
-
user_details: v.user,
|
|
336
|
-
placement_details: v.placement,
|
|
337
|
-
order_details: v.order,
|
|
338
|
-
purchases: v.purchases
|
|
339
|
-
},
|
|
340
|
-
running_experiments: v.experiments,
|
|
341
|
-
attributes: v.attributes,
|
|
342
|
-
...v.extras
|
|
343
|
-
}));
|
|
344
|
-
/**
|
|
345
|
-
* Build the raw request body from the public `RecommendationsRequest`: nest
|
|
346
|
-
* fields under `recommendations_data`, fold monetary fields into `cost_details`
|
|
347
|
-
* (omitted entirely when no amount/currency is present), and convert camelCase
|
|
348
|
-
* to snake_case. `extras` is spread at the top level untransformed.
|
|
349
|
-
*
|
|
350
|
-
* Validates the input first and throws `DiscoValidationError` if the request
|
|
351
|
-
* doesn't match the expected shape.
|
|
352
|
-
*
|
|
353
|
-
* @internal Built into `DiscoClient.getRecommendations`; not part of the public
|
|
354
|
-
* API. The wire shape is encapsulated by the client on purpose.
|
|
355
|
-
*/
|
|
356
|
-
function transformRequest(req) {
|
|
357
|
-
return parse(req, (value) => RecommendationsRequest$outboundSchema.parse(value), "Failed to validate recommendations request");
|
|
358
|
-
}
|
|
359
|
-
//#endregion
|
|
360
|
-
//#region src/internal/InternalDiscoClient.ts
|
|
361
|
-
/**
|
|
362
|
-
* Per-environment base URL for the internal/proxy backend — the legacy server
|
|
363
|
-
* that orchestrates and forwards to the downstream services. Both the
|
|
364
|
-
* recommendations and tracking endpoints sit under this origin, routed by path
|
|
365
|
-
* (the client appends `/core/recommendations/…` and `/track/partners_event/`).
|
|
366
|
-
*/
|
|
367
|
-
const INTERNAL_BASE_URL = {
|
|
368
|
-
production: "https://consumer.disconetwork.com",
|
|
369
|
-
staging: "https://consumer.disconetwork-staging.com"
|
|
370
|
-
};
|
|
371
|
-
/**
|
|
372
|
-
* Internal client for the legacy **proxy** recommendations endpoint
|
|
373
|
-
* (`/core/recommendations/` on the backend), which orchestrates placement,
|
|
374
|
-
* experiments, layout, and `publisher_customization` server-side and supports
|
|
375
|
-
* `shopGid` auth for first-party surfaces (e.g. the Shopify checkout
|
|
376
|
-
* extension).
|
|
377
|
-
*
|
|
378
|
-
* First-party / legacy only — exported from `@disconetwork/core/internal`.
|
|
379
|
-
* External partners use the `DiscoClient` from the package root, which talks
|
|
380
|
-
* directly to `disco-recommendations-api`.
|
|
381
|
-
*
|
|
382
|
-
* Renderer-agnostic: this class makes plain HTTP calls and has no React
|
|
383
|
-
* dependency.
|
|
384
|
-
*/
|
|
385
|
-
var InternalDiscoClient = class {
|
|
386
|
-
#env;
|
|
387
|
-
#url;
|
|
388
|
-
#headers;
|
|
389
|
-
#sdk;
|
|
390
|
-
#fetch;
|
|
391
|
-
get env() {
|
|
392
|
-
return this.#env;
|
|
393
|
-
}
|
|
394
|
-
constructor(config) {
|
|
395
|
-
this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
396
|
-
this.#sdk = config.sdk ? { ...config.sdk } : void 0;
|
|
397
|
-
if ("apiKey" in config) {
|
|
398
|
-
validatePublicApiKey(config.apiKey);
|
|
399
|
-
this.#env = "production";
|
|
400
|
-
const path = config.surface === "shopify" ? "shopify/" : "";
|
|
401
|
-
this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/${path}`;
|
|
402
|
-
this.#headers = {
|
|
403
|
-
"x-api-key": config.apiKey,
|
|
404
|
-
"Content-Type": "application/json"
|
|
405
|
-
};
|
|
406
|
-
} else {
|
|
407
|
-
this.#env = config.env;
|
|
408
|
-
const shopId = stripShopGid(config.shopGid);
|
|
409
|
-
this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;
|
|
410
|
-
this.#headers = { "Content-Type": "application/json" };
|
|
411
|
-
}
|
|
412
|
-
Object.assign(this.#headers, getSdkHeaders(this.#sdk));
|
|
413
|
-
}
|
|
414
|
-
/**
|
|
415
|
-
* Fetch recommendations for the given request.
|
|
416
|
-
*
|
|
417
|
-
* Validates and transforms the friendly camelCase `request` into the wire
|
|
418
|
-
* body, POSTs it, then validates and denormalizes the response into the
|
|
419
|
-
* friendly `RecommendationsResponse`. The snake_case wire format is fully
|
|
420
|
-
* encapsulated — callers never see it.
|
|
421
|
-
*
|
|
422
|
-
* Throws `DiscoValidationError` if the request or response fails schema
|
|
423
|
-
* validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`
|
|
424
|
-
* if the request can't reach the server (an abort rejects with the native
|
|
425
|
-
* `AbortError`). Parse failures propagate as-is.
|
|
426
|
-
*/
|
|
427
|
-
getRecommendations = async (request, options) => {
|
|
428
|
-
const body = JSON.stringify(transformRequest(request));
|
|
429
|
-
let response;
|
|
430
|
-
try {
|
|
431
|
-
response = await this.#fetch(this.#url, {
|
|
432
|
-
method: "POST",
|
|
433
|
-
headers: this.#headers,
|
|
434
|
-
body,
|
|
435
|
-
signal: options?.signal
|
|
436
|
-
});
|
|
437
|
-
} catch (error) {
|
|
438
|
-
if (isAbortError(error)) throw error;
|
|
439
|
-
throw new DiscoNetworkError("Recommendations request failed to reach the server", error);
|
|
440
|
-
}
|
|
441
|
-
if (!response.ok) {
|
|
442
|
-
const body = await safeReadBody(response);
|
|
443
|
-
throw new DiscoApiError(`Recommendations request failed: ${response.status} ${response.statusText}`, {
|
|
444
|
-
status: response.status,
|
|
445
|
-
statusText: response.statusText,
|
|
446
|
-
body
|
|
447
|
-
});
|
|
448
|
-
}
|
|
449
|
-
return mapRecommendationsResponse(await response.json());
|
|
450
|
-
};
|
|
451
|
-
/**
|
|
452
|
-
* Fetch recommendations and create a session-bound tracker in one call.
|
|
453
|
-
*
|
|
454
|
-
* Composition convenience over `getRecommendations` + `createTrackingManager`:
|
|
455
|
-
* it derives the tracker's session from the response so callers don't have to
|
|
456
|
-
* thread the session id through themselves (and can't bind a tracker to the
|
|
457
|
-
* wrong session). The returned `data` is the mapped `RecommendationsResponse`.
|
|
458
|
-
*
|
|
459
|
-
* Throws `DiscoValidationError` / `DiscoApiError` the same as
|
|
460
|
-
* `getRecommendations`.
|
|
461
|
-
*/
|
|
462
|
-
getRecommendationsWithTracker = async (request, options) => {
|
|
463
|
-
const data = await this.getRecommendations(request, { signal: options?.signal });
|
|
464
|
-
return {
|
|
465
|
-
data,
|
|
466
|
-
tracker: this.createTrackingManager(data.sessionId, { fetch: options?.fetch })
|
|
467
|
-
};
|
|
468
|
-
};
|
|
469
|
-
/**
|
|
470
|
-
* Create an event tracker bound to a recommendations session (the `sessionId`
|
|
471
|
-
* from a `getRecommendations` response).
|
|
472
|
-
*
|
|
473
|
-
* The tracker uses the same environment as the recommendations call.
|
|
474
|
-
* Both live and sandbox public keys use production.
|
|
475
|
-
*/
|
|
476
|
-
createTrackingManager = (sessionId, options) => new TrackingManager({
|
|
477
|
-
sessionId,
|
|
478
|
-
endpoint: `${INTERNAL_BASE_URL[this.#env]}/track/partners_event/`,
|
|
479
|
-
fetch: options?.fetch ?? this.#fetch,
|
|
480
|
-
sdk: this.#sdk
|
|
481
|
-
});
|
|
482
|
-
};
|
|
483
|
-
function stripShopGid(shopGid) {
|
|
484
|
-
return shopGid.replace("gid://shopify/Shop/", "");
|
|
485
|
-
}
|
|
486
|
-
//#endregion
|
|
487
|
-
//#region src/internal/screens.ts
|
|
488
|
-
const TextNodeSchema = z.object({
|
|
489
|
-
type: z.literal("text"),
|
|
490
|
-
text: z.string()
|
|
491
|
-
});
|
|
492
|
-
const ExternalLinkAttributesSchema = z.object({
|
|
493
|
-
to: z.url(),
|
|
494
|
-
external: z.boolean().optional().default(true)
|
|
495
|
-
});
|
|
496
|
-
const InternalLinkAttributesSchema = z.object({ targetScreenId: z.string() });
|
|
497
|
-
const LinkAttributesSchema = z.union([ExternalLinkAttributesSchema, InternalLinkAttributesSchema]);
|
|
498
|
-
const LinkNodeSchema = z.object({
|
|
499
|
-
type: z.literal("link"),
|
|
500
|
-
attributes: LinkAttributesSchema,
|
|
501
|
-
get children() {
|
|
502
|
-
return z.array(ASTNodeSchema).min(1);
|
|
503
|
-
}
|
|
504
|
-
});
|
|
505
|
-
const ParagraphNodeSchema = z.object({
|
|
506
|
-
type: z.literal("paragraph"),
|
|
507
|
-
get children() {
|
|
508
|
-
return z.array(ASTNodeSchema).min(1);
|
|
509
|
-
}
|
|
510
|
-
});
|
|
511
|
-
const ScrollViewNodeSchema = z.object({
|
|
512
|
-
type: z.literal("scrollview"),
|
|
513
|
-
attributes: z.object({ maxBlockSize: z.number().optional() }).optional(),
|
|
514
|
-
get children() {
|
|
515
|
-
return z.array(ASTNodeSchema).min(1);
|
|
516
|
-
}
|
|
517
|
-
});
|
|
518
|
-
const ASTNodeSchema = z.discriminatedUnion("type", [
|
|
519
|
-
TextNodeSchema,
|
|
520
|
-
LinkNodeSchema,
|
|
521
|
-
ParagraphNodeSchema,
|
|
522
|
-
ScrollViewNodeSchema
|
|
523
|
-
]);
|
|
524
|
-
const ASTSchema = z.object({ get children() {
|
|
525
|
-
return z.array(ASTNodeSchema).min(1);
|
|
526
|
-
} });
|
|
527
|
-
const ScreenSchema = ASTSchema.extend({ id: z.string() });
|
|
528
|
-
function collectTargetScreenIds(nodes) {
|
|
529
|
-
const ids = [];
|
|
530
|
-
for (const node of nodes) {
|
|
531
|
-
if (node.type === "link" && "targetScreenId" in node.attributes) ids.push(node.attributes.targetScreenId);
|
|
532
|
-
if ("children" in node) ids.push(...collectTargetScreenIds(node.children));
|
|
533
|
-
}
|
|
534
|
-
return ids;
|
|
535
|
-
}
|
|
536
|
-
const ScreenDocumentSchema = z.object({ screens: z.array(ScreenSchema).min(1) }).refine((doc) => {
|
|
537
|
-
const ids = doc.screens.map((s) => s.id);
|
|
538
|
-
return new Set(ids).size === ids.length;
|
|
539
|
-
}, { message: "Duplicate screen IDs" }).refine((doc) => {
|
|
540
|
-
const screenIds = new Set(doc.screens.map((s) => s.id));
|
|
541
|
-
return doc.screens.flatMap((s) => collectTargetScreenIds(s.children)).every((id) => screenIds.has(id));
|
|
542
|
-
}, { message: "targetScreenId references a non-existent screen" });
|
|
543
|
-
/**
|
|
544
|
-
* Parse offer screens content into a list of screens. Returns `null` when the
|
|
545
|
-
* content is missing or matches neither the screen document nor the legacy
|
|
546
|
-
* single-root shape, so callers can render a fallback.
|
|
547
|
-
*/
|
|
548
|
-
function parseScreens(jsonContent) {
|
|
549
|
-
if (!jsonContent) return null;
|
|
550
|
-
const screenResult = ScreenDocumentSchema.safeParse(jsonContent);
|
|
551
|
-
if (screenResult.success) return screenResult.data.screens;
|
|
552
|
-
const legacyResult = ASTSchema.safeParse(jsonContent);
|
|
553
|
-
if (legacyResult.success) return [{
|
|
554
|
-
id: "default",
|
|
555
|
-
children: legacyResult.data.children
|
|
556
|
-
}];
|
|
557
|
-
return null;
|
|
558
|
-
}
|
|
559
|
-
//#endregion
|
|
2
|
+
import { DiscoApiError, DiscoError, DiscoNetworkError, DiscoValidationError } from "./errors.js";
|
|
3
|
+
import { TrackingManager } from "./TrackingManager.js";
|
|
4
|
+
import { denormalize } from "./internal/denormalize.js";
|
|
5
|
+
import { INTERNAL_BASE_URL, InternalDiscoClient } from "./internal/InternalDiscoClient.js";
|
|
6
|
+
import { parseScreens } from "./internal/screens.js";
|
|
560
7
|
export { DiscoApiError, DiscoError, DiscoNetworkError, DiscoValidationError, INTERNAL_BASE_URL, InternalDiscoClient, TrackingManager, denormalize, parseScreens };
|
|
561
|
-
|
|
562
|
-
//# sourceMappingURL=internal.js.map
|
package/dist/lib/case.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/lib/case.ts
|
|
2
|
+
/**
|
|
3
|
+
* Recursively convert an object's keys from camelCase to snake_case, descending
|
|
4
|
+
* into nested objects and arrays. Values are left untouched.
|
|
5
|
+
*
|
|
6
|
+
* Reserved for the request's `customMetadata` — an untyped map whose keys are
|
|
7
|
+
* known field names we want recased, not arbitrary data. Everything else on the
|
|
8
|
+
* request path is remapped field-by-field (see `recommendationsTransforms.ts`), so
|
|
9
|
+
* data-keyed values like a purchase `variant` map are never blindly recased.
|
|
10
|
+
*/
|
|
11
|
+
function toSnakeKeys(value) {
|
|
12
|
+
if (Array.isArray(value)) return value.map(toSnakeKeys);
|
|
13
|
+
if (value !== null && typeof value === "object") {
|
|
14
|
+
const out = {};
|
|
15
|
+
for (const [key, v] of Object.entries(value)) out[snakeCase(key)] = toSnakeKeys(v);
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function snakeCase(key) {
|
|
21
|
+
return key.replace(/([A-Za-z])([0-9])/g, "$1_$2").replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { toSnakeKeys };
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=case.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"case.js","names":[],"sources":["../../src/lib/case.ts"],"sourcesContent":["/**\n * Recursively convert an object's keys from camelCase to snake_case, descending\n * into nested objects and arrays. Values are left untouched.\n *\n * Reserved for the request's `customMetadata` — an untyped map whose keys are\n * known field names we want recased, not arbitrary data. Everything else on the\n * request path is remapped field-by-field (see `recommendationsTransforms.ts`), so\n * data-keyed values like a purchase `variant` map are never blindly recased.\n */\nexport function toSnakeKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(toSnakeKeys);\n }\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(value)) {\n out[snakeCase(key)] = toSnakeKeys(v);\n }\n return out;\n }\n return value;\n}\n\nfunction snakeCase(key: string): string {\n return (\n key\n // Split a letter→digit boundary so `addressLine1` → `address_line_1`.\n .replace(/([A-Za-z])([0-9])/g, \"$1_$2\")\n .replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`)\n );\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,YAAY,OAAyB;CACnD,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,WAAW;CAE9B,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,MAAM,MAA+B,CAAC;EACtC,KAAK,MAAM,CAAC,KAAK,MAAM,OAAO,QAAQ,KAAK,GACzC,IAAI,UAAU,GAAG,KAAK,YAAY,CAAC;EAErC,OAAO;CACT;CACA,OAAO;AACT;AAEA,SAAS,UAAU,KAAqB;CACtC,OACE,IAEG,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,WAAW,UAAU,IAAI,MAAM,YAAY,GAAG;AAE7D"}
|
package/dist/lib/http.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region src/lib/http.ts
|
|
2
|
+
/**
|
|
3
|
+
* Best-effort read of a non-2xx response body: try JSON, fall back to text,
|
|
4
|
+
* then give up with `undefined`. Used by both clients to populate
|
|
5
|
+
* `DiscoApiError.body` without ever throwing from the error path.
|
|
6
|
+
*/
|
|
7
|
+
async function safeReadBody(response) {
|
|
8
|
+
try {
|
|
9
|
+
return await response.clone().json();
|
|
10
|
+
} catch {
|
|
11
|
+
try {
|
|
12
|
+
return await response.text();
|
|
13
|
+
} catch {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
export { safeReadBody };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=http.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.js","names":[],"sources":["../../src/lib/http.ts"],"sourcesContent":["/**\n * Best-effort read of a non-2xx response body: try JSON, fall back to text,\n * then give up with `undefined`. Used by both clients to populate\n * `DiscoApiError.body` without ever throwing from the error path.\n */\nexport async function safeReadBody(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n }\n}\n"],"mappings":";;;;;;AAKA,eAAsB,aAAa,UAAsC;CACvE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,EAAE,KAAK;CACrC,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,SAAS,KAAK;EAC7B,QAAQ;GACN;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/lib/primitives.ts
|
|
2
|
+
/**
|
|
3
|
+
* Return a new object with `inp`'s keys renamed according to `mappings`.
|
|
4
|
+
* A key mapped to a string is renamed; a key mapped to `null` is dropped; a key
|
|
5
|
+
* absent from the mapping is kept as-is.
|
|
6
|
+
*/
|
|
7
|
+
function remap(inp, mappings) {
|
|
8
|
+
let out = {};
|
|
9
|
+
if (!Object.keys(mappings).length) {
|
|
10
|
+
out = inp;
|
|
11
|
+
return out;
|
|
12
|
+
}
|
|
13
|
+
for (const [k, v] of Object.entries(inp)) {
|
|
14
|
+
const j = mappings[k];
|
|
15
|
+
if (j === null) continue;
|
|
16
|
+
out[j ?? k] = v;
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
export { remap };
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=primitives.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"primitives.js","names":[],"sources":["../../src/lib/primitives.ts"],"sourcesContent":["/**\n * Key-remapping helper used inside Zod `.transform()` steps to rename fields\n * between the public camelCase shape and the snake_case wire shape — the same\n * utility Speakeasy emits in its generated SDKs.\n */\n\nexport type Remap<Inp, Mapping extends { [k in keyof Inp]?: string | null }> = {\n [k in keyof Inp as Mapping[k] extends string\n ? Mapping[k]\n : Mapping[k] extends null\n ? never\n : k]: Inp[k];\n};\n\n/**\n * Return a new object with `inp`'s keys renamed according to `mappings`.\n * A key mapped to a string is renamed; a key mapped to `null` is dropped; a key\n * absent from the mapping is kept as-is.\n */\nexport function remap<\n Inp extends Record<string, unknown>,\n const Mapping extends { [k in keyof Inp]?: string | null },\n>(inp: Inp, mappings: Mapping): Remap<Inp, Mapping> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let out: any = {};\n\n if (!Object.keys(mappings).length) {\n out = inp;\n return out;\n }\n\n for (const [k, v] of Object.entries(inp)) {\n const j = (mappings as Record<string, string | null | undefined>)[k];\n if (j === null) {\n continue;\n }\n out[j ?? k] = v;\n }\n\n return out;\n}\n"],"mappings":";;;;;;AAmBA,SAAgB,MAGd,KAAU,UAAwC;CAElD,IAAI,MAAW,CAAC;CAEhB,IAAI,CAAC,OAAO,KAAK,QAAQ,EAAE,QAAQ;EACjC,MAAM;EACN,OAAO;CACT;CAEA,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,GAAG,GAAG;EACxC,MAAM,IAAK,SAAuD;EAClE,IAAI,MAAM,MACR;EAEF,IAAI,KAAK,KAAK;CAChB;CAEA,OAAO;AACT"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { DiscoValidationError } from "../errors.js";
|
|
2
|
+
import { $ZodError } from "zod/v4/core";
|
|
3
|
+
//#region src/lib/schemas.ts
|
|
4
|
+
/**
|
|
5
|
+
* Thin wrappers around Zod parsing that convert a thrown `$ZodError` into a
|
|
6
|
+
* `DiscoValidationError`, so validation failures surface as a Disco error type
|
|
7
|
+
* rather than leaking Zod's internals to consumers. Modeled on the equivalent
|
|
8
|
+
* helpers in Speakeasy-generated SDKs.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Run `fn` (typically a `schema.parse`) and, if it throws a `$ZodError`, rethrow
|
|
12
|
+
* it as a `DiscoValidationError`. Any non-Zod error propagates untouched.
|
|
13
|
+
*/
|
|
14
|
+
function parse(rawValue, fn, errorMessage) {
|
|
15
|
+
try {
|
|
16
|
+
return fn(rawValue);
|
|
17
|
+
} catch (err) {
|
|
18
|
+
if (err instanceof $ZodError) throw new DiscoValidationError(errorMessage, err, rawValue);
|
|
19
|
+
throw err;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
export { parse };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=schemas.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schemas.js","names":[],"sources":["../../src/lib/schemas.ts"],"sourcesContent":["/**\n * Thin wrappers around Zod parsing that convert a thrown `$ZodError` into a\n * `DiscoValidationError`, so validation failures surface as a Disco error type\n * rather than leaking Zod's internals to consumers. Modeled on the equivalent\n * helpers in Speakeasy-generated SDKs.\n */\n\nimport { $ZodError } from \"zod/v4/core\";\nimport { DiscoValidationError } from \"../errors.js\";\n\n/**\n * Run `fn` (typically a `schema.parse`) and, if it throws a `$ZodError`, rethrow\n * it as a `DiscoValidationError`. Any non-Zod error propagates untouched.\n */\nexport function parse<Inp, Out>(\n rawValue: Inp,\n fn: (value: Inp) => Out,\n errorMessage: string,\n): Out {\n try {\n return fn(rawValue);\n } catch (err) {\n if (err instanceof $ZodError) {\n throw new DiscoValidationError(errorMessage, err, rawValue);\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAgB,MACd,UACA,IACA,cACK;CACL,IAAI;EACF,OAAO,GAAG,QAAQ;CACpB,SAAS,KAAK;EACZ,IAAI,eAAe,WACjB,MAAM,IAAI,qBAAqB,cAAc,KAAK,QAAQ;EAE5D,MAAM;CACR;AACF"}
|