@daouypkgs/commerce-commercetools 0.0.183

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.
Files changed (39) hide show
  1. package/README.md +1 -0
  2. package/dist/cart/index.d.ts +2 -0
  3. package/dist/cart/use-add-item.d.ts +5 -0
  4. package/dist/cart/use-cart.d.ts +5 -0
  5. package/dist/cart/use-remove-item.d.ts +11 -0
  6. package/dist/cart/use-update-item.d.ts +11 -0
  7. package/dist/client.d.ts +3 -0
  8. package/dist/commerce-commercetools.cjs.development.js +1201 -0
  9. package/dist/commerce-commercetools.cjs.development.js.map +1 -0
  10. package/dist/commerce-commercetools.cjs.production.min.js +2 -0
  11. package/dist/commerce-commercetools.cjs.production.min.js.map +1 -0
  12. package/dist/commerce-commercetools.esm.js +1189 -0
  13. package/dist/commerce-commercetools.esm.js.map +1 -0
  14. package/dist/commercetools.d.ts +5 -0
  15. package/dist/const.d.ts +4 -0
  16. package/dist/fetcher.d.ts +3 -0
  17. package/dist/index.d.ts +5 -0
  18. package/dist/index.js +8 -0
  19. package/dist/product/use-product.d.ts +8 -0
  20. package/dist/product/use-search.d.ts +12 -0
  21. package/dist/provider.d.ts +49 -0
  22. package/dist/registerCommerceProvider.d.ts +11 -0
  23. package/dist/registerable.d.ts +6 -0
  24. package/dist/site/use-brands.d.ts +5 -0
  25. package/dist/site/use-categories.d.ts +5 -0
  26. package/dist/types/cart.d.ts +24 -0
  27. package/dist/types/index.d.ts +4 -0
  28. package/dist/types/product.d.ts +14 -0
  29. package/dist/types/site.d.ts +7 -0
  30. package/dist/utils/cart-active.d.ts +4 -0
  31. package/dist/utils/cart-cookie.d.ts +3 -0
  32. package/dist/utils/cart-create.d.ts +4 -0
  33. package/dist/utils/common.d.ts +2 -0
  34. package/dist/utils/cookies.d.ts +3 -0
  35. package/dist/utils/get-sort-variables.d.ts +2 -0
  36. package/dist/utils/index.d.ts +7 -0
  37. package/dist/utils/localized-string.d.ts +2 -0
  38. package/dist/utils/normalize.d.ts +21 -0
  39. package/package.json +47 -0
