shop-client 3.16.0 → 3.18.0
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 +74 -7
- package/dist/ai/enrich.d.ts +1 -1
- package/dist/ai/enrich.mjs +2 -2
- package/dist/{chunk-QCB3U4AO.mjs → chunk-242GBM2V.mjs} +136 -14
- package/dist/{chunk-ZX4IG4TY.mjs → chunk-5TGMDRUF.mjs} +88 -44
- package/dist/chunk-6XDBGOFZ.mjs +804 -0
- package/dist/{chunk-D5MTUWFO.mjs → chunk-O77Z6OBJ.mjs} +21 -6
- package/dist/{chunk-G7OCMGA6.mjs → chunk-SBHTEKLB.mjs} +3 -1
- package/dist/{chunk-OA76XD32.mjs → chunk-YWAW6C74.mjs} +5 -5
- package/dist/collections.d.ts +16 -2
- package/dist/collections.mjs +2 -2
- package/dist/index.d.ts +8 -4
- package/dist/index.mjs +180 -79
- package/dist/products.d.ts +65 -2
- package/dist/products.mjs +2 -2
- package/dist/store.d.ts +1 -1
- package/dist/store.mjs +3 -3
- package/dist/{types-BRXamZMS.d.ts → types-B4WDm14E.d.ts} +58 -1
- package/dist/utils/detect-country.d.ts +1 -1
- package/dist/utils/detect-country.mjs +1 -1
- package/dist/utils/func.d.ts +1 -1
- package/dist/utils/rate-limit.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-THCO3JT4.mjs +0 -593
package/dist/chunk-THCO3JT4.mjs
DELETED
|
@@ -1,593 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
rateLimitedFetch
|
|
3
|
-
} from "./chunk-D5MTUWFO.mjs";
|
|
4
|
-
import {
|
|
5
|
-
formatPrice
|
|
6
|
-
} from "./chunk-U3RQRBXZ.mjs";
|
|
7
|
-
|
|
8
|
-
// src/products.ts
|
|
9
|
-
import { filter, isNonNullish } from "remeda";
|
|
10
|
-
function createProductOperations(baseUrl, storeDomain, fetchProducts, productsDto, productDto, getStoreInfo, findProduct, ai) {
|
|
11
|
-
const cacheExpiryMs = 5 * 60 * 1e3;
|
|
12
|
-
const findCache = /* @__PURE__ */ new Map();
|
|
13
|
-
const getCached = (key) => {
|
|
14
|
-
const entry = findCache.get(key);
|
|
15
|
-
if (!entry) return void 0;
|
|
16
|
-
if (Date.now() - entry.ts < cacheExpiryMs) return entry.value;
|
|
17
|
-
findCache.delete(key);
|
|
18
|
-
return void 0;
|
|
19
|
-
};
|
|
20
|
-
const setCached = (key, value) => {
|
|
21
|
-
findCache.set(key, { ts: Date.now(), value });
|
|
22
|
-
};
|
|
23
|
-
function applyCurrencyOverride(product, currency) {
|
|
24
|
-
var _a, _b, _c, _d, _e, _f;
|
|
25
|
-
const priceMin = (_b = (_a = product.priceMin) != null ? _a : product.price) != null ? _b : 0;
|
|
26
|
-
const priceMax = (_d = (_c = product.priceMax) != null ? _c : product.price) != null ? _d : 0;
|
|
27
|
-
const compareAtMin = (_f = (_e = product.compareAtPriceMin) != null ? _e : product.compareAtPrice) != null ? _f : 0;
|
|
28
|
-
return {
|
|
29
|
-
...product,
|
|
30
|
-
currency,
|
|
31
|
-
localizedPricing: {
|
|
32
|
-
currency,
|
|
33
|
-
priceFormatted: formatPrice(priceMin, currency),
|
|
34
|
-
priceMinFormatted: formatPrice(priceMin, currency),
|
|
35
|
-
priceMaxFormatted: formatPrice(priceMax, currency),
|
|
36
|
-
compareAtPriceFormatted: formatPrice(compareAtMin, currency)
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
function maybeOverrideProductsCurrency(products, currency) {
|
|
41
|
-
if (!products || !currency) return products;
|
|
42
|
-
return products.map((p) => applyCurrencyOverride(p, currency));
|
|
43
|
-
}
|
|
44
|
-
const operations = {
|
|
45
|
-
/**
|
|
46
|
-
* Fetches all products from the store across all pages.
|
|
47
|
-
*
|
|
48
|
-
* @returns {Promise<Product[] | null>} Array of all products or null if error occurs
|
|
49
|
-
*
|
|
50
|
-
* @throws {Error} When there's a network error or API failure
|
|
51
|
-
*
|
|
52
|
-
* @example
|
|
53
|
-
* ```typescript
|
|
54
|
-
* const shop = new ShopClient('https://exampleshop.com');
|
|
55
|
-
* const allProducts = await shop.products.all();
|
|
56
|
-
*
|
|
57
|
-
* console.log(`Found ${allProducts?.length} products`);
|
|
58
|
-
* allProducts?.forEach(product => {
|
|
59
|
-
* console.log(product.title, product.price);
|
|
60
|
-
* });
|
|
61
|
-
* ```
|
|
62
|
-
*/
|
|
63
|
-
all: async (options) => {
|
|
64
|
-
const limit = 250;
|
|
65
|
-
const allProducts = [];
|
|
66
|
-
async function fetchAll() {
|
|
67
|
-
let currentPage = 1;
|
|
68
|
-
while (true) {
|
|
69
|
-
const products = await fetchProducts(currentPage, limit);
|
|
70
|
-
if (!products || products.length === 0 || products.length < limit) {
|
|
71
|
-
if (products && products.length > 0) {
|
|
72
|
-
allProducts.push(...products);
|
|
73
|
-
}
|
|
74
|
-
break;
|
|
75
|
-
}
|
|
76
|
-
allProducts.push(...products);
|
|
77
|
-
currentPage++;
|
|
78
|
-
}
|
|
79
|
-
return allProducts;
|
|
80
|
-
}
|
|
81
|
-
try {
|
|
82
|
-
const products = await fetchAll();
|
|
83
|
-
return maybeOverrideProductsCurrency(products, options == null ? void 0 : options.currency);
|
|
84
|
-
} catch (error) {
|
|
85
|
-
console.error("Failed to fetch all products:", storeDomain, error);
|
|
86
|
-
throw error;
|
|
87
|
-
}
|
|
88
|
-
},
|
|
89
|
-
/**
|
|
90
|
-
* Fetches products with pagination support.
|
|
91
|
-
*
|
|
92
|
-
* @param options - Pagination options
|
|
93
|
-
* @param options.page - Page number (default: 1)
|
|
94
|
-
* @param options.limit - Number of products per page (default: 250, max: 250)
|
|
95
|
-
*
|
|
96
|
-
* @returns {Promise<Product[] | null>} Array of products for the specified page or null if error occurs
|
|
97
|
-
*
|
|
98
|
-
* @throws {Error} When there's a network error or API failure
|
|
99
|
-
*
|
|
100
|
-
* @example
|
|
101
|
-
* ```typescript
|
|
102
|
-
* const shop = new ShopClient('https://example.myshopify.com');
|
|
103
|
-
*
|
|
104
|
-
* // Get first page with default limit (250)
|
|
105
|
-
* const firstPage = await shop.products.paginated();
|
|
106
|
-
*
|
|
107
|
-
* // Get second page with custom limit
|
|
108
|
-
* const secondPage = await shop.products.paginated({ page: 2, limit: 50 });
|
|
109
|
-
* ```
|
|
110
|
-
*/
|
|
111
|
-
paginated: async (options) => {
|
|
112
|
-
var _a, _b;
|
|
113
|
-
const page = (_a = options == null ? void 0 : options.page) != null ? _a : 1;
|
|
114
|
-
const limit = Math.min((_b = options == null ? void 0 : options.limit) != null ? _b : 250, 250);
|
|
115
|
-
const url = `${baseUrl}products.json?limit=${limit}&page=${page}`;
|
|
116
|
-
try {
|
|
117
|
-
const response = await rateLimitedFetch(url, {
|
|
118
|
-
rateLimitClass: "products:paginated"
|
|
119
|
-
});
|
|
120
|
-
if (!response.ok) {
|
|
121
|
-
console.error(
|
|
122
|
-
`HTTP error! status: ${response.status} for ${storeDomain} page ${page}`
|
|
123
|
-
);
|
|
124
|
-
throw new Error(`HTTP error! status: ${response.status}`);
|
|
125
|
-
}
|
|
126
|
-
const data = await response.json();
|
|
127
|
-
if (data.products.length === 0) {
|
|
128
|
-
return [];
|
|
129
|
-
}
|
|
130
|
-
const normalized = productsDto(data.products);
|
|
131
|
-
return maybeOverrideProductsCurrency(normalized, options == null ? void 0 : options.currency);
|
|
132
|
-
} catch (error) {
|
|
133
|
-
console.error(
|
|
134
|
-
`Error fetching products for ${storeDomain} page ${page} with limit ${limit}:`,
|
|
135
|
-
error
|
|
136
|
-
);
|
|
137
|
-
return null;
|
|
138
|
-
}
|
|
139
|
-
},
|
|
140
|
-
/**
|
|
141
|
-
* Finds a specific product by its handle.
|
|
142
|
-
*
|
|
143
|
-
* @param productHandle - The product handle (URL slug) to search for
|
|
144
|
-
*
|
|
145
|
-
* @returns {Promise<Product | null>} The product if found, null if not found
|
|
146
|
-
*
|
|
147
|
-
* @throws {Error} When the handle is invalid or there's a network error
|
|
148
|
-
*
|
|
149
|
-
* @example
|
|
150
|
-
* ```typescript
|
|
151
|
-
* const shop = new ShopClient('https://exampleshop.com');
|
|
152
|
-
*
|
|
153
|
-
* // Find product by handle
|
|
154
|
-
* const product = await shop.products.find('awesome-t-shirt');
|
|
155
|
-
*
|
|
156
|
-
* if (product) {
|
|
157
|
-
* console.log(product.title, product.price);
|
|
158
|
-
* console.log('Available variants:', product.variants.length);
|
|
159
|
-
* }
|
|
160
|
-
*
|
|
161
|
-
* // Handle with query string
|
|
162
|
-
* const productWithVariant = await shop.products.find('t-shirt?variant=123');
|
|
163
|
-
* ```
|
|
164
|
-
*/
|
|
165
|
-
find: async (productHandle, options) => {
|
|
166
|
-
var _a, _b;
|
|
167
|
-
if (!productHandle || typeof productHandle !== "string") {
|
|
168
|
-
throw new Error("Product handle is required and must be a string");
|
|
169
|
-
}
|
|
170
|
-
try {
|
|
171
|
-
let qs = null;
|
|
172
|
-
if (productHandle.includes("?")) {
|
|
173
|
-
const parts = productHandle.split("?");
|
|
174
|
-
const handlePart = (_a = parts[0]) != null ? _a : productHandle;
|
|
175
|
-
const qsPart = (_b = parts[1]) != null ? _b : null;
|
|
176
|
-
productHandle = handlePart;
|
|
177
|
-
qs = qsPart;
|
|
178
|
-
}
|
|
179
|
-
const sanitizedHandle = productHandle.trim().replace(/[^a-zA-Z0-9\-_]/g, "");
|
|
180
|
-
if (!sanitizedHandle) {
|
|
181
|
-
throw new Error("Invalid product handle format");
|
|
182
|
-
}
|
|
183
|
-
if (sanitizedHandle.length > 255) {
|
|
184
|
-
throw new Error("Product handle is too long");
|
|
185
|
-
}
|
|
186
|
-
const cached = getCached(sanitizedHandle);
|
|
187
|
-
if (typeof cached !== "undefined") {
|
|
188
|
-
return (options == null ? void 0 : options.currency) ? cached ? applyCurrencyOverride(cached, options.currency) : null : cached;
|
|
189
|
-
}
|
|
190
|
-
let finalHandle = sanitizedHandle;
|
|
191
|
-
try {
|
|
192
|
-
const htmlResp = await rateLimitedFetch(
|
|
193
|
-
`${baseUrl}products/${encodeURIComponent(sanitizedHandle)}`,
|
|
194
|
-
{ rateLimitClass: "products:resolve" }
|
|
195
|
-
);
|
|
196
|
-
if (htmlResp.ok) {
|
|
197
|
-
const finalUrl = htmlResp.url;
|
|
198
|
-
if (finalUrl) {
|
|
199
|
-
const pathname = new URL(finalUrl).pathname.replace(/\/$/, "");
|
|
200
|
-
const parts = pathname.split("/").filter(Boolean);
|
|
201
|
-
const idx = parts.indexOf("products");
|
|
202
|
-
const maybeHandle = idx >= 0 ? parts[idx + 1] : void 0;
|
|
203
|
-
if (typeof maybeHandle === "string" && maybeHandle.length) {
|
|
204
|
-
finalHandle = maybeHandle;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
} catch {
|
|
209
|
-
}
|
|
210
|
-
const url = `${baseUrl}products/${encodeURIComponent(finalHandle)}.js${qs ? `?${qs}` : ""}`;
|
|
211
|
-
const response = await rateLimitedFetch(url, {
|
|
212
|
-
rateLimitClass: "products:single"
|
|
213
|
-
});
|
|
214
|
-
if (!response.ok) {
|
|
215
|
-
if (response.status === 404) {
|
|
216
|
-
return null;
|
|
217
|
-
}
|
|
218
|
-
throw new Error(`HTTP error! status: ${response.status}`);
|
|
219
|
-
}
|
|
220
|
-
const product = await response.json();
|
|
221
|
-
const productData = productDto(product);
|
|
222
|
-
setCached(sanitizedHandle, productData);
|
|
223
|
-
if (finalHandle !== sanitizedHandle)
|
|
224
|
-
setCached(finalHandle, productData);
|
|
225
|
-
return (options == null ? void 0 : options.currency) ? applyCurrencyOverride(productData, options.currency) : productData;
|
|
226
|
-
} catch (error) {
|
|
227
|
-
if (error instanceof Error) {
|
|
228
|
-
console.error(
|
|
229
|
-
`Error fetching product ${productHandle}:`,
|
|
230
|
-
baseUrl,
|
|
231
|
-
error.message
|
|
232
|
-
);
|
|
233
|
-
}
|
|
234
|
-
throw error;
|
|
235
|
-
}
|
|
236
|
-
},
|
|
237
|
-
/**
|
|
238
|
-
* Enrich a product by generating merged markdown from body_html and product page.
|
|
239
|
-
* Adds `enriched_content` to the returned product.
|
|
240
|
-
*/
|
|
241
|
-
enriched: async (productHandle, options) => {
|
|
242
|
-
if (!productHandle || typeof productHandle !== "string") {
|
|
243
|
-
throw new Error("Product handle is required and must be a string");
|
|
244
|
-
}
|
|
245
|
-
const baseProduct = await operations.find(productHandle);
|
|
246
|
-
if (!baseProduct) {
|
|
247
|
-
return null;
|
|
248
|
-
}
|
|
249
|
-
const handle = baseProduct.handle;
|
|
250
|
-
const { enrichProduct } = await import("./ai/enrich.mjs");
|
|
251
|
-
const enriched = await enrichProduct(storeDomain, handle, {
|
|
252
|
-
apiKey: options == null ? void 0 : options.apiKey,
|
|
253
|
-
openRouter: ai == null ? void 0 : ai.openRouter,
|
|
254
|
-
useGfm: options == null ? void 0 : options.useGfm,
|
|
255
|
-
inputType: options == null ? void 0 : options.inputType,
|
|
256
|
-
model: options == null ? void 0 : options.model,
|
|
257
|
-
outputFormat: options == null ? void 0 : options.outputFormat,
|
|
258
|
-
htmlContent: options == null ? void 0 : options.content
|
|
259
|
-
});
|
|
260
|
-
return {
|
|
261
|
-
...baseProduct,
|
|
262
|
-
enriched_content: enriched.mergedMarkdown
|
|
263
|
-
};
|
|
264
|
-
},
|
|
265
|
-
enrichedPrompts: async (productHandle, options) => {
|
|
266
|
-
if (!productHandle || typeof productHandle !== "string") {
|
|
267
|
-
throw new Error("Product handle is required and must be a string");
|
|
268
|
-
}
|
|
269
|
-
const baseProduct = await operations.find(productHandle);
|
|
270
|
-
if (!baseProduct) {
|
|
271
|
-
throw new Error("Product not found");
|
|
272
|
-
}
|
|
273
|
-
const handle = baseProduct.handle;
|
|
274
|
-
const { buildEnrichPromptForProduct } = await import("./ai/enrich.mjs");
|
|
275
|
-
return buildEnrichPromptForProduct(storeDomain, handle, {
|
|
276
|
-
useGfm: options == null ? void 0 : options.useGfm,
|
|
277
|
-
inputType: options == null ? void 0 : options.inputType,
|
|
278
|
-
outputFormat: options == null ? void 0 : options.outputFormat,
|
|
279
|
-
htmlContent: options == null ? void 0 : options.content
|
|
280
|
-
});
|
|
281
|
-
},
|
|
282
|
-
classify: async (productHandle, options) => {
|
|
283
|
-
if (!productHandle || typeof productHandle !== "string") {
|
|
284
|
-
throw new Error("Product handle is required and must be a string");
|
|
285
|
-
}
|
|
286
|
-
const enrichedProduct = await operations.enriched(productHandle, {
|
|
287
|
-
apiKey: options == null ? void 0 : options.apiKey,
|
|
288
|
-
inputType: "html",
|
|
289
|
-
model: options == null ? void 0 : options.model,
|
|
290
|
-
outputFormat: "json",
|
|
291
|
-
content: options == null ? void 0 : options.content
|
|
292
|
-
});
|
|
293
|
-
if (!enrichedProduct || !enrichedProduct.enriched_content) return null;
|
|
294
|
-
let productContent = enrichedProduct.enriched_content;
|
|
295
|
-
try {
|
|
296
|
-
const obj = JSON.parse(enrichedProduct.enriched_content);
|
|
297
|
-
const lines = [];
|
|
298
|
-
if (obj.title && typeof obj.title === "string")
|
|
299
|
-
lines.push(`Title: ${obj.title}`);
|
|
300
|
-
if (obj.description && typeof obj.description === "string")
|
|
301
|
-
lines.push(`Description: ${obj.description}`);
|
|
302
|
-
if (Array.isArray(obj.materials) && obj.materials.length)
|
|
303
|
-
lines.push(`Materials: ${obj.materials.join(", ")}`);
|
|
304
|
-
if (Array.isArray(obj.care) && obj.care.length)
|
|
305
|
-
lines.push(`Care: ${obj.care.join(", ")}`);
|
|
306
|
-
if (obj.fit && typeof obj.fit === "string")
|
|
307
|
-
lines.push(`Fit: ${obj.fit}`);
|
|
308
|
-
if (obj.returnPolicy && typeof obj.returnPolicy === "string")
|
|
309
|
-
lines.push(`ReturnPolicy: ${obj.returnPolicy}`);
|
|
310
|
-
productContent = lines.join("\n");
|
|
311
|
-
} catch {
|
|
312
|
-
}
|
|
313
|
-
const { classifyProduct } = await import("./ai/enrich.mjs");
|
|
314
|
-
const classification = await classifyProduct(productContent, {
|
|
315
|
-
apiKey: options == null ? void 0 : options.apiKey,
|
|
316
|
-
openRouter: ai == null ? void 0 : ai.openRouter,
|
|
317
|
-
model: options == null ? void 0 : options.model
|
|
318
|
-
});
|
|
319
|
-
return classification;
|
|
320
|
-
},
|
|
321
|
-
classifyPrompts: async (productHandle, options) => {
|
|
322
|
-
if (!productHandle || typeof productHandle !== "string") {
|
|
323
|
-
throw new Error("Product handle is required and must be a string");
|
|
324
|
-
}
|
|
325
|
-
const baseProduct = await operations.find(productHandle);
|
|
326
|
-
if (!baseProduct) {
|
|
327
|
-
throw new Error("Product not found");
|
|
328
|
-
}
|
|
329
|
-
const handle = baseProduct.handle;
|
|
330
|
-
const { buildClassifyPromptForProduct } = await import("./ai/enrich.mjs");
|
|
331
|
-
return buildClassifyPromptForProduct(storeDomain, handle, {
|
|
332
|
-
useGfm: options == null ? void 0 : options.useGfm,
|
|
333
|
-
inputType: options == null ? void 0 : options.inputType,
|
|
334
|
-
htmlContent: options == null ? void 0 : options.content
|
|
335
|
-
});
|
|
336
|
-
},
|
|
337
|
-
generateSEOContent: async (productHandle, options) => {
|
|
338
|
-
if (!productHandle || typeof productHandle !== "string") {
|
|
339
|
-
throw new Error("Product handle is required and must be a string");
|
|
340
|
-
}
|
|
341
|
-
const baseProduct = await operations.find(productHandle);
|
|
342
|
-
if (!baseProduct) return null;
|
|
343
|
-
const payload = {
|
|
344
|
-
title: baseProduct.title,
|
|
345
|
-
description: baseProduct.bodyHtml || void 0,
|
|
346
|
-
vendor: baseProduct.vendor,
|
|
347
|
-
price: baseProduct.price,
|
|
348
|
-
tags: baseProduct.tags
|
|
349
|
-
};
|
|
350
|
-
const {
|
|
351
|
-
extractMainSection,
|
|
352
|
-
fetchAjaxProduct,
|
|
353
|
-
fetchProductPage,
|
|
354
|
-
generateSEOContent: generateSEOContentLLM,
|
|
355
|
-
mergeWithLLM
|
|
356
|
-
} = await import("./ai/enrich.mjs");
|
|
357
|
-
const seo = await generateSEOContentLLM(payload, {
|
|
358
|
-
apiKey: options == null ? void 0 : options.apiKey,
|
|
359
|
-
openRouter: ai == null ? void 0 : ai.openRouter,
|
|
360
|
-
model: options == null ? void 0 : options.model
|
|
361
|
-
});
|
|
362
|
-
return seo;
|
|
363
|
-
},
|
|
364
|
-
/**
|
|
365
|
-
* Fetches the extracted HTML content from the product page.
|
|
366
|
-
* This is useful for getting the main product description and content directly from the page HTML.
|
|
367
|
-
*
|
|
368
|
-
* @param productHandle - The handle of the product
|
|
369
|
-
* @param content - Optional HTML content to extract from. If provided, skips fetching the product page.
|
|
370
|
-
* @returns {Promise<string | null>} The extracted HTML content or null if not found
|
|
371
|
-
*
|
|
372
|
-
* @example
|
|
373
|
-
* ```typescript
|
|
374
|
-
* // Fetch from store
|
|
375
|
-
* const html = await shop.products.infoHtml("product-handle");
|
|
376
|
-
*
|
|
377
|
-
* // Use provided HTML
|
|
378
|
-
* const htmlFromContent = await shop.products.infoHtml("product-handle", "<html>...</html>");
|
|
379
|
-
* ```
|
|
380
|
-
*/
|
|
381
|
-
infoHtml: async (productHandle, content) => {
|
|
382
|
-
if (!productHandle || typeof productHandle !== "string") {
|
|
383
|
-
throw new Error("Product handle is required and must be a string");
|
|
384
|
-
}
|
|
385
|
-
const { extractMainSection, fetchProductPage } = await import("./ai/enrich.mjs");
|
|
386
|
-
if (content) {
|
|
387
|
-
return extractMainSection(content);
|
|
388
|
-
}
|
|
389
|
-
const baseProduct = await operations.find(productHandle);
|
|
390
|
-
if (!baseProduct) return null;
|
|
391
|
-
const pageHtml = await fetchProductPage(storeDomain, baseProduct.handle);
|
|
392
|
-
return extractMainSection(pageHtml);
|
|
393
|
-
},
|
|
394
|
-
/**
|
|
395
|
-
* Fetches products that are showcased/featured on the store's homepage.
|
|
396
|
-
*
|
|
397
|
-
* @returns {Promise<Product[]>} Array of showcased products found on the homepage
|
|
398
|
-
*
|
|
399
|
-
* @throws {Error} When there's a network error or API failure
|
|
400
|
-
*
|
|
401
|
-
* @example
|
|
402
|
-
* ```typescript
|
|
403
|
-
* const shop = new ShopClient('https://exampleshop.com');
|
|
404
|
-
* const showcasedProducts = await shop.products.showcased();
|
|
405
|
-
*
|
|
406
|
-
* console.log(`Found ${showcasedProducts.length} showcased products`);
|
|
407
|
-
* showcasedProducts.forEach(product => {
|
|
408
|
-
* console.log(`Featured: ${product.title} - ${product.price}`);
|
|
409
|
-
* });
|
|
410
|
-
* ```
|
|
411
|
-
*/
|
|
412
|
-
showcased: async () => {
|
|
413
|
-
const storeInfo = await getStoreInfo();
|
|
414
|
-
const normalizedHandles = storeInfo.showcase.products.map((h) => {
|
|
415
|
-
var _a;
|
|
416
|
-
return (_a = h.split("?")[0]) == null ? void 0 : _a.replace(/^\/|\/$/g, "");
|
|
417
|
-
}).filter((base) => Boolean(base));
|
|
418
|
-
const seen = /* @__PURE__ */ new Set();
|
|
419
|
-
const uniqueHandles = [];
|
|
420
|
-
for (const base of normalizedHandles) {
|
|
421
|
-
if (seen.has(base)) continue;
|
|
422
|
-
seen.add(base);
|
|
423
|
-
uniqueHandles.push(base);
|
|
424
|
-
}
|
|
425
|
-
const products = await Promise.all(
|
|
426
|
-
uniqueHandles.map((productHandle) => findProduct(productHandle))
|
|
427
|
-
);
|
|
428
|
-
return filter(products, isNonNullish);
|
|
429
|
-
},
|
|
430
|
-
/**
|
|
431
|
-
* Creates a filter map of variant options and their distinct values from all products.
|
|
432
|
-
*
|
|
433
|
-
* @returns {Promise<Record<string, string[]> | null>} Map of option names to their distinct values or null if error occurs
|
|
434
|
-
*
|
|
435
|
-
* @throws {Error} When there's a network error or API failure
|
|
436
|
-
*
|
|
437
|
-
* @example
|
|
438
|
-
* ```typescript
|
|
439
|
-
* const shop = new ShopClient('https://exampleshop.com');
|
|
440
|
-
* const filters = await shop.products.filter();
|
|
441
|
-
*
|
|
442
|
-
* console.log('Available filters:', filters);
|
|
443
|
-
* // Output: { "Size": ["S", "M", "L", "XL"], "Color": ["Red", "Blue", "Green"] }
|
|
444
|
-
*
|
|
445
|
-
* // Use filters for UI components
|
|
446
|
-
* Object.entries(filters || {}).forEach(([optionName, values]) => {
|
|
447
|
-
* console.log(`${optionName}: ${values.join(', ')}`);
|
|
448
|
-
* });
|
|
449
|
-
* ```
|
|
450
|
-
*/
|
|
451
|
-
filter: async () => {
|
|
452
|
-
try {
|
|
453
|
-
const products = await operations.all();
|
|
454
|
-
if (!products || products.length === 0) {
|
|
455
|
-
return {};
|
|
456
|
-
}
|
|
457
|
-
const filterMap = {};
|
|
458
|
-
products.forEach((product) => {
|
|
459
|
-
if (product.variants && product.variants.length > 0) {
|
|
460
|
-
if (product.options && product.options.length > 0) {
|
|
461
|
-
product.options.forEach((option) => {
|
|
462
|
-
const lowercaseOptionName = option.name.toLowerCase();
|
|
463
|
-
if (!filterMap[lowercaseOptionName]) {
|
|
464
|
-
filterMap[lowercaseOptionName] = /* @__PURE__ */ new Set();
|
|
465
|
-
}
|
|
466
|
-
option.values.forEach((value) => {
|
|
467
|
-
const trimmed = value == null ? void 0 : value.trim();
|
|
468
|
-
if (trimmed) {
|
|
469
|
-
let set = filterMap[lowercaseOptionName];
|
|
470
|
-
if (!set) {
|
|
471
|
-
set = /* @__PURE__ */ new Set();
|
|
472
|
-
filterMap[lowercaseOptionName] = set;
|
|
473
|
-
}
|
|
474
|
-
set.add(trimmed.toLowerCase());
|
|
475
|
-
}
|
|
476
|
-
});
|
|
477
|
-
});
|
|
478
|
-
}
|
|
479
|
-
product.variants.forEach((variant) => {
|
|
480
|
-
var _a, _b, _c, _d, _e, _f;
|
|
481
|
-
if (variant.option1) {
|
|
482
|
-
const optionName = (((_b = (_a = product.options) == null ? void 0 : _a[0]) == null ? void 0 : _b.name) || "Option 1").toLowerCase();
|
|
483
|
-
let set1 = filterMap[optionName];
|
|
484
|
-
if (!set1) {
|
|
485
|
-
set1 = /* @__PURE__ */ new Set();
|
|
486
|
-
filterMap[optionName] = set1;
|
|
487
|
-
}
|
|
488
|
-
set1.add(variant.option1.trim().toLowerCase());
|
|
489
|
-
}
|
|
490
|
-
if (variant.option2) {
|
|
491
|
-
const optionName = (((_d = (_c = product.options) == null ? void 0 : _c[1]) == null ? void 0 : _d.name) || "Option 2").toLowerCase();
|
|
492
|
-
let set2 = filterMap[optionName];
|
|
493
|
-
if (!set2) {
|
|
494
|
-
set2 = /* @__PURE__ */ new Set();
|
|
495
|
-
filterMap[optionName] = set2;
|
|
496
|
-
}
|
|
497
|
-
set2.add(variant.option2.trim().toLowerCase());
|
|
498
|
-
}
|
|
499
|
-
if (variant.option3) {
|
|
500
|
-
const optionName = (((_f = (_e = product.options) == null ? void 0 : _e[2]) == null ? void 0 : _f.name) || "Option 3").toLowerCase();
|
|
501
|
-
if (!filterMap[optionName]) {
|
|
502
|
-
filterMap[optionName] = /* @__PURE__ */ new Set();
|
|
503
|
-
}
|
|
504
|
-
filterMap[optionName].add(variant.option3.trim().toLowerCase());
|
|
505
|
-
}
|
|
506
|
-
});
|
|
507
|
-
}
|
|
508
|
-
});
|
|
509
|
-
const result = {};
|
|
510
|
-
Object.entries(filterMap).forEach(([optionName, valueSet]) => {
|
|
511
|
-
result[optionName] = Array.from(valueSet).sort();
|
|
512
|
-
});
|
|
513
|
-
return result;
|
|
514
|
-
} catch (error) {
|
|
515
|
-
console.error("Failed to create product filters:", storeDomain, error);
|
|
516
|
-
throw error;
|
|
517
|
-
}
|
|
518
|
-
},
|
|
519
|
-
predictiveSearch: async (query, options) => {
|
|
520
|
-
var _a, _b, _c, _d, _e;
|
|
521
|
-
if (!query || typeof query !== "string") {
|
|
522
|
-
throw new Error("Query is required and must be a string");
|
|
523
|
-
}
|
|
524
|
-
const limit = Math.max(1, Math.min((_a = options == null ? void 0 : options.limit) != null ? _a : 10, 10));
|
|
525
|
-
const unavailable = (options == null ? void 0 : options.unavailableProducts) === "show" || (options == null ? void 0 : options.unavailableProducts) === "hide" ? options.unavailableProducts : "hide";
|
|
526
|
-
const localeValue = (options == null ? void 0 : options.locale) && options.locale.trim() || "en";
|
|
527
|
-
const localePrefix = `${localeValue.replace(/^\/|\/$/g, "")}/`;
|
|
528
|
-
const url = `${baseUrl}${localePrefix}search/suggest.json?q=${encodeURIComponent(query)}&resources[type]=product&resources[limit]=${limit}&resources[options][unavailable_products]=${unavailable}`;
|
|
529
|
-
const response = await rateLimitedFetch(url, {
|
|
530
|
-
rateLimitClass: "search:predictive",
|
|
531
|
-
timeoutMs: 7e3,
|
|
532
|
-
retry: { maxRetries: 2, baseDelayMs: 300 }
|
|
533
|
-
});
|
|
534
|
-
let resp = response;
|
|
535
|
-
if (!resp.ok && (resp.status === 404 || resp.status === 417)) {
|
|
536
|
-
const fallbackUrl = `${baseUrl}search/suggest.json?q=${encodeURIComponent(query)}&resources[type]=product&resources[limit]=${limit}&resources[options][unavailable_products]=${unavailable}`;
|
|
537
|
-
resp = await rateLimitedFetch(fallbackUrl, {
|
|
538
|
-
rateLimitClass: "search:predictive",
|
|
539
|
-
timeoutMs: 7e3,
|
|
540
|
-
retry: { maxRetries: 2, baseDelayMs: 300 }
|
|
541
|
-
});
|
|
542
|
-
}
|
|
543
|
-
if (!resp.ok) {
|
|
544
|
-
throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
|
|
545
|
-
}
|
|
546
|
-
const data = await resp.json();
|
|
547
|
-
const raw = (_d = (_c = (_b = data == null ? void 0 : data.resources) == null ? void 0 : _b.results) == null ? void 0 : _c.products) != null ? _d : [];
|
|
548
|
-
const handles = raw.filter((p) => {
|
|
549
|
-
var _a2;
|
|
550
|
-
return Boolean((_a2 = p == null ? void 0 : p.available) != null ? _a2 : true);
|
|
551
|
-
}).map((p) => {
|
|
552
|
-
var _a2;
|
|
553
|
-
return String((_a2 = p == null ? void 0 : p.handle) != null ? _a2 : "");
|
|
554
|
-
}).filter((h) => h.length > 0).slice(0, limit);
|
|
555
|
-
const fetched = await Promise.all(handles.map((h) => findProduct(h)));
|
|
556
|
-
const results = filter(fetched, isNonNullish);
|
|
557
|
-
const finalProducts = (_e = maybeOverrideProductsCurrency(results, options == null ? void 0 : options.currency)) != null ? _e : [];
|
|
558
|
-
return finalProducts;
|
|
559
|
-
},
|
|
560
|
-
recommendations: async (productId, options) => {
|
|
561
|
-
var _a, _b;
|
|
562
|
-
if (!Number.isFinite(productId) || productId <= 0) {
|
|
563
|
-
throw new Error("Valid productId is required");
|
|
564
|
-
}
|
|
565
|
-
const limit = Math.max(1, Math.min((_a = options == null ? void 0 : options.limit) != null ? _a : 10, 10));
|
|
566
|
-
const intent = (options == null ? void 0 : options.intent) === "complementary" ? "complementary" : "related";
|
|
567
|
-
const localeValue = (options == null ? void 0 : options.locale) && options.locale.trim() || "en";
|
|
568
|
-
const localePrefix = `${localeValue.replace(/^\/|\/$/g, "")}/`;
|
|
569
|
-
const url = `${baseUrl}${localePrefix}recommendations/products.json?product_id=${encodeURIComponent(String(productId))}&limit=${limit}&intent=${intent}`;
|
|
570
|
-
const resp = await rateLimitedFetch(url, {
|
|
571
|
-
rateLimitClass: "products:recommendations",
|
|
572
|
-
timeoutMs: 7e3,
|
|
573
|
-
retry: { maxRetries: 2, baseDelayMs: 300 }
|
|
574
|
-
});
|
|
575
|
-
if (!resp.ok) {
|
|
576
|
-
if (resp.status === 404) {
|
|
577
|
-
return [];
|
|
578
|
-
}
|
|
579
|
-
throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
|
|
580
|
-
}
|
|
581
|
-
const data = await resp.json();
|
|
582
|
-
const productsArray = Array.isArray(data) ? data : Array.isArray(data == null ? void 0 : data.products) ? data.products : [];
|
|
583
|
-
const normalized = productsDto(productsArray) || [];
|
|
584
|
-
const finalProducts = (_b = maybeOverrideProductsCurrency(normalized, options == null ? void 0 : options.currency)) != null ? _b : [];
|
|
585
|
-
return finalProducts;
|
|
586
|
-
}
|
|
587
|
-
};
|
|
588
|
-
return operations;
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
export {
|
|
592
|
-
createProductOperations
|
|
593
|
-
};
|