@shopkit/data-layer 1.4.5 → 1.5.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
@@ -296,6 +296,16 @@ var BaseCommerceClient = class {
296
296
  getCollectionFilters(params, options) {
297
297
  this.throwNotImplemented("getCollectionFilters");
298
298
  }
299
+ /**
300
+ * Read a page of collections, with their products and variants, from one query document
301
+ * @param params - Query document (filter, fields, include, sort, paging)
302
+ * @param options - Request options (headers, timeout, etc.)
303
+ * @returns Promise resolving to collections, with paging in meta.pagination
304
+ * @throws NotImplementedError if not implemented in adapter
305
+ */
306
+ queryCollections(params, options) {
307
+ this.throwNotImplemented("queryCollections");
308
+ }
299
309
  // ========================================
300
310
  // ORDER OPERATIONS
301
311
  // ========================================
@@ -3730,6 +3740,11 @@ var BaseCustomService = class {
3730
3740
  `Request failed: ${response.status} ${response.statusText}`
3731
3741
  );
3732
3742
  error.status = response.status;
3743
+ try {
3744
+ error.body = await response.json();
3745
+ } catch {
3746
+ error.body = void 0;
3747
+ }
3733
3748
  throw error;
3734
3749
  }
3735
3750
  this.logger.info("API request successful", {
@@ -3770,6 +3785,9 @@ function mapGetCollectionsByHandelsResponse(response) {
3770
3785
  function mapGetCollectionFiltersResponse(response) {
3771
3786
  return response;
3772
3787
  }
3788
+ function mapQueryCollectionsResponse(response) {
3789
+ return response?.collections || [];
3790
+ }
3773
3791
 
3774
3792
  // src/adapters/custom/product/urls.ts
3775
3793
  var DEFAULT_VERSION = "v1";
@@ -3778,10 +3796,11 @@ var PRODUCT_ENDPOINTS = {
3778
3796
  getProduct: (v = DEFAULT_VERSION) => `/api/${v}/product/details`,
3779
3797
  getProductsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/product/details`,
3780
3798
  getCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections`,
3781
- getCollectionByHandle: (v = DEFAULT_VERSION, h) => `/api/${v}/collections/handle/${h}`,
3782
- getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${id}`,
3799
+ getCollectionByHandle: (v = DEFAULT_VERSION, h) => `/api/${v}/collections/handle/${encodeURIComponent(h)}`,
3800
+ getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${encodeURIComponent(id)}`,
3783
3801
  getCollectionsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/collections/details`,
3784
- getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${collectionHandle}/filters`
3802
+ getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${encodeURIComponent(collectionHandle)}/filters`,
3803
+ queryCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections/query`
3785
3804
  };
3786
3805
 
3787
3806
  // src/adapters/custom/product/service.ts
@@ -4358,7 +4377,123 @@ var ProductService2 = class extends BaseCustomService {
4358
4377
  });
4359
4378
  }
4360
4379
  }
4380
+ /**
4381
+ * Read a page of collections, with their products and variants, from one
4382
+ * query document. A POST because the document is too nested for a URL; it is
4383
+ * still a read and answers 200.
4384
+ */
4385
+ async queryCollections(params, options) {
4386
+ try {
4387
+ const payload = buildCollectionsQueryPayload(params);
4388
+ const handles = handlesNamedBy(payload.filter);
4389
+ const result = await this.request(
4390
+ PRODUCT_ENDPOINTS.queryCollections(options?.version),
4391
+ "POST",
4392
+ payload,
4393
+ {
4394
+ ...options || {},
4395
+ // Same coverage as the other collection reads: the broad tag for
4396
+ // catalog-wide purges, plus one per handle the filter names, so a
4397
+ // collection.updated / product.updated webhook reaches every page built
4398
+ // from this read. A filter that names no handle (published: true, a
4399
+ // $like, ...) cannot know its result set in advance — broad tag only.
4400
+ // No `revalidate`, as with getCollectionsByHandles.
4401
+ next: {
4402
+ ...options?.next || {},
4403
+ tags: [
4404
+ CacheTags.collections(),
4405
+ ...handles.map((h) => CacheTags.collection(h)),
4406
+ ...options?.next?.tags || []
4407
+ ]
4408
+ }
4409
+ }
4410
+ );
4411
+ const errors = Array.isArray(result?.errors) ? result.errors : [];
4412
+ if (!result?.data) {
4413
+ return formatResponse({
4414
+ success: false,
4415
+ message: "Collections query returned no data.",
4416
+ error: {
4417
+ code: "UPSTREAM_UNAVAILABLE",
4418
+ message: "No data in collections query response."
4419
+ },
4420
+ meta: { requestId: result?.request_id }
4421
+ });
4422
+ }
4423
+ return formatResponse({
4424
+ success: true,
4425
+ message: "Collections retrieved successfully.",
4426
+ data: mapQueryCollectionsResponse(result.data),
4427
+ meta: {
4428
+ pagination: result.data.paging,
4429
+ requestId: result.request_id,
4430
+ ...errors.length > 0 ? { errors } : {}
4431
+ }
4432
+ });
4433
+ } catch (error) {
4434
+ this.logger.error("Error in queryCollections", void 0, { error });
4435
+ const body = error?.body;
4436
+ if (isUpstreamUnavailable(error)) {
4437
+ return formatResponse({
4438
+ success: false,
4439
+ message: "An error occurred while processing the request.",
4440
+ error: {
4441
+ code: "UPSTREAM_UNAVAILABLE",
4442
+ message: typeof error?.status === "number" ? `Request failed: ${error.status}` : "Collections query did not complete."
4443
+ },
4444
+ meta: { requestId: body?.request_id }
4445
+ });
4446
+ }
4447
+ const upstreamErrors = Array.isArray(body?.errors) ? body.errors : [];
4448
+ return formatResponse({
4449
+ success: false,
4450
+ message: "The collections query was rejected.",
4451
+ error: {
4452
+ code: "QUERY_REJECTED",
4453
+ message: upstreamErrors[0]?.message || error.message,
4454
+ details: upstreamErrors
4455
+ },
4456
+ meta: { requestId: body?.request_id }
4457
+ });
4458
+ }
4459
+ }
4361
4460
  };
