@labdigital/commercetools-mock 0.6.4 → 0.7.1

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 (118) hide show
  1. package/dist/index.d.ts +385 -3
  2. package/dist/index.global.js +49770 -0
  3. package/dist/index.global.js.map +1 -0
  4. package/dist/index.js +4622 -6
  5. package/dist/index.js.map +1 -0
  6. package/dist/index.mjs +4590 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/package.json +30 -17
  9. package/src/ctMock.ts +5 -0
  10. package/src/helpers.ts +15 -0
  11. package/src/lib/projectionSearchFilter.test.ts +177 -0
  12. package/src/lib/projectionSearchFilter.ts +248 -0
  13. package/src/priceSelector.test.ts +96 -0
  14. package/src/priceSelector.ts +109 -0
  15. package/src/product-projection-search.ts +149 -0
  16. package/src/projectAPI.ts +19 -20
  17. package/src/repositories/category.ts +36 -0
  18. package/src/repositories/channel.ts +104 -0
  19. package/src/repositories/customer-group.ts +37 -0
  20. package/src/repositories/discount-code.ts +37 -0
  21. package/src/repositories/helpers.ts +46 -4
  22. package/src/repositories/product-discount.ts +181 -0
  23. package/src/repositories/product-projection.ts +29 -55
  24. package/src/repositories/product-type.ts +88 -6
  25. package/src/repositories/product.ts +49 -9
  26. package/src/repositories/shipping-method.ts +31 -0
  27. package/src/repositories/store.ts +43 -3
  28. package/src/repositories/type.ts +19 -0
  29. package/src/services/custom-object.test.ts +2 -2
  30. package/src/services/product-discount.ts +33 -0
  31. package/src/services/product-projection.test.ts +171 -116
  32. package/src/services/product.test.ts +12 -0
  33. package/src/storage.ts +116 -58
  34. package/src/types.ts +9 -2
  35. package/dist/commercetools-mock.cjs.development.js +0 -4380
  36. package/dist/commercetools-mock.cjs.development.js.map +0 -1
  37. package/dist/commercetools-mock.cjs.production.min.js +0 -2
  38. package/dist/commercetools-mock.cjs.production.min.js.map +0 -1
  39. package/dist/commercetools-mock.esm.js +0 -4372
  40. package/dist/commercetools-mock.esm.js.map +0 -1
  41. package/dist/constants.d.ts +0 -2
  42. package/dist/ctMock.d.ts +0 -32
  43. package/dist/exceptions.d.ts +0 -12
  44. package/dist/helpers.d.ts +0 -6
  45. package/dist/lib/expandParser.d.ts +0 -15
  46. package/dist/lib/filterParser.d.ts +0 -1
  47. package/dist/lib/haversine.d.ts +0 -8
  48. package/dist/lib/masking.d.ts +0 -1
  49. package/dist/lib/predicateParser.d.ts +0 -11
  50. package/dist/lib/proxy.d.ts +0 -1
  51. package/dist/oauth/errors.d.ts +0 -8
  52. package/dist/oauth/helpers.d.ts +0 -2
  53. package/dist/oauth/server.d.ts +0 -12
  54. package/dist/oauth/store.d.ts +0 -14
  55. package/dist/projectAPI.d.ts +0 -12
  56. package/dist/repositories/abstract.d.ts +0 -33
  57. package/dist/repositories/cart-discount.d.ts +0 -9
  58. package/dist/repositories/cart.d.ts +0 -21
  59. package/dist/repositories/category.d.ts +0 -18
  60. package/dist/repositories/channel.d.ts +0 -6
  61. package/dist/repositories/custom-object.d.ts +0 -8
  62. package/dist/repositories/customer-group.d.ts +0 -11
  63. package/dist/repositories/customer.d.ts +0 -11
  64. package/dist/repositories/discount-code.d.ts +0 -8
  65. package/dist/repositories/errors.d.ts +0 -2
  66. package/dist/repositories/extension.d.ts +0 -8
  67. package/dist/repositories/helpers.d.ts +0 -10
  68. package/dist/repositories/inventory-entry.d.ts +0 -14
  69. package/dist/repositories/my-order.d.ts +0 -6
  70. package/dist/repositories/order.d.ts +0 -26
  71. package/dist/repositories/payment.d.ts +0 -23
  72. package/dist/repositories/product-projection.d.ts +0 -10
  73. package/dist/repositories/product-type.d.ts +0 -10
  74. package/dist/repositories/product.d.ts +0 -11
  75. package/dist/repositories/project.d.ts +0 -8
  76. package/dist/repositories/shipping-method.d.ts +0 -10
  77. package/dist/repositories/shopping-list.d.ts +0 -6
  78. package/dist/repositories/state.d.ts +0 -8
  79. package/dist/repositories/store.d.ts +0 -10
  80. package/dist/repositories/subscription.d.ts +0 -6
  81. package/dist/repositories/tax-category.d.ts +0 -10
  82. package/dist/repositories/type.d.ts +0 -8
  83. package/dist/repositories/zone.d.ts +0 -8
  84. package/dist/server.d.ts +0 -1
  85. package/dist/services/abstract.d.ts +0 -20
  86. package/dist/services/cart-discount.d.ts +0 -9
  87. package/dist/services/cart.d.ts +0 -12
  88. package/dist/services/category.d.ts +0 -9
  89. package/dist/services/channel.d.ts +0 -9
  90. package/dist/services/custom-object.d.ts +0 -13
  91. package/dist/services/customer-group.d.ts +0 -9
  92. package/dist/services/customer.d.ts +0 -10
  93. package/dist/services/discount-code.d.ts +0 -9
  94. package/dist/services/extension.d.ts +0 -9
  95. package/dist/services/inventory-entry.d.ts +0 -9
  96. package/dist/services/my-cart.d.ts +0 -11
  97. package/dist/services/my-customer.d.ts +0 -13
  98. package/dist/services/my-order.d.ts +0 -10
  99. package/dist/services/my-payment.d.ts +0 -9
  100. package/dist/services/order.d.ts +0 -12
  101. package/dist/services/payment.d.ts +0 -9
  102. package/dist/services/product-projection.d.ts +0 -11
  103. package/dist/services/product-type.d.ts +0 -11
  104. package/dist/services/product.d.ts +0 -9
  105. package/dist/services/project.d.ts +0 -11
  106. package/dist/services/shipping-method.d.ts +0 -10
  107. package/dist/services/shopping-list.d.ts +0 -9
  108. package/dist/services/state.d.ts +0 -9
  109. package/dist/services/store.d.ts +0 -11
  110. package/dist/services/subscription.d.ts +0 -9
  111. package/dist/services/tax-category.d.ts +0 -11
  112. package/dist/services/type.d.ts +0 -9
  113. package/dist/services/zone.d.ts +0 -9
  114. package/dist/storage.d.ts +0 -56
  115. package/dist/types.d.ts +0 -89
  116. package/dist/validate.d.ts +0 -7482
  117. package/src/lib/filterParser.test.ts +0 -15
  118. package/src/lib/filterParser.ts +0 -17
