@labdigital/commercetools-mock 0.7.0 → 0.9.0

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