@labdigital/commercetools-mock 0.6.5 → 0.8.0

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