@labdigital/commercetools-mock 0.7.0 → 0.7.1

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