@@ -0,0 +1,1189 @@
1
+ import registerGlobalContext from '@daouy/host/registerGlobalContext';
2
+ import { useDaouyQueryData } from '@daouy/query';
3
+ import { useCart, ValidationError, useCommerce as useCommerce$1, getCommerceProvider as getCommerceProvider$1, CartActionsProvider, globalActionsRegistrations } from '@daouypkgs/commerce';
4
+ import React, { useMemo, useCallback } from 'react';
5
+ import Cookies from 'js-cookie';
6
+ import debounce from 'debounce';
7
+ import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk';
8
+ import { ClientBuilder } from '@commercetools/sdk-client-v2';
9
+
10
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
11
+ try {
12
+ var i = n[a](c),
13
+ u = i.value;
14
+ } catch (n) {
15
+ return void e(n);
16
+ }
17
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
18
+ }
19
+ function _asyncToGenerator(n) {
20
+ return function () {
21
+ var t = this,
22
+ e = arguments;
23
+ return new Promise(function (r, o) {
24
+ var a = n.apply(t, e);
25
+ function _next(n) {
26
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
27
+ }
28
+ function _throw(n) {
29
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
30
+ }
31
+ _next(void 0);
32
+ });
33
+ };
34
+ }
35
+ function _extends() {
36
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
37
+ for (var e = 1; e < arguments.length; e++) {
38
+ var t = arguments[e];
39
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
40
+ }
41
+ return n;
42
+ }, _extends.apply(null, arguments);
43
+ }
44
+ function _regenerator() {
45
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
46
+ var e,
47
+ t,
48
+ r = "function" == typeof Symbol ? Symbol : {},
49
+ n = r.iterator || "@@iterator",
50
+ o = r.toStringTag || "@@toStringTag";
51
+ function i(r, n, o, i) {
52
+ var c = n && n.prototype instanceof Generator ? n : Generator,
53
+ u = Object.create(c.prototype);
54
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
55
+ var i,
56
+ c,
57
+ u,
58
+ f = 0,
59
+ p = o || [],
60
+ y = !1,
61
+ G = {
62
+ p: 0,
63
+ n: 0,
64
+ v: e,
65
+ a: d,
66
+ f: d.bind(e, 4),
67
+ d: function (t, r) {
68
+ return i = t, c = 0, u = e, G.n = r, a;
69
+ }
70
+ };
71
+ function d(r, n) {
72
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
73
+ var o,
74
+ i = p[t],
75
+ d = G.p,
76
+ l = i[2];
77
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
78
+ }
79
+ if (o || r > 1) return a;
80
+ throw y = !0, n;
81
+ }
82
+ return function (o, p, l) {
83
+ if (f > 1) throw TypeError("Generator is already running");
84
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
85
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
86
+ try {
87
+ if (f = 2, i) {
88
+ if (c || (o = "next"), t = i[o]) {
89
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
90
+ if (!t.done) return t;
91
+ u = t.value, c < 2 && (c = 0);
92
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
93
+ i = e;
94
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
95
+ } catch (t) {
96
+ i = e, c = 1, u = t;
97
+ } finally {
98
+ f = 1;
99
+ }
100
+ }
101
+ return {
102
+ value: t,
103
+ done: y
104
+ };
105
+ };
106
+ }(r, o, i), !0), u;
107
+ }
108
+ var a = {};
109
+ function Generator() {}
110
+ function GeneratorFunction() {}
111
+ function GeneratorFunctionPrototype() {}
112
+ t = Object.getPrototypeOf;
113
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
114
+ return this;
115
+ }), t),
116
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
117
+ function f(e) {
118
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
119
+ }
120
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
121
+ return this;
122
+ }), _regeneratorDefine(u, "toString", function () {
123
+ return "[object Generator]";
124
+ }), (_regenerator = function () {
125
+ return {
126
+ w: i,
127
+ m: f
128
+ };
129
+ })();
130
+ }
131
+ function _regeneratorDefine(e, r, n, t) {
132
+ var i = Object.defineProperty;
133
+ try {
134
+ i({}, "", {});
135
+ } catch (e) {
136
+ i = 0;
137
+ }
138
+ _regeneratorDefine = function (e, r, n, t) {
139
+ function o(r, n) {
140
+ _regeneratorDefine(e, r, function (e) {
141
+ return this._invoke(r, n, e);
142
+ });
143
+ }
144
+ r ? i ? i(e, r, {
145
+ value: n,
146
+ enumerable: !t,
147
+ configurable: !t,
148
+ writable: !t
149
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
150
+ }, _regeneratorDefine(e, r, n, t);
151
+ }
152
+
153
+ var getSortVariables = function getSortVariables(sort, isCategory) {
154
+ var output = undefined;
155
+ switch (sort) {
156
+ case 'price-asc':
157
+ output = 'price asc';
158
+ break;
159
+ case 'price-desc':
160
+ output = 'price desc';
161
+ break;
162
+ case 'trending-desc':
163
+ // default option
164
+ output = undefined;
165
+ break;
166
+ case 'latest-desc':
167
+ output = 'createdAt desc';
168
+ break;
169
+ }
170
+ return output;
171
+ };
172
+
173
+ var COMMERCETOOLS_COOKIE_EXPIRE = 30;
174
+ var COMMERCETOOLS_CART_COOKIE = 'commercetools_cart';
175
+
176
+ var options = {
177
+ expires: COMMERCETOOLS_COOKIE_EXPIRE,
178
+ sameSite: "none",
179
+ secure: true
180
+ };
181
+ var getCookies = function getCookies(name) {
182
+ var cookie = Cookies.get(name);
183
+ return cookie ? JSON.parse(cookie) : undefined;
184
+ };
185
+ var setCookies = function setCookies(name, value) {
186
+ return Cookies.set(name, JSON.stringify(value), options);
187
+ };
188
+ var removeCookies = function removeCookies(name) {
189
+ return Cookies.remove(name);
190
+ };
191
+
192
+ var getCartId = function getCartId() {
193
+ return getCookies(COMMERCETOOLS_CART_COOKIE);
194
+ };
195
+ var setCartId = function setCartId(id) {
196
+ return setCookies(COMMERCETOOLS_CART_COOKIE, id);
197
+ };
198
+ var removeCartCookie = function removeCartCookie() {
199
+ return removeCookies(COMMERCETOOLS_CART_COOKIE);
200
+ };
201
+
202
+ var createCart = /*#__PURE__*/function () {
203
+ var _ref = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(fetch) {
204
+ var draft, cart;
205
+ return _regenerator().w(function (_context) {
206
+ while (1) switch (_context.n) {
207
+ case 0:
208
+ draft = {
209
+ currency: 'USD',
210
+ country: 'US'
211
+ };
212
+ _context.n = 1;
213
+ return fetch({
214
+ query: 'carts',
215
+ method: 'post',
216
+ body: draft
217
+ });
218
+ case 1:
219
+ cart = _context.v;
220
+ if (!cart.body) {
221
+ removeCartCookie();
222
+ } else {
223
+ setCartId(cart.body.id);
224
+ }
225
+ return _context.a(2, cart.body);
226
+ }
227
+ }, _callee);
228
+ }));
229
+ return function createCart(_x) {
230
+ return _ref.apply(this, arguments);
231
+ };
232
+ }();
233
+
234
+ var getActiveCart = /*#__PURE__*/function () {
235
+ var _ref = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(fetch) {
236
+ var cartId, activeCart;
237
+ return _regenerator().w(function (_context) {
238
+ while (1) switch (_context.n) {
239
+ case 0:
240
+ cartId = getCartId();
241
+ if (!cartId) {
242
+ _context.n = 2;
243
+ break;
244
+ }
245
+ _context.n = 1;
246
+ return fetch({
247
+ query: 'carts',
248
+ method: 'get',
249
+ variables: {
250
+ id: cartId
251
+ }
252
+ });
253
+ case 1:
254
+ activeCart = _context.v.body;
255
+ _context.n = 4;
256
+ break;
257
+ case 2:
258
+ _context.n = 3;
259
+ return createCart(fetch);
260
+ case 3:
261
+ activeCart = _context.v;
262
+ case 4:
263
+ if (!activeCart) {
264
+ removeCartCookie();
265
+ } else {
266
+ setCartId(activeCart.id);
267
+ }
268
+ return _context.a(2, activeCart);
269
+ }
270
+ }, _callee);
271
+ }));
272
+ return function getActiveCart(_x) {
273
+ return _ref.apply(this, arguments);
274
+ };
275
+ }();
276
+
277
+ var getLocalizedString = function getLocalizedString(localizedString, locale) {
278
+ return !localizedString || !locale ? undefined : locale in localizedString ? localizedString[locale] : Object.values(localizedString)[0];
279
+ };
280
+
281
+ var withoutNils = function withoutNils(xs) {
282
+ return xs.filter(function (x) {
283
+ return x != null;
284
+ });
285
+ };
286
+ var dedup = function dedup(xs) {
287
+ return [].concat(new Set(xs));
288
+ };
289
+
290
+ var currencyCode = 'USD';
291
+ var stringify = function stringify(value) {
292
+ return typeof value === 'string' ? value : JSON.stringify(value);
293
+ };
294
+ var money = function money(price) {
295
+ return price ? {
296
+ value: price.centAmount / 100,
297
+ currencyCode: price.currencyCode
298
+ } : {
299
+ value: -1.0,
300
+ currencyCode: currencyCode
301
+ };
302
+ };
303
+ var normalizeProductOption = function normalizeProductOption(option) {
304
+ return {
305
+ __typename: 'MultipleChoiceOption',
306
+ id: option.name,
307
+ displayName: option.name,
308
+ values: dedup(Array.isArray(option.value) ? option.value : [option.value]).map(function (val) {
309
+ if (option.name.match(/colou?r/gi) && /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i.test(val)) {
310
+ return {
311
+ label: stringify(val),
312
+ hexColors: [val]
313
+ };
314
+ } else {
315
+ return {
316
+ label: stringify(val)
317
+ };
318
+ }
319
+ })
320
+ };
321
+ };
322
+ var normalizeProductImages = function normalizeProductImages(images) {
323
+ return images.map(function (image) {
324
+ return _extends({
325
+ url: image.url
326
+ }, image.label ? {
327
+ alt: image.label
328
+ } : {}, {
329
+ width: image.dimensions.w,
330
+ height: image.dimensions.h
331
+ });
332
+ });
333
+ };
334
+ var normalizeProductVariant = function normalizeProductVariant(variant) {
335
+ var _variant$prices$find$, _variant$prices, _variant$prices2, _variant$sku, _variant$attributes$m, _variant$attributes;
336
+ var price = money((_variant$prices$find$ = (_variant$prices = variant.prices) == null || (_variant$prices = _variant$prices.find(function (price) {
337
+ return price.value.currencyCode === currencyCode;
338
+ })) == null ? void 0 : _variant$prices.value) != null ? _variant$prices$find$ : (_variant$prices2 = variant.prices) == null || (_variant$prices2 = _variant$prices2[0]) == null ? void 0 : _variant$prices2.value).value;
339
+ return {
340
+ id: "" + variant.id,
341
+ name: "" + variant.id,
342
+ sku: (_variant$sku = variant.sku) != null ? _variant$sku : '',
343
+ price: price,
344
+ options: (_variant$attributes$m = (_variant$attributes = variant.attributes) == null ? void 0 : _variant$attributes.map(function (attribute) {
345
+ return normalizeProductOption({
346
+ name: attribute.name,
347
+ value: attribute.value.key
348
+ });
349
+ })) != null ? _variant$attributes$m : [],
350
+ requiresShipping: false,
351
+ listPrice: price
352
+ };
353
+ };
354
+ var normalizeProduct = function normalizeProduct(product, locale) {
355
+ var _getLocalizedString, _getLocalizedString2, _product$masterVarian, _product$masterVarian2, _product$masterVarian3;
356
+ return {
357
+ id: product.id,
358
+ name: (_getLocalizedString = getLocalizedString(product.name, locale)) != null ? _getLocalizedString : "",
359
+ slug: getLocalizedString(product.slug, locale),
360
+ path: "/" + getLocalizedString(product.slug, locale),
361
+ description: (_getLocalizedString2 = getLocalizedString(product.description, locale)) != null ? _getLocalizedString2 : '',
362
+ price: money((_product$masterVarian = (_product$masterVarian2 = product.masterVariant.prices) == null || (_product$masterVarian2 = _product$masterVarian2.find(function (price) {
363
+ return price.value.currencyCode === currencyCode;
364
+ })) == null ? void 0 : _product$masterVarian2.value) != null ? _product$masterVarian : (_product$masterVarian3 = product.masterVariant.prices) == null || (_product$masterVarian3 = _product$masterVarian3[0]) == null ? void 0 : _product$masterVarian3.value),
365
+ images: normalizeProductImages(withoutNils([].concat(product.masterVariant.images ? product.masterVariant.images : [], product.variants.flatMap(function (variant) {
366
+ return variant.images;
367
+ })))),
368
+ variants: [product.masterVariant].concat(product.variants).map(normalizeProductVariant),
369
+ options: withoutNils([].concat(product.masterVariant.attributes ? product.masterVariant.attributes : [], product.variants.flatMap(function (variant) {
370
+ return variant.attributes;
371
+ }))).reduce(function (groupedAttributes, attribute) {
372
+ var groupedAttribute = groupedAttributes.find(function (gAttr) {
373
+ return gAttr.name === attribute.name;
374
+ });
375
+ if (groupedAttribute) {
376
+ groupedAttribute.value.push(stringify(attribute.value.key));
377
+ } else {
378
+ groupedAttributes.push({
379
+ name: attribute.name,
380
+ value: [stringify(attribute.value.key)]
381
+ });
382
+ }
383
+ return groupedAttributes;
384
+ }, []).map(normalizeProductOption)
385
+ };
386
+ };
387
+ var normalizeLineItem = function normalizeLineItem(lineItem, locale) {
388
+ var _getLocalizedString3, _lineItem$variant$att, _lineItem$variant$att2;
389
+ return {
390
+ id: lineItem.id,
391
+ variantId: "" + lineItem.variant.id,
392
+ productId: lineItem.productId,
393
+ name: (_getLocalizedString3 = getLocalizedString(lineItem.name, locale)) != null ? _getLocalizedString3 : "",
394
+ path: '',
395
+ quantity: lineItem.quantity,
396
+ discounts: [],
397
+ variant: normalizeProductVariant(lineItem.variant),
398
+ options: (_lineItem$variant$att = (_lineItem$variant$att2 = lineItem.variant.attributes) == null ? void 0 : _lineItem$variant$att2.map(function (attribute) {
399
+ return {
400
+ id: attribute.name,
401
+ name: attribute.name,
402
+ value: attribute.value.key
403
+ };
404
+ })) != null ? _lineItem$variant$att : []
405
+ };
406
+ };
407
+ var normalizeCart = function normalizeCart(cart, locale) {
408
+ return {
409
+ id: cart.id,
410
+ customerId: cart.customerId,
411
+ email: cart.customerEmail,
412
+ createdAt: cart.createdAt,
413
+ currency: {
414
+ code: currencyCode
415
+ },
416
+ taxesIncluded: cart.taxMode !== 'Disabled',
417
+ lineItems: cart.lineItems.map(function (item) {
418
+ return normalizeLineItem(item, locale);
419
+ }),
420
+ lineItemsSubtotalPrice: 0,
421
+ subtotalPrice: money(cart.totalPrice).value,
422
+ totalPrice: money(cart.totalPrice).value,
423
+ discounts: []
424
+ };
425
+ };
426
+ var normalizeCategory = function normalizeCategory(category, locale) {
427
+ var _getLocalizedString4, _getLocalizedString5;
428
+ return {
429
+ id: category.id,
430
+ name: (_getLocalizedString4 = getLocalizedString(category.name, locale)) != null ? _getLocalizedString4 : "",
431
+ slug: (_getLocalizedString5 = getLocalizedString(category.slug, locale)) != null ? _getLocalizedString5 : "",
432
+ path: "/" + getLocalizedString(category.slug, locale)
433
+ };
434
+ };
435
+
436
+ var handler = {
437
+ fetchOptions: {
438
+ query: "cart",
439
+ method: "get"
440
+ },
441
+ fetcher: function fetcher(_ref) {
442
+ return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
443
+ var fetch, provider, activeCart;
444
+ return _regenerator().w(function (_context) {
445
+ while (1) switch (_context.n) {
446
+ case 0:
447
+ fetch = _ref.fetch, provider = _ref.provider;
448
+ _context.n = 1;
449
+ return getActiveCart(fetch);
450
+ case 1:
451
+ activeCart = _context.v;
452
+ return _context.a(2, activeCart ? normalizeCart(activeCart, provider.locale) : null);
453
+ }
454
+ }, _callee);
455
+ }))();
456
+ },
457
+ useHook: function useHook(_ref2) {
458
+ var useData = _ref2.useData;
459
+ return function (input) {
460
+ var response = useData({
461
+ swrOptions: _extends({
462
+ revalidateOnFocus: false
463
+ }, input == null ? void 0 : input.swrOptions)
464
+ });
465
+ return useMemo(function () {
466
+ return Object.create(response, {
467
+ isEmpty: {
468
+ get: function get() {
469
+ var _response$data$lineIt, _response$data;
470
+ return ((_response$data$lineIt = (_response$data = response.data) == null ? void 0 : _response$data.lineItems.length) != null ? _response$data$lineIt : 0) <= 0;
471
+ },
472
+ enumerable: true
473
+ }
474
+ });
475
+ }, [response]);
476
+ };
477
+ }
478
+ };
479
+
480
+ var handler$1 = {
481
+ fetchOptions: {
482
+ query: "cart",
483
+ method: "post"
484
+ },
485
+ fetcher: function fetcher(_ref) {
486
+ return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
487
+ var _item$quantity;
488
+ var item, fetch, provider, activeCart, updatedCart;
489
+ return _regenerator().w(function (_context) {
490
+ while (1) switch (_context.n) {
491
+ case 0:
492
+ item = _ref.input, fetch = _ref.fetch, provider = _ref.provider;
493
+ _context.n = 1;
494
+ return getActiveCart(fetch);
495
+ case 1:
496
+ activeCart = _context.v;
497
+ if (!(item.quantity && (!Number.isInteger(item.quantity) || item.quantity < 1) || !activeCart)) {
498
+ _context.n = 2;
499
+ break;
500
+ }
501
+ return _context.a(2, undefined);
502
+ case 2:
503
+ _context.n = 3;
504
+ return fetch({
505
+ query: "carts",
506
+ method: "post",
507
+ variables: {
508
+ id: activeCart.id
509
+ },
510
+ body: {
511
+ version: activeCart.version,
512
+ actions: [{
513
+ action: "addLineItem",
514
+ variantId: +item.variantId,
515
+ productId: item.productId,
516
+ quantity: (_item$quantity = item.quantity) != null ? _item$quantity : 1
517
+ }]
518
+ }
519
+ });
520
+ case 3:
521
+ updatedCart = _context.v;
522
+ if (updatedCart.body) {
523
+ setCartId(updatedCart.body.id);
524
+ } else {
525
+ removeCartCookie();
526
+ }
527
+ return _context.a(2, updatedCart.body ? normalizeCart(updatedCart.body, provider.locale) : undefined);
528
+ }
529
+ }, _callee);
530
+ }))();
531
+ },
532
+ useHook: function useHook(_ref2) {
533
+ var fetch = _ref2.fetch;
534
+ return function () {
535
+ var _useCart = useCart(),
536
+ mutate = _useCart.mutate;
537
+ return useCallback(/*#__PURE__*/function () {
538
+ var _addItem = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(input) {
539
+ var data;
540
+ return _regenerator().w(function (_context2) {
541
+ while (1) switch (_context2.n) {
542
+ case 0:
543
+ _context2.n = 1;
544
+ return fetch({
545
+ input: input
546
+ });
547
+ case 1:
548
+ data = _context2.v;
549
+ _context2.n = 2;
550
+ return mutate(data, false);
551
+ case 2:
552
+ return _context2.a(2, data);
553
+ }
554
+ }, _callee2);
555
+ }));
556
+ function addItem(_x) {
557
+ return _addItem.apply(this, arguments);
558
+ }
559
+ return addItem;
560
+ }(), [fetch, mutate]);
561
+ };
562
+ }
563
+ };
564
+
565
+ var handler$2 = {
566
+ fetchOptions: {
567
+ query: "cart",
568
+ method: "post"
569
+ },
570
+ fetcher: function fetcher(_ref) {
571
+ return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
572
+ var itemId, fetch, provider, activeCart, updatedCart;
573
+ return _regenerator().w(function (_context) {
574
+ while (1) switch (_context.n) {
575
+ case 0:
576
+ itemId = _ref.input.itemId, fetch = _ref.fetch, provider = _ref.provider;
577
+ _context.n = 1;
578
+ return getActiveCart(fetch);
579
+ case 1:
580
+ activeCart = _context.v;
581
+ if (!(!itemId || !activeCart)) {
582
+ _context.n = 2;
583
+ break;
584
+ }
585
+ return _context.a(2, undefined);
586
+ case 2:
587
+ _context.n = 3;
588
+ return fetch({
589
+ query: "carts",
590
+ method: "post",
591
+ variables: {
592
+ id: activeCart.id
593
+ },
594
+ body: {
595
+ version: activeCart.version,
596
+ actions: [{
597
+ action: "removeLineItem",
598
+ lineItemId: itemId
599
+ }]
600
+ }
601
+ });
602
+ case 3:
603
+ updatedCart = _context.v;
604
+ if (updatedCart.body) {
605
+ setCartId(updatedCart.body.id);
606
+ } else {
607
+ removeCartCookie();
608
+ }
609
+ return _context.a(2, normalizeCart(updatedCart.body, provider.locale));
610
+ }
611
+ }, _callee);
612
+ }))();
613
+ },
614
+ useHook: function useHook(_ref2) {
615
+ var fetch = _ref2.fetch;
616
+ return function (ctx) {
617
+ if (ctx === void 0) {
618
+ ctx = {};
619
+ }
620
+ var _ctx = ctx,
621
+ item = _ctx.item;
622
+ var _useCart = useCart(),
623
+ mutate = _useCart.mutate;
624
+ var removeItem = /*#__PURE__*/function () {
625
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(input) {
626
+ var _input$id;
627
+ var itemId, data;
628
+ return _regenerator().w(function (_context2) {
629
+ while (1) switch (_context2.n) {
630
+ case 0:
631
+ itemId = (_input$id = input == null ? void 0 : input.id) != null ? _input$id : item == null ? void 0 : item.id;
632
+ if (itemId) {
633
+ _context2.n = 1;
634
+ break;
635
+ }
636
+ throw new ValidationError({
637
+ message: "Invalid input used for this operation"
638
+ });
639
+ case 1:
640
+ _context2.n = 2;
641
+ return fetch({
642
+ input: {
643
+ itemId: itemId
644
+ }
645
+ });
646
+ case 2:
647
+ data = _context2.v;
648
+ _context2.n = 3;
649
+ return mutate(data, false);
650
+ case 3:
651
+ return _context2.a(2, data);
652
+ }
653
+ }, _callee2);
654
+ }));
655
+ return function removeItem(_x) {
656
+ return _ref3.apply(this, arguments);
657
+ };
658
+ }();
659
+ return useCallback(removeItem, [fetch, mutate]);
660
+ };
661
+ }
662
+ };
663
+
664
+ var handler$3 = {
665
+ fetchOptions: {
666
+ query: "cart",
667
+ method: "post"
668
+ },
669
+ fetcher: function fetcher(_ref) {
670
+ return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
671
+ var _item$quantity;
672
+ var _ref$input, item, itemId, fetch, provider, activeCart, updatedCart;
673
+ return _regenerator().w(function (_context) {
674
+ while (1) switch (_context.n) {
675
+ case 0:
676
+ _ref$input = _ref.input, item = _ref$input.item, itemId = _ref$input.itemId, fetch = _ref.fetch, provider = _ref.provider;
677
+ if (!Number.isInteger(item.quantity)) {
678
+ _context.n = 2;
679
+ break;
680
+ }
681
+ if (!(item.quantity < 1)) {
682
+ _context.n = 1;
683
+ break;
684
+ }
685
+ return _context.a(2, handler$2.fetcher == null ? void 0 : handler$2.fetcher({
686
+ options: handler$2.fetchOptions,
687
+ input: {
688
+ itemId: itemId
689
+ },
690
+ fetch: fetch,
691
+ provider: provider
692
+ }));
693
+ case 1:
694
+ _context.n = 3;
695
+ break;
696
+ case 2:
697
+ if (!item.quantity) {
698
+ _context.n = 3;
699
+ break;
700
+ }
701
+ throw new ValidationError({
702
+ message: "The item quantity has to be a valid integer"
703
+ });
704
+ case 3:
705
+ _context.n = 4;
706
+ return getActiveCart(fetch);
707
+ case 4:
708
+ activeCart = _context.v;
709
+ if (!(item.quantity && (!Number.isInteger(item.quantity) || item.quantity < 1) || !activeCart)) {
710
+ _context.n = 5;
711
+ break;
712
+ }
713
+ return _context.a(2, undefined);
714
+ case 5:
715
+ _context.n = 6;
716
+ return fetch({
717
+ query: "carts",
718
+ method: "post",
719
+ variables: {
720
+ id: activeCart.id
721
+ },
722
+ body: {
723
+ version: activeCart.version,
724
+ actions: [{
725
+ action: "changeLineItemQuantity",
726
+ lineItemId: itemId,
727
+ quantity: (_item$quantity = item.quantity) != null ? _item$quantity : 1
728
+ }]
729
+ }
730
+ });
731
+ case 6:
732
+ updatedCart = _context.v;
733
+ if (updatedCart.body) {
734
+ setCartId(updatedCart.body.id);
735
+ } else {
736
+ removeCartCookie();
737
+ }
738
+ return _context.a(2, updatedCart.body ? normalizeCart(updatedCart.body, provider.locale) : undefined);
739
+ }
740
+ }, _callee);
741
+ }))();
742
+ },
743
+ useHook: function useHook(_ref2) {
744
+ var fetch = _ref2.fetch;
745
+ return function (ctx) {
746
+ var _ctx$wait;
747
+ if (ctx === void 0) {
748
+ ctx = {};
749
+ }
750
+ var _ctx = ctx,
751
+ item = _ctx.item;
752
+ var _useCart = useCart(),
753
+ mutate = _useCart.mutate;
754
+ return useCallback(debounce(/*#__PURE__*/function () {
755
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(input) {
756
+ var _input$id;
757
+ var itemId, data;
758
+ return _regenerator().w(function (_context2) {
759
+ while (1) switch (_context2.n) {
760
+ case 0:
761
+ itemId = (_input$id = input.id) != null ? _input$id : item == null ? void 0 : item.id;
762
+ if (!(!itemId || input.quantity == null)) {
763
+ _context2.n = 1;
764
+ break;
765
+ }
766
+ throw new ValidationError({
767
+ message: "Invalid input used for this operation"
768
+ });
769
+ case 1:
770
+ _context2.n = 2;
771
+ return fetch({
772
+ input: {
773
+ item: {
774
+ quantity: input.quantity
775
+ },
776
+ itemId: itemId
777
+ }
778
+ });
779
+ case 2:
780
+ data = _context2.v;
781
+ _context2.n = 3;
782
+ return mutate(data, false);
783
+ case 3:
784
+ return _context2.a(2, data);
785
+ }
786
+ }, _callee2);
787
+ }));
788
+ return function (_x) {
789
+ return _ref3.apply(this, arguments);
790
+ };
791
+ }(), (_ctx$wait = ctx.wait) != null ? _ctx$wait : 500), [fetch, mutate]);
792
+ };
793
+ }
794
+ };
795
+
796
+ var initCommercetoolsSDKClient = function initCommercetoolsSDKClient(creds) {
797
+ var scopes = ["manage_project:" + creds.projectKey];
798
+ // Configure authMiddlewareOptions
799
+ var authMiddlewareOptions = {
800
+ host: "https://auth." + creds.region + ".commercetools.com",
801
+ projectKey: creds.clientSecret,
802
+ credentials: {
803
+ clientId: creds.clientId,
804
+ clientSecret: creds.clientSecret
805
+ },
806
+ scopes: scopes,
807
+ fetch: fetch
808
+ };
809
+ // Configure httpMiddlewareOptions
810
+ var httpMiddlewareOptions = {
811
+ host: "https://api." + creds.region + ".commercetools.com",
812
+ fetch: fetch
813
+ };
814
+ // Export the ClientBuilder
815
+ return new ClientBuilder().withProjectKey(creds.projectKey).withClientCredentialsFlow(authMiddlewareOptions).withHttpMiddleware(httpMiddlewareOptions).build();
816
+ };
817
+
818
+ var getFetcher = function getFetcher(creds) {
819
+ var client = initCommercetoolsSDKClient(creds);
820
+ var apiRoot = createApiBuilderFromCtpClient(client).withProjectKey({
821
+ projectKey: creds.projectKey
822
+ });
823
+ return /*#__PURE__*/function () {
824
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(_ref) {
825
+ var method, variables, query, body, queryBuilder;
826
+ return _regenerator().w(function (_context) {
827
+ while (1) switch (_context.n) {
828
+ case 0:
829
+ method = _ref.method, variables = _ref.variables, query = _ref.query, body = _ref.body;
830
+ queryBuilder = apiRoot;
831
+ if (query) {
832
+ queryBuilder = queryBuilder[query]();
833
+ }
834
+ if (variables != null && variables.id) {
835
+ queryBuilder = queryBuilder.withId({
836
+ ID: variables.id
837
+ });
838
+ }
839
+ if (variables != null && variables.search) {
840
+ queryBuilder = queryBuilder.search();
841
+ }
842
+ _context.n = 1;
843
+ return queryBuilder[method]({
844
+ body: body,
845
+ queryArgs: _extends({
846
+ expand: variables == null ? void 0 : variables.expand,
847
+ limit: variables == null ? void 0 : variables.limit
848
+ }, variables != null && variables.sort ? {
849
+ sort: variables.sort
850
+ } : {}, variables != null && variables.search ? variables.search : {}, variables != null && variables.filters ? {
851
+ filter: variables.filters
852
+ } : {}, variables != null && variables.where ? {
853
+ where: variables.where
854
+ } : {})
855
+ }).execute();
856
+ case 1:
857
+ return _context.a(2, _context.v);
858
+ }
859
+ }, _callee);
860
+ }));
861
+ return function (_x) {
862
+ return _ref2.apply(this, arguments);
863
+ };
864
+ }();
865
+ };
866
+
867
+ var handler$4 = {
868
+ fetchOptions: {
869
+ query: "productProjections",
870
+ method: "get"
871
+ },
872
+ fetcher: function fetcher(_ref) {
873
+ return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
874
+ var input, options, fetch, provider, id, product;
875
+ return _regenerator().w(function (_context) {
876
+ while (1) switch (_context.n) {
877
+ case 0:
878
+ input = _ref.input, options = _ref.options, fetch = _ref.fetch, provider = _ref.provider;
879
+ id = input.id;
880
+ if (id) {
881
+ _context.n = 1;
882
+ break;
883
+ }
884
+ return _context.a(2, null);
885
+ case 1:
886
+ _context.n = 2;
887
+ return fetch(_extends({}, options, {
888
+ variables: {
889
+ id: id
890
+ }
891
+ }));
892
+ case 2:
893
+ product = _context.v;
894
+ return _context.a(2, product.body ? normalizeProduct(product.body, provider.locale) : null);
895
+ }
896
+ }, _callee);
897
+ }))();
898
+ },
899
+ useHook: function useHook(_ref2) {
900
+ var useData = _ref2.useData;
901
+ return function (input) {
902
+ if (input === void 0) {
903
+ input = {};
904
+ }
905
+ return useData({
906
+ input: [['id', input.id]],
907
+ swrOptions: _extends({
908
+ revalidateOnFocus: false
909
+ }, input.swrOptions)
910
+ });
911
+ };
912
+ }
913
+ };
914
+
915
+ var handler$5 = {
916
+ fetchOptions: {
917
+ method: "get",
918
+ query: "productProjections"
919
+ },
920
+ fetcher: function fetcher(_ref) {
921
+ return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
922
+ var _search;
923
+ var input, options, fetch, provider, search, categoryId, sort, count, response;
924
+ return _regenerator().w(function (_context) {
925
+ while (1) switch (_context.n) {
926
+ case 0:
927
+ input = _ref.input, options = _ref.options, fetch = _ref.fetch, provider = _ref.provider;
928
+ search = input.search, categoryId = input.categoryId, sort = input.sort, count = input.count;
929
+ _context.n = 1;
930
+ return fetch(_extends({}, options, {
931
+ variables: _extends({
932
+ expand: ["masterData.current"],
933
+ sort: getSortVariables(sort),
934
+ limit: count
935
+ }, search ?
936
+ // eslint-disable-next-line
937
+ {
938
+ search: (_search = {}, _search["text." + (provider == null ? void 0 : provider.locale)] = search, _search)
939
+ } : {}, categoryId ? {
940
+ filters: "categories.id: subtree(\"" + categoryId + "\")"
941
+ } : {})
942
+ }));
943
+ case 1:
944
+ response = _context.v;
945
+ return _context.a(2, {
946
+ products: response.body.results.map(function (product) {
947
+ return normalizeProduct(product, provider.locale);
948
+ }),
949
+ found: response.body.count > 0
950
+ });
951
+ }
952
+ }, _callee);
953
+ }))();
954
+ },
955
+ useHook: function useHook(_ref2) {
956
+ var useData = _ref2.useData;
957
+ return function (input) {
958
+ if (input === void 0) {
959
+ input = {};
960
+ }
961
+ return useData({
962
+ input: [["search", input.search], ["categoryId", input.categoryId], ["brandId", input.brandId], ["sort", input.sort], ["locale", input.locale], ["count", input.count]],
963
+ swrOptions: _extends({
964
+ revalidateOnFocus: false
965
+ }, input.swrOptions)
966
+ });
967
+ };
968
+ }
969
+ };
970
+
971
+ var handler$6 = {
972
+ fetchOptions: {
973
+ query: ""
974
+ },
975
+ fetcher: function fetcher(_ref) {
976
+ return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
977
+ return _regenerator().w(function (_context) {
978
+ while (1) switch (_context.n) {
979
+ case 0:
980
+ return _context.a(2, null);
981
+ }
982
+ }, _callee);
983
+ }))();
984
+ },
985
+ useHook: function useHook(_ref2) {
986
+ var useData = _ref2.useData;
987
+ return function (input) {
988
+ var response = useData({
989
+ swrOptions: _extends({
990
+ revalidateOnFocus: false
991
+ }, input == null ? void 0 : input.swrOptions)
992
+ });
993
+ return useMemo(function () {
994
+ return Object.create(response, {
995
+ isEmpty: {
996
+ get: function get() {
997
+ var _response$data$length, _response$data;
998
+ return ((_response$data$length = (_response$data = response.data) == null ? void 0 : _response$data.length) != null ? _response$data$length : 0) <= 0;
999
+ },
1000
+ enumerable: true
1001
+ }
1002
+ });
1003
+ }, [response]);
1004
+ };
1005
+ }
1006
+ };
1007
+
1008
+ var handler$7 = {
1009
+ fetchOptions: {
1010
+ query: "categories",
1011
+ method: "get"
1012
+ },
1013
+ fetcher: function fetcher(_ref) {
1014
+ return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
1015
+ var input, options, fetch, provider, categoryId, categories, category;
1016
+ return _regenerator().w(function (_context) {
1017
+ while (1) switch (_context.n) {
1018
+ case 0:
1019
+ input = _ref.input, options = _ref.options, fetch = _ref.fetch, provider = _ref.provider;
1020
+ categoryId = input.categoryId;
1021
+ if (categoryId) {
1022
+ _context.n = 2;
1023
+ break;
1024
+ }
1025
+ _context.n = 1;
1026
+ return fetch(_extends({}, options));
1027
+ case 1:
1028
+ categories = _context.v;
1029
+ return _context.a(2, categories.body ? categories.body.results.map(function (category) {
1030
+ return normalizeCategory(category, provider.locale);
1031
+ }) : []);
1032
+ case 2:
1033
+ _context.n = 3;
1034
+ return fetch(_extends({}, options, {
1035
+ variables: _extends({}, categoryId ? {
1036
+ id: categoryId
1037
+ } : {})
1038
+ }));
1039
+ case 3:
1040
+ category = _context.v;
1041
+ return _context.a(2, category.body ? [normalizeCategory(category.body, provider.locale)] : []);
1042
+ case 4:
1043
+ return _context.a(2);
1044
+ }
1045
+ }, _callee);
1046
+ }))();
1047
+ },
1048
+ useHook: function useHook(_ref2) {
1049
+ var useData = _ref2.useData;
1050
+ return function (input) {
1051
+ var response = useData({
1052
+ input: [["categoryId", input == null ? void 0 : input.categoryId]],
1053
+ swrOptions: _extends({
1054
+ revalidateOnFocus: false
1055
+ }, input == null ? void 0 : input.swrOptions)
1056
+ });
1057
+ return useMemo(function () {
1058
+ return Object.create(response, {
1059
+ isEmpty: {
1060
+ get: function get() {
1061
+ var _response$data$length, _response$data;
1062
+ return ((_response$data$length = (_response$data = response.data) == null ? void 0 : _response$data.length) != null ? _response$data$length : 0) <= 0;
1063
+ },
1064
+ enumerable: true
1065
+ }
1066
+ });
1067
+ }, [response]);
1068
+ };
1069
+ }
1070
+ };
1071
+
1072
+ var getCommercetoolsProvider = function getCommercetoolsProvider(creds, locale) {
1073
+ return {
1074
+ locale: locale,
1075
+ cartCookie: COMMERCETOOLS_CART_COOKIE,
1076
+ cart: {
1077
+ useCart: handler,
1078
+ useAddItem: handler$1,
1079
+ useRemoveItem: handler$2,
1080
+ useUpdateItem: handler$3
1081
+ },
1082
+ fetcher: getFetcher(creds),
1083
+ products: {
1084
+ useSearch: handler$5,
1085
+ useProduct: handler$4
1086
+ },
1087
+ site: {
1088
+ useCategories: handler$7,
1089
+ useBrands: handler$6
1090
+ }
1091
+ };
1092
+ };
1093
+
1094
+ var useCommerce = function useCommerce() {
1095
+ return useCommerce$1();
1096
+ };
1097
+ var getCommerceProvider = function getCommerceProvider(creds, locale) {
1098
+ return getCommerceProvider$1(getCommercetoolsProvider(creds, locale));
1099
+ };
1100
+
1101
+ var globalContextName = "daouy-commerce-commercetools-provider";
1102
+ var commerceProviderMeta = /*#__PURE__*/_extends({
1103
+ name: globalContextName,
1104
+ displayName: "Commercetools Provider",
1105
+ props: {
1106
+ projectKey: {
1107
+ type: "string",
1108
+ defaultValue: "daouy-demo"
1109
+ },
1110
+ clientId: {
1111
+ type: "string",
1112
+ defaultValue: "B4hmK61xvz5LvdSDtsFmcflM"
1113
+ },
1114
+ clientSecret: {
1115
+ type: "string",
1116
+ defaultValue: "KhzjcjSu1Oul4aomSmOsLZOCZKbvfHqx"
1117
+ },
1118
+ region: {
1119
+ type: "choice",
1120
+ options: ["us-central1.gcp", "us-east-2.aws", "europe-west1.gcp", "eu-central-1.aws", "australia-southeast1.gcp"],
1121
+ defaultValue: "us-central1.gcp"
1122
+ }
1123
+ }
1124
+ }, {
1125
+ globalActions: globalActionsRegistrations
1126
+ }, {
1127
+ importPath: "@daouypkgs/commercetools",
1128
+ importName: "CommerceProviderComponent"
1129
+ });
1130
+ function CommerceProviderComponent(props) {
1131
+ var children = props.children,
1132
+ projectKey = props.projectKey,
1133
+ clientId = props.clientId,
1134
+ clientSecret = props.clientSecret,
1135
+ region = props.region;
1136
+ var creds = React.useMemo(function () {
1137
+ return {
1138
+ projectKey: projectKey,
1139
+ clientId: clientId,
1140
+ clientSecret: clientSecret,
1141
+ region: region
1142
+ };
1143
+ }, [projectKey, clientId, clientSecret, region]);
1144
+ var _useDaouyQueryData = useDaouyQueryData(JSON.stringify({
1145
+ creds: creds
1146
+ }) + "locale", /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
1147
+ var fetcher, project;
1148
+ return _regenerator().w(function (_context) {
1149
+ while (1) switch (_context.n) {
1150
+ case 0:
1151
+ fetcher = getFetcher(creds);
1152
+ _context.n = 1;
1153
+ return fetcher({
1154
+ method: "get"
1155
+ });
1156
+ case 1:
1157
+ project = _context.v;
1158
+ return _context.a(2, project.body ? project.body.languages[0] : undefined);
1159
+ }
1160
+ }, _callee);
1161
+ }))),
1162
+ locale = _useDaouyQueryData.data,
1163
+ error = _useDaouyQueryData.error,
1164
+ isLoading = _useDaouyQueryData.isLoading;
1165
+ var CommerceProvider = React.useMemo(function () {
1166
+ return getCommerceProvider(creds, locale != null ? locale : "");
1167
+ }, [creds, locale]);
1168
+ if (isLoading) {
1169
+ return null;
1170
+ } else if (error || !locale) {
1171
+ throw new Error(error ? error.message : "Project language not found");
1172
+ }
1173
+ return React.createElement(CommerceProvider, null, React.createElement(CartActionsProvider, {
1174
+ globalContextName: globalContextName
1175
+ }, children));
1176
+ }
1177
+ function registerCommerceProvider(loader, customCommerceProviderMeta) {
1178
+ var doRegisterComponent = function doRegisterComponent() {
1179
+ return loader ? loader.registerGlobalContext.apply(loader, arguments) : registerGlobalContext.apply(void 0, arguments);
1180
+ };
1181
+ doRegisterComponent(CommerceProviderComponent, customCommerceProviderMeta != null ? customCommerceProviderMeta : commerceProviderMeta);
1182
+ }
1183
+
1184
+ function registerAll(loader) {
1185
+ registerCommerceProvider(loader);
1186
+ }
1187
+
1188
+ export { CommerceProviderComponent, commerceProviderMeta, getCommerceProvider, registerAll, registerCommerceProvider, useCommerce };
1189
+ //# sourceMappingURL=commerce-commercetools.esm.js.map