@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.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { I as ICommerceClient } from './interface-NJcjuqaL.mjs';
2
- import { I as IShopifyConfig, L as LoggerConfig, a as ICustomConfig, C as CustomBackendClient, S as ShopifyCommerceClient } from './service-DBKEK2oS.mjs';
3
- export { EAvailability, ECollectionSortKey, EFulfillmentStatus, EOrderSortKey, EOrderStatus, EPaymentStatus, EProductSortKey, IAddToCartRequest, IAddress, IArticleByHandleRequest, IBaseQueryParams, IBlogArticleRequest, ICartItemRequest, ICollectionFilterRequest, ICollectionQueryRequest, ICollectionsByhandlesRequest, ICreateCheckoutRequest, ICustomerQueryRequest, ICustomerRequest, IFetchRequest, IGetArticleRequest, IGraphqlRequest, IImage, IMetafield, IMoney, IOptionsRequest, IOrderByIdRequest, IOrderHistoryRequest, IOrderQueryRequest, IOrderRequest, IPaginationParams, IProductFilters, IProductQueryReqest, IProductRecommendationsRequest, IProductsByHandlesRequest, IRemoveFromCartRequest, IResponse, IResponseMeta, ISeo, ISingleCartRequest, ISingleCollectionRequest, ISingleCustomerRequest, ISingleOrderRequest, ISingleProductRequest, ITrendingArticleRequest, IUpdateCartRequest, IUpdateCustomerRequest, IUpdateOrderRequest } from './models/index.mjs';
1
+ import { I as ICommerceClient } from './interface-CgPiwpPe.mjs';
2
+ import { I as IShopifyConfig, L as LoggerConfig, a as ICustomConfig, C as CustomBackendClient, S as ShopifyCommerceClient } from './service-BPzeuSLS.mjs';
3
+ export { EAvailability, ECollectionSortKey, EFulfillmentStatus, EOrderSortKey, EOrderStatus, EPaymentStatus, EProductSortKey, IAddToCartRequest, IAddress, IArticleByHandleRequest, IBaseQueryParams, IBlogArticleRequest, ICartItemRequest, ICollectionFilterRequest, ICollectionQueryRequest, ICollectionsByhandlesRequest, ICreateCheckoutRequest, ICustomerQueryRequest, ICustomerRequest, IFetchRequest, IGetArticleRequest, IGraphqlRequest, IImage, IMetafield, IMoney, IOptionsRequest, IOrderByIdRequest, IOrderHistoryRequest, IOrderQueryRequest, IOrderRequest, IPaginationParams, IProductFilters, IProductQueryReqest, IProductRecommendationsRequest, IProductsByHandlesRequest, IQueryCollectionsInclude, IQueryCollectionsRequest, IRemoveFromCartRequest, IResponse, IResponseMeta, ISeo, ISingleCartRequest, ISingleCollectionRequest, ISingleCustomerRequest, ISingleOrderRequest, ISingleProductRequest, ITrendingArticleRequest, IUpdateCartRequest, IUpdateCustomerRequest, IUpdateOrderRequest, QueryCollectionsErrorCode, QuerySortDirection } from './models/index.mjs';
4
4
  export { createCollectionProductStaticParams, createCollectionStaticParams, createProductStaticParams, createProductViaCollectionsStaticParams } from './static-params/index.mjs';
5
5
 