4461
+ var COLLECTIONS_QUERY_KEYS = [
4462
+ "filter",
4463
+ "fields",
4464
+ "include",
4465
+ "sort",
4466
+ "limit",
4467
+ "skip",
4468
+ "after",
4469
+ "count",
4470
+ "metafields",
4471
+ "availability",
4472
+ "ratings"
4473
+ ];
4474
+ function buildCollectionsQueryPayload(params) {
4475
+ const source = params || {};
4476
+ const payload = {};
4477
+ for (const key of COLLECTIONS_QUERY_KEYS) {
4478
+ if (source[key] !== void 0) payload[key] = source[key];
4479
+ }
4480
+ const filter = payload.filter && typeof payload.filter === "object" ? payload.filter : {};
4481
+ const routeHandle = source.useRouteHandle === true ? source.handle : void 0;
4482
+ if (typeof routeHandle === "string" && routeHandle.trim() !== "" && filter.handle === void 0) {
4483
+ payload.filter = { ...filter, handle: routeHandle };
4484
+ }
4485
+ return payload;
4486
+ }
4487
+ function handlesNamedBy(filter) {
4488
+ const handle = filter?.handle;
4489
+ const candidates = typeof handle === "string" ? [handle] : handle && typeof handle === "object" ? [
4490
+ handle.$eq,
4491
+ ...Array.isArray(handle.$in) ? handle.$in : []
4492
+ ] : [];
4493
+ return candidates.filter(
4494
+ (h) => typeof h === "string" && h.trim() !== ""
4495
+ );
4496
+ }
4362
4497
 
4363
4498
  // src/adapters/custom/order/urls.ts
4364
4499
  var DEFAULT_VERSION2 = "v1";
@@ -4940,6 +5075,12 @@ var CustomBackendClient = class extends BaseCommerceClient {
4940
5075
  filterRestOptions(options)
4941
5076
  );
4942
5077
  }
5078
+ async queryCollections(params, options) {
5079
+ return this.productService.queryCollections(
5080
+ params,
5081
+ filterRestOptions(options)
5082
+ );
5083
+ }
4943
5084
  // ========================================
4944
5085
  // CART OPERATIONS
4945
5086
  // ========================================
@@ -5008,12 +5149,69 @@ var CustomBackendClient = class extends BaseCommerceClient {
5008
5149
  }
5009
5150
  };
5010
5151
 
5152
+ // src/core/normalize-handle.ts
5153
+ function isUnsafeHandle(value) {
5154
+ for (const char of value) {
5155
+ const code = char.codePointAt(0) ?? 0;
5156
+ if (code < 32 || code === 127) {
5157
+ return true;
5158
+ }
5159
+ if (char === "/" || char === "\\" || char === "?" || char === "#" || char === '"') {
5160
+ return true;
5161
+ }
5162
+ }
5163
+ return false;
5164
+ }
5165
+ function decodeHandle(value) {
5166
+ let decoded;
5167
+ try {
5168
+ decoded = decodeURIComponent(value);
5169
+ } catch {
5170
+ return value;
5171
+ }
5172
+ return isUnsafeHandle(decoded) ? value : decoded;
5173
+ }
5174
+ function normalizeParams(params) {
5175
+ if (!params || typeof params !== "object") {
5176
+ return params;
5177
+ }
5178
+ const { handle, handles } = params;
5179
+ const hasHandle = typeof handle === "string";
5180
+ const hasHandles = Array.isArray(handles);
5181
+ if (!hasHandle && !hasHandles) {
5182
+ return params;
5183
+ }
5184
+ const next = { ...params };
5185
+ if (hasHandle) {
5186
+ next.handle = decodeHandle(handle);
5187
+ }
5188
+ if (hasHandles) {
5189
+ next.handles = handles.map(
5190
+ (h) => typeof h === "string" ? decodeHandle(h) : h
5191
+ );
5192
+ }
5193
+ return next;
5194
+ }
5195
+ function withHandleNormalization(client) {
5196
+ return new Proxy(client, {
5197
+ get(target, prop) {
5198
+ const value = Reflect.get(target, prop);
5199
+ if (typeof value !== "function") {
5200
+ return value;
5201
+ }
5202
+ return function(params, ...rest) {
5203
+ return value.call(target, normalizeParams(params), ...rest);
5204
+ };
5205
+ }
5206
+ });
5207
+ }
5208
+
5011
5209
  // src/core/init.ts
5012
5210
  function createShopifyClient(config, logging) {
5013
- return new ShopifyCommerceClient(config, logging);
5211
+ return withHandleNormalization(new ShopifyCommerceClient(config, logging));
5014
5212
  }
5015
5213
  function createCustomClient(config, logging) {
5016
- return new CustomBackendClient(config, logging);
5214
+ return withHandleNormalization(new CustomBackendClient(config, logging));
5017
5215
  }
5018
5216
  function createCommerceClient(clientConfig) {
5019
5217
  switch (clientConfig.type) {