package/dist/index.mjs ADDED
@@ -0,0 +1,4590 @@
1
+ // src/ctMock.ts
2
+ import nock from "nock";
3
+ import express2 from "express";
4
+ import supertest from "supertest";
5
+ import morgan from "morgan";
6
+
7
+ // src/storage.ts
8
+ import assert from "assert";
9
+
10
+ // src/lib/expandParser.ts
11
+ var parseExpandClause = (clause) => {
12
+ const result = {
13
+ element: clause,
14
+ index: void 0,
15
+ rest: void 0
16
+ };
17
+ const pos = clause.indexOf(".");
18
+ if (pos > 0) {
19
+ result.element = clause.substring(0, pos);
20
+ result.rest = clause.substring(pos + 1);
21
+ }
22
+ const match = result.element.match(/\[([^\]+])]/);
23
+ if (match) {
24
+ result.index = match[1] === "*" ? "*" : parseInt(match[1], 10);
25
+ result.element = result.element.substring(0, match.index);
26
+ }
27
+ return result;
28
+ };
29
+
30
+ // src/lib/predicateParser.ts
31
+ import perplex from "perplex";
32
+ import { Parser } from "pratt";
33
+
34
+ // src/lib/haversine.ts
35
+ var haversineDistance = (src, dst) => {
36
+ const RADIUS_OF_EARTH_IN_KM = 6371;
37
+ const toRadian = (deg) => deg * (Math.PI / 180);
38
+ const dLat = toRadian(dst.latitude - src.latitude);
39
+ const dLon = toRadian(dst.longitude - src.longitude);
40
+ var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRadian(src.latitude)) * Math.cos(toRadian(dst.latitude)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
41
+ var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
42
+ return RADIUS_OF_EARTH_IN_KM * c * 1e3;
43
+ };
44
+
45
+ // src/lib/predicateParser.ts
46
+ var PredicateError = class {
47
+ constructor(message) {
48
+ this.message = message;
49
+ }
50
+ };
51
+ var parseQueryExpression = (predicate) => {
52
+ if (Array.isArray(predicate)) {
53
+ const callbacks = predicate.map((item) => generateMatchFunc(item));
54
+ return (target, variables) => {
55
+ return callbacks.every((callback) => callback(target, variables));
56
+ };
57
+ } else {
58
+ return generateMatchFunc(predicate);
59
+ }
60
+ };
61
+ var validateSymbol = (val) => {
62
+ var _a, _b;
63
+ if (!val.type) {
64
+ throw new PredicateError("Internal error");
65
+ }
66
+ if (val.type === "identifier") {
67
+ const char = val.value.charAt(0);
68
+ const line = (_a = val.pos) == null ? void 0 : _a.start.line;
69
+ const column = (_b = val.pos) == null ? void 0 : _b.start.column;
70
+ throw new PredicateError(
71
+ `Invalid input '${char}', expected input parameter or primitive value (line ${line}, column ${column})`
72
+ );
73
+ }
74
+ };
75
+ var resolveSymbol = (val, vars) => {
76
+ if (val.type === "var") {
77
+ if (!(val.value in vars)) {
78
+ throw new PredicateError(`Missing parameter value for ${val.value}`);
79
+ }
80
+ return vars[val.value];
81
+ }
82
+ return val.value;
83
+ };
84
+ var resolveValue = (obj, val) => {
85
+ if (val.type !== "identifier") {
86
+ throw new PredicateError("Internal error");
87
+ }
88
+ if (!(val.value in obj)) {
89
+ if (Array.isArray(obj)) {
90
+ return Object.values(obj).filter((v) => val.value in v).map((v) => v[val.value]);
91
+ }
92
+ throw new PredicateError(`The field '${val.value}' does not exist.`);
93
+ }
94
+ return obj[val.value];
95
+ };
96
+ var getLexer = (value) => {
97
+ return new perplex(value).token("AND", /and(?![-_a-z0-9]+)/i).token("OR", /or(?![-_a-z0-9]+)/i).token("NOT", /not(?![-_a-z0-9]+)/i).token("WITHIN", /within(?![-_a-z0-9]+)/i).token("IN", /in(?![-_a-z0-9]+)/i).token("MATCHES_IGNORE_CASE", /matches\s+ignore\s+case(?![-_a-z0-9]+)/i).token("CONTAINS", /contains(?![-_a-z0-9]+)/i).token("ALL", /all(?![-_a-z0-9]+)/i).token("ANY", /any(?![-_a-z0-9]+)/i).token("EMPTY", /empty(?![-_a-z0-9]+)/i).token("IS", /is(?![-_a-z0-9]+)/i).token("DEFINED", /defined(?![-_a-z0-9]+)/i).token("FLOAT", /\d+\.\d+/).token("INT", /\d+/).token("VARIABLE", /:([-_A-Za-z0-9]+)/).token("IDENTIFIER", /[-_A-Za-z0-9]+/).token("STRING", /"((?:\\.|[^"\\])*)"/).token("STRING", /'((?:\\.|[^'\\])*)'/).token("COMMA", ",").token("(", "(").token(")", ")").token(">=", ">=").token("<=", "<=").token(">", ">").token("<", "<").token("!=", "!=").token("=", "=").token('"', '"').token("WS", /\s+/, true);
98
+ };
99
+ var generateMatchFunc = (predicate) => {
100
+ const lexer = getLexer(predicate);
101
+ const parser = new Parser(lexer).builder().nud("IDENTIFIER", 100, (t) => {
102
+ return {
103
+ type: "identifier",
104
+ value: t.token.match,
105
+ pos: t.token.strpos()
106
+ };
107
+ }).nud("VARIABLE", 100, (t) => {
108
+ return {
109
+ type: "var",
110
+ value: t.token.groups[1],
111
+ pos: t.token.strpos()
112
+ };
113
+ }).nud("STRING", 100, (t) => {
114
+ return {
115
+ type: "string",
116
+ value: t.token.groups[1],
117
+ pos: t.token.strpos()
118
+ };
119
+ }).nud("INT", 1, (t) => {
120
+ return {
121
+ type: "int",
122
+ value: parseInt(t.token.match, 10),
123
+ pos: t.token.strpos()
124
+ };
125
+ }).nud("FLOAT", 1, (t) => {
126
+ return {
127
+ type: "float",
128
+ value: parseFloat(t.token.match),
129
+ pos: t.token.strpos()
130
+ };
131
+ }).nud("NOT", 100, ({ bp }) => {
132
+ const expr = parser.parse({ terminals: [bp - 1] });
133
+ return (obj) => {
134
+ return !expr(obj);
135
+ };
136
+ }).nud("EMPTY", 10, ({ bp }) => {
137
+ return "empty";
138
+ }).nud("DEFINED", 10, ({ bp }) => {
139
+ return "defined";
140
+ }).led("AND", 5, ({ left, bp }) => {
141
+ const expr = parser.parse({ terminals: [bp - 1] });
142
+ return (obj) => {
143
+ return left(obj) && expr(obj);
144
+ };
145
+ }).led("OR", 5, ({ left, token, bp }) => {
146
+ const expr = parser.parse({ terminals: [bp - 1] });
147
+ return (obj, vars) => {
148
+ return left(obj, vars) || expr(obj, vars);
149
+ };
150
+ }).led("COMMA", 1, ({ left, token, bp }) => {
151
+ const expr = parser.parse({ terminals: [bp - 1] });
152
+ if (Array.isArray(expr)) {
153
+ return [left, ...expr];
154
+ } else {
155
+ return [left, expr];
156
+ }
157
+ }).nud("(", 100, (t) => {
158
+ const expr = parser.parse({ terminals: [")"] });
159
+ return expr;
160
+ }).led("(", 100, ({ left, bp }) => {
161
+ const expr = parser.parse();
162
+ lexer.expect(")");
163
+ return (obj, vars) => {
164
+ const value = resolveValue(obj, left);
165
+ if (value) {
166
+ return expr(value);
167
+ }
168
+ return false;
169
+ };
170
+ }).bp(")", 0).led("=", 20, ({ left, bp }) => {
171
+ const expr = parser.parse({ terminals: [bp - 1] });
172
+ validateSymbol(expr);
173
+ return (obj, vars) => {
174
+ const resolvedValue = resolveValue(obj, left);
175
+ const resolvedSymbol = resolveSymbol(expr, vars);
176
+ if (Array.isArray(resolvedValue)) {
177
+ return !!resolvedValue.some((elem) => elem === resolvedSymbol);
178
+ }
179
+ return resolvedValue === resolvedSymbol;
180
+ };
181
+ }).led("!=", 20, ({ left, bp }) => {
182
+ const expr = parser.parse({ terminals: [bp - 1] });
183
+ validateSymbol(expr);
184
+ return (obj, vars) => {
185
+ return resolveValue(obj, left) !== resolveSymbol(expr, vars);
186
+ };
187
+ }).led(">", 20, ({ left, bp }) => {
188
+ const expr = parser.parse({ terminals: [bp - 1] });
189
+ validateSymbol(expr);
190
+ return (obj, vars) => {
191
+ return resolveValue(obj, left) > resolveSymbol(expr, vars);
192
+ };
193
+ }).led(">=", 20, ({ left, bp }) => {
194
+ const expr = parser.parse({ terminals: [bp - 1] });
195
+ validateSymbol(expr);
196
+ return (obj, vars) => {
197
+ return resolveValue(obj, left) >= resolveSymbol(expr, vars);
198
+ };
199
+ }).led("<", 20, ({ left, bp }) => {
200
+ const expr = parser.parse({ terminals: [bp - 1] });
201
+ validateSymbol(expr);
202
+ return (obj, vars) => {
203
+ return resolveValue(obj, left) < resolveSymbol(expr, vars);
204
+ };
205
+ }).led("<=", 20, ({ left, bp }) => {
206
+ const expr = parser.parse({ terminals: [bp - 1] });
207
+ validateSymbol(expr);
208
+ return (obj, vars) => {
209
+ return resolveValue(obj, left) <= resolveSymbol(expr, vars);
210
+ };
211
+ }).led("IS", 20, ({ left, bp }) => {
212
+ let invert = false;
213
+ const next = lexer.peek();
214
+ if (next.type === "NOT") {
215
+ invert = true;
216
+ lexer.next();
217
+ }
218
+ const expr = parser.parse({ terminals: [bp - 1] });
219
+ switch (expr) {
220
+ case "empty": {
221
+ if (!invert) {
222
+ return (obj, vars) => {
223
+ const val = resolveValue(obj, left);
224
+ return val.length === 0;
225
+ };
226
+ } else {
227
+ return (obj, vars) => {
228
+ const val = resolveValue(obj, left);
229
+ return val.length !== 0;
230
+ };
231
+ }
232
+ }
233
+ case "defined": {
234
+ if (!invert) {
235
+ return (obj, vars) => {
236
+ const val = resolveValue(obj, left);
237
+ return val !== void 0;
238
+ };
239
+ } else {
240
+ return (obj, vars) => {
241
+ const val = resolveValue(obj, left);
242
+ return val === void 0;
243
+ };
244
+ }
245
+ }
246
+ default: {
247
+ throw new Error("Unexpected");
248
+ }
249
+ }
250
+ }).led("IN", 20, ({ left, bp }) => {
251
+ const expr = parser.parse({ terminals: [bp - 1] });
252
+ return (obj, vars) => {
253
+ let symbols = expr;
254
+ if (!Array.isArray(symbols)) {
255
+ symbols = [expr];
256
+ }
257
+ const inValues = symbols.map(
258
+ (item) => resolveSymbol(item, vars)
259
+ );
260
+ return inValues.includes(resolveValue(obj, left));
261
+ };
262
+ }).led("MATCHES_IGNORE_CASE", 20, ({ left, bp }) => {
263
+ const expr = parser.parse({ terminals: [bp - 1] });
264
+ validateSymbol(expr);
265
+ return (obj, vars) => {
266
+ const value = resolveValue(obj, left);
267
+ const other = resolveSymbol(expr, vars);
268
+ if (typeof value != "string") {
269
+ throw new PredicateError(
270
+ `The field '${left.value}' does not support this expression.`
271
+ );
272
+ }
273
+ return value.toLowerCase() === other.toLowerCase();
274
+ };
275
+ }).led("WITHIN", 20, ({ left, bp }) => {
276
+ const type = lexer.next();
277
+ if (type.match !== "circle") {
278
+ throw new PredicateError(
279
+ `Invalid input '${type.match}', expected circle`
280
+ );
281
+ }
282
+ lexer.expect("(");
283
+ const expr = parser.parse({ terminals: [")"] });
284
+ return (obj, vars) => {
285
+ const value = resolveValue(obj, left);
286
+ if (!value)
287
+ return false;
288
+ const maxDistance = resolveSymbol(expr[2], vars);
289
+ const distance = haversineDistance(
290
+ {
291
+ longitude: value[0],
292
+ latitude: value[1]
293
+ },
294
+ {
295
+ longitude: resolveSymbol(expr[0], vars),
296
+ latitude: resolveSymbol(expr[1], vars)
297
+ }
298
+ );
299
+ return distance <= maxDistance;
300
+ };
301
+ }).led("CONTAINS", 20, ({ left, bp }) => {
302
+ const keyword = lexer.next();
303
+ let expr = parser.parse();
304
+ if (!Array.isArray(expr)) {
305
+ expr = [expr];
306
+ }
307
+ return (obj, vars) => {
308
+ const value = resolveValue(obj, left);
309
+ if (!Array.isArray(value)) {
310
+ throw new PredicateError(
311
+ `The field '${left.value}' does not support this expression.`
312
+ );
313
+ }
314
+ const array = expr.map((item) => resolveSymbol(item, vars));
315
+ if (keyword.type === "ALL") {
316
+ return array.every((item) => value.includes(item));
317
+ } else {
318
+ return array.some((item) => value.includes(item));
319
+ }
320
+ };
321
+ }).build();
322
+ const result = parser.parse();
323
+ if (typeof result !== "function") {
324
+ const lines = predicate.split("\n");
325
+ const column = lines[lines.length - 1].length;
326
+ throw new PredicateError(
327
+ `Unexpected end of input, expected SphereIdentifierChar, comparison operator, not, in, contains, is, within or matches (line ${lines.length}, column ${column})`
328
+ );
329
+ }
330
+ return result;
331
+ };
332
+
333
+ // src/exceptions.ts
334
+ var CommercetoolsError = class extends Error {
335
+ constructor(info, statusCode = 400) {
336
+ super(info.message);
337
+ this.info = info;
338
+ this.statusCode = statusCode || 500;
339
+ }
340
+ };
341
+
342
+ // src/storage.ts
343
+ var AbstractStorage = class {
344
+ };
345
+ var InMemoryStorage = class extends AbstractStorage {
346
+ constructor() {
347
+ super(...arguments);
348
+ this.resources = {};
349
+ this.projects = {};
350
+ this.addProject = (projectKey) => {
351
+ if (!this.projects[projectKey]) {
352
+ this.projects[projectKey] = {
353
+ key: projectKey,
354
+ name: "",
355
+ countries: [],
356
+ currencies: [],
357
+ languages: [],
358
+ createdAt: "2018-10-04T11:32:12.603Z",
359
+ trialUntil: "2018-12",
360
+ carts: {
361
+ countryTaxRateFallbackEnabled: false,
362
+ deleteDaysAfterLastModification: 90
363
+ },
364
+ messages: { enabled: false, deleteDaysAfterCreation: 15 },
365
+ shippingRateInputType: void 0,
366
+ externalOAuth: void 0,
367
+ searchIndexing: {
368
+ products: {
369
+ status: "Deactivated"
370
+ },
371
+ orders: {
372
+ status: "Deactivated"
373
+ }
374
+ },
375
+ version: 1
376
+ };
377
+ }
378
+ return this.projects[projectKey];
379
+ };
380
+ this.saveProject = (project) => {
381
+ this.projects[project.key] = project;
382
+ return project;
383
+ };
384
+ this.getProject = (projectKey) => {
385
+ return this.addProject(projectKey);
386
+ };
387
+ this.expand = (projectKey, obj, clause) => {
388
+ if (!clause)
389
+ return obj;
390
+ const newObj = JSON.parse(JSON.stringify(obj));
391
+ if (Array.isArray(clause)) {
392
+ clause.forEach((c) => {
393
+ this._resolveResource(projectKey, newObj, c);
394
+ });
395
+ } else {
396
+ this._resolveResource(projectKey, newObj, clause);
397
+ }
398
+ return newObj;
399
+ };
400
+ this._resolveResource = (projectKey, obj, expand) => {
401
+ const params = parseExpandClause(expand);
402
+ if (!params.index) {
403
+ const reference = obj[params.element];
404
+ if (reference === void 0) {
405
+ return;
406
+ }
407
+ this._resolveReference(projectKey, reference, params.rest);
408
+ } else if (params.index === "*") {
409
+ const reference = obj[params.element];
410
+ if (reference === void 0 || !Array.isArray(reference))
411
+ return;
412
+ reference.forEach((itemRef) => {
413
+ this._resolveReference(projectKey, itemRef, params.rest);
414
+ });
415
+ } else {
416
+ const reference = obj[params.element][params.index];
417
+ if (reference === void 0)
418
+ return;
419
+ this._resolveReference(projectKey, reference, params.rest);
420
+ }
421
+ };
422
+ }
423
+ forProjectKey(projectKey) {
424
+ this.addProject(projectKey);
425
+ let projectStorage = this.resources[projectKey];
426
+ if (!projectStorage) {
427
+ projectStorage = this.resources[projectKey] = {
428
+ cart: /* @__PURE__ */ new Map(),
429
+ "cart-discount": /* @__PURE__ */ new Map(),
430
+ category: /* @__PURE__ */ new Map(),
431
+ channel: /* @__PURE__ */ new Map(),
432
+ customer: /* @__PURE__ */ new Map(),
433
+ "customer-group": /* @__PURE__ */ new Map(),
434
+ "discount-code": /* @__PURE__ */ new Map(),
435
+ extension: /* @__PURE__ */ new Map(),
436
+ "inventory-entry": /* @__PURE__ */ new Map(),
437
+ "key-value-document": /* @__PURE__ */ new Map(),
438
+ order: /* @__PURE__ */ new Map(),
439
+ "order-edit": /* @__PURE__ */ new Map(),
440
+ payment: /* @__PURE__ */ new Map(),
441
+ product: /* @__PURE__ */ new Map(),
442
+ "product-discount": /* @__PURE__ */ new Map(),
443
+ "product-price": /* @__PURE__ */ new Map(),
444
+ "product-selection": /* @__PURE__ */ new Map(),
445
+ "product-type": /* @__PURE__ */ new Map(),
446
+ "product-projection": /* @__PURE__ */ new Map(),
447
+ review: /* @__PURE__ */ new Map(),
448
+ "shipping-method": /* @__PURE__ */ new Map(),
449
+ state: /* @__PURE__ */ new Map(),
450
+ store: /* @__PURE__ */ new Map(),
451
+ "shopping-list": /* @__PURE__ */ new Map(),
452
+ "standalone-price": /* @__PURE__ */ new Map(),
453
+ subscription: /* @__PURE__ */ new Map(),
454
+ "tax-category": /* @__PURE__ */ new Map(),
455
+ type: /* @__PURE__ */ new Map(),
456
+ zone: /* @__PURE__ */ new Map()
457
+ };
458
+ }
459
+ return projectStorage;
460
+ }
461
+ clear() {
462
+ for (const [, projectStorage] of Object.entries(this.resources)) {
463
+ for (const [, value] of Object.entries(projectStorage)) {
464
+ value == null ? void 0 : value.clear();
465
+ }
466
+ }
467
+ }
468
+ assertStorage(typeId) {
469
+ }
470
+ all(projectKey, typeId) {
471
+ const store = this.forProjectKey(projectKey)[typeId];
472
+ if (store) {
473
+ return Array.from(store.values());
474
+ }
475
+ return [];
476
+ }
477
+ add(projectKey, typeId, obj, params = {}) {
478
+ var _a;
479
+ const store = this.forProjectKey(projectKey);
480
+ (_a = store[typeId]) == null ? void 0 : _a.set(obj.id, obj);
481
+ const resource = this.get(projectKey, typeId, obj.id, params);
482
+ assert(resource, `resource of type ${typeId} with id ${obj.id} not created`);
483
+ return resource;
484
+ }
485
+ get(projectKey, typeId, id, params = {}) {
486
+ var _a;
487
+ const resource = (_a = this.forProjectKey(projectKey)[typeId]) == null ? void 0 : _a.get(id);
488
+ if (resource) {
489
+ return this.expand(projectKey, resource, params.expand);
490
+ }
491
+ return null;
492
+ }
493
+ getByKey(projectKey, typeId, key, params = {}) {
494
+ const store = this.forProjectKey(projectKey);
495
+ const resourceStore = store[typeId];
496
+ if (!store) {
497
+ throw new Error("No type");
498
+ }
499
+ const resources = Array.from(resourceStore.values());
500
+ const resource = resources.find((e) => e.key === key);
501
+ if (resource) {
502
+ return this.expand(projectKey, resource, params.expand);
503
+ }
504
+ return null;
505
+ }
506
+ delete(projectKey, typeId, id, params = {}) {
507
+ var _a;
508
+ const resource = this.get(projectKey, typeId, id);
509
+ if (resource) {
510
+ (_a = this.forProjectKey(projectKey)[typeId]) == null ? void 0 : _a.delete(id);
511
+ return this.expand(projectKey, resource, params.expand);
512
+ }
513
+ return resource;
514
+ }
515
+ query(projectKey, typeId, params) {
516
+ const store = this.forProjectKey(projectKey)[typeId];
517
+ if (!store) {
518
+ throw new Error("No type");
519
+ }
520
+ let resources = Array.from(store.values());
521
+ if (params.where) {
522
+ try {
523
+ const filterFunc = parseQueryExpression(params.where);
524
+ resources = resources.filter((resource) => filterFunc(resource, {}));
525
+ } catch (err) {
526
+ throw new CommercetoolsError(
527
+ {
528
+ code: "InvalidInput",
529
+ message: err.message
530
+ },
531
+ 400
532
+ );
533
+ }
534
+ }
535
+ const totalResources = resources.length;
536
+ const offset = params.offset || 0;
537
+ const limit = params.limit || 20;
538
+ resources = resources.slice(offset, offset + limit);
539
+ if (params.expand !== void 0) {
540
+ resources = resources.map((resource) => {
541
+ return this.expand(projectKey, resource, params.expand);
542
+ });
543
+ }
544
+ return {
545
+ count: totalResources,
546
+ total: resources.length,
547
+ offset,
548
+ limit,
549
+ results: resources
550
+ };
551
+ }
552
+ search(projectKey, typeId, params) {
553
+ const store = this.forProjectKey(projectKey)[typeId];
554
+ if (!store) {
555
+ throw new Error("No type");
556
+ }
557
+ let resources = Array.from(store.values());
558
+ if (params.where) {
559
+ try {
560
+ const filterFunc = parseQueryExpression(params.where);
561
+ resources = resources.filter((resource) => filterFunc(resource, {}));
562
+ } catch (err) {
563
+ throw new CommercetoolsError(
564
+ {
565
+ code: "InvalidInput",
566
+ message: err.message
567
+ },
568
+ 400
569
+ );
570
+ }
571
+ }
572
+ const totalResources = resources.length;
573
+ const offset = params.offset || 0;
574
+ const limit = params.limit || 20;
575
+ resources = resources.slice(offset, offset + limit);
576
+ if (params.expand !== void 0) {
577
+ resources = resources.map((resource) => {
578
+ return this.expand(projectKey, resource, params.expand);
579
+ });
580
+ }
581
+ return {
582
+ count: totalResources,
583
+ total: resources.length,
584
+ offset,
585
+ limit,
586
+ results: resources
587
+ };
588
+ }
589
+ getByResourceIdentifier(projectKey, identifier) {
590
+ if (identifier.id) {
591
+ const resource = this.get(projectKey, identifier.typeId, identifier.id);
592
+ if (resource) {
593
+ return resource;
594
+ }
595
+ console.error(
596
+ `No resource found with typeId=${identifier.typeId}, id=${identifier.id}`
597
+ );
598
+ return void 0;
599
+ }
600
+ if (identifier.key) {
601
+ const store = this.forProjectKey(projectKey)[identifier.typeId];
602
+ if (store) {
603
+ const resource = Array.from(store.values()).find(
604
+ (r) => r.key === identifier.key
605
+ );
606
+ if (resource) {
607
+ return resource;
608
+ }
609
+ } else {
610
+ throw new Error(
611
+ `No storage found for resource type: ${identifier.typeId}`
612
+ );
613
+ }
614
+ }
615
+ return void 0;
616
+ }
617
+ _resolveReference(projectKey, reference, expand) {
618
+ if (reference === void 0)
619
+ return;
620
+ if (reference.typeId !== void 0 && (reference.id !== void 0 || reference.key !== void 0)) {
621
+ reference.obj = this.getByResourceIdentifier(projectKey, {
622
+ typeId: reference.typeId,
623
+ id: reference.id,
624
+ key: reference.key
625
+ });
626
+ if (expand) {
627
+ this._resolveResource(projectKey, reference.obj, expand);
628
+ }
629
+ } else {
630
+ if (expand) {
631
+ this._resolveResource(projectKey, reference, expand);
632
+ }
633
+ }
634
+ }
635
+ };
636
+
637
+ // src/oauth/server.ts
638
+ import auth from "basic-auth";
639
+ import bodyParser from "body-parser";
640
+ import express from "express";
641
+
642
+ // src/oauth/store.ts
643
+ import { randomBytes } from "crypto";
644
+ var OAuth2Store = class {
645
+ constructor(validate = true) {
646
+ this.tokens = [];
647
+ this.validate = true;
648
+ this.validate = validate;
649
+ }
650
+ getClientToken(clientId, clientSecret, scope) {
651
+ const token = {
652
+ access_token: randomBytes(16).toString("base64"),
653
+ token_type: "Bearer",
654
+ expires_in: 172800,
655
+ scope: scope || "todo"
656
+ };
657
+ this.tokens.push(token);
658
+ return token;
659
+ }
660
+ validateToken(token) {
661
+ if (!this.validate)
662
+ return true;
663
+ const foundToken = this.tokens.find((t) => t.access_token === token);
664
+ if (foundToken) {
665
+ return true;
666
+ }
667
+ return false;
668
+ }
669
+ };
670
+
671
+ // src/oauth/helpers.ts
672
+ var getBearerToken = (request) => {
673
+ var _a;
674
+ const authHeader = request.header("Authorization");
675
+ const match = authHeader == null ? void 0 : authHeader.match(/^Bearer\s(?<token>[^\s]+)$/);
676
+ if (match) {
677
+ return (_a = match.groups) == null ? void 0 : _a.token;
678
+ }
679
+ return void 0;
680
+ };
681
+
682
+ // src/oauth/server.ts
683
+ var OAuth2Server = class {
684
+ constructor(options) {
685
+ this.store = new OAuth2Store(options.validate);
686
+ }
687
+ createRouter() {
688
+ const router = express.Router();
689
+ router.use(bodyParser.urlencoded({ extended: true }));
690
+ router.post("/token", this.tokenHandler.bind(this));
691
+ return router;
692
+ }
693
+ createMiddleware() {
694
+ return async (request, response, next) => {
695
+ const token = getBearerToken(request);
696
+ if (!token) {
697
+ next(
698
+ new CommercetoolsError(
699
+ {
700
+ code: "access_denied",
701
+ message: "This endpoint requires an access token. You can get one from the authorization server."
702
+ },
703
+ 401
704
+ )
705
+ );
706
+ }
707
+ if (!token || !this.store.validateToken(token)) {
708
+ next(
709
+ new CommercetoolsError(
710
+ {
711
+ code: "invalid_token",
712
+ message: "invalid_token"
713
+ },
714
+ 401
715
+ )
716
+ );
717
+ }
718
+ next();
719
+ };
720
+ }
721
+ async tokenHandler(request, response, next) {
722
+ var _a;
723
+ const authHeader = request.header("Authorization");
724
+ if (!authHeader) {
725
+ return next(
726
+ new CommercetoolsError(
727
+ {
728
+ code: "invalid_client",
729
+ message: "Please provide valid client credentials using HTTP Basic Authentication."
730
+ },
731
+ 401
732
+ )
733
+ );
734
+ }
735
+ const credentials = auth.parse(authHeader);
736
+ if (!credentials) {
737
+ return next(
738
+ new CommercetoolsError(
739
+ {
740
+ code: "invalid_client",
741
+ message: "Please provide valid client credentials using HTTP Basic Authentication."
742
+ },
743
+ 400
744
+ )
745
+ );
746
+ }
747
+ const grantType = request.query.grant_type || request.body.grant_type;
748
+ if (!grantType) {
749
+ return next(
750
+ new CommercetoolsError(
751
+ {
752
+ code: "invalid_request",
753
+ message: "Missing required parameter: grant_type."
754
+ },
755
+ 400
756
+ )
757
+ );
758
+ }
759
+ if (grantType === "client_credentials") {
760
+ const token = this.store.getClientToken(
761
+ credentials.name,
762
+ credentials.pass,
763
+ (_a = request.query.scope) == null ? void 0 : _a.toString()
764
+ );
765
+ return response.status(200).send(token);
766
+ } else {
767
+ return next(
768
+ new CommercetoolsError(
769
+ {
770
+ code: "unsupported_grant_type",
771
+ message: `Invalid parameter: grant_type: Invalid grant type: ${grantType}`
772
+ },
773
+ 400
774
+ )
775
+ );
776
+ }
777
+ }
778
+ };
779
+
780
+ // src/helpers.ts
781
+ import { v4 as uuidv4 } from "uuid";
782
+ var getBaseResourceProperties = () => {
783
+ return {
784
+ id: uuidv4(),
785
+ createdAt: new Date().toISOString(),
786
+ lastModifiedAt: new Date().toISOString(),
787
+ version: 0
788
+ };
789
+ };
790
+ var QueryParamsAsArray = (input) => {
791
+ if (input == void 0) {
792
+ return [];
793
+ }
794
+ if (Array.isArray(input)) {
795
+ return input;
796
+ }
797
+ return [input];
798
+ };
799
+
800
+ // src/projectAPI.ts
801
+ var ProjectAPI = class {
802
+ constructor(projectKey, services, storage) {
803
+ this.projectKey = projectKey;
804
+ this._storage = storage;
805
+ this._services = services;
806
+ }
807
+ add(typeId, resource) {
808
+ const service = this._services[typeId];
809
+ if (service) {
810
+ this._storage.add(this.projectKey, typeId, {
811
+ ...getBaseResourceProperties(),
812
+ ...resource
813
+ });
814
+ } else {
815
+ throw new Error(`Service for ${typeId} not implemented yet`);
816
+ }
817
+ }
818
+ get(typeId, id, params) {
819
+ return this._storage.get(
820
+ this.projectKey,
821
+ typeId,
822
+ id,
823
+ params
824
+ );
825
+ }
826
+ getRepository(typeId) {
827
+ const service = this._services[typeId];
828
+ if (service !== void 0) {
829
+ return service.repository;
830
+ }
831
+ throw new Error("No such repository");
832
+ }
833
+ };
834
+
835
+ // src/lib/proxy.ts
836
+ var copyHeaders = (headers) => {
837
+ const validHeaders = ["accept", "host", "authorization"];
838
+ const result = {};
839
+ Object.entries(headers).forEach(([key, value]) => {
840
+ if (validHeaders.includes(key.toLowerCase())) {
841
+ result[key] = value;
842
+ }
843
+ });
844
+ return result;
845
+ };
846
+
847
+ // src/constants.ts
848
+ var DEFAULT_API_HOSTNAME = /^https:\/\/api\..*?\.commercetools.com:443$/;
849
+ var DEFAULT_AUTH_HOSTNAME = /^https:\/\/auth\..*?\.commercetools.com:443$/;
850
+
851
+ // src/services/abstract.ts
852
+ import { Router } from "express";
853
+
854
+ // src/repositories/helpers.ts
855
+ import { v4 as uuidv42 } from "uuid";
856
+ var createAddress = (base, projectKey, storage) => {
857
+ if (!base)
858
+ return void 0;
859
+ if (!(base == null ? void 0 : base.country)) {
860
+ throw new Error("Country is required");
861
+ }
862
+ return {
863
+ ...base
864
+ };
865
+ };
866
+ var createCustomFields = (draft, projectKey, storage) => {
867
+ if (!draft)
868
+ return void 0;
869
+ if (!draft.type)
870
+ return void 0;
871
+ if (!draft.type.typeId)
872
+ return void 0;
873
+ if (!draft.fields)
874
+ return void 0;
875
+ const typeResource = storage.getByResourceIdentifier(
876
+ projectKey,
877
+ draft.type
878
+ );
879
+ if (!typeResource) {
880
+ throw new Error(
881
+ `No type '${draft.type.typeId}' with id=${draft.type.id} or key=${draft.type.key}`
882
+ );
883
+ }
884
+ return {
885
+ type: {
886
+ typeId: draft.type.typeId,
887
+ id: typeResource.id
888
+ },
889
+ fields: draft.fields
890
+ };
891
+ };
892
+ var createPrice = (draft) => {
893
+ return {
894
+ id: uuidv42(),
895
+ value: createTypedMoney(draft.value)
896
+ };
897
+ };
898
+ var createTypedMoney = (value) => {
899
+ return {
900
+ type: "centPrecision",
901
+ fractionDigits: 2,
902
+ ...value
903
+ };
904
+ };
905
+ var resolveStoreReference = (ref, projectKey, storage) => {
906
+ if (!ref)
907
+ return void 0;
908
+ const resource = storage.getByResourceIdentifier(projectKey, ref);
909
+ if (!resource) {
910
+ throw new Error("No such store");
911
+ }
912
+ const store = resource;
913
+ return {
914
+ typeId: "store",
915
+ key: store.key
916
+ };
917
+ };
918
+ var getReferenceFromResourceIdentifier = (resourceIdentifier, projectKey, storage) => {
919
+ if (!resourceIdentifier.id && !resourceIdentifier.key) {
920
+ throw new CommercetoolsError(
921
+ {
922
+ code: "InvalidJsonInput",
923
+ message: `${resourceIdentifier.typeId}: ResourceIdentifier requires an 'id' xor a 'key'`
924
+ },
925
+ 400
926
+ );
927
+ }
928
+ const resource = storage.getByResourceIdentifier(
929
+ projectKey,
930
+ resourceIdentifier
931
+ );
932
+ if (!resource) {
933
+ const errIdentifier = resourceIdentifier.key ? `key '${resourceIdentifier.key}'` : `identifier '${resourceIdentifier.key}'`;
934
+ throw new CommercetoolsError(
935
+ {
936
+ code: "ReferencedResourceNotFound",
937
+ typeId: resourceIdentifier.typeId,
938
+ message: `The referenced object of type '${resourceIdentifier.typeId}' with '${errIdentifier}' was not found. It either doesn't exist, or it can't be accessed from this endpoint (e.g., if the endpoint filters by store or customer account).`
939
+ },
940
+ 400
941
+ );
942
+ }
943
+ return {
944
+ typeId: resourceIdentifier.typeId,
945
+ id: resource == null ? void 0 : resource.id
946
+ };
947
+ };
948
+ var getRepositoryContext = (request) => {
949
+ return {
950
+ projectKey: request.params.projectKey,
951
+ storeKey: request.params.storeKey
952
+ };
953
+ };
954
+
955
+ // src/services/abstract.ts
956
+ var AbstractService = class {
957
+ constructor(parent) {
958
+ this.createStatusCode = 201;
959
+ this.registerRoutes(parent);
960
+ }
961
+ extraRoutes(router) {
962
+ }
963
+ registerRoutes(parent) {
964
+ const basePath = this.getBasePath();
965
+ const router = Router({ mergeParams: true });
966
+ this.extraRoutes(router);
967
+ router.get("/", this.get.bind(this));
968
+ router.get("/key=:key", this.getWithKey.bind(this));
969
+ router.get("/:id", this.getWithId.bind(this));
970
+ router.delete("/key=:key", this.deletewithKey.bind(this));
971
+ router.delete("/:id", this.deletewithId.bind(this));
972
+ router.post("/", this.post.bind(this));
973
+ router.post("/key=:key", this.postWithKey.bind(this));
974
+ router.post("/:id", this.postWithId.bind(this));
975
+ parent.use(`/${basePath}`, router);
976
+ }
977
+ get(request, response) {
978
+ const limit = this._parseParam(request.query.limit);
979
+ const offset = this._parseParam(request.query.offset);
980
+ const result = this.repository.query(getRepositoryContext(request), {
981
+ expand: this._parseParam(request.query.expand),
982
+ where: this._parseParam(request.query.where),
983
+ limit: limit !== void 0 ? Number(limit) : void 0,
984
+ offset: offset !== void 0 ? Number(offset) : void 0
985
+ });
986
+ return response.status(200).send(result);
987
+ }
988
+ getWithId(request, response) {
989
+ const result = this._expandWithId(request, request.params["id"]);
990
+ if (!result) {
991
+ return response.status(404).send();
992
+ }
993
+ return response.status(200).send(result);
994
+ }
995
+ getWithKey(request, response) {
996
+ const result = this.repository.getByKey(
997
+ getRepositoryContext(request),
998
+ request.params["key"],
999
+ { expand: this._parseParam(request.query.expand) }
1000
+ );
1001
+ if (!result)
1002
+ return response.status(404).send();
1003
+ return response.status(200).send(result);
1004
+ }
1005
+ deletewithId(request, response) {
1006
+ const result = this.repository.delete(
1007
+ getRepositoryContext(request),
1008
+ request.params["id"],
1009
+ {
1010
+ expand: this._parseParam(request.query.expand)
1011
+ }
1012
+ );
1013
+ if (!result) {
1014
+ return response.status(404).send("Not found");
1015
+ }
1016
+ return response.status(200).send(result);
1017
+ }
1018
+ deletewithKey(request, response) {
1019
+ return response.status(500).send("Not implemented");
1020
+ }
1021
+ post(request, response) {
1022
+ const draft = request.body;
1023
+ const resource = this.repository.create(
1024
+ getRepositoryContext(request),
1025
+ draft
1026
+ );
1027
+ const result = this._expandWithId(request, resource.id);
1028
+ return response.status(this.createStatusCode).send(result);
1029
+ }
1030
+ postWithId(request, response) {
1031
+ const updateRequest = request.body;
1032
+ const resource = this.repository.get(
1033
+ getRepositoryContext(request),
1034
+ request.params["id"]
1035
+ );
1036
+ if (!resource) {
1037
+ return response.status(404).send("Not found");
1038
+ }
1039
+ if (resource.version !== updateRequest.version) {
1040
+ return response.status(409).send("Concurrent modification");
1041
+ }
1042
+ const updatedResource = this.repository.processUpdateActions(
1043
+ getRepositoryContext(request),
1044
+ resource,
1045
+ updateRequest.actions
1046
+ );
1047
+ const result = this._expandWithId(request, updatedResource.id);
1048
+ return response.status(200).send(result);
1049
+ }
1050
+ postWithKey(request, response) {
1051
+ return response.status(500).send("Not implemented");
1052
+ }
1053
+ _expandWithId(request, resourceId) {
1054
+ const result = this.repository.get(
1055
+ getRepositoryContext(request),
1056
+ resourceId,
1057
+ {
1058
+ expand: this._parseParam(request.query.expand)
1059
+ }
1060
+ );
1061
+ return result;
1062
+ }
1063
+ _parseParam(value) {
1064
+ if (Array.isArray(value)) {
1065
+ return value;
1066
+ } else if (value !== void 0) {
1067
+ return [`${value}`];
1068
+ }
1069
+ return void 0;
1070
+ }
1071
+ };
1072
+
1073
+ // src/repositories/abstract.ts
1074
+ import deepEqual from "deep-equal";
1075
+
1076
+ // src/repositories/errors.ts
1077
+ var checkConcurrentModification = (resource, expectedVersion) => {
1078
+ if (resource.version === expectedVersion)
1079
+ return;
1080
+ const identifier = resource.id ? resource.id : resource.key;
1081
+ throw new CommercetoolsError(
1082
+ {
1083
+ message: `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${resource.version}.`,
1084
+ currentVersion: resource.version,
1085
+ code: "ConcurrentModification"
1086
+ },
1087
+ 409
1088
+ );
1089
+ };
1090
+
1091
+ // src/repositories/abstract.ts
1092
+ var AbstractRepository = class {
1093
+ constructor(storage) {
1094
+ this.actions = {};
1095
+ this._storage = storage;
1096
+ }
1097
+ processUpdateActions(context, resource, actions) {
1098
+ const modifiedResource = JSON.parse(JSON.stringify(resource));
1099
+ actions.forEach((action) => {
1100
+ const updateFunc = this.actions[action.action];
1101
+ if (!updateFunc) {
1102
+ console.error(`No mock implemented for update action ${action.action}`);
1103
+ return;
1104
+ }
1105
+ updateFunc(context, modifiedResource, action);
1106
+ });
1107
+ if (!deepEqual(modifiedResource, resource)) {
1108
+ this.save(context, modifiedResource);
1109
+ }
1110
+ return modifiedResource;
1111
+ }
1112
+ };
1113
+ var AbstractResourceRepository = class extends AbstractRepository {
1114
+ constructor(storage) {
1115
+ super(storage);
1116
+ this._storage.assertStorage(this.getTypeId());
1117
+ }
1118
+ query(context, params = {}) {
1119
+ return this._storage.query(context.projectKey, this.getTypeId(), {
1120
+ expand: params.expand,
1121
+ where: params.where,
1122
+ offset: params.offset,
1123
+ limit: params.limit
1124
+ });
1125
+ }
1126
+ get(context, id, params = {}) {
1127
+ return this._storage.get(context.projectKey, this.getTypeId(), id, params);
1128
+ }
1129
+ getByKey(context, key, params = {}) {
1130
+ return this._storage.getByKey(
1131
+ context.projectKey,
1132
+ this.getTypeId(),
1133
+ key,
1134
+ params
1135
+ );
1136
+ }
1137
+ delete(context, id, params = {}) {
1138
+ return this._storage.delete(
1139
+ context.projectKey,
1140
+ this.getTypeId(),
1141
+ id,
1142
+ params
1143
+ );
1144
+ }
1145
+ save(context, resource) {
1146
+ const current = this.get(context, resource.id);
1147
+ if (current) {
1148
+ checkConcurrentModification(current, resource.version);
1149
+ } else {
1150
+ if (resource.version !== 0) {
1151
+ throw new CommercetoolsError(
1152
+ {
1153
+ code: "InvalidOperation",
1154
+ message: "version on create must be 0"
1155
+ },
1156
+ 400
1157
+ );
1158
+ }
1159
+ }
1160
+ resource.version += 1;
1161
+ this._storage.add(context.projectKey, this.getTypeId(), resource);
1162
+ }
1163
+ };
1164
+
1165
+ // src/repositories/cart-discount.ts
1166
+ var CartDiscountRepository = class extends AbstractResourceRepository {
1167
+ constructor() {
1168
+ super(...arguments);
1169
+ this.actions = {
1170
+ setKey: (context, resource, { key }) => {
1171
+ resource.key = key;
1172
+ },
1173
+ setDescription: (context, resource, { description }) => {
1174
+ resource.description = description;
1175
+ },
1176
+ setValidFrom: (context, resource, { validFrom }) => {
1177
+ resource.validFrom = validFrom;
1178
+ },
1179
+ setValidUntil: (context, resource, { validUntil }) => {
1180
+ resource.validUntil = validUntil;
1181
+ },
1182
+ setValidFromAndUntil: (context, resource, { validFrom, validUntil }) => {
1183
+ resource.validFrom = validFrom;
1184
+ resource.validUntil = validUntil;
1185
+ },
1186
+ changeSortOrder: (context, resource, { sortOrder }) => {
1187
+ resource.sortOrder = sortOrder;
1188
+ },
1189
+ changeIsActive: (context, resource, { isActive }) => {
1190
+ resource.isActive = isActive;
1191
+ }
1192
+ };
1193
+ }
1194
+ getTypeId() {
1195
+ return "cart-discount";
1196
+ }
1197
+ create(context, draft) {
1198
+ const resource = {
1199
+ ...getBaseResourceProperties(),
1200
+ key: draft.key,
1201
+ description: draft.description,
1202
+ cartPredicate: draft.cartPredicate,
1203
+ isActive: draft.isActive || false,
1204
+ name: draft.name,
1205
+ references: [],
1206
+ target: draft.target,
1207
+ requiresDiscountCode: draft.requiresDiscountCode || false,
1208
+ sortOrder: draft.sortOrder,
1209
+ stackingMode: draft.stackingMode || "Stacking",
1210
+ validFrom: draft.validFrom,
1211
+ validUntil: draft.validUntil,
1212
+ value: this.transformValueDraft(draft.value)
1213
+ };
1214
+ this.save(context, resource);
1215
+ return resource;
1216
+ }
1217
+ transformValueDraft(value) {
1218
+ switch (value.type) {
1219
+ case "absolute": {
1220
+ return {
1221
+ type: "absolute",
1222
+ money: value.money.map(createTypedMoney)
1223
+ };
1224
+ }
1225
+ case "fixed": {
1226
+ return {
1227
+ type: "fixed",
1228
+ money: value.money.map(createTypedMoney)
1229
+ };
1230
+ }
1231
+ case "giftLineItem": {
1232
+ return {
1233
+ ...value
1234
+ };
1235
+ }
1236
+ case "relative": {
1237
+ return {
1238
+ ...value
1239
+ };
1240
+ }
1241
+ }
1242
+ return value;
1243
+ }
1244
+ };
1245
+
1246
+ // src/services/cart-discount.ts
1247
+ var CartDiscountService = class extends AbstractService {
1248
+ constructor(parent, storage) {
1249
+ super(parent);
1250
+ this.repository = new CartDiscountRepository(storage);
1251
+ }
1252
+ getBasePath() {
1253
+ return "cart-discounts";
1254
+ }
1255
+ };
1256
+
1257
+ // src/repositories/cart.ts
1258
+ import { v4 as uuidv43 } from "uuid";
1259
+ var CartRepository = class extends AbstractResourceRepository {
1260
+ constructor() {
1261
+ super(...arguments);
1262
+ this.actions = {
1263
+ addLineItem: (context, resource, { productId, variantId, sku, quantity = 1 }) => {
1264
+ var _a;
1265
+ let product = null;
1266
+ let variant;
1267
+ if (productId && variantId) {
1268
+ product = this._storage.get(
1269
+ context.projectKey,
1270
+ "product",
1271
+ productId,
1272
+ {}
1273
+ );
1274
+ } else if (sku) {
1275
+ const items = this._storage.query(context.projectKey, "product", {
1276
+ where: [
1277
+ `masterData(current(masterVariant(sku="${sku}"))) or masterData(current(variants(sku="${sku}")))`
1278
+ ]
1279
+ });
1280
+ if (items.count === 1) {
1281
+ product = items.results[0];
1282
+ }
1283
+ }
1284
+ if (!product) {
1285
+ throw new CommercetoolsError({
1286
+ code: "General",
1287
+ message: sku ? `A product containing a variant with SKU '${sku}' not found.` : `A product with ID '${productId}' not found.`
1288
+ });
1289
+ }
1290
+ variant = [
1291
+ product.masterData.current.masterVariant,
1292
+ ...product.masterData.current.variants
1293
+ ].find((x) => {
1294
+ if (sku)
1295
+ return x.sku === sku;
1296
+ if (variantId)
1297
+ return x.id === variantId;
1298
+ return false;
1299
+ });
1300
+ if (!variant) {
1301
+ throw new CommercetoolsError({
1302
+ code: "General",
1303
+ message: sku ? `A variant with SKU '${sku}' for product '${product.id}' not found.` : `A variant with ID '${variantId}' for product '${product.id}' not found.`
1304
+ });
1305
+ }
1306
+ const alreadyAdded = resource.lineItems.some(
1307
+ (x) => x.productId === (product == null ? void 0 : product.id) && x.variant.id === (variant == null ? void 0 : variant.id)
1308
+ );
1309
+ if (alreadyAdded) {
1310
+ resource.lineItems.map((x) => {
1311
+ if (x.productId === (product == null ? void 0 : product.id) && x.variant.id === (variant == null ? void 0 : variant.id)) {
1312
+ x.quantity += quantity;
1313
+ x.totalPrice.centAmount = calculateLineItemTotalPrice(x);
1314
+ }
1315
+ return x;
1316
+ });
1317
+ } else {
1318
+ if (!((_a = variant.prices) == null ? void 0 : _a.length)) {
1319
+ throw new CommercetoolsError({
1320
+ code: "General",
1321
+ message: `A product with ID '${productId}' doesn't have any prices.`
1322
+ });
1323
+ }
1324
+ const currency = resource.totalPrice.currencyCode;
1325
+ const price = selectPrice({
1326
+ prices: variant.prices,
1327
+ currency,
1328
+ country: resource.country
1329
+ });
1330
+ if (!price) {
1331
+ throw new Error(
1332
+ `No valid price found for ${productId} for country ${resource.country} and currency ${currency}`
1333
+ );
1334
+ }
1335
+ resource.lineItems.push({
1336
+ id: uuidv43(),
1337
+ productId: product.id,
1338
+ productKey: product.key,
1339
+ name: product.masterData.current.name,
1340
+ productSlug: product.masterData.current.slug,
1341
+ productType: product.productType,
1342
+ variant,
1343
+ price,
1344
+ totalPrice: {
1345
+ ...price.value,
1346
+ centAmount: price.value.centAmount * quantity
1347
+ },
1348
+ quantity,
1349
+ discountedPricePerQuantity: [],
1350
+ lineItemMode: "Standard",
1351
+ priceMode: "Platform",
1352
+ state: []
1353
+ });
1354
+ }
1355
+ resource.totalPrice.centAmount = calculateCartTotalPrice(resource);
1356
+ },
1357
+ removeLineItem: (context, resource, { lineItemId, quantity }) => {
1358
+ const lineItem = resource.lineItems.find((x) => x.id === lineItemId);
1359
+ if (!lineItem) {
1360
+ throw new CommercetoolsError({
1361
+ code: "General",
1362
+ message: `A line item with ID '${lineItemId}' not found.`
1363
+ });
1364
+ }
1365
+ const shouldDelete = !quantity || quantity >= lineItem.quantity;
1366
+ if (shouldDelete) {
1367
+ resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
1368
+ } else {
1369
+ resource.lineItems.map((x) => {
1370
+ if (x.id === lineItemId && quantity) {
1371
+ x.quantity -= quantity;
1372
+ x.totalPrice.centAmount = calculateLineItemTotalPrice(x);
1373
+ }
1374
+ return x;
1375
+ });
1376
+ }
1377
+ resource.totalPrice.centAmount = calculateCartTotalPrice(resource);
1378
+ },
1379
+ setBillingAddress: (context, resource, { address }) => {
1380
+ resource.billingAddress = address;
1381
+ },
1382
+ setShippingMethod: (context, resource, { shippingMethod }) => {
1383
+ const resolvedType = this._storage.getByResourceIdentifier(
1384
+ context.projectKey,
1385
+ shippingMethod
1386
+ );
1387
+ if (!resolvedType) {
1388
+ throw new Error(`Type ${shippingMethod} not found`);
1389
+ }
1390
+ resource.shippingInfo = {
1391
+ shippingMethod: {
1392
+ typeId: "shipping-method",
1393
+ id: resolvedType.id
1394
+ }
1395
+ };
1396
+ },
1397
+ setCountry: (context, resource, { country }) => {
1398
+ resource.country = country;
1399
+ },
1400
+ setCustomerEmail: (context, resource, { email }) => {
1401
+ resource.customerEmail = email;
1402
+ },
1403
+ setCustomField: (context, resource, { name, value }) => {
1404
+ if (!resource.custom) {
1405
+ throw new Error("Resource has no custom field");
1406
+ }
1407
+ resource.custom.fields[name] = value;
1408
+ },
1409
+ setCustomType: (context, resource, { type, fields }) => {
1410
+ if (!type) {
1411
+ resource.custom = void 0;
1412
+ } else {
1413
+ const resolvedType = this._storage.getByResourceIdentifier(
1414
+ context.projectKey,
1415
+ type
1416
+ );
1417
+ if (!resolvedType) {
1418
+ throw new Error(`Type ${type} not found`);
1419
+ }
1420
+ resource.custom = {
1421
+ type: {
1422
+ typeId: "type",
1423
+ id: resolvedType.id
1424
+ },
1425
+ fields: fields || []
1426
+ };
1427
+ }
1428
+ },
1429
+ setLocale: (context, resource, { locale }) => {
1430
+ resource.locale = locale;
1431
+ },
1432
+ setShippingAddress: (context, resource, { address }) => {
1433
+ resource.shippingAddress = address;
1434
+ }
1435
+ };
1436
+ this.draftLineItemtoLineItem = (projectKey, draftLineItem, currency, country) => {
1437
+ const { productId, quantity, variantId, sku } = draftLineItem;
1438
+ let product = null;
1439
+ let variant;
1440
+ if (productId && variantId) {
1441
+ product = this._storage.get(projectKey, "product", productId, {});
1442
+ } else if (sku) {
1443
+ const items = this._storage.query(projectKey, "product", {
1444
+ where: [
1445
+ `masterData(current(masterVariant(sku="${sku}"))) or masterData(current(variants(sku="${sku}")))`
1446
+ ]
1447
+ });
1448
+ if (items.count === 1) {
1449
+ product = items.results[0];
1450
+ }
1451
+ }
1452
+ if (!product) {
1453
+ throw new CommercetoolsError({
1454
+ code: "General",
1455
+ message: sku ? `A product containing a variant with SKU '${sku}' not found.` : `A product with ID '${productId}' not found.`
1456
+ });
1457
+ }
1458
+ variant = [
1459
+ product.masterData.current.masterVariant,
1460
+ ...product.masterData.current.variants
1461
+ ].find((x) => {
1462
+ if (sku)
1463
+ return x.sku === sku;
1464
+ if (variantId)
1465
+ return x.id === variantId;
1466
+ return false;
1467
+ });
1468
+ if (!variant) {
1469
+ throw new Error(
1470
+ sku ? `A variant with SKU '${sku}' for product '${product.id}' not found.` : `A variant with ID '${variantId}' for product '${product.id}' not found.`
1471
+ );
1472
+ }
1473
+ const quant = quantity ?? 1;
1474
+ const price = selectPrice({ prices: variant.prices, currency, country });
1475
+ if (!price) {
1476
+ throw new Error(
1477
+ `No valid price found for ${productId} for country ${country} and currency ${currency}`
1478
+ );
1479
+ }
1480
+ return {
1481
+ id: uuidv43(),
1482
+ productId: product.id,
1483
+ productKey: product.key,
1484
+ name: product.masterData.current.name,
1485
+ productSlug: product.masterData.current.slug,
1486
+ productType: product.productType,
1487
+ variant,
1488
+ price,
1489
+ totalPrice: {
1490
+ ...price.value,
1491
+ centAmount: price.value.centAmount * quant
1492
+ },
1493
+ quantity: quant,
1494
+ discountedPricePerQuantity: [],
1495
+ lineItemMode: "Standard",
1496
+ priceMode: "Platform",
1497
+ state: []
1498
+ };
1499
+ };
1500
+ }
1501
+ getTypeId() {
1502
+ return "cart";
1503
+ }
1504
+ create(context, draft) {
1505
+ var _a;
1506
+ const lineItems = ((_a = draft.lineItems) == null ? void 0 : _a.map(
1507
+ (draftLineItem) => this.draftLineItemtoLineItem(
1508
+ context.projectKey,
1509
+ draftLineItem,
1510
+ draft.currency,
1511
+ draft.country
1512
+ )
1513
+ )) ?? [];
1514
+ const resource = {
1515
+ ...getBaseResourceProperties(),
1516
+ cartState: "Active",
1517
+ lineItems,
1518
+ customLineItems: [],
1519
+ totalPrice: {
1520
+ type: "centPrecision",
1521
+ centAmount: 0,
1522
+ currencyCode: draft.currency,
1523
+ fractionDigits: 0
1524
+ },
1525
+ taxMode: draft.taxMode ?? "Platform",
1526
+ taxRoundingMode: draft.taxRoundingMode ?? "HalfEven",
1527
+ taxCalculationMode: draft.taxCalculationMode ?? "LineItemLevel",
1528
+ refusedGifts: [],
1529
+ locale: draft.locale,
1530
+ country: draft.country,
1531
+ origin: draft.origin ?? "Customer",
1532
+ custom: createCustomFields(
1533
+ draft.custom,
1534
+ context.projectKey,
1535
+ this._storage
1536
+ )
1537
+ };
1538
+ resource.totalPrice.centAmount = calculateCartTotalPrice(resource);
1539
+ this.save(context, resource);
1540
+ return resource;
1541
+ }
1542
+ getActiveCart(projectKey) {
1543
+ const results = this._storage.query(projectKey, this.getTypeId(), {
1544
+ where: [`cartState="Active"`]
1545
+ });
1546
+ if (results.count > 0) {
1547
+ return results.results[0];
1548
+ }
1549
+ return;
1550
+ }
1551
+ };
1552
+ var selectPrice = ({
1553
+ prices,
1554
+ currency,
1555
+ country
1556
+ }) => {
1557
+ if (!prices) {
1558
+ return void 0;
1559
+ }
1560
+ return prices.find((price) => {
1561
+ const countryMatch = !price.country || price.country === country;
1562
+ const currencyMatch = price.value.currencyCode === currency;
1563
+ return countryMatch && currencyMatch;
1564
+ });
1565
+ };
1566
+ var calculateLineItemTotalPrice = (lineItem) => lineItem.price.value.centAmount * lineItem.quantity;
1567
+ var calculateCartTotalPrice = (cart) => cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
1568
+
1569
+ // src/repositories/order.ts
1570
+ import assert2 from "assert";
1571
+ var OrderRepository = class extends AbstractResourceRepository {
1572
+ constructor() {
1573
+ super(...arguments);
1574
+ this.actions = {
1575
+ addPayment: (context, resource, { payment }) => {
1576
+ const resolvedPayment = this._storage.getByResourceIdentifier(
1577
+ context.projectKey,
1578
+ payment
1579
+ );
1580
+ if (!resolvedPayment) {
1581
+ throw new Error(`Payment ${payment.id} not found`);
1582
+ }
1583
+ if (!resource.paymentInfo) {
1584
+ resource.paymentInfo = {
1585
+ payments: []
1586
+ };
1587
+ }
1588
+ resource.paymentInfo.payments.push({
1589
+ typeId: "payment",
1590
+ id: payment.id
1591
+ });
1592
+ },
1593
+ changeOrderState: (context, resource, { orderState }) => {
1594
+ resource.orderState = orderState;
1595
+ },
1596
+ changePaymentState: (context, resource, { paymentState }) => {
1597
+ resource.paymentState = paymentState;
1598
+ },
1599
+ transitionState: (context, resource, { state }) => {
1600
+ const resolvedType = this._storage.getByResourceIdentifier(
1601
+ context.projectKey,
1602
+ state
1603
+ );
1604
+ if (!resolvedType) {
1605
+ throw new Error(
1606
+ `No state found with key=${state.key} or id=${state.key}`
1607
+ );
1608
+ }
1609
+ resource.state = { typeId: "state", id: resolvedType.id };
1610
+ },
1611
+ setBillingAddress: (context, resource, { address }) => {
1612
+ resource.billingAddress = address;
1613
+ },
1614
+ setCustomerEmail: (context, resource, { email }) => {
1615
+ resource.customerEmail = email;
1616
+ },
1617
+ setCustomField: (context, resource, { name, value }) => {
1618
+ if (!resource.custom) {
1619
+ throw new Error("Resource has no custom field");
1620
+ }
1621
+ resource.custom.fields[name] = value;
1622
+ },
1623
+ setCustomType: (context, resource, { type, fields }) => {
1624
+ if (!type) {
1625
+ resource.custom = void 0;
1626
+ } else {
1627
+ const resolvedType = this._storage.getByResourceIdentifier(
1628
+ context.projectKey,
1629
+ type
1630
+ );
1631
+ if (!resolvedType) {
1632
+ throw new Error(`Type ${type} not found`);
1633
+ }
1634
+ resource.custom = {
1635
+ type: {
1636
+ typeId: "type",
1637
+ id: resolvedType.id
1638
+ },
1639
+ fields: fields || []
1640
+ };
1641
+ }
1642
+ },
1643
+ setLocale: (context, resource, { locale }) => {
1644
+ resource.locale = locale;
1645
+ },
1646
+ setOrderNumber: (context, resource, { orderNumber }) => {
1647
+ resource.orderNumber = orderNumber;
1648
+ },
1649
+ setShippingAddress: (context, resource, { address }) => {
1650
+ resource.shippingAddress = address;
1651
+ },
1652
+ setStore: (context, resource, { store }) => {
1653
+ if (!store)
1654
+ return;
1655
+ const resolvedType = this._storage.getByResourceIdentifier(
1656
+ context.projectKey,
1657
+ store
1658
+ );
1659
+ if (!resolvedType) {
1660
+ throw new Error(`No store found with key=${store.key}`);
1661
+ }
1662
+ const storeReference = resolvedType;
1663
+ resource.store = {
1664
+ typeId: "store",
1665
+ key: storeReference.key
1666
+ };
1667
+ }
1668
+ };
1669
+ }
1670
+ getTypeId() {
1671
+ return "order";
1672
+ }
1673
+ create(context, draft) {
1674
+ assert2(draft.cart, "draft.cart is missing");
1675
+ return this.createFromCart(
1676
+ context,
1677
+ {
1678
+ id: draft.cart.id,
1679
+ typeId: "cart"
1680
+ },
1681
+ draft.orderNumber
1682
+ );
1683
+ }
1684
+ createFromCart(context, cartReference, orderNumber) {
1685
+ const cart = this._storage.getByResourceIdentifier(
1686
+ context.projectKey,
1687
+ cartReference
1688
+ );
1689
+ if (!cart) {
1690
+ throw new Error("Cannot find cart");
1691
+ }
1692
+ const resource = {
1693
+ ...getBaseResourceProperties(),
1694
+ orderNumber,
1695
+ cart: cartReference,
1696
+ orderState: "Open",
1697
+ lineItems: [],
1698
+ customLineItems: [],
1699
+ totalPrice: cart.totalPrice,
1700
+ refusedGifts: [],
1701
+ origin: "Customer",
1702
+ syncInfo: [],
1703
+ store: context.storeKey ? {
1704
+ key: context.storeKey,
1705
+ typeId: "store"
1706
+ } : void 0,
1707
+ lastMessageSequenceNumber: 0
1708
+ };
1709
+ this.save(context, resource);
1710
+ return resource;
1711
+ }
1712
+ import(context, draft) {
1713
+ var _a, _b;
1714
+ assert2(this, "OrderRepository not valid");
1715
+ const resource = {
1716
+ ...getBaseResourceProperties(),
1717
+ billingAddress: draft.billingAddress,
1718
+ shippingAddress: draft.shippingAddress,
1719
+ custom: createCustomFields(
1720
+ draft.custom,
1721
+ context.projectKey,
1722
+ this._storage
1723
+ ),
1724
+ customerEmail: draft.customerEmail,
1725
+ lastMessageSequenceNumber: 0,
1726
+ orderNumber: draft.orderNumber,
1727
+ orderState: draft.orderState || "Open",
1728
+ origin: draft.origin || "Customer",
1729
+ paymentState: draft.paymentState,
1730
+ refusedGifts: [],
1731
+ store: resolveStoreReference(
1732
+ draft.store,
1733
+ context.projectKey,
1734
+ this._storage
1735
+ ),
1736
+ syncInfo: [],
1737
+ lineItems: ((_a = draft.lineItems) == null ? void 0 : _a.map(
1738
+ (item) => this.lineItemFromImportDraft.bind(this)(context, item)
1739
+ )) || [],
1740
+ customLineItems: ((_b = draft.customLineItems) == null ? void 0 : _b.map(
1741
+ (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
1742
+ )) || [],
1743
+ totalPrice: {
1744
+ type: "centPrecision",
1745
+ ...draft.totalPrice,
1746
+ fractionDigits: 2
1747
+ }
1748
+ };
1749
+ this.save(context, resource);
1750
+ return resource;
1751
+ }
1752
+ lineItemFromImportDraft(context, draft) {
1753
+ let product;
1754
+ let variant;
1755
+ if (draft.variant.sku) {
1756
+ variant = {
1757
+ id: 0,
1758
+ sku: draft.variant.sku
1759
+ };
1760
+ var items = this._storage.query(context.projectKey, "product", {
1761
+ where: [
1762
+ `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
1763
+ ]
1764
+ });
1765
+ if (items.count !== 1) {
1766
+ throw new CommercetoolsError({
1767
+ code: "General",
1768
+ message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
1769
+ });
1770
+ }
1771
+ product = items.results[0];
1772
+ if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
1773
+ variant = product.masterData.current.masterVariant;
1774
+ } else {
1775
+ variant = product.masterData.current.variants.find(
1776
+ (v) => v.sku === draft.variant.sku
1777
+ );
1778
+ }
1779
+ if (!variant) {
1780
+ throw new Error("Internal state error");
1781
+ }
1782
+ } else {
1783
+ throw new Error("No product found");
1784
+ }
1785
+ const lineItem = {
1786
+ ...getBaseResourceProperties(),
1787
+ custom: createCustomFields(
1788
+ draft.custom,
1789
+ context.projectKey,
1790
+ this._storage
1791
+ ),
1792
+ discountedPricePerQuantity: [],
1793
+ lineItemMode: "Standard",
1794
+ name: draft.name,
1795
+ price: createPrice(draft.price),
1796
+ priceMode: "Platform",
1797
+ productId: product.id,
1798
+ productType: product.productType,
1799
+ quantity: draft.quantity,
1800
+ state: draft.state || [],
1801
+ taxRate: draft.taxRate,
1802
+ totalPrice: createTypedMoney(draft.price.value),
1803
+ variant: {
1804
+ id: variant.id,
1805
+ sku: variant.sku,
1806
+ price: createPrice(draft.price)
1807
+ }
1808
+ };
1809
+ return lineItem;
1810
+ }
1811
+ customLineItemFromImportDraft(context, draft) {
1812
+ const lineItem = {
1813
+ ...getBaseResourceProperties(),
1814
+ custom: createCustomFields(
1815
+ draft.custom,
1816
+ context.projectKey,
1817
+ this._storage
1818
+ ),
1819
+ discountedPricePerQuantity: [],
1820
+ money: createTypedMoney(draft.money),
1821
+ name: draft.name,
1822
+ quantity: draft.quantity,
1823
+ slug: draft.slug,
1824
+ state: [],
1825
+ totalPrice: createTypedMoney(draft.money)
1826
+ };
1827
+ return lineItem;
1828
+ }
1829
+ getWithOrderNumber(context, orderNumber, params = {}) {
1830
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
1831
+ ...params,
1832
+ where: [`orderNumber="${orderNumber}"`]
1833
+ });
1834
+ if (result.count === 1) {
1835
+ return result.results[0];
1836
+ }
1837
+ if (result.count > 1) {
1838
+ throw new Error("Duplicate order numbers");
1839
+ }
1840
+ return;
1841
+ }
1842
+ };
1843
+
1844
+ // src/services/cart.ts
1845
+ var CartService = class extends AbstractService {
1846
+ constructor(parent, storage) {
1847
+ super(parent);
1848
+ this.repository = new CartRepository(storage);
1849
+ this.orderRepository = new OrderRepository(storage);
1850
+ }
1851
+ getBasePath() {
1852
+ return "carts";
1853
+ }
1854
+ extraRoutes(parent) {
1855
+ parent.post("/replicate", (request, response) => {
1856
+ const context = getRepositoryContext(request);
1857
+ const cartOrOrder = request.body.reference.typeId === "order" ? this.orderRepository.get(context, request.body.reference.id) : this.repository.get(context, request.body.reference.id);
1858
+ if (!cartOrOrder) {
1859
+ return response.status(400).send();
1860
+ }
1861
+ const cartDraft = {
1862
+ ...cartOrOrder,
1863
+ currency: cartOrOrder.totalPrice.currencyCode,
1864
+ discountCodes: [],
1865
+ lineItems: cartOrOrder.lineItems.map((lineItem) => {
1866
+ return {
1867
+ ...lineItem,
1868
+ variantId: lineItem.variant.id,
1869
+ sku: lineItem.variant.sku
1870
+ };
1871
+ })
1872
+ };
1873
+ const newCart = this.repository.create(context, cartDraft);
1874
+ return response.status(200).send(newCart);
1875
+ });
1876
+ }
1877
+ };
1878
+
1879
+ // src/repositories/category.ts
1880
+ import { v4 as uuidv44 } from "uuid";
1881
+ var CategoryRepository = class extends AbstractResourceRepository {
1882
+ constructor() {
1883
+ super(...arguments);
1884
+ this.actions = {
1885
+ changeAssetName: (context, resource, { assetId, assetKey, name }) => {
1886
+ var _a;
1887
+ (_a = resource.assets) == null ? void 0 : _a.forEach((asset) => {
1888
+ if (assetId && assetId === asset.id) {
1889
+ asset.name = name;
1890
+ }
1891
+ if (assetKey && assetKey === asset.key) {
1892
+ asset.name = name;
1893
+ }
1894
+ });
1895
+ },
1896
+ changeSlug: (context, resource, { slug }) => {
1897
+ resource.slug = slug;
1898
+ },
1899
+ setKey: (context, resource, { key }) => {
1900
+ resource.key = key;
1901
+ },
1902
+ setAssetDescription: (context, resource, { assetId, assetKey, description }) => {
1903
+ var _a;
1904
+ (_a = resource.assets) == null ? void 0 : _a.forEach((asset) => {
1905
+ if (assetId && assetId === asset.id) {
1906
+ asset.description = description;
1907
+ }
1908
+ if (assetKey && assetKey === asset.key) {
1909
+ asset.description = description;
1910
+ }
1911
+ });
1912
+ },
1913
+ setAssetSources: (context, resource, { assetId, assetKey, sources }) => {
1914
+ var _a;
1915
+ (_a = resource.assets) == null ? void 0 : _a.forEach((asset) => {
1916
+ if (assetId && assetId === asset.id) {
1917
+ asset.sources = sources;
1918
+ }
1919
+ if (assetKey && assetKey === asset.key) {
1920
+ asset.sources = sources;
1921
+ }
1922
+ });
1923
+ },
1924
+ setDescription: (context, resource, { description }) => {
1925
+ resource.description = description;
1926
+ },
1927
+ setMetaDescription: (context, resource, { metaDescription }) => {
1928
+ resource.metaDescription = metaDescription;
1929
+ },
1930
+ setMetaKeywords: (context, resource, { metaKeywords }) => {
1931
+ resource.metaKeywords = metaKeywords;
1932
+ },
1933
+ setMetaTitle: (context, resource, { metaTitle }) => {
1934
+ resource.metaTitle = metaTitle;
1935
+ },
1936
+ setCustomType: (context, resource, { type, fields }) => {
1937
+ if (type) {
1938
+ resource.custom = createCustomFields(
1939
+ { type, fields },
1940
+ context.projectKey,
1941
+ this._storage
1942
+ );
1943
+ } else {
1944
+ resource.custom = void 0;
1945
+ }
1946
+ },
1947
+ setCustomField: (context, resource, { name, value }) => {
1948
+ if (!resource.custom) {
1949
+ return;
1950
+ }
1951
+ if (value === null) {
1952
+ delete resource.custom.fields[name];
1953
+ } else {
1954
+ resource.custom.fields[name] = value;
1955
+ }
1956
+ }
1957
+ };
1958
+ }
1959
+ getTypeId() {
1960
+ return "category";
1961
+ }
1962
+ create(context, draft) {
1963
+ var _a;
1964
+ const resource = {
1965
+ ...getBaseResourceProperties(),
1966
+ key: draft.key,
1967
+ name: draft.name,
1968
+ slug: draft.slug,
1969
+ orderHint: draft.orderHint || "",
1970
+ externalId: draft.externalId || "",
1971
+ parent: draft.parent ? { typeId: "category", id: draft.parent.id } : void 0,
1972
+ ancestors: [],
1973
+ assets: ((_a = draft.assets) == null ? void 0 : _a.map((d) => {
1974
+ return {
1975
+ id: uuidv44(),
1976
+ name: d.name,
1977
+ description: d.description,
1978
+ sources: d.sources,
1979
+ tags: d.tags,
1980
+ key: d.key,
1981
+ custom: createCustomFields(
1982
+ draft.custom,
1983
+ context.projectKey,
1984
+ this._storage
1985
+ )
1986
+ };
1987
+ })) || [],
1988
+ custom: createCustomFields(
1989
+ draft.custom,
1990
+ context.projectKey,
1991
+ this._storage
1992
+ )
1993
+ };
1994
+ this.save(context, resource);
1995
+ return resource;
1996
+ }
1997
+ };
1998
+
1999
+ // src/services/category.ts
2000
+ var CategoryServices = class extends AbstractService {
2001
+ constructor(parent, storage) {
2002
+ super(parent);
2003
+ this.repository = new CategoryRepository(storage);
2004
+ }
2005
+ getBasePath() {
2006
+ return "categories";
2007
+ }
2008
+ };
2009
+
2010
+ // src/repositories/channel.ts
2011
+ var ChannelRepository = class extends AbstractResourceRepository {
2012
+ constructor() {
2013
+ super(...arguments);
2014
+ this.actions = {
2015
+ changeKey: (context, resource, { key }) => {
2016
+ resource.key = key;
2017
+ },
2018
+ changeName: (context, resource, { name }) => {
2019
+ resource.name = name;
2020
+ },
2021
+ changeDescription: (context, resource, { description }) => {
2022
+ resource.description = description;
2023
+ },
2024
+ setAddress: (context, resource, { address }) => {
2025
+ resource.address = createAddress(
2026
+ address,
2027
+ context.projectKey,
2028
+ this._storage
2029
+ );
2030
+ },
2031
+ setGeoLocation: (context, resource, { geoLocation }) => {
2032
+ resource.geoLocation = geoLocation;
2033
+ },
2034
+ setCustomType: (context, resource, { type, fields }) => {
2035
+ if (type) {
2036
+ resource.custom = createCustomFields(
2037
+ { type, fields },
2038
+ context.projectKey,
2039
+ this._storage
2040
+ );
2041
+ } else {
2042
+ resource.custom = void 0;
2043
+ }
2044
+ },
2045
+ setCustomField: (context, resource, { name, value }) => {
2046
+ if (!resource.custom) {
2047
+ return;
2048
+ }
2049
+ if (value === null) {
2050
+ delete resource.custom.fields[name];
2051
+ } else {
2052
+ resource.custom.fields[name] = value;
2053
+ }
2054
+ }
2055
+ };
2056
+ }
2057
+ getTypeId() {
2058
+ return "channel";
2059
+ }
2060
+ create(context, draft) {
2061
+ const resource = {
2062
+ ...getBaseResourceProperties(),
2063
+ key: draft.key,
2064
+ name: draft.name,
2065
+ description: draft.description,
2066
+ roles: draft.roles || [],
2067
+ geoLocation: draft.geoLocation,
2068
+ address: createAddress(draft.address, context.projectKey, this._storage),
2069
+ custom: createCustomFields(
2070
+ draft.custom,
2071
+ context.projectKey,
2072
+ this._storage
2073
+ )
2074
+ };
2075
+ this.save(context, resource);
2076
+ return resource;
2077
+ }
2078
+ };
2079
+
2080
+ // src/services/channel.ts
2081
+ var ChannelService = class extends AbstractService {
2082
+ constructor(parent, storage) {
2083
+ super(parent);
2084
+ this.repository = new ChannelRepository(storage);
2085
+ }
2086
+ getBasePath() {
2087
+ return "channels";
2088
+ }
2089
+ };
2090
+
2091
+ // src/repositories/customer-group.ts
2092
+ var CustomerGroupRepository = class extends AbstractResourceRepository {
2093
+ constructor() {
2094
+ super(...arguments);
2095
+ this.actions = {
2096
+ setKey: (context, resource, { key }) => {
2097
+ resource.key = key;
2098
+ },
2099
+ changeName: (context, resource, { name }) => {
2100
+ resource.name = name;
2101
+ },
2102
+ setCustomType: (context, resource, { type, fields }) => {
2103
+ if (type) {
2104
+ resource.custom = createCustomFields(
2105
+ { type, fields },
2106
+ context.projectKey,
2107
+ this._storage
2108
+ );
2109
+ } else {
2110
+ resource.custom = void 0;
2111
+ }
2112
+ },
2113
+ setCustomField: (context, resource, { name, value }) => {
2114
+ if (!resource.custom) {
2115
+ return;
2116
+ }
2117
+ if (value === null) {
2118
+ delete resource.custom.fields[name];
2119
+ } else {
2120
+ resource.custom.fields[name] = value;
2121
+ }
2122
+ }
2123
+ };
2124
+ }
2125
+ getTypeId() {
2126
+ return "customer";
2127
+ }
2128
+ create(context, draft) {
2129
+ const resource = {
2130
+ ...getBaseResourceProperties(),
2131
+ key: draft.key,
2132
+ name: draft.groupName,
2133
+ custom: createCustomFields(
2134
+ draft.custom,
2135
+ context.projectKey,
2136
+ this._storage
2137
+ )
2138
+ };
2139
+ this.save(context, resource);
2140
+ return resource;
2141
+ }
2142
+ };
2143
+
2144
+ // src/services/customer-group.ts
2145
+ var CustomerGroupService = class extends AbstractService {
2146
+ constructor(parent, storage) {
2147
+ super(parent);
2148
+ this.repository = new CustomerGroupRepository(storage);
2149
+ }
2150
+ getBasePath() {
2151
+ return "customer-groups";
2152
+ }
2153
+ };
2154
+
2155
+ // src/repositories/customer.ts
2156
+ var CustomerRepository = class extends AbstractResourceRepository {
2157
+ constructor() {
2158
+ super(...arguments);
2159
+ this.actions = {
2160
+ changeEmail: (_context, resource, { email }) => {
2161
+ resource.email = email;
2162
+ }
2163
+ };
2164
+ }
2165
+ getTypeId() {
2166
+ return "customer";
2167
+ }
2168
+ create(context, draft) {
2169
+ const resource = {
2170
+ ...getBaseResourceProperties(),
2171
+ email: draft.email,
2172
+ password: draft.password ? Buffer.from(draft.password).toString("base64") : void 0,
2173
+ isEmailVerified: draft.isEmailVerified || false,
2174
+ addresses: []
2175
+ };
2176
+ this.save(context, resource);
2177
+ return resource;
2178
+ }
2179
+ getMe(context) {
2180
+ const results = this._storage.query(
2181
+ context.projectKey,
2182
+ this.getTypeId(),
2183
+ {}
2184
+ );
2185
+ if (results.count > 0) {
2186
+ return results.results[0];
2187
+ }
2188
+ return;
2189
+ }
2190
+ };
2191
+
2192
+ // src/services/customer.ts
2193
+ import { v4 as uuidv45 } from "uuid";
2194
+ var CustomerService = class extends AbstractService {
2195
+ constructor(parent, storage) {
2196
+ super(parent);
2197
+ this.repository = new CustomerRepository(storage);
2198
+ }
2199
+ getBasePath() {
2200
+ return "customers";
2201
+ }
2202
+ extraRoutes(parent) {
2203
+ parent.post("/password-token", (request, response) => {
2204
+ const customer = this.repository.query(getRepositoryContext(request), {
2205
+ where: [`email="${request.body.email}"`]
2206
+ });
2207
+ const ttlMinutes = request.params.ttlMinutes ? +request.params.ttlMinutes : 34560;
2208
+ const { version, ...rest } = getBaseResourceProperties();
2209
+ return response.status(200).send({
2210
+ ...rest,
2211
+ customerId: customer.results[0].id,
2212
+ expiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),
2213
+ value: uuidv45()
2214
+ });
2215
+ });
2216
+ }
2217
+ };
2218
+
2219
+ // src/repositories/custom-object.ts
2220
+ var CustomObjectRepository = class extends AbstractResourceRepository {
2221
+ getTypeId() {
2222
+ return "key-value-document";
2223
+ }
2224
+ create(context, draft) {
2225
+ const current = this.getWithContainerAndKey(
2226
+ context,
2227
+ draft.container,
2228
+ draft.key
2229
+ );
2230
+ const baseProperties = getBaseResourceProperties();
2231
+ if (current) {
2232
+ baseProperties.id = current.id;
2233
+ if (!draft.version) {
2234
+ draft.version = current.version;
2235
+ }
2236
+ checkConcurrentModification(current, draft.version);
2237
+ if (draft.value === current.value) {
2238
+ return current;
2239
+ }
2240
+ baseProperties.version = current.version;
2241
+ } else {
2242
+ if (draft.version) {
2243
+ baseProperties.version = draft.version;
2244
+ }
2245
+ }
2246
+ const resource = {
2247
+ ...baseProperties,
2248
+ container: draft.container,
2249
+ key: draft.key,
2250
+ value: draft.value
2251
+ };
2252
+ this.save(context, resource);
2253
+ return resource;
2254
+ }
2255
+ getWithContainerAndKey(context, container, key) {
2256
+ const items = this._storage.all(
2257
+ context.projectKey,
2258
+ this.getTypeId()
2259
+ );
2260
+ return items.find((item) => item.container === container && item.key === key);
2261
+ }
2262
+ };
2263
+
2264
+ // src/services/custom-object.ts
2265
+ var CustomObjectService = class extends AbstractService {
2266
+ constructor(parent, storage) {
2267
+ super(parent);
2268
+ this.repository = new CustomObjectRepository(storage);
2269
+ }
2270
+ getBasePath() {
2271
+ return "custom-objects";
2272
+ }
2273
+ extraRoutes(router) {
2274
+ router.get("/:container/:key", this.getWithContainerAndKey.bind(this));
2275
+ router.post("/:container/:key", this.createWithContainerAndKey.bind(this));
2276
+ router.delete("/:container/:key", this.deleteWithContainerAndKey.bind(this));
2277
+ }
2278
+ getWithContainerAndKey(request, response) {
2279
+ const result = this.repository.getWithContainerAndKey(
2280
+ getRepositoryContext(request),
2281
+ request.params.container,
2282
+ request.params.key
2283
+ );
2284
+ if (!result) {
2285
+ return response.status(404).send("Not Found");
2286
+ }
2287
+ return response.status(200).send(result);
2288
+ }
2289
+ createWithContainerAndKey(request, response) {
2290
+ const draft = {
2291
+ ...request.body,
2292
+ key: request.params.key,
2293
+ container: request.params.container
2294
+ };
2295
+ const result = this.repository.create(getRepositoryContext(request), draft);
2296
+ return response.status(200).send(result);
2297
+ }
2298
+ deleteWithContainerAndKey(request, response) {
2299
+ const current = this.repository.getWithContainerAndKey(
2300
+ getRepositoryContext(request),
2301
+ request.params.container,
2302
+ request.params.key
2303
+ );
2304
+ if (!current) {
2305
+ return response.status(404).send("Not Found");
2306
+ }
2307
+ const result = this.repository.delete(
2308
+ getRepositoryContext(request),
2309
+ current.id
2310
+ );
2311
+ return response.status(200).send(result);
2312
+ }
2313
+ };
2314
+
2315
+ // src/repositories/discount-code.ts
2316
+ var DiscountCodeRepository = class extends AbstractResourceRepository {
2317
+ constructor() {
2318
+ super(...arguments);
2319
+ this.actions = {
2320
+ changeIsActive: (context, resource, { isActive }) => {
2321
+ resource.isActive = isActive;
2322
+ },
2323
+ changeCartDiscounts: (context, resource, { cartDiscounts }) => {
2324
+ resource.cartDiscounts = cartDiscounts.map(
2325
+ (obj) => ({
2326
+ typeId: "cart-discount",
2327
+ id: obj.id
2328
+ })
2329
+ );
2330
+ },
2331
+ setDescription: (context, resource, { description }) => {
2332
+ resource.description = description;
2333
+ },
2334
+ setCartPredicate: (context, resource, { cartPredicate }) => {
2335
+ resource.cartPredicate = cartPredicate;
2336
+ },
2337
+ setName: (context, resource, { name }) => {
2338
+ resource.name = name;
2339
+ },
2340
+ setMaxApplications: (context, resource, { maxApplications }) => {
2341
+ resource.maxApplications = maxApplications;
2342
+ },
2343
+ setMaxApplicationsPerCustomer: (context, resource, {
2344
+ maxApplicationsPerCustomer
2345
+ }) => {
2346
+ resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer;
2347
+ },
2348
+ setValidFrom: (context, resource, { validFrom }) => {
2349
+ resource.validFrom = validFrom;
2350
+ },
2351
+ setValidUntil: (context, resource, { validUntil }) => {
2352
+ resource.validUntil = validUntil;
2353
+ },
2354
+ setValidFromAndUntil: (context, resource, { validFrom, validUntil }) => {
2355
+ resource.validFrom = validFrom;
2356
+ resource.validUntil = validUntil;
2357
+ },
2358
+ setCustomType: (context, resource, { type, fields }) => {
2359
+ if (type) {
2360
+ resource.custom = createCustomFields(
2361
+ { type, fields },
2362
+ context.projectKey,
2363
+ this._storage
2364
+ );
2365
+ } else {
2366
+ resource.custom = void 0;
2367
+ }
2368
+ },
2369
+ setCustomField: (context, resource, { name, value }) => {
2370
+ if (!resource.custom) {
2371
+ return;
2372
+ }
2373
+ if (value === null) {
2374
+ delete resource.custom.fields[name];
2375
+ } else {
2376
+ resource.custom.fields[name] = value;
2377
+ }
2378
+ }
2379
+ };
2380
+ }
2381
+ getTypeId() {
2382
+ return "cart-discount";
2383
+ }
2384
+ create(context, draft) {
2385
+ const resource = {
2386
+ ...getBaseResourceProperties(),
2387
+ applicationVersion: 1,
2388
+ cartDiscounts: draft.cartDiscounts.map(
2389
+ (obj) => ({
2390
+ typeId: "cart-discount",
2391
+ id: obj.id
2392
+ })
2393
+ ),
2394
+ cartPredicate: draft.cartPredicate,
2395
+ code: draft.code,
2396
+ description: draft.description,
2397
+ groups: draft.groups || [],
2398
+ isActive: draft.isActive || true,
2399
+ name: draft.name,
2400
+ references: [],
2401
+ validFrom: draft.validFrom,
2402
+ validUntil: draft.validUntil,
2403
+ maxApplications: draft.maxApplications,
2404
+ maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,
2405
+ custom: createCustomFields(
2406
+ draft.custom,
2407
+ context.projectKey,
2408
+ this._storage
2409
+ )
2410
+ };
2411
+ this.save(context, resource);
2412
+ return resource;
2413
+ }
2414
+ };
2415
+
2416
+ // src/services/discount-code.ts
2417
+ var DiscountCodeService = class extends AbstractService {
2418
+ constructor(parent, storage) {
2419
+ super(parent);
2420
+ this.repository = new DiscountCodeRepository(storage);
2421
+ }
2422
+ getBasePath() {
2423
+ return "discount-codes";
2424
+ }
2425
+ };
2426
+
2427
+ // src/repositories/extension.ts
2428
+ var ExtensionRepository = class extends AbstractResourceRepository {
2429
+ constructor() {
2430
+ super(...arguments);
2431
+ this.actions = {
2432
+ setKey: (context, resource, { key }) => {
2433
+ resource.key = key;
2434
+ },
2435
+ setTimeoutInMs: (context, resource, { timeoutInMs }) => {
2436
+ resource.timeoutInMs = timeoutInMs;
2437
+ },
2438
+ changeTriggers: (context, resource, { triggers }) => {
2439
+ resource.triggers = triggers;
2440
+ },
2441
+ changeDestination: (context, resource, { destination }) => {
2442
+ resource.destination = destination;
2443
+ }
2444
+ };
2445
+ }
2446
+ getTypeId() {
2447
+ return "extension";
2448
+ }
2449
+ create(context, draft) {
2450
+ const resource = {
2451
+ ...getBaseResourceProperties(),
2452
+ key: draft.key,
2453
+ timeoutInMs: draft.timeoutInMs,
2454
+ destination: draft.destination,
2455
+ triggers: draft.triggers
2456
+ };
2457
+ this.save(context, resource);
2458
+ return resource;
2459
+ }
2460
+ };
2461
+
2462
+ // src/services/extension.ts
2463
+ var ExtensionServices = class extends AbstractService {
2464
+ constructor(parent, storage) {
2465
+ super(parent);
2466
+ this.repository = new ExtensionRepository(storage);
2467
+ }
2468
+ getBasePath() {
2469
+ return "extensions";
2470
+ }
2471
+ };
2472
+
2473
+ // src/repositories/inventory-entry.ts
2474
+ var InventoryEntryRepository = class extends AbstractResourceRepository {
2475
+ constructor() {
2476
+ super(...arguments);
2477
+ this.actions = {
2478
+ changeQuantity: (context, resource, { quantity }) => {
2479
+ resource.quantityOnStock = quantity;
2480
+ resource.availableQuantity = quantity;
2481
+ },
2482
+ setExpectedDelivery: (context, resource, { expectedDelivery }) => {
2483
+ resource.expectedDelivery = new Date(expectedDelivery).toISOString();
2484
+ },
2485
+ setCustomField: (context, resource, { name, value }) => {
2486
+ if (!resource.custom) {
2487
+ throw new Error("Resource has no custom field");
2488
+ }
2489
+ resource.custom.fields[name] = value;
2490
+ },
2491
+ setCustomType: (context, resource, { type, fields }) => {
2492
+ if (!type) {
2493
+ resource.custom = void 0;
2494
+ } else {
2495
+ const resolvedType = this._storage.getByResourceIdentifier(
2496
+ context.projectKey,
2497
+ type
2498
+ );
2499
+ if (!resolvedType) {
2500
+ throw new Error(`Type ${type} not found`);
2501
+ }
2502
+ resource.custom = {
2503
+ type: {
2504
+ typeId: "type",
2505
+ id: resolvedType.id
2506
+ },
2507
+ fields: fields || []
2508
+ };
2509
+ }
2510
+ },
2511
+ setRestockableInDays: (context, resource, { restockableInDays }) => {
2512
+ resource.restockableInDays = restockableInDays;
2513
+ }
2514
+ };
2515
+ }
2516
+ getTypeId() {
2517
+ return "inventory-entry";
2518
+ }
2519
+ create(context, draft) {
2520
+ var _a;
2521
+ const resource = {
2522
+ ...getBaseResourceProperties(),
2523
+ sku: draft.sku,
2524
+ quantityOnStock: draft.quantityOnStock,
2525
+ availableQuantity: draft.quantityOnStock,
2526
+ expectedDelivery: draft.expectedDelivery,
2527
+ restockableInDays: draft.restockableInDays,
2528
+ supplyChannel: {
2529
+ ...draft.supplyChannel,
2530
+ typeId: "channel",
2531
+ id: ((_a = draft.supplyChannel) == null ? void 0 : _a.id) ?? ""
2532
+ },
2533
+ custom: createCustomFields(
2534
+ draft.custom,
2535
+ context.projectKey,
2536
+ this._storage
2537
+ )
2538
+ };
2539
+ this.save(context, resource);
2540
+ return resource;
2541
+ }
2542
+ };
2543
+
2544
+ // src/services/inventory-entry.ts
2545
+ var InventoryEntryService = class extends AbstractService {
2546
+ constructor(parent, storage) {
2547
+ super(parent);
2548
+ this.repository = new InventoryEntryRepository(storage);
2549
+ }
2550
+ getBasePath() {
2551
+ return "inventory";
2552
+ }
2553
+ };
2554
+
2555
+ // src/services/my-cart.ts
2556
+ import { Router as Router2 } from "express";
2557
+ var MyCartService = class extends AbstractService {
2558
+ constructor(parent, storage) {
2559
+ super(parent);
2560
+ this.repository = new CartRepository(storage);
2561
+ }
2562
+ getBasePath() {
2563
+ return "me";
2564
+ }
2565
+ registerRoutes(parent) {
2566
+ const basePath = this.getBasePath();
2567
+ const router = Router2({ mergeParams: true });
2568
+ this.extraRoutes(router);
2569
+ router.get("/active-cart", this.activeCart.bind(this));
2570
+ router.get("/carts/", this.get.bind(this));
2571
+ router.get("/carts/:id", this.getWithId.bind(this));
2572
+ router.delete("/carts/:id", this.deletewithId.bind(this));
2573
+ router.post("/carts/", this.post.bind(this));
2574
+ router.post("/carts/:id", this.postWithId.bind(this));
2575
+ parent.use(`/${basePath}`, router);
2576
+ }
2577
+ activeCart(request, response) {
2578
+ const resource = this.repository.getActiveCart(request.params.projectKey);
2579
+ if (!resource) {
2580
+ return response.status(404).send("Not found");
2581
+ }
2582
+ return response.status(200).send(resource);
2583
+ }
2584
+ };
2585
+
2586
+ // src/repositories/payment.ts
2587
+ import { v4 as uuidv46 } from "uuid";
2588
+ var PaymentRepository = class extends AbstractResourceRepository {
2589
+ constructor() {
2590
+ super(...arguments);
2591
+ this.transactionFromTransactionDraft = (draft, context) => ({
2592
+ ...draft,
2593
+ id: uuidv46(),
2594
+ amount: createTypedMoney(draft.amount),
2595
+ custom: createCustomFields(draft.custom, context.projectKey, this._storage)
2596
+ });
2597
+ this.actions = {
2598
+ setCustomField: (context, resource, { name, value }) => {
2599
+ if (!resource.custom) {
2600
+ throw new Error("Resource has no custom field");
2601
+ }
2602
+ resource.custom.fields[name] = value;
2603
+ },
2604
+ setCustomType: (context, resource, { type, fields }) => {
2605
+ if (!type) {
2606
+ resource.custom = void 0;
2607
+ } else {
2608
+ const resolvedType = this._storage.getByResourceIdentifier(
2609
+ context.projectKey,
2610
+ type
2611
+ );
2612
+ if (!resolvedType) {
2613
+ throw new Error(`Type ${type} not found`);
2614
+ }
2615
+ resource.custom = {
2616
+ type: {
2617
+ typeId: "type",
2618
+ id: resolvedType.id
2619
+ },
2620
+ fields: fields || []
2621
+ };
2622
+ }
2623
+ },
2624
+ addTransaction: (context, resource, { transaction }) => {
2625
+ resource.transactions = [
2626
+ ...resource.transactions,
2627
+ this.transactionFromTransactionDraft(transaction, context)
2628
+ ];
2629
+ },
2630
+ changeTransactionState: (_context, resource, { transactionId, state }) => {
2631
+ const index = resource.transactions.findIndex(
2632
+ (e) => e.id === transactionId
2633
+ );
2634
+ const updatedTransaction = {
2635
+ ...resource.transactions[index],
2636
+ state
2637
+ };
2638
+ resource.transactions[index] = updatedTransaction;
2639
+ },
2640
+ transitionState: (context, resource, { state }) => {
2641
+ const stateObj = this._storage.getByResourceIdentifier(
2642
+ context.projectKey,
2643
+ state
2644
+ );
2645
+ if (!stateObj) {
2646
+ throw new Error(`State ${state} not found`);
2647
+ }
2648
+ resource.paymentStatus.state = {
2649
+ typeId: "state",
2650
+ id: stateObj.id,
2651
+ obj: stateObj
2652
+ };
2653
+ }
2654
+ };
2655
+ }
2656
+ getTypeId() {
2657
+ return "payment";
2658
+ }
2659
+ create(context, draft) {
2660
+ const resource = {
2661
+ ...getBaseResourceProperties(),
2662
+ amountPlanned: createTypedMoney(draft.amountPlanned),
2663
+ paymentMethodInfo: draft.paymentMethodInfo,
2664
+ paymentStatus: draft.paymentStatus ? {
2665
+ ...draft.paymentStatus,
2666
+ state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(
2667
+ draft.paymentStatus.state,
2668
+ context.projectKey,
2669
+ this._storage
2670
+ ) : void 0
2671
+ } : {},
2672
+ transactions: (draft.transactions || []).map(
2673
+ (t) => this.transactionFromTransactionDraft(t, context)
2674
+ ),
2675
+ interfaceInteractions: (draft.interfaceInteractions || []).map(
2676
+ (interaction) => createCustomFields(interaction, context.projectKey, this._storage)
2677
+ ),
2678
+ custom: createCustomFields(
2679
+ draft.custom,
2680
+ context.projectKey,
2681
+ this._storage
2682
+ )
2683
+ };
2684
+ this.save(context, resource);
2685
+ return resource;
2686
+ }
2687
+ };
2688
+
2689
+ // src/services/my-payment.ts
2690
+ var MyPaymentService = class extends AbstractService {
2691
+ constructor(parent, storage) {
2692
+ super(parent);
2693
+ this.repository = new PaymentRepository(storage);
2694
+ }
2695
+ getBasePath() {
2696
+ return "me/payments";
2697
+ }
2698
+ };
2699
+
2700
+ // src/services/order.ts
2701
+ var OrderService = class extends AbstractService {
2702
+ constructor(parent, storage) {
2703
+ super(parent);
2704
+ this.repository = new OrderRepository(storage);
2705
+ }
2706
+ getBasePath() {
2707
+ return "orders";
2708
+ }
2709
+ extraRoutes(router) {
2710
+ router.post("/import", this.import.bind(this));
2711
+ router.get("/order-number=:orderNumber", this.getWithOrderNumber.bind(this));
2712
+ }
2713
+ import(request, response) {
2714
+ const importDraft = request.body;
2715
+ const resource = this.repository.import(
2716
+ getRepositoryContext(request),
2717
+ importDraft
2718
+ );
2719
+ return response.status(200).send(resource);
2720
+ }
2721
+ getWithOrderNumber(request, response) {
2722
+ const resource = this.repository.getWithOrderNumber(
2723
+ getRepositoryContext(request),
2724
+ request.params.orderNumber,
2725
+ request.query
2726
+ );
2727
+ if (resource) {
2728
+ return response.status(200).send(resource);
2729
+ }
2730
+ return response.status(404).send("Not found");
2731
+ }
2732
+ };
2733
+
2734
+ // src/services/payment.ts
2735
+ var PaymentService = class extends AbstractService {
2736
+ constructor(parent, storage) {
2737
+ super(parent);
2738
+ this.repository = new PaymentRepository(storage);
2739
+ }
2740
+ getBasePath() {
2741
+ return "payments";
2742
+ }
2743
+ };
2744
+
2745
+ // src/repositories/product-discount.ts
2746
+ var ProductDiscountRepository = class extends AbstractResourceRepository {
2747
+ constructor() {
2748
+ super(...arguments);
2749
+ this.actions = {
2750
+ setKey: (context, resource, { key }) => {
2751
+ resource.key = key;
2752
+ },
2753
+ setDescription: (context, resource, { description }) => {
2754
+ if (description && Object.keys(description).length > 0) {
2755
+ resource.description = description;
2756
+ } else {
2757
+ resource.description = void 0;
2758
+ }
2759
+ },
2760
+ changeName: (context, resource, { name }) => {
2761
+ resource.name = name;
2762
+ },
2763
+ changeValue: (context, resource, { value }) => {
2764
+ resource.value = this.transformValueDraft(value);
2765
+ },
2766
+ changePredicate: (context, resource, { predicate }) => {
2767
+ resource.predicate = predicate;
2768
+ },
2769
+ changeSortOrder: (context, resource, { sortOrder }) => {
2770
+ resource.sortOrder = sortOrder;
2771
+ },
2772
+ changeIsActive: (context, resource, { isActive }) => {
2773
+ resource.isActive = isActive;
2774
+ },
2775
+ setValidFrom: (context, resource, { validFrom }) => {
2776
+ resource.validFrom = validFrom;
2777
+ },
2778
+ setValidUntil: (context, resource, { validUntil }) => {
2779
+ resource.validUntil = validUntil;
2780
+ },
2781
+ setValidFromAndUntil: (context, resource, { validFrom, validUntil }) => {
2782
+ resource.validFrom = validFrom;
2783
+ resource.validUntil = validUntil;
2784
+ }
2785
+ };
2786
+ }
2787
+ getTypeId() {
2788
+ return "product-discount";
2789
+ }
2790
+ create(context, draft) {
2791
+ const resource = {
2792
+ ...getBaseResourceProperties(),
2793
+ key: draft.key,
2794
+ name: draft.name,
2795
+ description: draft.description,
2796
+ value: this.transformValueDraft(draft.value),
2797
+ predicate: draft.predicate,
2798
+ sortOrder: draft.sortOrder,
2799
+ isActive: draft.isActive || false,
2800
+ validFrom: draft.validFrom,
2801
+ validUntil: draft.validUntil,
2802
+ references: []
2803
+ };
2804
+ this.save(context, resource);
2805
+ return resource;
2806
+ }
2807
+ transformValueDraft(value) {
2808
+ switch (value.type) {
2809
+ case "absolute": {
2810
+ return {
2811
+ type: "absolute",
2812
+ money: value.money.map(createTypedMoney)
2813
+ };
2814
+ }
2815
+ case "external": {
2816
+ return {
2817
+ type: "external"
2818
+ };
2819
+ }
2820
+ case "relative": {
2821
+ return {
2822
+ ...value
2823
+ };
2824
+ }
2825
+ }
2826
+ }
2827
+ getWithKey(context, key) {
2828
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
2829
+ where: [`key="${key}"`]
2830
+ });
2831
+ if (result.count === 1) {
2832
+ return result.results[0];
2833
+ }
2834
+ if (result.count > 1) {
2835
+ throw new Error("Duplicate product discount key");
2836
+ }
2837
+ return;
2838
+ }
2839
+ };
2840
+
2841
+ // src/services/product-discount.ts
2842
+ var ProductDiscountService = class extends AbstractService {
2843
+ constructor(parent, storage) {
2844
+ super(parent);
2845
+ this.repository = new ProductDiscountRepository(storage);
2846
+ }
2847
+ getBasePath() {
2848
+ return "product-discounts";
2849
+ }
2850
+ extraRoutes(router) {
2851
+ router.get("/key=:key", this.getWithKey.bind(this));
2852
+ }
2853
+ getWithKey(request, response) {
2854
+ const resource = this.repository.getWithKey(
2855
+ getRepositoryContext(request),
2856
+ request.params.key
2857
+ );
2858
+ if (resource) {
2859
+ return response.status(200).send(resource);
2860
+ }
2861
+ return response.status(404).send("Not found");
2862
+ }
2863
+ };
2864
+
2865
+ // src/lib/projectionSearchFilter.ts
2866
+ import perplex2 from "perplex";
2867
+ import Parser2 from "pratt";
2868
+ var parseFilterExpression = (filter, staged) => {
2869
+ const exprFunc = generateMatchFunc2(filter);
2870
+ const [source] = filter.split(":", 1);
2871
+ if (source.startsWith("variants.")) {
2872
+ return filterVariants(source, staged, exprFunc);
2873
+ }
2874
+ return filterProduct(source, exprFunc);
2875
+ };
2876
+ var getLexer2 = (value) => {
2877
+ return new perplex2(value).token("MISSING", /missing(?![-_a-z0-9]+)/i).token("EXISTS", /exists(?![-_a-z0-9]+)/i).token("RANGE", /range(?![-_a-z0-9]+)/i).token("TO", /to(?![-_a-z0-9]+)/i).token("IDENTIFIER", /[-_\.a-z]+/i).token("FLOAT", /\d+\.\d+/).token("INT", /\d+/).token("STRING", /"((?:\\.|[^"\\])*)"/).token("STRING", /'((?:\\.|[^'\\])*)'/).token("COMMA", ",").token("STAR", "*").token("(", "(").token(":", ":").token(")", ")").token('"', '"').token("WS", /\s+/, true);
2878
+ };
2879
+ var generateMatchFunc2 = (filter) => {
2880
+ const lexer = getLexer2(filter);
2881
+ const parser = new Parser2(lexer).builder().nud("IDENTIFIER", 100, (t) => {
2882
+ return t.token.match;
2883
+ }).led(":", 100, ({ left, bp }) => {
2884
+ const expr = parser.parse({ terminals: [bp - 1] });
2885
+ if (Array.isArray(expr)) {
2886
+ return (obj) => {
2887
+ return expr.includes(obj);
2888
+ };
2889
+ }
2890
+ if (typeof expr === "function") {
2891
+ return (obj) => {
2892
+ return expr(obj);
2893
+ };
2894
+ }
2895
+ return (obj) => {
2896
+ return obj === expr;
2897
+ };
2898
+ }).nud("STRING", 20, (t) => {
2899
+ return t.token.groups[1];
2900
+ }).nud("INT", 5, (t) => {
2901
+ return parseInt(t.token.match, 10);
2902
+ }).nud("STAR", 5, (t) => {
2903
+ return null;
2904
+ }).nud("EXISTS", 10, ({ bp }) => {
2905
+ return (val) => {
2906
+ return val !== void 0;
2907
+ };
2908
+ }).nud("MISSING", 10, ({ bp }) => {
2909
+ return (val) => {
2910
+ return val === void 0;
2911
+ };
2912
+ }).led("COMMA", 200, ({ left, token, bp }) => {
2913
+ const expr = parser.parse({ terminals: [bp - 1] });
2914
+ if (Array.isArray(expr)) {
2915
+ return [left, ...expr];
2916
+ } else {
2917
+ return [left, expr];
2918
+ }
2919
+ }).bp(")", 0).led("TO", 20, ({ left, bp }) => {
2920
+ const expr = parser.parse({ terminals: [bp - 1] });
2921
+ return [left, expr];
2922
+ }).nud("RANGE", 20, ({ bp }) => {
2923
+ lexer.next();
2924
+ const [start, stop] = parser.parse();
2925
+ console.log(start, stop);
2926
+ if (start !== null && stop !== null) {
2927
+ return (obj) => {
2928
+ return obj >= start && obj <= stop;
2929
+ };
2930
+ } else if (start === null && stop !== null) {
2931
+ return (obj) => {
2932
+ return obj <= stop;
2933
+ };
2934
+ } else if (start !== null && stop === null) {
2935
+ return (obj) => {
2936
+ return obj >= start;
2937
+ };
2938
+ } else {
2939
+ return (obj) => {
2940
+ return true;
2941
+ };
2942
+ }
2943
+ }).build();
2944
+ const result = parser.parse();
2945
+ if (typeof result !== "function") {
2946
+ const lines = filter.split("\n");
2947
+ const column = lines[lines.length - 1].length;
2948
+ throw new Error(`Syntax error while parsing '${filter}'.`);
2949
+ }
2950
+ return result;
2951
+ };
2952
+ var filterProduct = (source, exprFunc) => {
2953
+ return (p, markMatchingVariants) => {
2954
+ const value = nestedLookup(p, source);
2955
+ return exprFunc(value);
2956
+ };
2957
+ };
2958
+ var filterVariants = (source, staged, exprFunc) => {
2959
+ return (p, markMatchingVariants) => {
2960
+ const [, ...paths] = source.split(".");
2961
+ const path = paths.join(".");
2962
+ const variants = getVariants(p, staged);
2963
+ for (const variant of variants) {
2964
+ const value = resolveVariantValue(variant, path);
2965
+ if (exprFunc(value)) {
2966
+ if (markMatchingVariants) {
2967
+ variants.forEach((v) => v.isMatchingVariant = false);
2968
+ variant.isMatchingVariant = true;
2969
+ }
2970
+ return true;
2971
+ }
2972
+ }
2973
+ return false;
2974
+ };
2975
+ };
2976
+ var resolveVariantValue = (obj, path) => {
2977
+ if (path === void 0) {
2978
+ return obj;
2979
+ }
2980
+ if (path.startsWith("attributes.")) {
2981
+ const [, attrName, ...rest] = path.split(".");
2982
+ if (!obj.attributes) {
2983
+ return void 0;
2984
+ }
2985
+ for (const attr of obj.attributes) {
2986
+ if (attr.name === attrName) {
2987
+ return nestedLookup(attr.value, rest.join("."));
2988
+ }
2989
+ }
2990
+ }
2991
+ if (path === "price.centAmount") {
2992
+ return obj.prices && obj.prices.length > 0 ? obj.prices[0].value.centAmount : void 0;
2993
+ }
2994
+ return nestedLookup(obj, path);
2995
+ };
2996
+ var nestedLookup = (obj, path) => {
2997
+ if (!path || path === "") {
2998
+ return obj;
2999
+ }
3000
+ const parts = path.split(".");
3001
+ let val = obj;
3002
+ for (let i = 0; i < parts.length; i++) {
3003
+ const part = parts[i];
3004
+ if (val == void 0) {
3005
+ return void 0;
3006
+ }
3007
+ val = val[part];
3008
+ }
3009
+ return val;
3010
+ };
3011
+ var getVariants = (p, staged) => {
3012
+ var _a, _b, _c, _d;
3013
+ return [
3014
+ staged ? (_a = p.masterData.staged) == null ? void 0 : _a.masterVariant : (_b = p.masterData.current) == null ? void 0 : _b.masterVariant,
3015
+ ...staged ? (_c = p.masterData.staged) == null ? void 0 : _c.variants : (_d = p.masterData.current) == null ? void 0 : _d.variants
3016
+ ];
3017
+ };
3018
+
3019
+ // src/priceSelector.ts
3020
+ var applyPriceSelector = (products, selector) => {
3021
+ var _a, _b, _c, _d, _e;
3022
+ validatePriceSelector(selector);
3023
+ for (const product of products) {
3024
+ const variants = [
3025
+ (_a = product.masterData.staged) == null ? void 0 : _a.masterVariant,
3026
+ ...((_b = product.masterData.staged) == null ? void 0 : _b.variants) || [],
3027
+ (_c = product.masterData.current) == null ? void 0 : _c.masterVariant,
3028
+ ...((_d = product.masterData.current) == null ? void 0 : _d.variants) || []
3029
+ ].filter((x) => x != void 0);
3030
+ for (const variant of variants) {
3031
+ const scopedPrices = ((_e = variant.prices) == null ? void 0 : _e.filter((p) => priceSelectorFilter(p, selector))) ?? [];
3032
+ if (scopedPrices.length > 0) {
3033
+ const price = scopedPrices[0];
3034
+ variant.scopedPriceDiscounted = false;
3035
+ variant.scopedPrice = {
3036
+ ...price,
3037
+ currentValue: price.value
3038
+ };
3039
+ }
3040
+ }
3041
+ }
3042
+ };
3043
+ var validatePriceSelector = (selector) => {
3044
+ if ((selector.country || selector.channel || selector.customerGroup) && !selector.currency) {
3045
+ throw new CommercetoolsError(
3046
+ {
3047
+ code: "InvalidInput",
3048
+ message: "The price selecting parameters country, channel and customerGroup cannot be used without the currency."
3049
+ },
3050
+ 400
3051
+ );
3052
+ }
3053
+ };
3054
+ var priceSelectorFilter = (price, selector) => {
3055
+ var _a, _b, _c, _d;
3056
+ if ((selector.country || price.country) && selector.country !== price.country) {
3057
+ return false;
3058
+ }
3059
+ if ((selector.currency || price.value.currencyCode) && selector.currency !== price.value.currencyCode) {
3060
+ return false;
3061
+ }
3062
+ if ((selector.channel || ((_a = price.channel) == null ? void 0 : _a.id)) && selector.channel !== ((_b = price.channel) == null ? void 0 : _b.id)) {
3063
+ return false;
3064
+ }
3065
+ if ((selector.customerGroup || ((_c = price.customerGroup) == null ? void 0 : _c.id)) && selector.customerGroup !== ((_d = price.customerGroup) == null ? void 0 : _d.id)) {
3066
+ return false;
3067
+ }
3068
+ return true;
3069
+ };
3070
+
3071
+ // src/product-projection-search.ts
3072
+ var ProductProjectionSearch = class {
3073
+ constructor(storage) {
3074
+ this._storage = storage;
3075
+ }
3076
+ search(projectKey, params) {
3077
+ let resources = this._storage.all(projectKey, "product").map((r) => JSON.parse(JSON.stringify(r)));
3078
+ let markMatchingVariant = params.markMatchingVariants ?? false;
3079
+ applyPriceSelector(resources, {
3080
+ country: params.priceCountry,
3081
+ channel: params.priceChannel,
3082
+ customerGroup: params.priceCustomerGroup,
3083
+ currency: params.priceCurrency
3084
+ });
3085
+ if (params.filter) {
3086
+ try {
3087
+ const filters = params.filter.map(
3088
+ (f) => parseFilterExpression(f, params.staged ?? false)
3089
+ );
3090
+ resources = resources.filter(
3091
+ (resource) => filters.every((f) => f(resource, markMatchingVariant))
3092
+ );
3093
+ } catch (err) {
3094
+ throw new CommercetoolsError(
3095
+ {
3096
+ code: "InvalidInput",
3097
+ message: err.message
3098
+ },
3099
+ 400
3100
+ );
3101
+ }
3102
+ }
3103
+ if (params["filter.query"]) {
3104
+ try {
3105
+ const filters = params["filter.query"].map(
3106
+ (f) => parseFilterExpression(f, params.staged ?? false)
3107
+ );
3108
+ resources = resources.filter(
3109
+ (resource) => filters.every((f) => f(resource, markMatchingVariant))
3110
+ );
3111
+ } catch (err) {
3112
+ throw new CommercetoolsError(
3113
+ {
3114
+ code: "InvalidInput",
3115
+ message: err.message
3116
+ },
3117
+ 400
3118
+ );
3119
+ }
3120
+ }
3121
+ const totalResources = resources.length;
3122
+ const offset = params.offset || 0;
3123
+ const limit = params.limit || 20;
3124
+ resources = resources.slice(offset, offset + limit);
3125
+ if (params.expand !== void 0) {
3126
+ resources = resources.map((resource) => {
3127
+ return this._storage.expand(projectKey, resource, params.expand);
3128
+ });
3129
+ }
3130
+ return {
3131
+ count: totalResources,
3132
+ total: resources.length,
3133
+ offset,
3134
+ limit,
3135
+ results: resources.map(this.transform),
3136
+ facets: {}
3137
+ };
3138
+ }
3139
+ transform(product) {
3140
+ const obj = product.masterData.current;
3141
+ return {
3142
+ id: product.id,
3143
+ createdAt: product.createdAt,
3144
+ lastModifiedAt: product.lastModifiedAt,
3145
+ version: product.version,
3146
+ name: obj.name,
3147
+ slug: obj.slug,
3148
+ categories: obj.categories,
3149
+ masterVariant: obj.masterVariant,
3150
+ variants: obj.variants,
3151
+ productType: product.productType
3152
+ };
3153
+ }
3154
+ };
3155
+
3156
+ // src/repositories/product-projection.ts
3157
+ var ProductProjectionRepository = class extends AbstractResourceRepository {
3158
+ constructor(storage) {
3159
+ super(storage);
3160
+ this.actions = {};
3161
+ this._searchService = new ProductProjectionSearch(storage);
3162
+ }
3163
+ getTypeId() {
3164
+ return "product-projection";
3165
+ }
3166
+ create(context, draft) {
3167
+ throw new Error("No valid action");
3168
+ }
3169
+ query(context, params = {}) {
3170
+ return this._storage.query(context.projectKey, "product", {
3171
+ expand: params.expand,
3172
+ where: params.where,
3173
+ offset: params.offset,
3174
+ limit: params.limit
3175
+ });
3176
+ }
3177
+ search(context, query) {
3178
+ const results = this._searchService.search(context.projectKey, {
3179
+ filter: QueryParamsAsArray(query.filter),
3180
+ "filter.query": QueryParamsAsArray(query["filter.query"]),
3181
+ offset: query.offset ? Number(query.offset) : void 0,
3182
+ limit: query.limit ? Number(query.limit) : void 0,
3183
+ expand: QueryParamsAsArray(query.expand)
3184
+ });
3185
+ return results;
3186
+ }
3187
+ };
3188
+
3189
+ // src/services/product-projection.ts
3190
+ var ProductProjectionService = class extends AbstractService {
3191
+ constructor(parent, storage) {
3192
+ super(parent);
3193
+ this.repository = new ProductProjectionRepository(storage);
3194
+ }
3195
+ getBasePath() {
3196
+ return "product-projections";
3197
+ }
3198
+ extraRoutes(router) {
3199
+ router.get("/search", this.search.bind(this));
3200
+ }
3201
+ search(request, response) {
3202
+ const resource = this.repository.search(
3203
+ getRepositoryContext(request),
3204
+ request.query
3205
+ );
3206
+ return response.status(200).send(resource);
3207
+ }
3208
+ };
3209
+
3210
+ // src/repositories/product.ts
3211
+ import { v4 as uuidv47 } from "uuid";
3212
+ var ProductRepository = class extends AbstractResourceRepository {
3213
+ constructor() {
3214
+ super(...arguments);
3215
+ this.actions = {
3216
+ publish: (context, resource, { scope }) => {
3217
+ if (resource.masterData.staged) {
3218
+ resource.masterData.current = resource.masterData.staged;
3219
+ resource.masterData.staged = void 0;
3220
+ }
3221
+ resource.masterData.hasStagedChanges = false;
3222
+ resource.masterData.published = true;
3223
+ },
3224
+ setAttribute: (context, resource, { variantId, sku, name, value, staged }) => {
3225
+ const isStaged = staged !== void 0 ? staged : false;
3226
+ const productData = getProductData(resource, isStaged);
3227
+ const { variant, isMasterVariant, variantIndex } = getVariant(
3228
+ productData,
3229
+ variantId,
3230
+ sku
3231
+ );
3232
+ if (!variant) {
3233
+ throw new Error(
3234
+ `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`
3235
+ );
3236
+ }
3237
+ if (!variant.attributes) {
3238
+ variant.attributes = [];
3239
+ }
3240
+ const existingAttr = variant.attributes.find((attr) => attr.name === name);
3241
+ if (existingAttr) {
3242
+ existingAttr.value = value;
3243
+ } else {
3244
+ variant.attributes.push({
3245
+ name,
3246
+ value
3247
+ });
3248
+ }
3249
+ if (isStaged) {
3250
+ resource.masterData.staged = productData;
3251
+ if (isMasterVariant) {
3252
+ resource.masterData.staged.masterVariant = variant;
3253
+ } else {
3254
+ resource.masterData.staged.variants[variantIndex] = variant;
3255
+ }
3256
+ resource.masterData.hasStagedChanges = true;
3257
+ } else {
3258
+ resource.masterData.current = productData;
3259
+ if (isMasterVariant) {
3260
+ resource.masterData.current.masterVariant = variant;
3261
+ } else {
3262
+ resource.masterData.current.variants[variantIndex] = variant;
3263
+ }
3264
+ }
3265
+ }
3266
+ };
3267
+ }
3268
+ getTypeId() {
3269
+ return "product";
3270
+ }
3271
+ create(context, draft) {
3272
+ var _a;
3273
+ if (!draft.masterVariant) {
3274
+ throw new Error("Missing master variant");
3275
+ }
3276
+ let productType = void 0;
3277
+ try {
3278
+ productType = getReferenceFromResourceIdentifier(
3279
+ draft.productType,
3280
+ context.projectKey,
3281
+ this._storage
3282
+ );
3283
+ } catch (err) {
3284
+ console.warn(
3285
+ `Error resolving product-type '${draft.productType.id}'. This will be throw an error in later releases.`
3286
+ );
3287
+ productType = {
3288
+ typeId: "product-type",
3289
+ id: draft.productType.id || ""
3290
+ };
3291
+ }
3292
+ const productData = {
3293
+ name: draft.name,
3294
+ slug: draft.slug,
3295
+ categories: [],
3296
+ masterVariant: variantFromDraft(1, draft.masterVariant),
3297
+ variants: ((_a = draft.variants) == null ? void 0 : _a.map((variant, index) => {
3298
+ return variantFromDraft(index + 2, variant);
3299
+ })) ?? [],
3300
+ searchKeywords: draft.searchKeywords
3301
+ };
3302
+ const resource = {
3303
+ ...getBaseResourceProperties(),
3304
+ productType,
3305
+ masterData: {
3306
+ current: draft.publish ? productData : void 0,
3307
+ staged: draft.publish ? void 0 : productData,
3308
+ hasStagedChanges: draft.publish ?? true,
3309
+ published: draft.publish ?? false
3310
+ }
3311
+ };
3312
+ this.save(context, resource);
3313
+ return resource;
3314
+ }
3315
+ };
3316
+ var getProductData = (product, staged) => {
3317
+ if (!staged && product.masterData.current) {
3318
+ return product.masterData.current;
3319
+ }
3320
+ return product.masterData.staged;
3321
+ };
3322
+ var getVariant = (productData, variantId, sku) => {
3323
+ const variants = [productData.masterVariant, ...productData.variants];
3324
+ const foundVariant = variants.find((variant) => {
3325
+ if (variantId) {
3326
+ return variant.id === variantId;
3327
+ }
3328
+ if (sku) {
3329
+ return variant.sku === sku;
3330
+ }
3331
+ return false;
3332
+ });
3333
+ const isMasterVariant = foundVariant === productData.masterVariant;
3334
+ return {
3335
+ variant: foundVariant,
3336
+ isMasterVariant,
3337
+ variantIndex: !isMasterVariant && foundVariant ? productData.variants.indexOf(foundVariant) : -1
3338
+ };
3339
+ };
3340
+ var variantFromDraft = (variantId, variant) => {
3341
+ var _a;
3342
+ return {
3343
+ id: variantId,
3344
+ sku: variant == null ? void 0 : variant.sku,
3345
+ attributes: (variant == null ? void 0 : variant.attributes) ?? [],
3346
+ prices: (_a = variant == null ? void 0 : variant.prices) == null ? void 0 : _a.map(priceFromDraft),
3347
+ assets: [],
3348
+ images: []
3349
+ };
3350
+ };
3351
+ var priceFromDraft = (draft) => {
3352
+ return {
3353
+ id: uuidv47(),
3354
+ value: {
3355
+ currencyCode: draft.value.currencyCode,
3356
+ centAmount: draft.value.centAmount,
3357
+ fractionDigits: 2,
3358
+ type: "centPrecision"
3359
+ }
3360
+ };
3361
+ };
3362
+
3363
+ // src/services/product.ts
3364
+ var ProductService = class extends AbstractService {
3365
+ constructor(parent, storage) {
3366
+ super(parent);
3367
+ this.repository = new ProductRepository(storage);
3368
+ }
3369
+ getBasePath() {
3370
+ return "products";
3371
+ }
3372
+ };
3373
+
3374
+ // src/repositories/product-type.ts
3375
+ var ProductTypeRepository = class extends AbstractResourceRepository {
3376
+ constructor() {
3377
+ super(...arguments);
3378
+ this.attributeDefinitionFromAttributeDefinitionDraft = (_context, draft) => {
3379
+ return {
3380
+ ...draft,
3381
+ attributeConstraint: draft.attributeConstraint ?? "None",
3382
+ inputHint: draft.inputHint ?? "SingleLine",
3383
+ inputTip: draft.inputTip && Object.keys(draft.inputTip).length > 0 ? draft.inputTip : void 0,
3384
+ isSearchable: draft.isSearchable ?? true
3385
+ };
3386
+ };
3387
+ this.actions = {
3388
+ changeLocalizedEnumValueLabel: (context, resource, {
3389
+ attributeName,
3390
+ newValue
3391
+ }) => {
3392
+ var _a;
3393
+ const updateAttributeType = (type) => {
3394
+ switch (type.name) {
3395
+ case "lenum":
3396
+ type.values.forEach((v) => {
3397
+ if (v.key === newValue.key) {
3398
+ v.label = newValue.label;
3399
+ }
3400
+ });
3401
+ return;
3402
+ case "set":
3403
+ updateAttributeType(type.elementType);
3404
+ return;
3405
+ }
3406
+ };
3407
+ (_a = resource.attributes) == null ? void 0 : _a.forEach((value) => {
3408
+ if (value.name === attributeName) {
3409
+ updateAttributeType(value.type);
3410
+ }
3411
+ });
3412
+ },
3413
+ changeLabel: (context, resource, { attributeName, label }) => {
3414
+ var _a;
3415
+ (_a = resource.attributes) == null ? void 0 : _a.forEach((value) => {
3416
+ if (value.name === attributeName) {
3417
+ value.label = label;
3418
+ }
3419
+ });
3420
+ },
3421
+ addAttributeDefinition: (context, resource, { attribute }) => {
3422
+ var _a;
3423
+ (_a = resource.attributes) == null ? void 0 : _a.push(
3424
+ this.attributeDefinitionFromAttributeDefinitionDraft(context, attribute)
3425
+ );
3426
+ },
3427
+ changeAttributeOrder: (context, resource, { attributes }) => {
3428
+ var _a;
3429
+ const attrs = new Map((_a = resource.attributes) == null ? void 0 : _a.map((item) => [item.name, item]));
3430
+ const result = [];
3431
+ let current = resource.attributes;
3432
+ attributes.forEach((iAttr) => {
3433
+ const attr = attrs.get(iAttr.name);
3434
+ if (attr === void 0) {
3435
+ throw new Error("New attr");
3436
+ }
3437
+ result.push(attr);
3438
+ current = current == null ? void 0 : current.filter((f) => {
3439
+ return f.name !== iAttr.name;
3440
+ });
3441
+ });
3442
+ resource.attributes = result;
3443
+ if (current) {
3444
+ resource.attributes.push(...current);
3445
+ }
3446
+ },
3447
+ removeAttributeDefinition: (context, resource, { name }) => {
3448
+ var _a;
3449
+ resource.attributes = (_a = resource.attributes) == null ? void 0 : _a.filter((f) => {
3450
+ return f.name !== name;
3451
+ });
3452
+ },
3453
+ removeEnumValues: (context, resource, { attributeName, keys }) => {
3454
+ var _a;
3455
+ (_a = resource.attributes) == null ? void 0 : _a.forEach((attr) => {
3456
+ if (attr.name == attributeName) {
3457
+ if (attr.type.name == "enum") {
3458
+ attr.type.values = attr.type.values.filter((v) => {
3459
+ return !keys.includes(v.key);
3460
+ });
3461
+ }
3462
+ if (attr.type.name == "set") {
3463
+ if (attr.type.elementType.name == "enum") {
3464
+ attr.type.elementType.values = attr.type.elementType.values.filter(
3465
+ (v) => {
3466
+ return !keys.includes(v.key);
3467
+ }
3468
+ );
3469
+ }
3470
+ }
3471
+ }
3472
+ });
3473
+ }
3474
+ };
3475
+ }
3476
+ getTypeId() {
3477
+ return "product-type";
3478
+ }
3479
+ create(context, draft) {
3480
+ const resource = {
3481
+ ...getBaseResourceProperties(),
3482
+ key: draft.key,
3483
+ name: draft.name,
3484
+ description: draft.description,
3485
+ attributes: (draft.attributes ?? []).map(
3486
+ (a) => this.attributeDefinitionFromAttributeDefinitionDraft(context, a)
3487
+ )
3488
+ };
3489
+ this.save(context, resource);
3490
+ return resource;
3491
+ }
3492
+ getWithKey(context, key) {
3493
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
3494
+ where: [`key="${key}"`]
3495
+ });
3496
+ if (result.count === 1) {
3497
+ return result.results[0];
3498
+ }
3499
+ if (result.count > 1) {
3500
+ throw new Error("Duplicate product type key");
3501
+ }
3502
+ return;
3503
+ }
3504
+ };
3505
+
3506
+ // src/services/product-type.ts
3507
+ var ProductTypeService = class extends AbstractService {
3508
+ constructor(parent, storage) {
3509
+ super(parent);
3510
+ this.repository = new ProductTypeRepository(storage);
3511
+ }
3512
+ getBasePath() {
3513
+ return "product-types";
3514
+ }
3515
+ extraRoutes(router) {
3516
+ router.get("/key=:key", this.getWithKey.bind(this));
3517
+ }
3518
+ getWithKey(request, response) {
3519
+ const resource = this.repository.getWithKey(
3520
+ getRepositoryContext(request),
3521
+ request.params.key
3522
+ );
3523
+ if (resource) {
3524
+ return response.status(200).send(resource);
3525
+ }
3526
+ return response.status(404).send("Not found");
3527
+ }
3528
+ };
3529
+
3530
+ // src/lib/masking.ts
3531
+ var maskSecretValue = (resource, path) => {
3532
+ const parts = path.split(".");
3533
+ const clone = JSON.parse(JSON.stringify(resource));
3534
+ let val = clone;
3535
+ const target = parts.pop();
3536
+ for (let i = 0; i < parts.length; i++) {
3537
+ const part = parts[i];
3538
+ val = val[part];
3539
+ if (val === void 0) {
3540
+ return resource;
3541
+ }
3542
+ }
3543
+ if (val && target && val[target]) {
3544
+ val[target] = "****";
3545
+ }
3546
+ return clone;
3547
+ };
3548
+
3549
+ // src/repositories/project.ts
3550
+ var ProjectRepository = class extends AbstractRepository {
3551
+ constructor() {
3552
+ super(...arguments);
3553
+ this.actions = {
3554
+ changeName: (context, resource, { name }) => {
3555
+ resource.name = name;
3556
+ },
3557
+ changeCurrencies: (context, resource, { currencies }) => {
3558
+ resource.currencies = currencies;
3559
+ },
3560
+ changeCountries: (context, resource, { countries }) => {
3561
+ resource.countries = countries;
3562
+ },
3563
+ changeLanguages: (context, resource, { languages }) => {
3564
+ resource.languages = languages;
3565
+ },
3566
+ changeMessagesEnabled: (context, resource, { messagesEnabled }) => {
3567
+ resource.messages.enabled = messagesEnabled;
3568
+ },
3569
+ changeProductSearchIndexingEnabled: (context, resource, { enabled }) => {
3570
+ var _a;
3571
+ if (!((_a = resource.searchIndexing) == null ? void 0 : _a.products)) {
3572
+ throw new Error("Invalid project state");
3573
+ }
3574
+ resource.searchIndexing.products.status = enabled ? "Activated" : "Deactivated";
3575
+ resource.searchIndexing.products.lastModifiedAt = new Date().toISOString();
3576
+ },
3577
+ changeOrderSearchStatus: (context, resource, { status }) => {
3578
+ var _a;
3579
+ if (!((_a = resource.searchIndexing) == null ? void 0 : _a.orders)) {
3580
+ throw new Error("Invalid project state");
3581
+ }
3582
+ resource.searchIndexing.orders.status = status;
3583
+ resource.searchIndexing.orders.lastModifiedAt = new Date().toISOString();
3584
+ },
3585
+ setShippingRateInputType: (context, resource, { shippingRateInputType }) => {
3586
+ resource.shippingRateInputType = shippingRateInputType;
3587
+ },
3588
+ setExternalOAuth: (context, resource, { externalOAuth }) => {
3589
+ resource.externalOAuth = externalOAuth;
3590
+ },
3591
+ changeCountryTaxRateFallbackEnabled: (context, resource, {
3592
+ countryTaxRateFallbackEnabled
3593
+ }) => {
3594
+ resource.carts.countryTaxRateFallbackEnabled = countryTaxRateFallbackEnabled;
3595
+ },
3596
+ changeCartsConfiguration: (context, resource, { cartsConfiguration }) => {
3597
+ resource.carts = cartsConfiguration || {
3598
+ countryTaxRateFallbackEnabled: false,
3599
+ deleteDaysAfterLastModification: 90
3600
+ };
3601
+ }
3602
+ };
3603
+ }
3604
+ get(context) {
3605
+ const resource = this._storage.getProject(context.projectKey);
3606
+ const masked = maskSecretValue(
3607
+ resource,
3608
+ "externalOAuth.authorizationHeader"
3609
+ );
3610
+ return masked;
3611
+ }
3612
+ save(context, resource) {
3613
+ const current = this.get(context);
3614
+ if (current) {
3615
+ checkConcurrentModification(current, resource.version);
3616
+ } else {
3617
+ if (resource.version !== 0) {
3618
+ throw new CommercetoolsError(
3619
+ {
3620
+ code: "InvalidOperation",
3621
+ message: "version on create must be 0"
3622
+ },
3623
+ 400
3624
+ );
3625
+ }
3626
+ }
3627
+ resource.version += 1;
3628
+ this._storage.saveProject(resource);
3629
+ }
3630
+ };
3631
+
3632
+ // src/services/project.ts
3633
+ var ProjectService = class {
3634
+ constructor(parent, storage) {
3635
+ this.repository = new ProjectRepository(storage);
3636
+ this.registerRoutes(parent);
3637
+ }
3638
+ registerRoutes(parent) {
3639
+ parent.get("", this.get.bind(this));
3640
+ parent.post("", this.post.bind(this));
3641
+ }
3642
+ get(request, response) {
3643
+ const project = this.repository.get(getRepositoryContext(request));
3644
+ return response.status(200).send(project);
3645
+ }
3646
+ post(request, response) {
3647
+ const updateRequest = request.body;
3648
+ const project = this.repository.get(getRepositoryContext(request));
3649
+ if (!project) {
3650
+ return response.status(404).send({});
3651
+ }
3652
+ this.repository.processUpdateActions(
3653
+ getRepositoryContext(request),
3654
+ project,
3655
+ updateRequest.actions
3656
+ );
3657
+ return response.status(200).send({});
3658
+ }
3659
+ };
3660
+
3661
+ // src/repositories/shipping-method.ts
3662
+ import deepEqual2 from "deep-equal";
3663
+ var ShippingMethodRepository = class extends AbstractResourceRepository {
3664
+ constructor() {
3665
+ super(...arguments);
3666
+ this._transformZoneRateDraft = (context, draft) => {
3667
+ var _a;
3668
+ return {
3669
+ ...draft,
3670
+ zone: getReferenceFromResourceIdentifier(
3671
+ draft.zone,
3672
+ context.projectKey,
3673
+ this._storage
3674
+ ),
3675
+ shippingRates: (_a = draft.shippingRates) == null ? void 0 : _a.map(this._transformShippingRate)
3676
+ };
3677
+ };
3678
+ this._transformShippingRate = (rate) => {
3679
+ return {
3680
+ price: createTypedMoney(rate.price),
3681
+ freeAbove: rate.freeAbove && createTypedMoney(rate.freeAbove),
3682
+ tiers: rate.tiers || []
3683
+ };
3684
+ };
3685
+ this.actions = {
3686
+ addShippingRate: (_context, resource, { shippingRate, zone }) => {
3687
+ const rate = this._transformShippingRate(shippingRate);
3688
+ resource.zoneRates.forEach((zoneRate) => {
3689
+ if (zoneRate.zone.id === zone.id) {
3690
+ zoneRate.shippingRates.push(rate);
3691
+ return;
3692
+ }
3693
+ });
3694
+ resource.zoneRates.push({
3695
+ zone: {
3696
+ typeId: "zone",
3697
+ id: zone.id
3698
+ },
3699
+ shippingRates: [rate]
3700
+ });
3701
+ },
3702
+ removeShippingRate: (_context, resource, { shippingRate, zone }) => {
3703
+ const rate = this._transformShippingRate(shippingRate);
3704
+ resource.zoneRates.forEach((zoneRate) => {
3705
+ if (zoneRate.zone.id === zone.id) {
3706
+ zoneRate.shippingRates = zoneRate.shippingRates.filter((otherRate) => {
3707
+ return !deepEqual2(rate, otherRate);
3708
+ });
3709
+ }
3710
+ });
3711
+ },
3712
+ addZone: (context, resource, { zone }) => {
3713
+ const zoneReference = getReferenceFromResourceIdentifier(
3714
+ zone,
3715
+ context.projectKey,
3716
+ this._storage
3717
+ );
3718
+ if (resource.zoneRates === void 0) {
3719
+ resource.zoneRates = [];
3720
+ }
3721
+ resource.zoneRates.push({
3722
+ zone: zoneReference,
3723
+ shippingRates: []
3724
+ });
3725
+ },
3726
+ removeZone: (_context, resource, { zone }) => {
3727
+ resource.zoneRates = resource.zoneRates.filter((zoneRate) => {
3728
+ return zoneRate.zone.id !== zone.id;
3729
+ });
3730
+ },
3731
+ setKey: (_context, resource, { key }) => {
3732
+ resource.key = key;
3733
+ },
3734
+ setDescription: (_context, resource, { description }) => {
3735
+ resource.description = description;
3736
+ },
3737
+ setLocalizedDescription: (_context, resource, { localizedDescription }) => {
3738
+ resource.localizedDescription = localizedDescription;
3739
+ },
3740
+ setPredicate: (_context, resource, { predicate }) => {
3741
+ resource.predicate = predicate;
3742
+ },
3743
+ changeIsDefault: (_context, resource, { isDefault }) => {
3744
+ resource.isDefault = isDefault;
3745
+ },
3746
+ changeName: (_context, resource, { name }) => {
3747
+ resource.name = name;
3748
+ },
3749
+ setCustomType: (context, resource, { type, fields }) => {
3750
+ if (type) {
3751
+ resource.custom = createCustomFields(
3752
+ { type, fields },
3753
+ context.projectKey,
3754
+ this._storage
3755
+ );
3756
+ } else {
3757
+ resource.custom = void 0;
3758
+ }
3759
+ },
3760
+ setCustomField: (context, resource, { name, value }) => {
3761
+ if (!resource.custom) {
3762
+ return;
3763
+ }
3764
+ if (value === null) {
3765
+ delete resource.custom.fields[name];
3766
+ } else {
3767
+ resource.custom.fields[name] = value;
3768
+ }
3769
+ }
3770
+ };
3771
+ }
3772
+ getTypeId() {
3773
+ return "shipping-method";
3774
+ }
3775
+ create(context, draft) {
3776
+ var _a;
3777
+ const resource = {
3778
+ ...getBaseResourceProperties(),
3779
+ ...draft,
3780
+ taxCategory: getReferenceFromResourceIdentifier(
3781
+ draft.taxCategory,
3782
+ context.projectKey,
3783
+ this._storage
3784
+ ),
3785
+ zoneRates: (_a = draft.zoneRates) == null ? void 0 : _a.map(
3786
+ (z) => this._transformZoneRateDraft(context, z)
3787
+ ),
3788
+ custom: createCustomFields(
3789
+ draft.custom,
3790
+ context.projectKey,
3791
+ this._storage
3792
+ )
3793
+ };
3794
+ this.save(context, resource);
3795
+ return resource;
3796
+ }
3797
+ };
3798
+
3799
+ // src/services/shipping-method.ts
3800
+ var ShippingMethodService = class extends AbstractService {
3801
+ constructor(parent, storage) {
3802
+ super(parent);
3803
+ this.repository = new ShippingMethodRepository(storage);
3804
+ this.registerRoutes(parent);
3805
+ }
3806
+ getBasePath() {
3807
+ return "shipping-methods";
3808
+ }
3809
+ extraRoutes(parent) {
3810
+ parent.get("/matching-cart", this.get.bind(this));
3811
+ }
3812
+ };
3813
+
3814
+ // src/repositories/shopping-list.ts
3815
+ var ShoppingListRepository = class extends AbstractResourceRepository {
3816
+ getTypeId() {
3817
+ return "shopping-list";
3818
+ }
3819
+ create(context, draft) {
3820
+ var _a, _b;
3821
+ const resource = {
3822
+ ...getBaseResourceProperties(),
3823
+ ...draft,
3824
+ custom: createCustomFields(
3825
+ draft.custom,
3826
+ context.projectKey,
3827
+ this._storage
3828
+ ),
3829
+ textLineItems: [],
3830
+ lineItems: (_a = draft.lineItems) == null ? void 0 : _a.map((e) => ({
3831
+ ...getBaseResourceProperties(),
3832
+ ...e,
3833
+ addedAt: e.addedAt ?? "",
3834
+ productId: e.productId ?? "",
3835
+ name: {},
3836
+ quantity: e.quantity ?? 1,
3837
+ productType: { typeId: "product-type", id: "" },
3838
+ custom: createCustomFields(e.custom, context.projectKey, this._storage)
3839
+ })),
3840
+ customer: draft.customer ? getReferenceFromResourceIdentifier(
3841
+ draft.customer,
3842
+ context.projectKey,
3843
+ this._storage
3844
+ ) : void 0,
3845
+ store: ((_b = draft.store) == null ? void 0 : _b.key) ? { typeId: "store", key: draft.store.key } : void 0
3846
+ };
3847
+ this.save(context, resource);
3848
+ return resource;
3849
+ }
3850
+ };
3851
+
3852
+ // src/services/shopping-list.ts
3853
+ var ShoppingListService = class extends AbstractService {
3854
+ constructor(parent, storage) {
3855
+ super(parent);
3856
+ this.repository = new ShoppingListRepository(storage);
3857
+ }
3858
+ getBasePath() {
3859
+ return "shopping-lists";
3860
+ }
3861
+ };
3862
+
3863
+ // src/repositories/state.ts
3864
+ var StateRepository = class extends AbstractResourceRepository {
3865
+ constructor() {
3866
+ super(...arguments);
3867
+ this.actions = {
3868
+ changeKey: (context, resource, { key }) => {
3869
+ resource.key = key;
3870
+ },
3871
+ setDescription: (context, resource, { description }) => {
3872
+ resource.description = description;
3873
+ },
3874
+ setName: (context, resource, { name }) => {
3875
+ resource.name = name;
3876
+ },
3877
+ setRoles: (context, resource, { roles }) => {
3878
+ resource.roles = roles;
3879
+ }
3880
+ };
3881
+ }
3882
+ getTypeId() {
3883
+ return "state";
3884
+ }
3885
+ create(context, draft) {
3886
+ const resource = {
3887
+ ...getBaseResourceProperties(),
3888
+ ...draft,
3889
+ builtIn: false,
3890
+ initial: draft.initial || false,
3891
+ transitions: (draft.transitions || []).map(
3892
+ (t) => getReferenceFromResourceIdentifier(t, context.projectKey, this._storage)
3893
+ )
3894
+ };
3895
+ this.save(context, resource);
3896
+ return resource;
3897
+ }
3898
+ };
3899
+
3900
+ // src/services/state.ts
3901
+ var StateService = class extends AbstractService {
3902
+ constructor(parent, storage) {
3903
+ super(parent);
3904
+ this.repository = new StateRepository(storage);
3905
+ }
3906
+ getBasePath() {
3907
+ return "states";
3908
+ }
3909
+ };
3910
+
3911
+ // src/repositories/store.ts
3912
+ var StoreRepository = class extends AbstractResourceRepository {
3913
+ constructor() {
3914
+ super(...arguments);
3915
+ this.actions = {
3916
+ setName: (context, resource, { name }) => {
3917
+ resource.name = name;
3918
+ },
3919
+ setDistributionChannels: (context, resource, { distributionChannels }) => {
3920
+ resource.distributionChannels = this.transformChannels(
3921
+ context,
3922
+ distributionChannels
3923
+ );
3924
+ },
3925
+ setLanguages: (context, resource, { languages }) => {
3926
+ resource.languages = languages ?? [];
3927
+ },
3928
+ setCustomType: (context, resource, { type, fields }) => {
3929
+ if (type) {
3930
+ resource.custom = createCustomFields(
3931
+ { type, fields },
3932
+ context.projectKey,
3933
+ this._storage
3934
+ );
3935
+ } else {
3936
+ resource.custom = void 0;
3937
+ }
3938
+ },
3939
+ setCustomField: (context, resource, { name, value }) => {
3940
+ if (!resource.custom) {
3941
+ return;
3942
+ }
3943
+ if (value === null) {
3944
+ delete resource.custom.fields[name];
3945
+ } else {
3946
+ resource.custom.fields[name] = value;
3947
+ }
3948
+ }
3949
+ };
3950
+ }
3951
+ getTypeId() {
3952
+ return "store";
3953
+ }
3954
+ create(context, draft) {
3955
+ const resource = {
3956
+ ...getBaseResourceProperties(),
3957
+ key: draft.key,
3958
+ name: draft.name,
3959
+ languages: draft.languages ?? [],
3960
+ distributionChannels: this.transformChannels(
3961
+ context,
3962
+ draft.distributionChannels
3963
+ ),
3964
+ supplyChannels: this.transformChannels(context, draft.supplyChannels),
3965
+ productSelections: [],
3966
+ custom: createCustomFields(
3967
+ draft.custom,
3968
+ context.projectKey,
3969
+ this._storage
3970
+ )
3971
+ };
3972
+ this.save(context, resource);
3973
+ return resource;
3974
+ }
3975
+ transformChannels(context, channels) {
3976
+ if (!channels)
3977
+ return [];
3978
+ return channels.map(
3979
+ (ref) => getReferenceFromResourceIdentifier(
3980
+ ref,
3981
+ context.projectKey,
3982
+ this._storage
3983
+ )
3984
+ );
3985
+ }
3986
+ getWithKey(context, key) {
3987
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
3988
+ where: [`key="${key}"`]
3989
+ });
3990
+ if (result.count === 1) {
3991
+ return result.results[0];
3992
+ }
3993
+ if (result.count > 1) {
3994
+ throw new Error("Duplicate store key");
3995
+ }
3996
+ return;
3997
+ }
3998
+ };
3999
+
4000
+ // src/services/store.ts
4001
+ var StoreService = class extends AbstractService {
4002
+ constructor(parent, storage) {
4003
+ super(parent);
4004
+ this.repository = new StoreRepository(storage);
4005
+ }
4006
+ getBasePath() {
4007
+ return "stores";
4008
+ }
4009
+ extraRoutes(router) {
4010
+ router.get("/key=:key", this.getWithKey.bind(this));
4011
+ }
4012
+ getWithKey(request, response) {
4013
+ const resource = this.repository.getWithKey(
4014
+ getRepositoryContext(request),
4015
+ request.params.key
4016
+ );
4017
+ if (resource) {
4018
+ return response.status(200).send(resource);
4019
+ }
4020
+ return response.status(404).send("Not found");
4021
+ }
4022
+ };
4023
+
4024
+ // src/repositories/subscription.ts
4025
+ var SubscriptionRepository = class extends AbstractResourceRepository {
4026
+ getTypeId() {
4027
+ return "subscription";
4028
+ }
4029
+ create(context, draft) {
4030
+ if (draft.destination.type === "SQS") {
4031
+ const queueURL = new URL(draft.destination.queueUrl);
4032
+ const accountId = queueURL.pathname.split("/")[1];
4033
+ if (accountId === "0000000000") {
4034
+ const dest = draft.destination;
4035
+ throw new CommercetoolsError(
4036
+ {
4037
+ code: "InvalidInput",
4038
+ message: `A test message could not be delivered to this destination: SQS ${dest.queueUrl} in ${dest.region} for ${dest.accessKey}. Please make sure your destination is correctly configured.`
4039
+ },
4040
+ 400
4041
+ );
4042
+ }
4043
+ }
4044
+ const resource = {
4045
+ ...getBaseResourceProperties(),
4046
+ changes: draft.changes || [],
4047
+ destination: draft.destination,
4048
+ format: draft.format || {
4049
+ type: "Platform"
4050
+ },
4051
+ key: draft.key,
4052
+ messages: draft.messages || [],
4053
+ status: "Healthy"
4054
+ };
4055
+ this.save(context, resource);
4056
+ return resource;
4057
+ }
4058
+ };
4059
+
4060
+ // src/services/subscription.ts
4061
+ var SubscriptionService = class extends AbstractService {
4062
+ constructor(parent, storage) {
4063
+ super(parent);
4064
+ this.repository = new SubscriptionRepository(storage);
4065
+ }
4066
+ getBasePath() {
4067
+ return "subscriptions";
4068
+ }
4069
+ };
4070
+
4071
+ // src/repositories/tax-category.ts
4072
+ import { v4 as uuidv48 } from "uuid";
4073
+ var TaxCategoryRepository = class extends AbstractResourceRepository {
4074
+ constructor() {
4075
+ super(...arguments);
4076
+ this.taxRateFromTaxRateDraft = (draft) => ({
4077
+ ...draft,
4078
+ id: uuidv48(),
4079
+ amount: draft.amount || 0
4080
+ });
4081
+ this.actions = {
4082
+ addTaxRate: (context, resource, { taxRate }) => {
4083
+ if (resource.rates === void 0) {
4084
+ resource.rates = [];
4085
+ }
4086
+ resource.rates.push(this.taxRateFromTaxRateDraft(taxRate));
4087
+ },
4088
+ removeTaxRate: (context, resource, { taxRateId }) => {
4089
+ if (resource.rates === void 0) {
4090
+ resource.rates = [];
4091
+ }
4092
+ resource.rates = resource.rates.filter((taxRate) => {
4093
+ return taxRate.id !== taxRateId;
4094
+ });
4095
+ },
4096
+ replaceTaxRate: (context, resource, { taxRateId, taxRate }) => {
4097
+ if (resource.rates === void 0) {
4098
+ resource.rates = [];
4099
+ }
4100
+ const taxRateObj = this.taxRateFromTaxRateDraft(taxRate);
4101
+ for (let i = 0; i < resource.rates.length; i++) {
4102
+ const rate = resource.rates[i];
4103
+ if (rate.id === taxRateId) {
4104
+ resource.rates[i] = taxRateObj;
4105
+ }
4106
+ }
4107
+ },
4108
+ setDescription: (context, resource, { description }) => {
4109
+ resource.description = description;
4110
+ },
4111
+ setKey: (context, resource, { key }) => {
4112
+ resource.key = key;
4113
+ },
4114
+ changeName: (context, resource, { name }) => {
4115
+ resource.name = name;
4116
+ }
4117
+ };
4118
+ }
4119
+ getTypeId() {
4120
+ return "tax-category";
4121
+ }
4122
+ create(context, draft) {
4123
+ var _a;
4124
+ const resource = {
4125
+ ...getBaseResourceProperties(),
4126
+ ...draft,
4127
+ rates: ((_a = draft.rates) == null ? void 0 : _a.map(this.taxRateFromTaxRateDraft)) || []
4128
+ };
4129
+ this.save(context, resource);
4130
+ return resource;
4131
+ }
4132
+ getWithKey(context, key) {
4133
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
4134
+ where: [`key="${key}"`]
4135
+ });
4136
+ if (result.count === 1) {
4137
+ return result.results[0];
4138
+ }
4139
+ if (result.count > 1) {
4140
+ throw new Error("Duplicate tax category key");
4141
+ }
4142
+ return;
4143
+ }
4144
+ };
4145
+
4146
+ // src/services/tax-category.ts
4147
+ var TaxCategoryService = class extends AbstractService {
4148
+ constructor(parent, storage) {
4149
+ super(parent);
4150
+ this.repository = new TaxCategoryRepository(storage);
4151
+ }
4152
+ getBasePath() {
4153
+ return "tax-categories";
4154
+ }
4155
+ extraRoutes(router) {
4156
+ router.get("/key=:key", this.getWithKey.bind(this));
4157
+ }
4158
+ getWithKey(request, response) {
4159
+ const resource = this.repository.getWithKey(
4160
+ getRepositoryContext(request),
4161
+ request.params.key
4162
+ );
4163
+ if (resource) {
4164
+ return response.status(200).send(resource);
4165
+ }
4166
+ return response.status(404).send("Not found");
4167
+ }
4168
+ };
4169
+
4170
+ // src/repositories/type.ts
4171
+ import { isEqual } from "lodash";
4172
+ var TypeRepository = class extends AbstractResourceRepository {
4173
+ constructor() {
4174
+ super(...arguments);
4175
+ this.actions = {
4176
+ addFieldDefinition: (context, resource, { fieldDefinition }) => {
4177
+ resource.fieldDefinitions.push(fieldDefinition);
4178
+ },
4179
+ removeFieldDefinition: (context, resource, { fieldName }) => {
4180
+ resource.fieldDefinitions = resource.fieldDefinitions.filter((f) => {
4181
+ return f.name !== fieldName;
4182
+ });
4183
+ },
4184
+ setDescription: (context, resource, { description }) => {
4185
+ resource.description = description;
4186
+ },
4187
+ changeName: (context, resource, { name }) => {
4188
+ resource.name = name;
4189
+ },
4190
+ changeFieldDefinitionOrder: (context, resource, { fieldNames }) => {
4191
+ const fields = new Map(
4192
+ resource.fieldDefinitions.map((item) => [item.name, item])
4193
+ );
4194
+ const result = [];
4195
+ let current = resource.fieldDefinitions;
4196
+ fieldNames.forEach((fieldName) => {
4197
+ const field = fields.get(fieldName);
4198
+ if (field === void 0) {
4199
+ throw new Error("New field");
4200
+ }
4201
+ result.push(field);
4202
+ current = current.filter((f) => {
4203
+ return f.name !== fieldName;
4204
+ });
4205
+ });
4206
+ if (isEqual(
4207
+ fieldNames,
4208
+ resource.fieldDefinitions.map((item) => item.name)
4209
+ )) {
4210
+ throw new CommercetoolsError({
4211
+ code: "InvalidOperation",
4212
+ message: "'fieldDefinitions' has no changes.",
4213
+ action: {
4214
+ action: "changeFieldDefinitionOrder",
4215
+ fieldNames
4216
+ }
4217
+ });
4218
+ }
4219
+ resource.fieldDefinitions = result;
4220
+ resource.fieldDefinitions.push(...current);
4221
+ },
4222
+ addEnumValue: (context, resource, { fieldName, value }) => {
4223
+ resource.fieldDefinitions.forEach((field) => {
4224
+ if (field.name === fieldName) {
4225
+ if (field.type.name === "Enum") {
4226
+ field.type.values.push(value);
4227
+ } else if (field.type.name === "Set" && field.type.elementType.name === "Enum") {
4228
+ field.type.elementType.values.push(value);
4229
+ } else {
4230
+ throw new Error("Type is not a Enum (or Set of Enum)");
4231
+ }
4232
+ }
4233
+ });
4234
+ },
4235
+ changeEnumValueLabel: (context, resource, { fieldName, value }) => {
4236
+ resource.fieldDefinitions.forEach((field) => {
4237
+ if (field.name === fieldName) {
4238
+ if (field.type.name === "Enum") {
4239
+ field.type.values.forEach((v) => {
4240
+ if (v.key === value.key) {
4241
+ v.label = value.label;
4242
+ }
4243
+ });
4244
+ } else if (field.type.name === "Set" && field.type.elementType.name === "Enum") {
4245
+ field.type.elementType.values.forEach((v) => {
4246
+ if (v.key === value.key) {
4247
+ v.label = value.label;
4248
+ }
4249
+ });
4250
+ } else {
4251
+ throw new Error("Type is not a Enum (or Set of Enum)");
4252
+ }
4253
+ }
4254
+ });
4255
+ }
4256
+ };
4257
+ }
4258
+ getTypeId() {
4259
+ return "type";
4260
+ }
4261
+ create(context, draft) {
4262
+ const resource = {
4263
+ ...getBaseResourceProperties(),
4264
+ key: draft.key,
4265
+ name: draft.name,
4266
+ resourceTypeIds: draft.resourceTypeIds,
4267
+ fieldDefinitions: draft.fieldDefinitions || [],
4268
+ description: draft.description
4269
+ };
4270
+ this.save(context, resource);
4271
+ return resource;
4272
+ }
4273
+ };
4274
+
4275
+ // src/services/type.ts
4276
+ var TypeService = class extends AbstractService {
4277
+ constructor(parent, storage) {
4278
+ super(parent);
4279
+ this.repository = new TypeRepository(storage);
4280
+ }
4281
+ getBasePath() {
4282
+ return "types";
4283
+ }
4284
+ };
4285
+
4286
+ // src/repositories/zone.ts
4287
+ var ZoneRepository = class extends AbstractResourceRepository {
4288
+ constructor() {
4289
+ super(...arguments);
4290
+ this.actions = {
4291
+ addLocation: (context, resource, { location }) => {
4292
+ resource.locations.push(location);
4293
+ },
4294
+ removeLocation: (context, resource, { location }) => {
4295
+ resource.locations = resource.locations.filter((loc) => {
4296
+ return !(loc.country === location.country && loc.state === location.state);
4297
+ });
4298
+ },
4299
+ changeName: (context, resource, { name }) => {
4300
+ resource.name = name;
4301
+ },
4302
+ setDescription: (context, resource, { description }) => {
4303
+ resource.description = description;
4304
+ },
4305
+ setKey: (context, resource, { key }) => {
4306
+ resource.key = key;
4307
+ }
4308
+ };
4309
+ }
4310
+ getTypeId() {
4311
+ return "zone";
4312
+ }
4313
+ create(context, draft) {
4314
+ const resource = {
4315
+ ...getBaseResourceProperties(),
4316
+ key: draft.key,
4317
+ locations: draft.locations || [],
4318
+ name: draft.name,
4319
+ description: draft.description
4320
+ };
4321
+ this.save(context, resource);
4322
+ return resource;
4323
+ }
4324
+ };
4325
+
4326
+ // src/services/zone.ts
4327
+ var ZoneService = class extends AbstractService {
4328
+ constructor(parent, storage) {
4329
+ super(parent);
4330
+ this.repository = new ZoneRepository(storage);
4331
+ }
4332
+ getBasePath() {
4333
+ return "zones";
4334
+ }
4335
+ };
4336
+
4337
+ // src/services/my-customer.ts
4338
+ import { Router as Router3 } from "express";
4339
+ var MyCustomerService = class extends AbstractService {
4340
+ constructor(parent, storage) {
4341
+ super(parent);
4342
+ this.repository = new CustomerRepository(storage);
4343
+ }
4344
+ getBasePath() {
4345
+ return "me";
4346
+ }
4347
+ registerRoutes(parent) {
4348
+ const basePath = this.getBasePath();
4349
+ const router = Router3({ mergeParams: true });
4350
+ this.extraRoutes(router);
4351
+ router.get("", this.getMe.bind(this));
4352
+ router.post("/signup", this.signUp.bind(this));
4353
+ router.post("/login", this.signIn.bind(this));
4354
+ parent.use(`/${basePath}`, router);
4355
+ }
4356
+ getMe(request, response) {
4357
+ const resource = this.repository.getMe(getRepositoryContext(request));
4358
+ if (!resource) {
4359
+ return response.status(404).send("Not found");
4360
+ }
4361
+ return response.status(200).send(resource);
4362
+ }
4363
+ signUp(request, response) {
4364
+ const draft = request.body;
4365
+ const resource = this.repository.create(
4366
+ getRepositoryContext(request),
4367
+ draft
4368
+ );
4369
+ const result = this._expandWithId(request, resource.id);
4370
+ return response.status(this.createStatusCode).send({ customer: result });
4371
+ }
4372
+ signIn(request, response) {
4373
+ const { email, password } = request.body;
4374
+ const encodedPassword = Buffer.from(password).toString("base64");
4375
+ const result = this.repository.query(getRepositoryContext(request), {
4376
+ where: [`email = "${email}"`, `password = "${encodedPassword}"`]
4377
+ });
4378
+ if (result.count === 0) {
4379
+ return response.status(400).send({
4380
+ message: "Account with the given credentials not found.",
4381
+ errors: [
4382
+ {
4383
+ code: "InvalidCredentials",
4384
+ message: "Account with the given credentials not found."
4385
+ }
4386
+ ]
4387
+ });
4388
+ }
4389
+ return response.status(200).send({ customer: result.results[0] });
4390
+ }
4391
+ };
4392
+
4393
+ // src/services/my-order.ts
4394
+ import { Router as Router4 } from "express";
4395
+
4396
+ // src/repositories/my-order.ts
4397
+ import assert3 from "assert";
4398
+ var MyOrderRepository = class extends OrderRepository {
4399
+ create(context, draft) {
4400
+ assert3(draft.id, "draft.id is missing");
4401
+ const cartIdentifier = {
4402
+ id: draft.id,
4403
+ typeId: "cart"
4404
+ };
4405
+ return this.createFromCart(context, cartIdentifier);
4406
+ }
4407
+ };
4408
+
4409
+ // src/services/my-order.ts
4410
+ var MyOrderService = class extends AbstractService {
4411
+ constructor(parent, storage) {
4412
+ super(parent);
4413
+ this.repository = new MyOrderRepository(storage);
4414
+ }
4415
+ getBasePath() {
4416
+ return "me";
4417
+ }
4418
+ registerRoutes(parent) {
4419
+ const basePath = this.getBasePath();
4420
+ const router = Router4({ mergeParams: true });
4421
+ this.extraRoutes(router);
4422
+ router.get("/orders/", this.get.bind(this));
4423
+ router.get("/orders/:id", this.getWithId.bind(this));
4424
+ router.delete("/orders/:id", this.deletewithId.bind(this));
4425
+ router.post("/orders/", this.post.bind(this));
4426
+ router.post("/orders/:id", this.postWithId.bind(this));
4427
+ parent.use(`/${basePath}`, router);
4428
+ }
4429
+ };
4430
+
4431
+ // src/ctMock.ts
4432
+ var DEFAULT_OPTIONS = {
4433
+ enableAuthentication: false,
4434
+ validateCredentials: false,
4435
+ defaultProjectKey: void 0,
4436
+ apiHost: DEFAULT_API_HOSTNAME,
4437
+ authHost: DEFAULT_AUTH_HOSTNAME,
4438
+ silent: false
4439
+ };
4440
+ var CommercetoolsMock = class {
4441
+ constructor(options = {}) {
4442
+ this._nockScopes = { auth: void 0, api: void 0 };
4443
+ this.options = { ...DEFAULT_OPTIONS, ...options };
4444
+ this._services = {};
4445
+ this._projectService = void 0;
4446
+ this._storage = new InMemoryStorage();
4447
+ this._oauth2 = new OAuth2Server({
4448
+ enabled: this.options.enableAuthentication,
4449
+ validate: this.options.validateCredentials
4450
+ });
4451
+ this.app = this.createApp({ silent: this.options.silent });
4452
+ }
4453
+ start() {
4454
+ this.mockAuthHost();
4455
+ this.mockApiHost();
4456
+ }
4457
+ stop() {
4458
+ var _a, _b;
4459
+ (_a = this._nockScopes.auth) == null ? void 0 : _a.persist(false);
4460
+ this._nockScopes.auth = void 0;
4461
+ (_b = this._nockScopes.api) == null ? void 0 : _b.persist(false);
4462
+ this._nockScopes.api = void 0;
4463
+ }
4464
+ clear() {
4465
+ this._storage.clear();
4466
+ }
4467
+ project(projectKey) {
4468
+ if (!projectKey && !this.options.defaultProjectKey) {
4469
+ throw new Error("No projectKey passed and no default set");
4470
+ }
4471
+ return new ProjectAPI(
4472
+ projectKey || this.options.defaultProjectKey,
4473
+ this._services,
4474
+ this._storage
4475
+ );
4476
+ }
4477
+ runServer(port = 3e3, options) {
4478
+ const app = this.createApp(options);
4479
+ const server = app.listen(port, () => {
4480
+ console.log(`Mock server listening at http://localhost:${port}`);
4481
+ });
4482
+ server.keepAliveTimeout = 60 * 1e3;
4483
+ }
4484
+ createApp(options) {
4485
+ const app = express2();
4486
+ const projectRouter = express2.Router({ mergeParams: true });
4487
+ projectRouter.use(express2.json());
4488
+ if (!(options == null ? void 0 : options.silent)) {
4489
+ app.use(morgan("tiny"));
4490
+ }
4491
+ app.use("/oauth", this._oauth2.createRouter());
4492
+ if (this.options.enableAuthentication) {
4493
+ app.use("/:projectKey", this._oauth2.createMiddleware(), projectRouter);
4494
+ app.use(
4495
+ "/:projectKey/in-store/key=:storeKey",
4496
+ this._oauth2.createMiddleware(),
4497
+ projectRouter
4498
+ );
4499
+ } else {
4500
+ app.use("/:projectKey", projectRouter);
4501
+ app.use("/:projectKey/in-store/key=:storeKey", projectRouter);
4502
+ }
4503
+ this._projectService = new ProjectService(projectRouter, this._storage);
4504
+ this._services = {
4505
+ category: new CategoryServices(projectRouter, this._storage),
4506
+ cart: new CartService(projectRouter, this._storage),
4507
+ "cart-discount": new CartDiscountService(projectRouter, this._storage),
4508
+ customer: new CustomerService(projectRouter, this._storage),
4509
+ channel: new ChannelService(projectRouter, this._storage),
4510
+ "customer-group": new CustomerGroupService(projectRouter, this._storage),
4511
+ "discount-code": new DiscountCodeService(projectRouter, this._storage),
4512
+ extension: new ExtensionServices(projectRouter, this._storage),
4513
+ "inventory-entry": new InventoryEntryService(
4514
+ projectRouter,
4515
+ this._storage
4516
+ ),
4517
+ "key-value-document": new CustomObjectService(
4518
+ projectRouter,
4519
+ this._storage
4520
+ ),
4521
+ order: new OrderService(projectRouter, this._storage),
4522
+ payment: new PaymentService(projectRouter, this._storage),
4523
+ "my-cart": new MyCartService(projectRouter, this._storage),
4524
+ "my-order": new MyOrderService(projectRouter, this._storage),
4525
+ "my-customer": new MyCustomerService(projectRouter, this._storage),
4526
+ "my-payment": new MyPaymentService(projectRouter, this._storage),
4527
+ "shipping-method": new ShippingMethodService(
4528
+ projectRouter,
4529
+ this._storage
4530
+ ),
4531
+ "product-type": new ProductTypeService(projectRouter, this._storage),
4532
+ product: new ProductService(projectRouter, this._storage),
4533
+ "product-discount": new ProductDiscountService(
4534
+ projectRouter,
4535
+ this._storage
4536
+ ),
4537
+ "product-projection": new ProductProjectionService(
4538
+ projectRouter,
4539
+ this._storage
4540
+ ),
4541
+ "shopping-list": new ShoppingListService(projectRouter, this._storage),
4542
+ state: new StateService(projectRouter, this._storage),
4543
+ store: new StoreService(projectRouter, this._storage),
4544
+ subscription: new SubscriptionService(projectRouter, this._storage),
4545
+ "tax-category": new TaxCategoryService(projectRouter, this._storage),
4546
+ type: new TypeService(projectRouter, this._storage),
4547
+ zone: new ZoneService(projectRouter, this._storage)
4548
+ };
4549
+ app.use((err, req, resp, next) => {
4550
+ if (err instanceof CommercetoolsError) {
4551
+ return resp.status(err.statusCode).send({
4552
+ statusCode: err.statusCode,
4553
+ message: err.message,
4554
+ errors: [err.info]
4555
+ });
4556
+ } else {
4557
+ console.error(err);
4558
+ return resp.status(500).send({
4559
+ error: err.message
4560
+ });
4561
+ }
4562
+ });
4563
+ return app;
4564
+ }
4565
+ mockApiHost() {
4566
+ const app = this.app;
4567
+ this._nockScopes.api = nock(this.options.apiHost).persist().get(/.*/).reply(async function(uri) {
4568
+ const response = await supertest(app).get(uri).set(copyHeaders(this.req.headers));
4569
+ return [response.status, response.body];
4570
+ }).post(/.*/).reply(async function(uri, body) {
4571
+ const response = await supertest(app).post(uri).set(copyHeaders(this.req.headers)).send(body);
4572
+ return [response.status, response.body];
4573
+ }).delete(/.*/).reply(async function(uri, body) {
4574
+ const response = await supertest(app).delete(uri).set(copyHeaders(this.req.headers)).send(body);
4575
+ return [response.status, response.body];
4576
+ });
4577
+ }
4578
+ mockAuthHost() {
4579
+ const app = this.app;
4580
+ this._nockScopes.auth = nock(this.options.authHost).persist().post(/^\/oauth\/.*/).reply(async function(uri, body) {
4581
+ const response = await supertest(app).post(uri + "?" + body).set(copyHeaders(this.req.headers)).send();
4582
+ return [response.status, response.body];
4583
+ });
4584
+ }
4585
+ };
4586
+ export {
4587
+ CommercetoolsMock,
4588
+ getBaseResourceProperties
4589
+ };
4590
+ //# sourceMappingURL=index.mjs.map