6
6
  /**
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { I as ICommerceClient } from './interface-dqoKc63z.js';
2
- import { I as IShopifyConfig, L as LoggerConfig, a as ICustomConfig, C as CustomBackendClient, S as ShopifyCommerceClient } from './service-BHCLUEim.js';
3
- export { EAvailability, ECollectionSortKey, EFulfillmentStatus, EOrderSortKey, EOrderStatus, EPaymentStatus, EProductSortKey, IAddToCartRequest, IAddress, IArticleByHandleRequest, IBaseQueryParams, IBlogArticleRequest, ICartItemRequest, ICollectionFilterRequest, ICollectionQueryRequest, ICollectionsByhandlesRequest, ICreateCheckoutRequest, ICustomerQueryRequest, ICustomerRequest, IFetchRequest, IGetArticleRequest, IGraphqlRequest, IImage, IMetafield, IMoney, IOptionsRequest, IOrderByIdRequest, IOrderHistoryRequest, IOrderQueryRequest, IOrderRequest, IPaginationParams, IProductFilters, IProductQueryReqest, IProductRecommendationsRequest, IProductsByHandlesRequest, IRemoveFromCartRequest, IResponse, IResponseMeta, ISeo, ISingleCartRequest, ISingleCollectionRequest, ISingleCustomerRequest, ISingleOrderRequest, ISingleProductRequest, ITrendingArticleRequest, IUpdateCartRequest, IUpdateCustomerRequest, IUpdateOrderRequest } from './models/index.js';
1
+ import { I as ICommerceClient } from './interface-BGV7d5F8.js';
2
+ import { I as IShopifyConfig, L as LoggerConfig, a as ICustomConfig, C as CustomBackendClient, S as ShopifyCommerceClient } from './service-Cb074q9F.js';
3
+ export { EAvailability, ECollectionSortKey, EFulfillmentStatus, EOrderSortKey, EOrderStatus, EPaymentStatus, EProductSortKey, IAddToCartRequest, IAddress, IArticleByHandleRequest, IBaseQueryParams, IBlogArticleRequest, ICartItemRequest, ICollectionFilterRequest, ICollectionQueryRequest, ICollectionsByhandlesRequest, ICreateCheckoutRequest, ICustomerQueryRequest, ICustomerRequest, IFetchRequest, IGetArticleRequest, IGraphqlRequest, IImage, IMetafield, IMoney, IOptionsRequest, IOrderByIdRequest, IOrderHistoryRequest, IOrderQueryRequest, IOrderRequest, IPaginationParams, IProductFilters, IProductQueryReqest, IProductRecommendationsRequest, IProductsByHandlesRequest, IQueryCollectionsInclude, IQueryCollectionsRequest, IRemoveFromCartRequest, IResponse, IResponseMeta, ISeo, ISingleCartRequest, ISingleCollectionRequest, ISingleCustomerRequest, ISingleOrderRequest, ISingleProductRequest, ITrendingArticleRequest, IUpdateCartRequest, IUpdateCustomerRequest, IUpdateOrderRequest, QueryCollectionsErrorCode, QuerySortDirection } from './models/index.js';
4
4
  export { createCollectionProductStaticParams, createCollectionStaticParams, createProductStaticParams, createProductViaCollectionsStaticParams } from './static-params/index.js';
5
5
 
6
6
  /**
package/dist/index.js CHANGED
@@ -298,6 +298,16 @@ var BaseCommerceClient = class {
298
298
  getCollectionFilters(params, options) {
299
299
  this.throwNotImplemented("getCollectionFilters");
300
300
  }
301
+ /**
302
+ * Read a page of collections, with their products and variants, from one query document
303
+ * @param params - Query document (filter, fields, include, sort, paging)
304
+ * @param options - Request options (headers, timeout, etc.)
305
+ * @returns Promise resolving to collections, with paging in meta.pagination
306
+ * @throws NotImplementedError if not implemented in adapter
307
+ */
308
+ queryCollections(params, options) {
309
+ this.throwNotImplemented("queryCollections");
310
+ }
301
311
  // ========================================
302
312
  // ORDER OPERATIONS
303
313
  // ========================================
@@ -3732,6 +3742,11 @@ var BaseCustomService = class {
3732
3742
  `Request failed: ${response.status} ${response.statusText}`
3733
3743
  );
3734
3744
  error.status = response.status;
3745
+ try {
3746
+ error.body = await response.json();
3747
+ } catch {
3748
+ error.body = void 0;
3749
+ }
3735
3750
  throw error;
3736
3751
  }
3737
3752
  this.logger.info("API request successful", {
@@ -3772,6 +3787,9 @@ function mapGetCollectionsByHandelsResponse(response) {
3772
3787
  function mapGetCollectionFiltersResponse(response) {
3773
3788
  return response;
3774
3789
  }
3790
+ function mapQueryCollectionsResponse(response) {
3791
+ return response?.collections || [];
3792
+ }
3775
3793
 
3776
3794
  // src/adapters/custom/product/urls.ts
3777
3795
  var DEFAULT_VERSION = "v1";
@@ -3780,10 +3798,11 @@ var PRODUCT_ENDPOINTS = {
3780
3798
  getProduct: (v = DEFAULT_VERSION) => `/api/${v}/product/details`,
3781
3799
  getProductsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/product/details`,
3782
3800
  getCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections`,
3783
- getCollectionByHandle: (v = DEFAULT_VERSION, h) => `/api/${v}/collections/handle/${h}`,
3784
- getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${id}`,
3801
+ getCollectionByHandle: (v = DEFAULT_VERSION, h) => `/api/${v}/collections/handle/${encodeURIComponent(h)}`,
3802
+ getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${encodeURIComponent(id)}`,
3785
3803
  getCollectionsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/collections/details`,
3786
- getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${collectionHandle}/filters`
3804
+ getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${encodeURIComponent(collectionHandle)}/filters`,
3805
+ queryCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections/query`
3787
3806
  };
3788
3807
 
3789
3808
  // src/adapters/custom/product/service.ts
@@ -4360,7 +4379,123 @@ var ProductService2 = class extends BaseCustomService {
4360
4379
  });
4361
4380
  }
4362
4381
  }
