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