@shopkit/data-layer 1.6.0 → 1.8.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/dist/index.mjs CHANGED
@@ -160,7 +160,7 @@ function createDomainLogger(domain, adapter, config = {}) {
160
160
  function isUpstreamUnavailable(error) {
161
161
  const status = error?.status;
162
162
  if (typeof status !== "number") return true;
163
- return status >= 500;
163
+ return status >= 500 || status === 429;
164
164
  }
165
165
  function formatResponse(params) {
166
166
  const { success, message, data = null, error = null, meta = {} } = params;
@@ -306,6 +306,16 @@ var BaseCommerceClient = class {
306
306
  queryCollections(params, options) {
307
307
  this.throwNotImplemented("queryCollections");
308
308
  }
309
+ /**
310
+ * Read a page of a collection's products, with one card per matching variant
311
+ * @param params - Handle plus page/per_page, sort, filter, fields
312
+ * @param options - Request options (headers, timeout, etc.)
313
+ * @returns Promise resolving to a VariantCardsPageDto
314
+ * @throws NotImplementedError if not implemented in adapter (custom backend only)
315
+ */
316
+ getCollectionVariantCards(params, options) {
317
+ this.throwNotImplemented("getCollectionVariantCards");
318
+ }
309
319
  // ========================================
310
320
  // ORDER OPERATIONS
311
321
  // ========================================
@@ -3800,7 +3810,8 @@ var PRODUCT_ENDPOINTS = {
3800
3810
  getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${encodeURIComponent(id)}`,
3801
3811
  getCollectionsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/collections/details`,
3802
3812
  getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${encodeURIComponent(collectionHandle)}/filters`,
3803
- queryCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections/query`
3813
+ queryCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections/query`,
3814
+ collectionVariants: (v = DEFAULT_VERSION, handle) => `/api/${v}/collections/${encodeURIComponent(handle)}/variants`
3804
3815
  };
3805
3816
 
3806
3817
  // src/adapters/custom/product/service.ts
@@ -4465,7 +4476,268 @@ var ProductService2 = class extends BaseCustomService {
4465
4476
  });
4466
4477
  }
4467
4478
  }
4479
+ /**
4480
+ * A page of a collection's products, with one card per matching variant
4481
+ * (POST /api/v1/collections/{handle}/variants). A POST because filters are
4482
+ * nested; it is still a read and answers 200.
4483
+ *
4484
+ * With `allVariants: true`, follows `next_cursor` (same body + `after`,
4485
+ * 100 cards per call) and returns the whole page's variants in one result.
4486
+ * The result is complete or it is a failure — never a partial page, which
4487
+ * would be cached as if it were complete. It fails (`UPSTREAM_UNAVAILABLE`)
4488
+ * when a follow-up call fails, when the cursor repeats, or when the page is
4489
+ * not done within ALL_VARIANTS_MAX_CALLS calls or ALL_VARIANTS_DEADLINE_MS.
4490
+ */
4491
+ async getCollectionVariantCards(params, options) {
4492
+ const handle = typeof params?.handle === "string" ? params.handle.trim() : "";
4493
+ if (!handle) {
4494
+ return formatResponse({
4495
+ success: false,
4496
+ message: "Missing required variable: 'handle'",
4497
+ error: {
4498
+ code: "QUERY_REJECTED",
4499
+ message: "handle: is required"
4500
+ }
4501
+ });
4502
+ }
4503
+ if (handle.includes("/") || handle === "." || handle === "..") {
4504
+ return formatResponse({
4505
+ success: false,
4506
+ message: "Collection not found.",
4507
+ error: {
4508
+ code: "NOT_FOUND",
4509
+ message: `No collection with handle ${handle}`
4510
+ }
4511
+ });
4512
+ }
4513
+ const payload = buildCollectionVariantsPayload(params);
4514
+ const requestOptions = {
4515
+ ...options || {},
4516
+ // Same coverage as queryCollections: the broad tag for catalog-wide
4517
+ // purges plus the collection's own, which product.updated /
4518
+ // collection.updated webhooks already purge. No `revalidate`.
4519
+ next: {
4520
+ ...options?.next || {},
4521
+ tags: [
4522
+ CacheTags.collections(),
4523
+ CacheTags.collection(handle),
4524
+ ...options?.next?.tags || []
4525
+ ]
4526
+ }
4527
+ };
4528
+ const endpoint = PRODUCT_ENDPOINTS.collectionVariants(
4529
+ options?.version,
4530
+ handle
4531
+ );
4532
+ const allVariants = params.allVariants === true;
4533
+ const deadline = allVariants ? AbortSignal.timeout(ALL_VARIANTS_DEADLINE_MS) : void 0;
4534
+ const callOptions = () => deadline ? {
4535
+ ...requestOptions,
4536
+ signal: anySignal([
4537
+ deadline,
4538
+ options?.signal ?? AbortSignal.timeout(options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS)
4539
+ ])
4540
+ } : requestOptions;
4541
+ let followUp = false;
4542
+ try {
4543
+ let result = await this.request(endpoint, "POST", payload, callOptions());
4544
+ if (!result?.data) return noVariantCardsData(result?.request_id);
4545
+ const page = {
4546
+ ...result.data,
4547
+ variants: Array.isArray(result.data.variants) ? result.data.variants : []
4548
+ };
4549
+ const errors = Array.isArray(result.errors) ? [...result.errors] : [];
4550
+ if (allVariants) {
4551
+ followUp = true;
4552
+ const variants = [];
4553
+ const seenIds = /* @__PURE__ */ new Set();
4554
+ const addCards = (cards) => {
4555
+ for (const card of Array.isArray(cards) ? cards : []) {
4556
+ if (typeof card?.id === "string") {
4557
+ if (seenIds.has(card.id)) continue;
4558
+ seenIds.add(card.id);
4559
+ }
4560
+ variants.push(card);
4561
+ }
4562
+ };
4563
+ addCards(page.variants);
4564
+ const seenCursors = new Set(
4565
+ typeof payload.after === "string" ? [payload.after] : []
4566
+ );
4567
+ let cursor = page.next_cursor;
4568
+ let calls = 1;
4569
+ while (cursor) {
4570
+ if (seenCursors.has(cursor)) {
4571
+ return incompleteVariantCards(
4572
+ "the backend returned a cursor it had already sent",
4573
+ result.request_id,
4574
+ this.logger
4575
+ );
4576
+ }
4577
+ if (calls >= ALL_VARIANTS_MAX_CALLS) {
4578
+ return incompleteVariantCards(
4579
+ `the page has more cards than ${ALL_VARIANTS_MAX_CALLS} calls of ${MAX_VARIANT_CARDS_PER_CALL} hold`,
4580
+ result.request_id,
4581
+ this.logger
4582
+ );
4583
+ }
4584
+ seenCursors.add(cursor);
4585
+ result = await this.request(
4586
+ endpoint,
4587
+ "POST",
4588
+ { ...payload, after: cursor },
4589
+ callOptions()
4590
+ );
4591
+ calls++;
4592
+ if (!result?.data) return noVariantCardsData(result?.request_id);
4593
+ addCards(result.data.variants);
4594
+ if (Array.isArray(result.errors)) errors.push(...result.errors);
4595
+ cursor = result.data.next_cursor;
4596
+ }
4597
+ page.variants = variants;
4598
+ page.next_cursor = null;
4599
+ }
4600
+ const distinctErrors = dedupeErrors(errors);
4601
+ return formatResponse({
4602
+ success: true,
4603
+ message: "Collection variants retrieved successfully.",
4604
+ data: page,
4605
+ meta: {
4606
+ requestId: result.request_id,
4607
+ ...distinctErrors.length > 0 ? { errors: distinctErrors } : {}
4608
+ }
4609
+ });
4610
+ } catch (error) {
4611
+ this.logger.error("Error in getCollectionVariantCards", void 0, {
4612
+ error
4613
+ });
4614
+ const body = error?.body;
4615
+ if (deadline?.aborted) {
4616
+ return incompleteVariantCards(
4617
+ `the page was not complete within ${ALL_VARIANTS_DEADLINE_MS / 1e3}s`,
4618
+ body?.request_id,
4619
+ this.logger
4620
+ );
4621
+ }
4622
+ if (isUpstreamUnavailable(error)) {
4623
+ return formatResponse({
4624
+ success: false,
4625
+ message: "An error occurred while processing the request.",
4626
+ error: {
4627
+ code: "UPSTREAM_UNAVAILABLE",
4628
+ message: typeof error?.status === "number" ? `Request failed: ${error.status}` : "Collection variants request did not complete."
4629
+ },
4630
+ meta: { requestId: body?.request_id }
4631
+ });
4632
+ }
4633
+ const upstreamErrors = Array.isArray(body?.errors) ? body.errors : [];
4634
+ if (error?.status === 404) {
4635
+ if (!followUp && upstreamErrors[0]?.code === "NOT_FOUND") {
4636
+ return formatResponse({
4637
+ success: false,
4638
+ message: "Collection not found.",
4639
+ error: {
4640
+ code: "NOT_FOUND",
4641
+ message: upstreamErrors[0]?.message || `No collection with handle ${handle}`
4642
+ },
4643
+ meta: { requestId: body?.request_id }
4644
+ });
4645
+ }
4646
+ return formatResponse({
4647
+ success: false,
4648
+ message: "An error occurred while processing the request.",
4649
+ error: {
4650
+ code: "UPSTREAM_UNAVAILABLE",
4651
+ message: "Request failed: 404"
4652
+ },
4653
+ meta: { requestId: body?.request_id }
4654
+ });
4655
+ }
4656
+ return formatResponse({
4657
+ success: false,
4658
+ message: "The collection variants request was rejected.",
4659
+ error: {
4660
+ code: "QUERY_REJECTED",
4661
+ message: upstreamErrors[0]?.message || error.message,
4662
+ details: upstreamErrors
4663
+ },
4664
+ meta: { requestId: body?.request_id }
4665
+ });
4666
+ }
4667
+ }
4468
4668
  };
4669
+ function incompleteVariantCards(reason, requestId, logger2) {
4670
+ logger2.warn(`getCollectionVariantCards allVariants incomplete: ${reason}`);
4671
+ return formatResponse({
4672
+ success: false,
4673
+ message: "Collection variants page is incomplete.",
4674
+ error: {
4675
+ code: "UPSTREAM_UNAVAILABLE",
4676
+ message: `allVariants: ${reason}; not returning a partial page.`
4677
+ },
4678
+ meta: { requestId }
4679
+ });
4680
+ }
4681
+ function dedupeErrors(errors) {
4682
+ const seen = /* @__PURE__ */ new Set();
4683
+ return errors.filter((e) => {
4684
+ const err = e;
4685
+ const key = JSON.stringify([err?.code, err?.message]);
4686
+ if (seen.has(key)) return false;
4687
+ seen.add(key);
4688
+ return true;
4689
+ });
4690
+ }
4691
+ function anySignal(signals) {
4692
+ const controller = new AbortController();
4693
+ for (const signal of signals) {
4694
+ if (signal.aborted) {
4695
+ controller.abort(signal.reason);
4696
+ break;
4697
+ }
4698
+ signal.addEventListener("abort", () => controller.abort(signal.reason), {
4699
+ once: true
4700
+ });
4701
+ }
4702
+ return controller.signal;
4703
+ }
4704
+ function noVariantCardsData(requestId) {
4705
+ return formatResponse({
4706
+ success: false,
4707
+ message: "Collection variants request returned no data.",
4708
+ error: {
4709
+ code: "UPSTREAM_UNAVAILABLE",
4710
+ message: "No data in collection variants response."
4711
+ },
4712
+ meta: { requestId }
4713
+ });
4714
+ }
4715
+ var COLLECTION_VARIANTS_KEYS = [
4716
+ "filter",
4717
+ "fields",
4718
+ "product",
4719
+ "sort",
4720
+ "page",
4721
+ "per_page",
4722
+ "limit",
4723
+ "after",
4724
+ "ratings",
4725
+ "metafields"
4726
+ ];
4727
+ var MAX_VARIANT_CARDS_PER_CALL = 100;
4728
+ var ALL_VARIANTS_MAX_CALLS = 20;
4729
+ var ALL_VARIANTS_DEADLINE_MS = 15e3;
4730
+ function buildCollectionVariantsPayload(params) {
4731
+ const source = params || {};
4732
+ const payload = {};
4733
+ for (const key of COLLECTION_VARIANTS_KEYS) {
4734
+ if (source[key] !== void 0) payload[key] = source[key];
4735
+ }
4736
+ if (source.allVariants === true) {
4737
+ payload.limit = MAX_VARIANT_CARDS_PER_CALL;
4738
+ }
4739
+ return payload;
4740
+ }
4469
4741
  var COLLECTIONS_QUERY_KEYS = [
4470
4742
  "filter",
4471
4743
  "fields",
@@ -5107,6 +5379,12 @@ var CustomBackendClient = class extends BaseCommerceClient {
5107
5379
  filterRestOptions(options)
5108
5380
  );
5109
5381
  }
5382
+ async getCollectionVariantCards(params, options) {
5383
+ return this.productService.getCollectionVariantCards(
5384
+ params,
5385
+ filterRestOptions(options)
5386
+ );
5387
+ }
5110
5388
  // ========================================
5111
5389
  // CART OPERATIONS
5112
5390
  // ========================================
@@ -5250,6 +5528,23 @@ function createCommerceClient(clientConfig) {
5250
5528
  }
5251
5529
  }
5252
5530
 
5531
+ // src/core/shopper-ip.ts
5532
+ var IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
5533
+ var IPV6 = /^(?=.*:)[0-9a-f:]{2,39}(\.\d{1,3}){0,3}$/i;
5534
+ function getShopperIp(headers, options) {
5535
+ const entries = (headers.get("x-forwarded-for") ?? "").split(",").map((entry2) => entry2.trim()).filter(Boolean);
5536
+ const entry = entries[entries.length - (options?.trustedHops ?? 1)];
5537
+ if (!entry) return null;
5538
+ const candidate = entry.match(/^\[([^\]]+)\](?::\d+)?$/)?.[1] ?? entry.match(/^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/)?.[1] ?? entry;
5539
+ const ip = candidate.toLowerCase().startsWith("::ffff:") && IPV4.test(candidate.slice(7)) ? candidate.slice(7) : candidate;
5540
+ return IPV4.test(ip) || IPV6.test(ip) ? ip : null;
5541
+ }
5542
+ function shopperForwardHeaders(source, options) {
5543
+ const headers = source instanceof Headers ? source : source.headers;
5544
+ const ip = getShopperIp(headers, options);
5545
+ return ip ? { "x-forwarded-for": ip } : {};
5546
+ }
5547
+
5253
5548
  // src/models/enums.ts
5254
5549
  var EOrderStatus = /* @__PURE__ */ ((EOrderStatus2) => {
5255
5550
  EOrderStatus2["PENDING"] = "PENDING";
@@ -5308,6 +5603,9 @@ var EFulfillmentStatus = /* @__PURE__ */ ((EFulfillmentStatus2) => {
5308
5603
 
5309
5604
  // src/static-params/index.ts
5310
5605
  var log = logger.child({ module: "static-params" });
5606
+ function skipBuildStaticParams() {
5607
+ return process.env.SKIP_BUILD_STATIC_PARAMS === "true";
5608
+ }
5311
5609
  async function withConcurrency(thunks, limit) {
5312
5610
  const results = new Array(thunks.length);
5313
5611
  let next = 0;
@@ -5354,6 +5652,7 @@ async function traverseCollectionProducts(client, collectionsLimit, productsPerC
5354
5652
  }
5355
5653
  function createCollectionStaticParams(getClient, options) {
5356
5654
  return async function generateStaticParams() {
5655
+ if (skipBuildStaticParams()) return [];
5357
5656
  const limit = options?.limit ?? 250;
5358
5657
  try {
5359
5658
  const result = await getClient().getCollections({ first: limit });
@@ -5373,6 +5672,7 @@ function createCollectionStaticParams(getClient, options) {
5373
5672
  }
5374
5673
  function createProductStaticParams(getClient, options) {
5375
5674
  return async function generateStaticParams() {
5675
+ if (skipBuildStaticParams()) return [];
5376
5676
  const limit = options?.limit ?? 250;
5377
5677
  try {
5378
5678
  const result = await getClient().getProducts({ first: limit });
@@ -5392,6 +5692,7 @@ function createProductStaticParams(getClient, options) {
5392
5692
  }
5393
5693
  function createProductViaCollectionsStaticParams(getClient, options) {
5394
5694
  return async function generateStaticParams() {
5695
+ if (skipBuildStaticParams()) return [];
5395
5696
  try {
5396
5697
  const pairs = await traverseCollectionProducts(
5397
5698
  getClient(),
@@ -5413,6 +5714,7 @@ function createProductViaCollectionsStaticParams(getClient, options) {
5413
5714
  }
5414
5715
  function createCollectionProductStaticParams(getClient, options) {
5415
5716
  return async function generateStaticParams() {
5717
+ if (skipBuildStaticParams()) return [];
5416
5718
  try {
5417
5719
  const pairs = await traverseCollectionProducts(
5418
5720
  getClient(),
@@ -5437,6 +5739,6 @@ function createCollectionProductStaticParams(getClient, options) {
5437
5739
  };
5438
5740
  }
5439
5741
 
5440
- export { DEFAULT_REQUEST_TIMEOUT_MS, EAvailability, ECollectionSortKey, EFulfillmentStatus, EOrderSortKey, EOrderStatus, EPaymentStatus, EProductSortKey, createCollectionProductStaticParams, createCollectionStaticParams, createCommerceClient, createCustomClient, createProductStaticParams, createProductViaCollectionsStaticParams, createShopifyClient, resolveRequestSignal };
5742
+ export { DEFAULT_REQUEST_TIMEOUT_MS, EAvailability, ECollectionSortKey, EFulfillmentStatus, EOrderSortKey, EOrderStatus, EPaymentStatus, EProductSortKey, createCollectionProductStaticParams, createCollectionStaticParams, createCommerceClient, createCustomClient, createProductStaticParams, createProductViaCollectionsStaticParams, createShopifyClient, getShopperIp, resolveRequestSignal, shopperForwardHeaders };
5441
5743
  //# sourceMappingURL=index.mjs.map
5442
5744
  //# sourceMappingURL=index.mjs.map