4382
+ /**
4383
+ * Read a page of collections, with their products and variants, from one
4384
+ * query document. A POST because the document is too nested for a URL; it is
4385
+ * still a read and answers 200.
4386
+ */
4387
+ async queryCollections(params, options) {
4388
+ try {
4389
+ const payload = buildCollectionsQueryPayload(params);
4390
+ const handles = handlesNamedBy(payload.filter);
4391
+ const result = await this.request(
4392
+ PRODUCT_ENDPOINTS.queryCollections(options?.version),
4393
+ "POST",
4394
+ payload,
4395
+ {
4396
+ ...options || {},
4397
+ // Same coverage as the other collection reads: the broad tag for
4398
+ // catalog-wide purges, plus one per handle the filter names, so a
4399
+ // collection.updated / product.updated webhook reaches every page built
4400
+ // from this read. A filter that names no handle (published: true, a
4401
+ // $like, ...) cannot know its result set in advance — broad tag only.
4402
+ // No `revalidate`, as with getCollectionsByHandles.
4403
+ next: {
4404
+ ...options?.next || {},
4405
+ tags: [
4406
+ cacheTags.CacheTags.collections(),
4407
+ ...handles.map((h) => cacheTags.CacheTags.collection(h)),
4408
+ ...options?.next?.tags || []
4409
+ ]
4410
+ }
4411
+ }
4412
+ );
4413
+ const errors = Array.isArray(result?.errors) ? result.errors : [];
4414
+ if (!result?.data) {
4415
+ return formatResponse({
4416
+ success: false,
4417
+ message: "Collections query returned no data.",
4418
+ error: {
4419
+ code: "UPSTREAM_UNAVAILABLE",
4420
+ message: "No data in collections query response."
4421
+ },
4422
+ meta: { requestId: result?.request_id }
4423
+ });
4424
+ }
4425
+ return formatResponse({
4426
+ success: true,
4427
+ message: "Collections retrieved successfully.",
4428
+ data: mapQueryCollectionsResponse(result.data),
4429
+ meta: {
4430
+ pagination: result.data.paging,
4431
+ requestId: result.request_id,
4432
+ ...errors.length > 0 ? { errors } : {}
4433
+ }
4434
+ });
4435
+ } catch (error) {
4436
+ this.logger.error("Error in queryCollections", void 0, { error });
4437
+ const body = error?.body;
4438
+ if (isUpstreamUnavailable(error)) {
4439
+ return formatResponse({
4440
+ success: false,
4441
+ message: "An error occurred while processing the request.",
4442
+ error: {
4443
+ code: "UPSTREAM_UNAVAILABLE",
4444
+ message: typeof error?.status === "number" ? `Request failed: ${error.status}` : "Collections query did not complete."
4445
+ },
4446
+ meta: { requestId: body?.request_id }
4447
+ });
4448
+ }
4449
+ const upstreamErrors = Array.isArray(body?.errors) ? body.errors : [];
4450
+ return formatResponse({
4451
+ success: false,
4452
+ message: "The collections query was rejected.",
4453
+ error: {
4454
+ code: "QUERY_REJECTED",
4455
+ message: upstreamErrors[0]?.message || error.message,
4456
+ details: upstreamErrors
4457
+ },
4458
+ meta: { requestId: body?.request_id }
4459
+ });
4460
+ }
4461
+ }
4363
4462
  };
4463
+ var COLLECTIONS_QUERY_KEYS = [
4464
+ "filter",
4465
+ "fields",
4466
+ "include",
4467
+ "sort",
4468
+ "limit",
4469
+ "skip",
4470
+ "after",
4471
+ "count",
4472
+ "metafields",
4473
+ "availability",
4474
+ "ratings"
4475
+ ];
4476
+ function buildCollectionsQueryPayload(params) {
4477
+ const source = params || {};
4478
+ const payload = {};
4479
+ for (const key of COLLECTIONS_QUERY_KEYS) {
4480
+ if (source[key] !== void 0) payload[key] = source[key];
4481
+ }
4482
+ const filter = payload.filter && typeof payload.filter === "object" ? payload.filter : {};
4483
+ const routeHandle = source.useRouteHandle === true ? source.handle : void 0;
4484
+ if (typeof routeHandle === "string" && routeHandle.trim() !== "" && filter.handle === void 0) {
4485
+ payload.filter = { ...filter, handle: routeHandle };
4486
+ }
4487
+ return payload;
4488
+ }
4489
+ function handlesNamedBy(filter) {
4490
+ const handle = filter?.handle;
4491
+ const candidates = typeof handle === "string" ? [handle] : handle && typeof handle === "object" ? [
4492
+ handle.$eq,
4493
+ ...Array.isArray(handle.$in) ? handle.$in : []
4494
+ ] : [];
4495
+ return candidates.filter(
4496
+ (h) => typeof h === "string" && h.trim() !== ""
4497
+ );
4498
+ }
4364
4499
 
4365
4500
  // src/adapters/custom/order/urls.ts
4366
4501
  var DEFAULT_VERSION2 = "v1";
@@ -4942,6 +5077,12 @@ var CustomBackendClient = class extends BaseCommerceClient {
4942
5077
  filterRestOptions(options)
4943
5078
  );
4944
5079
  }
5080
+ async queryCollections(params, options) {
5081
+ return this.productService.queryCollections(
5082
+ params,
5083
+ filterRestOptions(options)
5084
+ );
5085
+ }
4945
5086
  // ========================================
4946
5087
  // CART OPERATIONS
4947
5088
  // ========================================
@@ -5010,12 +5151,69 @@ var CustomBackendClient = class extends BaseCommerceClient {
5010
5151
  }
5011
5152
  };
5012
5153
 
5154
+ // src/core/normalize-handle.ts
5155
+ function isUnsafeHandle(value) {
5156
+ for (const char of value) {
5157
+ const code = char.codePointAt(0) ?? 0;
5158
+ if (code < 32 || code === 127) {
5159
+ return true;
5160
+ }
5161
+ if (char === "/" || char === "\\" || char === "?" || char === "#" || char === '"') {
5162
+ return true;
5163
+ }
5164
+ }
5165
+ return false;
5166
+ }
5167
+ function decodeHandle(value) {
5168
+ let decoded;
5169
+ try {
5170
+ decoded = decodeURIComponent(value);
5171
+ } catch {
5172
+ return value;
5173
+ }
5174
+ return isUnsafeHandle(decoded) ? value : decoded;
5175
+ }
5176
+ function normalizeParams(params) {
5177
+ if (!params || typeof params !== "object") {
5178
+ return params;
5179
+ }
5180
+ const { handle, handles } = params;
5181
+ const hasHandle = typeof handle === "string";
5182
+ const hasHandles = Array.isArray(handles);
5183
+ if (!hasHandle && !hasHandles) {
5184
+ return params;
5185
+ }
5186
+ const next = { ...params };
5187
+ if (hasHandle) {
5188
+ next.handle = decodeHandle(handle);
5189
+ }
5190
+ if (hasHandles) {
5191
+ next.handles = handles.map(
5192
+ (h) => typeof h === "string" ? decodeHandle(h) : h
5193
+ );
5194
+ }
5195
+ return next;
5196
+ }
5197
+ function withHandleNormalization(client) {
5198
+ return new Proxy(client, {
5199
+ get(target, prop) {
5200
+ const value = Reflect.get(target, prop);
5201
+ if (typeof value !== "function") {
5202
+ return value;
5203
+ }
5204
+ return function(params, ...rest) {
5205
+ return value.call(target, normalizeParams(params), ...rest);
5206
+ };
5207
+ }
5208
+ });
5209
+ }
5210
+
5013
5211
  // src/core/init.ts
5014
5212
  function createShopifyClient(config, logging) {
5015
- return new ShopifyCommerceClient(config, logging);
5213
+ return withHandleNormalization(new ShopifyCommerceClient(config, logging));
5016
5214
  }
5017
5215
  function createCustomClient(config, logging) {
5018
- return new CustomBackendClient(config, logging);
5216
+ return withHandleNormalization(new CustomBackendClient(config, logging));
5019
5217
  }
5020
5218
  function createCommerceClient(clientConfig) {
5021
5219
  switch (clientConfig.type) {