@labdigital/commercetools-mock 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +5 -4
  2. package/dist/index.cjs +105 -17
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +29 -7
  5. package/dist/index.d.ts +29 -7
  6. package/dist/index.js +105 -17
  7. package/dist/index.js.map +1 -1
  8. package/package.json +4 -3
  9. package/src/constants.ts +2 -2
  10. package/src/ctMock.ts +176 -176
  11. package/src/exceptions.ts +10 -10
  12. package/src/helpers.ts +26 -26
  13. package/src/index.test.ts +173 -173
  14. package/src/index.ts +3 -3
  15. package/src/lib/expandParser.ts +19 -19
  16. package/src/lib/haversine.test.ts +13 -13
  17. package/src/lib/haversine.ts +14 -14
  18. package/src/lib/masking.ts +15 -15
  19. package/src/lib/parser.ts +2 -2
  20. package/src/lib/predicateParser.test.ts +204 -204
  21. package/src/lib/predicateParser.ts +398 -398
  22. package/src/lib/projectionSearchFilter.test.ts +168 -168
  23. package/src/lib/projectionSearchFilter.ts +272 -269
  24. package/src/lib/proxy.ts +8 -8
  25. package/src/oauth/errors.ts +4 -4
  26. package/src/oauth/helpers.ts +6 -6
  27. package/src/oauth/server.ts +103 -101
  28. package/src/oauth/store.ts +27 -27
  29. package/src/priceSelector.test.ts +68 -68
  30. package/src/priceSelector.ts +70 -70
  31. package/src/product-projection-search.ts +296 -296
  32. package/src/projectAPI.test.ts +3 -3
  33. package/src/projectAPI.ts +46 -46
  34. package/src/repositories/abstract.ts +190 -190
  35. package/src/repositories/associate-role.ts +10 -7
  36. package/src/repositories/attribute-group.ts +63 -8
  37. package/src/repositories/business-unit.ts +10 -7
  38. package/src/repositories/cart-discount.ts +134 -134
  39. package/src/repositories/cart.ts +517 -514
  40. package/src/repositories/category.ts +170 -167
  41. package/src/repositories/channel.ts +114 -111
  42. package/src/repositories/custom-object.ts +66 -63
  43. package/src/repositories/customer-group.ts +72 -69
  44. package/src/repositories/customer.ts +90 -90
  45. package/src/repositories/discount-code.ts +171 -168
  46. package/src/repositories/errors.ts +15 -15
  47. package/src/repositories/extension.ts +79 -76
  48. package/src/repositories/helpers.ts +180 -180
  49. package/src/repositories/index.ts +39 -39
  50. package/src/repositories/inventory-entry.ts +98 -95
  51. package/src/repositories/my-order.ts +11 -11
  52. package/src/repositories/order-edit.ts +29 -29
  53. package/src/repositories/order.test.ts +191 -191
  54. package/src/repositories/order.ts +393 -393
  55. package/src/repositories/payment.ts +155 -155
  56. package/src/repositories/product-discount.ts +149 -149
  57. package/src/repositories/product-projection.ts +116 -52
  58. package/src/repositories/product-selection.ts +31 -31
  59. package/src/repositories/product-type.ts +156 -156
  60. package/src/repositories/product.ts +600 -597
  61. package/src/repositories/project.ts +136 -135
  62. package/src/repositories/quote-request.ts +19 -19
  63. package/src/repositories/quote.ts +19 -19
  64. package/src/repositories/review.ts +24 -24
  65. package/src/repositories/shipping-method.ts +217 -217
  66. package/src/repositories/shopping-list.ts +49 -49
  67. package/src/repositories/staged-quote.ts +20 -20
  68. package/src/repositories/standalone-price.ts +72 -61
  69. package/src/repositories/state.ts +84 -84
  70. package/src/repositories/store.ts +114 -114
  71. package/src/repositories/subscription.ts +40 -40
  72. package/src/repositories/tax-category.ts +98 -98
  73. package/src/repositories/type.ts +157 -157
  74. package/src/repositories/zone.ts +71 -71
  75. package/src/server.ts +2 -2
  76. package/src/services/abstract.ts +173 -173
  77. package/src/services/attribute-group.ts +16 -0
  78. package/src/services/cart-discount.ts +8 -8
  79. package/src/services/cart.test.ts +409 -409
  80. package/src/services/cart.ts +50 -50
  81. package/src/services/category.test.ts +25 -25
  82. package/src/services/category.ts +8 -8
  83. package/src/services/channel.ts +8 -8
  84. package/src/services/custom-object.test.ts +184 -184
  85. package/src/services/custom-object.ts +48 -48
  86. package/src/services/customer-group.ts +8 -8
  87. package/src/services/customer.test.ts +151 -151
  88. package/src/services/customer.ts +27 -27
  89. package/src/services/discount-code.ts +8 -8
  90. package/src/services/extension.ts +8 -8
  91. package/src/services/index.ts +52 -44
  92. package/src/services/inventory-entry.test.ts +162 -162
  93. package/src/services/inventory-entry.ts +8 -8
  94. package/src/services/my-cart.test.ts +78 -78
  95. package/src/services/my-cart.ts +28 -28
  96. package/src/services/my-customer.test.ts +44 -44
  97. package/src/services/my-customer.ts +53 -53
  98. package/src/services/my-order.ts +20 -20
  99. package/src/services/my-payment.test.ts +65 -65
  100. package/src/services/my-payment.ts +8 -8
  101. package/src/services/order.test.ts +527 -527
  102. package/src/services/order.ts +31 -31
  103. package/src/services/payment.test.ts +65 -65
  104. package/src/services/payment.ts +8 -8
  105. package/src/services/product-discount.ts +8 -8
  106. package/src/services/product-projection.test.ts +492 -428
  107. package/src/services/product-projection.ts +32 -18
  108. package/src/services/product-type.test.ts +56 -56
  109. package/src/services/product-type.ts +8 -8
  110. package/src/services/product.test.ts +510 -510
  111. package/src/services/product.ts +8 -8
  112. package/src/services/project.ts +34 -34
  113. package/src/services/shipping-method.test.ts +81 -81
  114. package/src/services/shipping-method.ts +12 -12
  115. package/src/services/shopping-list.ts +8 -8
  116. package/src/services/standalone-price.test.ts +256 -256
  117. package/src/services/standalone-price.ts +8 -8
  118. package/src/services/state.test.ts +42 -42
  119. package/src/services/state.ts +8 -8
  120. package/src/services/store.test.ts +57 -57
  121. package/src/services/store.ts +8 -8
  122. package/src/services/subscription.ts +8 -8
  123. package/src/services/tax-category.test.ts +61 -61
  124. package/src/services/tax-category.ts +8 -8
  125. package/src/services/type.ts +8 -8
  126. package/src/services/zone.ts +8 -8
  127. package/src/storage/abstract.ts +58 -58
  128. package/src/storage/in-memory.ts +419 -419
  129. package/src/types.ts +82 -82
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ctMock.ts","../src/storage/abstract.ts","../src/storage/in-memory.ts","../src/exceptions.ts","../src/helpers.ts","../src/lib/expandParser.ts","../src/lib/haversine.ts","../vendor/perplex/lexer-state.ts","../vendor/perplex/token.ts","../vendor/perplex/token-types.ts","../vendor/perplex/lexer.ts","../vendor/pratt/index.ts","../src/lib/predicateParser.ts","../src/oauth/server.ts","../src/oauth/store.ts","../src/oauth/helpers.ts","../src/projectAPI.ts","../src/lib/proxy.ts","../src/constants.ts","../src/repositories/helpers.ts","../src/services/project.ts","../src/repositories/abstract.ts","../src/repositories/errors.ts","../src/repositories/associate-role.ts","../src/repositories/attribute-group.ts","../src/repositories/business-unit.ts","../src/repositories/cart.ts","../src/repositories/cart-discount.ts","../src/repositories/category.ts","../src/repositories/channel.ts","../src/repositories/custom-object.ts","../src/repositories/customer.ts","../src/repositories/customer-group.ts","../src/repositories/discount-code.ts","../src/lib/masking.ts","../src/repositories/extension.ts","../src/repositories/inventory-entry.ts","../src/repositories/my-order.ts","../src/repositories/order.ts","../src/repositories/order-edit.ts","../src/repositories/payment.ts","../src/repositories/product.ts","../src/repositories/product-discount.ts","../src/lib/projectionSearchFilter.ts","../src/priceSelector.ts","../src/product-projection-search.ts","../src/repositories/product-projection.ts","../src/repositories/product-selection.ts","../src/repositories/product-type.ts","../src/repositories/project.ts","../src/repositories/quote.ts","../src/repositories/quote-request.ts","../src/repositories/review.ts","../src/repositories/shipping-method.ts","../src/repositories/shopping-list.ts","../src/repositories/staged-quote.ts","../src/repositories/standalone-price.ts","../src/repositories/state.ts","../src/repositories/store.ts","../src/repositories/subscription.ts","../src/repositories/tax-category.ts","../src/repositories/type.ts","../src/repositories/zone.ts","../src/repositories/index.ts","../src/services/abstract.ts","../src/services/cart.ts","../src/services/cart-discount.ts","../src/services/category.ts","../src/services/channel.ts","../src/services/custom-object.ts","../src/services/customer.ts","../src/services/customer-group.ts","../src/services/discount-code.ts","../src/services/extension.ts","../src/services/inventory-entry.ts","../src/services/my-cart.ts","../src/services/my-customer.ts","../src/services/my-order.ts","../src/services/my-payment.ts","../src/services/order.ts","../src/services/payment.ts","../src/services/product.ts","../src/services/product-discount.ts","../src/services/product-projection.ts","../src/services/product-type.ts","../src/services/shipping-method.ts","../src/services/shopping-list.ts","../src/services/standalone-price.ts","../src/services/state.ts","../src/services/store.ts","../src/services/subscription.ts","../src/services/tax-category.ts","../src/services/type.ts","../src/services/zone.ts","../src/services/index.ts"],"sourcesContent":["import nock from 'nock'\nimport express, { NextFunction, Request, Response } from 'express'\nimport supertest from 'supertest'\nimport morgan from 'morgan'\nimport { AbstractStorage, InMemoryStorage } from './storage/index.js'\nimport { Services } from './types.js'\nimport { CommercetoolsError } from './exceptions.js'\nimport { OAuth2Server } from './oauth/server.js'\nimport { ProjectAPI } from './projectAPI.js'\nimport { copyHeaders } from './lib/proxy.js'\nimport { DEFAULT_API_HOSTNAME, DEFAULT_AUTH_HOSTNAME } from './constants.js'\n\n// Services\nimport { ProjectService } from './services/project.js'\nimport { createRepositories, RepositoryMap } from './repositories/index.js'\nimport { createServices } from './services/index.js'\nimport { ProjectRepository } from './repositories/project.js'\n\nexport type CommercetoolsMockOptions = {\n validateCredentials: boolean\n enableAuthentication: boolean\n defaultProjectKey: string | undefined\n apiHost: RegExp | string\n authHost: RegExp | string\n silent: boolean\n}\n\ntype AppOptions = { silent?: boolean }\n\nconst DEFAULT_OPTIONS: CommercetoolsMockOptions = {\n enableAuthentication: false,\n validateCredentials: false,\n defaultProjectKey: undefined,\n apiHost: DEFAULT_API_HOSTNAME,\n authHost: DEFAULT_AUTH_HOSTNAME,\n silent: false,\n}\n\nexport class CommercetoolsMock {\n public app: express.Express\n public options: CommercetoolsMockOptions\n\n private _storage: AbstractStorage\n private _oauth2: OAuth2Server\n private _nockScopes: {\n auth: nock.Scope | undefined\n api: nock.Scope | undefined\n } = { auth: undefined, api: undefined }\n private _services: Services | null\n private _repositories: RepositoryMap | null\n private _projectService?: ProjectService\n\n constructor(options: Partial<CommercetoolsMockOptions> = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options }\n this._services = null\n this._repositories = null\n this._projectService = undefined\n\n this._storage = new InMemoryStorage()\n this._oauth2 = new OAuth2Server({\n enabled: this.options.enableAuthentication,\n validate: this.options.validateCredentials,\n })\n\n this.app = this.createApp({ silent: this.options.silent })\n }\n\n start() {\n // Order is important here when the hostnames match\n this.mockAuthHost()\n this.mockApiHost()\n }\n\n stop() {\n this._nockScopes.auth?.persist(false)\n this._nockScopes.auth = undefined\n\n this._nockScopes.api?.persist(false)\n this._nockScopes.api = undefined\n }\n\n clear() {\n this._storage.clear()\n }\n\n project(projectKey?: string) {\n if (!projectKey && !this.options.defaultProjectKey) {\n throw new Error('No projectKey passed and no default set')\n }\n\n if (this._repositories === null) {\n throw new Error('repositories not initialized yet')\n }\n\n return new ProjectAPI(\n projectKey || this.options.defaultProjectKey!,\n this._repositories,\n this._storage\n )\n }\n\n runServer(port = 3000, options?: AppOptions) {\n const server = this.app.listen(port, () => {\n console.info(`Mock server listening at http://localhost:${port}`)\n })\n server.keepAliveTimeout = 60 * 1000\n }\n\n private createApp(options?: AppOptions): express.Express {\n this._repositories = createRepositories(this._storage)\n\n const app = express()\n\n const projectRouter = express.Router({ mergeParams: true })\n projectRouter.use(express.json())\n\n if (!options?.silent) {\n app.use(morgan('tiny'))\n }\n app.use('/oauth', this._oauth2.createRouter())\n\n // Only enable auth middleware if we have enabled this\n if (this.options.enableAuthentication) {\n app.use('/:projectKey', this._oauth2.createMiddleware(), projectRouter)\n app.use(\n '/:projectKey/in-store/key=:storeKey',\n this._oauth2.createMiddleware(),\n projectRouter\n )\n } else {\n app.use('/:projectKey', projectRouter)\n app.use('/:projectKey/in-store/key=:storeKey', projectRouter)\n }\n\n // Register the rest api services in the router\n this._services = createServices(projectRouter, this._repositories)\n this._projectService = new ProjectService(\n projectRouter,\n this._repositories.project as ProjectRepository\n )\n\n app.use((err: Error, req: Request, resp: Response, next: NextFunction) => {\n if (err instanceof CommercetoolsError) {\n return resp.status(err.statusCode).send({\n statusCode: err.statusCode,\n message: err.message,\n errors: [err.info],\n })\n } else {\n console.error(err)\n return resp.status(500).send({\n error: err.message,\n })\n }\n })\n\n return app\n }\n\n private mockApiHost() {\n const app = this.app\n\n this._nockScopes.api = nock(this.options.apiHost)\n .persist()\n .get(/.*/)\n .reply(async function (uri) {\n const response = await supertest(app)\n .get(uri)\n .set(copyHeaders(this.req.headers))\n return [response.status, response.body]\n })\n .post(/.*/)\n .reply(async function (uri, body) {\n const response = await supertest(app)\n .post(uri)\n .set(copyHeaders(this.req.headers))\n .send(body)\n return [response.status, response.body]\n })\n .delete(/.*/)\n .reply(async function (uri, body) {\n const response = await supertest(app)\n .delete(uri)\n .set(copyHeaders(this.req.headers))\n .send(body)\n return [response.status, response.body]\n })\n }\n\n private mockAuthHost() {\n const app = this.app\n\n this._nockScopes.auth = nock(this.options.authHost)\n .persist()\n .post(/^\\/oauth\\/.*/)\n .reply(async function (uri, body) {\n const response = await supertest(app)\n .post(uri + '?' + body)\n .set(copyHeaders(this.req.headers))\n .send()\n return [response.status, response.body]\n })\n }\n}\n","import type {\n BaseResource,\n Project,\n QueryParam,\n ResourceIdentifier\n} from '@commercetools/platform-sdk'\nimport { PagedQueryResponseMap, ResourceMap, ResourceType } from '../types.js'\n\nexport type GetParams = {\n expand?: string[]\n}\n\nexport type QueryParams = {\n expand?: string | string[]\n sort?: string | string[]\n limit?: number\n offset?: number\n withTotal?: boolean\n where?: string | string[]\n [key: string]: QueryParam\n}\n\nexport abstract class AbstractStorage {\n abstract clear(): void\n\n abstract all<RT extends ResourceType>(\n projectKey: string,\n typeId: RT\n ): Array<ResourceMap[RT]>\n\n abstract add<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n obj: ResourceMap[RT]\n ): void\n\n abstract get<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n id: string,\n params?: GetParams\n ): ResourceMap[RT] | null\n\n abstract getByKey<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n key: string,\n params: GetParams\n ): ResourceMap[RT] | null\n\n abstract addProject(projectKey: string): Project\n abstract getProject(projectKey: string): Project\n abstract saveProject(project: Project): Project\n\n abstract delete<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n id: string,\n params: GetParams\n ): ResourceMap[RT] | null\n\n abstract query<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n params: QueryParams\n ): PagedQueryResponseMap[RT]\n\n abstract getByResourceIdentifier<RT extends ResourceType>(\n projectKey: string,\n identifier: ResourceIdentifier\n ): ResourceMap[RT] | null\n\n abstract expand<T>(\n projectKey: string,\n obj: T,\n clause: undefined | string | string[]\n ): T\n}\n\nexport type ProjectStorage = {\n [index in ResourceType]: Map<string, BaseResource>\n}\n","import type {\n AssociateRole,\n AttributeGroup,\n BusinessUnit,\n Cart,\n CartDiscount,\n Category,\n Channel,\n Customer,\n CustomerGroup,\n CustomObject,\n DiscountCode,\n Extension,\n InvalidInputError,\n InventoryEntry,\n Order,\n PagedQueryResponse,\n Payment,\n Product,\n ProductDiscount,\n ProductProjection,\n ProductType,\n Project,\n Quote,\n QuoteRequest,\n Reference,\n ResourceIdentifier,\n ShippingMethod,\n ShoppingList,\n StagedQuote,\n State,\n Store,\n Subscription,\n TaxCategory,\n Type,\n Zone,\n} from '@commercetools/platform-sdk'\nimport assert from 'assert'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { cloneObject } from '../helpers.js'\nimport { parseExpandClause } from '../lib/expandParser.js'\nimport { parseQueryExpression } from '../lib/predicateParser.js'\nimport {\n PagedQueryResponseMap,\n ResourceMap,\n ResourceType,\n Writable,\n} from '../types.js'\nimport {\n AbstractStorage,\n GetParams,\n ProjectStorage,\n QueryParams,\n} from './abstract.js'\n\nexport class InMemoryStorage extends AbstractStorage {\n protected resources: {\n [projectKey: string]: ProjectStorage\n } = {}\n\n protected projects: {\n [projectKey: string]: Project\n } = {}\n\n private forProjectKey(projectKey: string): ProjectStorage {\n this.addProject(projectKey)\n\n let projectStorage = this.resources[projectKey]\n if (!projectStorage) {\n projectStorage = this.resources[projectKey] = {\n 'associate-role': new Map<string, AssociateRole>(),\n 'attribute-group': new Map<string, AttributeGroup>(),\n 'business-unit': new Map<string, BusinessUnit>(),\n cart: new Map<string, Cart>(),\n 'cart-discount': new Map<string, CartDiscount>(),\n category: new Map<string, Category>(),\n channel: new Map<string, Channel>(),\n customer: new Map<string, Customer>(),\n 'customer-group': new Map<string, CustomerGroup>(),\n 'discount-code': new Map<string, DiscountCode>(),\n extension: new Map<string, Extension>(),\n 'inventory-entry': new Map<string, InventoryEntry>(),\n 'key-value-document': new Map<string, CustomObject>(),\n order: new Map<string, Order>(),\n 'order-edit': new Map<string, any>(),\n payment: new Map<string, Payment>(),\n product: new Map<string, Product>(),\n quote: new Map<string, Quote>(),\n 'quote-request': new Map<string, QuoteRequest>(),\n 'product-discount': new Map<string, ProductDiscount>(),\n 'product-selection': new Map<string, any>(),\n 'product-type': new Map<string, ProductType>(),\n 'product-projection': new Map<string, ProductProjection>(),\n review: new Map<string, any>(),\n 'shipping-method': new Map<string, ShippingMethod>(),\n 'staged-quote': new Map<string, StagedQuote>(),\n state: new Map<string, State>(),\n store: new Map<string, Store>(),\n 'shopping-list': new Map<string, ShoppingList>(),\n 'standalone-price': new Map<string, any>(),\n subscription: new Map<string, Subscription>(),\n 'tax-category': new Map<string, TaxCategory>(),\n type: new Map<string, Type>(),\n zone: new Map<string, Zone>(),\n }\n }\n return projectStorage\n }\n\n clear() {\n for (const [, projectStorage] of Object.entries(this.resources)) {\n for (const [, value] of Object.entries(projectStorage)) {\n value?.clear()\n }\n }\n }\n\n all<RT extends ResourceType>(\n projectKey: string,\n typeId: RT\n ): ResourceMap[RT][] {\n const store = this.forProjectKey(projectKey)[typeId]\n if (store) {\n return Array.from(store.values()).map(cloneObject) as ResourceMap[RT][]\n }\n return []\n }\n\n add<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n obj: ResourceMap[RT],\n params: GetParams = {}\n ): ResourceMap[RT] {\n const store = this.forProjectKey(projectKey)\n store[typeId]?.set(obj.id, obj)\n\n const resource = this.get(projectKey, typeId, obj.id, params)\n assert(resource, `resource of type ${typeId} with id ${obj.id} not created`)\n return cloneObject(resource)\n }\n\n get<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n id: string,\n params: GetParams = {}\n ): ResourceMap[RT] | null {\n const resource = this.forProjectKey(projectKey)[typeId]?.get(id)\n if (resource) {\n const clone = cloneObject(resource)\n return this.expand(projectKey, clone, params.expand) as ResourceMap[RT]\n }\n return null\n }\n\n getByKey<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n key: string,\n params: GetParams = {}\n ): ResourceMap[RT] | null {\n const store = this.forProjectKey(projectKey)\n const resourceStore = store[typeId]\n if (!store) {\n throw new Error('No type')\n }\n\n const resources: any[] = Array.from(resourceStore.values())\n const resource = resources.find((e) => e.key === key)\n if (resource) {\n const clone = cloneObject(resource)\n return this.expand(projectKey, clone, params.expand) as ResourceMap[RT]\n }\n return null\n }\n\n delete<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n id: string,\n params: GetParams = {}\n ): ResourceMap[RT] | null {\n const resource = this.get(projectKey, typeId, id)\n\n if (resource) {\n this.forProjectKey(projectKey)[typeId]?.delete(id)\n return this.expand(projectKey, resource, params.expand)\n }\n return resource\n }\n\n query<RT extends ResourceType>(\n projectKey: string,\n typeId: RT,\n params: QueryParams\n ): PagedQueryResponseMap[RT] {\n const store = this.forProjectKey(projectKey)[typeId]\n if (!store) {\n throw new Error('No type')\n }\n\n let resources = this.all<RT>(projectKey, typeId)\n\n // Apply predicates\n if (params.where) {\n try {\n const filterFunc = parseQueryExpression(params.where)\n resources = resources.filter((resource) => filterFunc(resource, {}))\n } catch (err) {\n throw new CommercetoolsError<InvalidInputError>(\n {\n code: 'InvalidInput',\n message: (err as any).message,\n },\n 400\n )\n }\n }\n\n // Get the total before slicing the array\n const totalResources = resources.length\n\n // Apply offset, limit\n const offset = params.offset || 0\n const limit = params.limit || 20\n resources = resources.slice(offset, offset + limit)\n\n // Expand the resources\n if (params.expand !== undefined) {\n resources = resources.map((resource) =>\n this.expand(projectKey, resource, params.expand)\n )\n }\n\n return {\n count: totalResources,\n total: resources.length,\n offset: offset,\n limit: limit,\n results: resources.map(cloneObject),\n } as PagedQueryResponseMap[RT]\n }\n\n search(\n projectKey: string,\n typeId: ResourceType,\n params: QueryParams\n ): PagedQueryResponse {\n let resources = this.all(projectKey, typeId)\n\n // Apply predicates\n if (params.where) {\n try {\n const filterFunc = parseQueryExpression(params.where)\n resources = resources.filter((resource) => filterFunc(resource, {}))\n } catch (err) {\n throw new CommercetoolsError<InvalidInputError>(\n {\n code: 'InvalidInput',\n message: (err as any).message,\n },\n 400\n )\n }\n }\n\n // Get the total before slicing the array\n const totalResources = resources.length\n\n // Apply offset, limit\n const offset = params.offset || 0\n const limit = params.limit || 20\n resources = resources.slice(offset, offset + limit)\n\n // Expand the resources\n if (params.expand !== undefined) {\n resources = resources.map((resource) =>\n this.expand(projectKey, resource, params.expand)\n )\n }\n\n return {\n count: totalResources,\n total: resources.length,\n offset: offset,\n limit: limit,\n results: resources,\n }\n }\n\n getByResourceIdentifier<RT extends ResourceType>(\n projectKey: string,\n identifier: ResourceIdentifier\n ): ResourceMap[RT] | null {\n if (identifier.id) {\n const resource = this.get(projectKey, identifier.typeId, identifier.id)\n if (resource) {\n return resource as ResourceMap[RT]\n }\n console.error(\n `No resource found with typeId=${identifier.typeId}, id=${identifier.id}`\n )\n return null\n }\n\n if (identifier.key) {\n const store = this.forProjectKey(projectKey)[identifier.typeId]\n\n if (store) {\n // TODO: BaseResource has no key attribute, but the subclasses should\n // have them all.\n const resource = Array.from(store.values()).find(\n // @ts-ignore\n (r) => r.key === identifier.key\n )\n if (resource) {\n return resource as ResourceMap[RT]\n }\n } else {\n throw new Error(\n `No storage found for resource type: ${identifier.typeId}`\n )\n }\n }\n return null\n }\n\n addProject = (projectKey: string): Project => {\n if (!this.projects[projectKey]) {\n this.projects[projectKey] = {\n key: projectKey,\n name: '',\n countries: [],\n currencies: [],\n languages: [],\n createdAt: '2018-10-04T11:32:12.603Z',\n trialUntil: '2018-12',\n carts: {\n countryTaxRateFallbackEnabled: false,\n deleteDaysAfterLastModification: 90,\n },\n messages: { enabled: false, deleteDaysAfterCreation: 15 },\n shippingRateInputType: undefined,\n externalOAuth: undefined,\n searchIndexing: {\n products: {\n status: 'Deactivated',\n },\n orders: {\n status: 'Deactivated',\n },\n },\n version: 1,\n }\n }\n return this.projects[projectKey]\n }\n\n saveProject = (project: Project): Project => {\n this.projects[project.key] = project\n return project\n }\n\n getProject = (projectKey: string): Project => this.addProject(projectKey)\n\n // Expand resolves a nested reference and injects the object in the given obj\n public expand = <T>(\n projectKey: string,\n obj: T,\n clause: undefined | string | string[]\n ): T => {\n if (!clause) return obj\n const newObj = cloneObject(obj)\n if (Array.isArray(clause)) {\n clause.forEach((c) => {\n this._resolveResource(projectKey, newObj, c)\n })\n } else {\n this._resolveResource(projectKey, newObj, clause)\n }\n return newObj\n }\n\n private _resolveResource = (projectKey: string, obj: any, expand: string) => {\n const params = parseExpandClause(expand)\n\n if (!params.index) {\n const reference = obj[params.element]\n if (reference === undefined) {\n return\n }\n this._resolveReference(projectKey, reference, params.rest)\n } else if (params.index === '*') {\n const reference = obj[params.element]\n if (reference === undefined || !Array.isArray(reference)) return\n reference.forEach((itemRef: Writable<Reference>) => {\n this._resolveReference(projectKey, itemRef, params.rest)\n })\n } else {\n const reference = obj[params.element][params.index]\n if (reference === undefined) return\n this._resolveReference(projectKey, reference, params.rest)\n }\n }\n\n private _resolveReference(\n projectKey: string,\n reference: any,\n expand: string | undefined\n ) {\n if (reference === undefined) return\n\n if (\n reference.typeId !== undefined &&\n (reference.id !== undefined || reference.key !== undefined)\n ) {\n // @ts-ignore\n reference.obj = this.getByResourceIdentifier(projectKey, {\n typeId: reference.typeId,\n id: reference.id,\n key: reference.key,\n } as ResourceIdentifier)\n if (expand) {\n this._resolveResource(projectKey, reference.obj, expand)\n }\n } else {\n if (expand) {\n this._resolveResource(projectKey, reference, expand)\n }\n }\n }\n}\n","export abstract class BaseError {\n abstract message: string\n}\n\nexport class CommercetoolsError<T extends BaseError> extends Error {\n info: T\n statusCode: number\n\n constructor(info: T, statusCode = 400) {\n super(info.message)\n this.info = info\n this.statusCode = statusCode || 500\n }\n}\n\nexport interface InvalidRequestError {\n readonly code: 'invalid_request'\n readonly message: string\n}\n","import { ParsedQs } from 'qs'\nimport { v4 as uuidv4 } from 'uuid'\n\nexport const getBaseResourceProperties = () => ({\n id: uuidv4(),\n createdAt: new Date().toISOString(),\n lastModifiedAt: new Date().toISOString(),\n version: 0,\n})\n\n/**\n * Do a nested lookup by using a path. For example `foo.bar.value` will\n * return obj['foo']['bar']['value']\n */\nexport const nestedLookup = (obj: any, path: string): any => {\n if (!path || path === '') {\n return obj\n }\n\n const parts = path.split('.')\n let val = obj\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i]\n if (val == undefined) {\n return undefined\n }\n\n val = val[part]\n }\n\n return val\n}\n\nexport const QueryParamsAsArray = (\n input: string | ParsedQs | string[] | ParsedQs[] | undefined\n): string[] => {\n if (input == undefined) {\n return []\n }\n\n if (Array.isArray(input)) {\n return input as string[]\n }\n return [input] as string[]\n}\n\nexport const cloneObject = <T>(o: T): T => JSON.parse(JSON.stringify(o))\n","/**\n * This module implements the reference expansion as imeplemented by\n * commercetools.\n *\n * See https://docs.commercetools.com/api/general-concepts#reference-expansion\n *\n * TODO: implement support for multi-dimensional array\n */\ntype ExpandResult = {\n element: string\n index?: string | number\n rest?: string\n}\n\nexport const parseExpandClause = (clause: string): ExpandResult => {\n const result: ExpandResult = {\n element: clause,\n index: undefined,\n rest: undefined,\n }\n\n const pos = clause.indexOf('.')\n if (pos > 0) {\n result.element = clause.substring(0, pos)\n result.rest = clause.substring(pos + 1)\n }\n\n const match = result.element.match(/\\[([^\\]+])]/)\n if (match) {\n result.index = match[1] === '*' ? '*' : parseInt(match[1], 10)\n result.element = result.element.substring(0, match.index)\n }\n return result\n}\n","export type Location = {\n latitude: number\n longitude: number\n}\n\n/**\n * Returns the distance between src and dst as meters\n */\nexport const haversineDistance = (src: Location, dst: Location) => {\n const RADIUS_OF_EARTH_IN_KM = 6371\n const toRadian = (deg: number) => deg * (Math.PI / 180)\n\n const dLat = toRadian(dst.latitude - src.latitude)\n const dLon = toRadian(dst.longitude - src.longitude)\n\n const a =\n Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(toRadian(src.latitude)) *\n Math.cos(toRadian(dst.latitude)) *\n Math.sin(dLon / 2) *\n Math.sin(dLon / 2)\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))\n return RADIUS_OF_EARTH_IN_KM * c * 1000\n}\n","import TokenTypes from './token-types'\n\n/**\n * @private\n */\nexport default class LexerState<T> {\n\tpublic source: string\n\tpublic position: number\n\tpublic tokenTypes: TokenTypes<T>\n\n\tconstructor(source: string, position: number = 0) {\n\t\tthis.source = source\n\t\tthis.position = position\n\t}\n\n\tcopy() {\n\t\treturn new LexerState<T>(this.source, this.position)\n\t}\n}\n","import Lexer from './lexer'\n\n/**\n * @typedef {{\n * start: Position,\n * end: Position,\n * }} TokenPosition\n */\n\n/**\n * Represents a token instance\n */\nclass Token<T> {\n\ttype: T\n\tmatch: string\n\tgroups: string[]\n\tstart: number\n\tend: number\n\tlexer: Lexer<T>\n\n\t/* tslint:disable:indent */\n\t/**\n\t * Constructs a token\n\t * @param {T} type The token type\n\t * @param {string} match The string that the lexer consumed to create this token\n\t * @param {string[]} groups Any RegExp groups that accrued during the match\n\t * @param {number} start The string position where this match started\n\t * @param {number} end The string position where this match ends\n\t * @param {Lexer<T>} lexer The parent {@link Lexer}\n\t */\n\tconstructor(\n\t\ttype: T,\n\t\tmatch: string,\n\t\tgroups: string[],\n\t\tstart: number,\n\t\tend: number,\n\t\tlexer: Lexer<T>\n\t) {\n\t\t/* tslint:enable */\n\t\t/**\n\t\t * The token type\n\t\t * @type {T}\n\t\t */\n\t\tthis.type = type\n\n\t\t/**\n\t\t * The string that the lexer consumed to create this token\n\t\t * @type {string}\n\t\t */\n\t\tthis.match = match\n\n\t\t/**\n\t\t * Any RegExp groups that accrued during the match\n\t\t * @type {string[]}\n\t\t */\n\t\tthis.groups = groups\n\n\t\t/**\n\t\t * The string position where this match started\n\t\t * @type {number}\n\t\t */\n\t\tthis.start = start\n\n\t\t/**\n\t\t * The string position where this match ends\n\t\t * @type {number}\n\t\t */\n\t\tthis.end = end\n\n\t\t/**\n\t\t * The parent {@link Lexer}\n\t\t * @type {Lexer<T>}\n\t\t */\n\t\tthis.lexer = lexer\n\t}\n\n\t/**\n\t * Returns the bounds of this token, each in `{line, column}` format\n\t * @return {TokenPosition}\n\t */\n\tstrpos() {\n\t\tconst start = this.lexer.strpos(this.start)\n\t\tconst end = this.lexer.strpos(this.end)\n\t\treturn {start, end}\n\t}\n\n\t// tslint:disable-next-line prefer-function-over-method\n\tisEof() {\n\t\treturn false\n\t}\n}\n\nexport default Token\n\nexport class EOFToken<T> extends Token<T> {\n\tconstructor(lexer: Lexer<T>) {\n\t\tconst end = lexer.source.length\n\t\tsuper(null, '(eof)', [], end, end, lexer)\n\t}\n\n\t// tslint:disable-next-line prefer-function-over-method\n\tisEof() {\n\t\treturn true\n\t}\n}\n\n/**\n * @private\n */\nexport const EOF = (lexer: Lexer<any>) => new EOFToken(lexer)\n","// Thank you, http://stackoverflow.com/a/6969486\nfunction toRegExp(str: string): RegExp {\n\treturn new RegExp(str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&'))\n}\n\nfunction normalize(regex: RegExp | string): RegExp {\n\tif (typeof regex === 'string') regex = toRegExp(regex)\n\tif (!regex.source.startsWith('^'))\n\t\treturn new RegExp(`^${regex.source}`, regex.flags)\n\telse return regex\n}\n\nfunction first<T, U>(\n\tarr: T[],\n\tpredicate: (item: T, i: number) => U\n): {item: T; result: U} {\n\tlet i = 0\n\tfor (const item of arr) {\n\t\tconst result = predicate(item, i++)\n\t\tif (result) return {item, result}\n\t}\n}\n\n/**\n * @private\n */\nexport default class TokenTypes<T> {\n\tpublic tokenTypes: {\n\t\ttype: T\n\t\tregex: RegExp\n\t\tenabled: boolean\n\t\tskip: boolean\n\t}[]\n\n\tconstructor() {\n\t\tthis.tokenTypes = []\n\t}\n\n\tdisable(type: T): TokenTypes<T> {\n\t\treturn this.enable(type, false)\n\t}\n\n\tenable(type: T, enabled: boolean = true): TokenTypes<T> {\n\t\tthis.tokenTypes\n\t\t\t.filter(t => t.type == type)\n\t\t\t.forEach(t => (t.enabled = enabled))\n\t\treturn this\n\t}\n\n\tisEnabled(type: T) {\n\t\tconst ttypes = this.tokenTypes.filter(tt => tt.type == type)\n\t\tif (ttypes.length == 0)\n\t\t\tthrow new Error(`Token of type ${type} does not exists`)\n\t\treturn ttypes[0].enabled\n\t}\n\n\tpeek(source: string, position: number) {\n\t\tconst s = source.substr(position)\n\t\treturn first(this.tokenTypes.filter(tt => tt.enabled), tt => {\n\t\t\ttt.regex.lastIndex = 0\n\t\t\treturn tt.regex.exec(s)\n\t\t})\n\t}\n\n\ttoken(\n\t\ttype: T,\n\t\tpattern: RegExp | string,\n\t\tskip: boolean = false\n\t): TokenTypes<T> {\n\t\tthis.tokenTypes.push({\n\t\t\ttype,\n\t\t\tregex: normalize(pattern),\n\t\t\tenabled: true,\n\t\t\tskip,\n\t\t})\n\t\treturn this\n\t}\n}\n","import LexerState from './lexer-state'\nimport Token, {EOF} from './token'\nimport TokenTypes from './token-types'\n\n/**\n * @typedef {{\n * line: number,\n * column: number,\n * }} Position\n */\n\n/**\n * Lexes a source-string into tokens.\n *\n * @example\n * const lex = perplex('...')\n * .token('ID', /my-id-regex/)\n * .token('(', /\\(/)\n * .token(')', /\\)/)\n * .token('WS', /\\s+/, true) // true means 'skip'\n *\n * while ((let t = lex.next()).type != 'EOF') {\n * console.log(t)\n * }\n * // alternatively:\n * console.log(lex.toArray())\n * // or:\n * console.log(...lex)\n */\nclass Lexer<T> implements Iterable<Token<T>> {\n\t/* tslint:disable:variable-name */\n\tprivate _state: LexerState<T>\n\tprivate _tokenTypes: TokenTypes<T>\n\t/* tslint:enable */\n\n\t/**\n\t * Creates a new Lexer instance\n\t * @param {string} [source = ''] The source string to operate on.\n\t */\n\tconstructor(source: string = '') {\n\t\tthis._state = new LexerState<T>(source)\n\t\tthis._tokenTypes = new TokenTypes<T>()\n\t}\n\n\t//\n\t// Getters/Setters\n\t//\n\n\t/**\n\t * Gets the current lexer position\n\t * @return {number} Returns the position\n\t */\n\tget position() {\n\t\treturn this._state.position\n\t}\n\n\t/**\n\t * Sets the current lexer position\n\t * @param {number} i The position to move to\n\t */\n\tset position(i: number) {\n\t\tthis._state.position = i\n\t}\n\n\t/**\n\t * Gets the source the lexer is operating on\n\t * @return {string} Returns the source\n\t */\n\tget source() {\n\t\treturn this._state.source\n\t}\n\n\t/**\n\t * Sets the source the lexer is operating on\n\t * @param {string} s The source to set\n\t */\n\tset source(s: string) {\n\t\tthis._state = new LexerState<T>(s)\n\t}\n\n\t//\n\t// METHODS\n\t//\n\n\t/**\n\t * Attaches this lexer to another lexer's state\n\t * @param {Lexer<T>} other The other lexer to attach to\n\t */\n\tattachTo(other: Lexer<T>) {\n\t\tthis._state = other._state\n\t}\n\n\t/**\n\t * Disables a token type\n\t * @param {T} type The token type to disable\n\t * @return {Lexer<T>}\n\t */\n\tdisable(type: T) {\n\t\tthis._tokenTypes.disable(type)\n\t\treturn this\n\t}\n\n\t/**\n\t * Enables a token type\n\t * @param {T} type The token type to enalbe\n\t * @param {?boolean} [enabled=true] Whether to enable/disable the specified token type\n\t * @return {Lexer<T>}\n\t */\n\tenable(type: T, enabled?: boolean) {\n\t\tthis._tokenTypes.enable(type, enabled)\n\t\treturn this\n\t}\n\n\t/**\n\t * Like {@link next}, but throws an exception if the next token is\n\t * not of the required type.\n\t * @param {T} type The token type expected from {@link next}\n\t * @return {Token<T>} Returns the {@link Token} on success\n\t */\n\texpect(type: T): Token<T> {\n\t\tconst t = this.next()\n\t\tif (t.type != type) {\n\t\t\tconst pos = t.strpos()\n\t\t\tthrow new Error(\n\t\t\t\t'Expected ' +\n\t\t\t\t\ttype +\n\t\t\t\t\t(t ? ', got ' + t.type : '') +\n\t\t\t\t\t' at ' +\n\t\t\t\t\tpos.start.line +\n\t\t\t\t\t':' +\n\t\t\t\t\tpos.start.column\n\t\t\t)\n\t\t}\n\t\treturn t\n\t}\n\n\t/**\n\t * Looks up whether a token is enabled.\n\t * @param tokenType The token type to look up\n\t * @return {boolean} Returns whether the token is enabled\n\t */\n\tisEnabled(tokenType: T) {\n\t\treturn this._tokenTypes.isEnabled(tokenType)\n\t}\n\n\t/**\n\t * Consumes and returns the next {@link Token} in the source string.\n\t * If there are no more tokens, it returns a {@link Token} of type `$EOF`\n\t * @return {Token<T>}\n\t */\n\tnext(): Token<T> {\n\t\ttry {\n\t\t\tconst t = this.peek()\n\t\t\tthis._state.position = t.end\n\t\t\treturn t\n\t\t} catch (e) {\n\t\t\tthis._state.position = e.end\n\t\t\tthrow e\n\t\t}\n\t}\n\n\t/**\n\t * Returns the next {@link Token} in the source string, but does\n\t * not consume it.\n\t * If there are no more tokens, it returns a {@link Token} of type `$EOF`\n\t * @param {number} [position=`this.position`] The position at which to start reading\n\t * @return {Token<T>}\n\t */\n\tpeek(position: number = this._state.position): Token<T> {\n\t\tconst read = (i: number = position) => {\n\t\t\tif (i >= this._state.source.length) return EOF(this)\n\t\t\tconst n = this._tokenTypes.peek(this._state.source, i)\n\t\t\treturn n\n\t\t\t\t? n.item.skip\n\t\t\t\t\t? read(i + n.result[0].length)\n\t\t\t\t\t: new Token(\n\t\t\t\t\t\t\tn.item.type,\n\t\t\t\t\t\t\tn.result[0],\n\t\t\t\t\t\t\tn.result.map(x => x),\n\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t\ti + n.result[0].length,\n\t\t\t\t\t\t\tthis\n\t\t\t\t\t\t)\n\t\t\t\t: null\n\t\t}\n\t\tconst t = read()\n\t\tif (t) return t\n\n\t\t// we did not find a match\n\t\tlet unexpected = this._state.source.substring(position, position + 1)\n\t\ttry {\n\t\t\tthis.peek(position + 1)\n\t\t} catch (e) {\n\t\t\tunexpected += e.unexpected\n\t\t}\n\t\tconst {line, column} = this.strpos(position)\n\t\tconst e = new Error(\n\t\t\t`Unexpected input: ${unexpected} at (${line}:${column})`\n\t\t)\n\t\t;(e as any).unexpected = unexpected\n\t\t;(e as any).end = position + unexpected.length\n\t\tthrow e\n\t}\n\n\t/**\n\t * Converts a string-index (relative to the source string) to a line and a column.\n\t * @param {number} i The index to compute\n\t * @return {Position}\n\t */\n\tstrpos(\n\t\ti: number\n\t): {\n\t\tline: number\n\t\tcolumn: number\n\t} {\n\t\tlet lines = this._state.source.substring(0, i).split(/\\r?\\n/)\n\t\tif (!Array.isArray(lines)) lines = [lines]\n\n\t\tconst line = lines.length\n\t\tconst column = lines[lines.length - 1].length + 1\n\t\treturn {line, column}\n\t}\n\n\t/**\n\t * Converts the token stream to an array of Tokens\n\t * @return {Token<T>[]} The array of tokens (not including (EOF))\n\t */\n\ttoArray(): Token<T>[] {\n\t\treturn [...this]\n\t}\n\n\t/**\n\t * Implements the Iterable protocol\n\t * Iterates lazily over the entire token stream (not including (EOF))\n\t * @return {Iterator<Token<T>>} Returns an iterator over all remaining tokens\n\t */\n\t*[Symbol.iterator]() {\n\t\tconst oldState = this._state.copy()\n\t\tthis._state.position = 0\n\n\t\tlet t\n\t\twhile (\n\t\t\t!(t = this.next()).isEof() // tslint:disable-line no-conditional-assignment\n\t\t)\n\t\t\tyield t\n\n\t\tthis._state = oldState\n\t}\n\n\t/**\n\t * Creates a new token type\n\t * @param {T} type The token type\n\t * @param {string|RegExp} pattern The pattern to match\n\t * @param {?boolean} skip Whether this type of token should be skipped\n\t * @return {Lexer<T>}\n\t */\n\ttoken(type: T, pattern: string | RegExp, skip?: boolean) {\n\t\tthis._tokenTypes.token(type, pattern, skip)\n\t\treturn this\n\t}\n\n\t/**\n\t * Creates a keyword\n\t * @param kwd The keyword to add as a token\n\t */\n\tkeyword(kwd: T) {\n\t\treturn this.token(kwd, new RegExp(`${kwd}(?=\\\\W|$)`))\n\t}\n\n\t/**\n\t * Creates an operator\n\t * @param op The operator to add as a token\n\t */\n\toperator(op: T) {\n\t\tconst sOp = new String(op).valueOf()\n\t\treturn this.token(op, sOp)\n\t}\n}\n\nexport default Lexer\nexport {EOF, Token, TokenTypes, LexerState, Lexer}\n","// From https://github.com/jrop/pratt/blob/master/src/index.ts\n\nexport interface IPosition {\n\tline: number\n\tcolumn: number\n}\nexport interface ITokenPosition {\n\tstart: IPosition\n\tend: IPosition\n}\nexport interface IToken<T> {\n\ttype: T\n\tmatch: string\n\tstrpos(): ITokenPosition\n\tisEof(): boolean\n}\nexport interface ILexer<T> {\n\tnext(): IToken<T>\n\tpeek(): IToken<T>\n}\n\nexport type BPResolver = () => number\nexport type BP = number | BPResolver\n\nexport type StopFunction = (<T>(x: T) => T) & {isStopped(): boolean}\n\nexport type NudInfo<T> = {\n\ttoken: IToken<T>\n\tbp: number\n\tstop: StopFunction\n\n\t// TODO: with the below addition of `options`\n\t// the `ctx parameter is carried through anyway\n\t// remove in a breaking API change release\n\tctx: any\n\toptions: ParseOpts<T>\n}\nexport type LedInfo<T> = NudInfo<T> & {left: any}\n\nexport type NudFunction<T> = (inf: NudInfo<T>) => any\nexport type LedFunction<T> = (inf: LedInfo<T>) => any\n\nexport type NudMap<T> = Map<T, NudFunction<T>>\nexport type LedMap<T> = Map<T, LedFunction<T>>\n\nexport type ParseOpts<T> = {\n\tctx?: any\n\tstop?: StopFunction\n\tterminals?: (number | T)[]\n}\n\nconst createStop = <T>(): StopFunction => {\n\tlet stopCalled = false\n\treturn Object.assign(\n\t\t(x: T) => {\n\t\t\tstopCalled = true\n\t\t\treturn x\n\t\t},\n\t\t{\n\t\t\tisStopped() {\n\t\t\t\treturn stopCalled\n\t\t\t},\n\t\t}\n\t) as StopFunction\n}\n\n/**\n * A Pratt parser.\n * @example\n * const lex = new perplex.Lexer('1 + -2 * 3^4')\n * .token('NUM', /\\d+/)\n * .token('+', /\\+/)\n * .token('-', /-/)\n * .token('*', new RegExp('*'))\n * .token('/', /\\//)\n * .token('^', /\\^/)\n * .token('(', /\\(/)\n * .token(')', /\\)/)\n * .token('$SKIP_WS', /\\s+/)\n *\n * const parser = new Parser(lex)\n * .builder()\n * .nud('NUM', 100, t => parseInt(t.match))\n * .nud('-', 10, (t, bp) => -parser.parse(bp))\n * .nud('(', 10, (t, bp) => {\n * const expr = parser.parse(bp)\n * lex.expect(')')\n * return expr\n * })\n * .bp(')', 0)\n *\n * .led('^', 20, (left, t, bp) => Math.pow(left, parser.parse(20 - 1)))\n * .led('+', 30, (left, t, bp) => left + parser.parse(bp))\n * .led('-', 30, (left, t, bp) => left - parser.parse(bp))\n * .led('*', 40, (left, t, bp) => left * parser.parse(bp))\n * .led('/', 40, (left, t, bp) => left / parser.parse(bp))\n * .build()\n * parser.parse()\n * // => 161\n */\nexport class Parser<T> {\n\tpublic lexer: ILexer<T>\n\t_nuds: NudMap<T>\n\t_leds: LedMap<T>\n\t_bps: Map<T, BP>\n\n\t/**\n\t * Constructs a Parser instance\n\t * @param {ILexer<T>} lexer The lexer to obtain tokens from\n\t */\n\tconstructor(lexer: ILexer<T>) {\n\t\t/**\n\t\t * The lexer that this parser is operating on.\n\t\t * @type {ILexer<T>}\n\t\t */\n\t\tthis.lexer = lexer\n\t\tthis._nuds = new Map()\n\t\tthis._leds = new Map()\n\t\tthis._bps = new Map()\n\t}\n\n\tprivate _type(tokenOrType: IToken<T> | T): T {\n\t\treturn tokenOrType && typeof (tokenOrType as IToken<T>).isEof == 'function'\n\t\t\t? (tokenOrType as IToken<T>).type\n\t\t\t: (tokenOrType as T)\n\t}\n\n\t/**\n\t * Create a {@link ParserBuilder}\n\t * @return {ParserBuilder<T>} Returns the ParserBuilder\n\t */\n\tbuilder(): ParserBuilder<T> {\n\t\treturn new ParserBuilder(this)\n\t}\n\n\t/**\n\t * Define binding power for a token-type\n\t * @param {IToken<T>|T} tokenOrType The token type to define the binding power for\n\t * @returns {number} The binding power of the specified token type\n\t */\n\tbp(tokenOrType: IToken<T> | T) {\n\t\tif (tokenOrType == null) return Number.NEGATIVE_INFINITY\n\t\tif (\n\t\t\ttokenOrType &&\n\t\t\ttypeof (tokenOrType as IToken<T>).isEof == 'function' &&\n\t\t\t(tokenOrType as IToken<T>).isEof()\n\t\t)\n\t\t\treturn Number.NEGATIVE_INFINITY\n\t\tconst type = this._type(tokenOrType)\n\t\tconst bp = this._bps.has(type)\n\t\t\t? this._bps.get(type)\n\t\t\t: Number.POSITIVE_INFINITY\n\t\treturn typeof bp == 'function' ? bp() : bp\n\t}\n\n\t/**\n\t * Computes the token's `nud` value and returns it\n\t * @param {NudInfo<T>} info The info to compute the `nud` from\n\t * @returns {any} The result of invoking the pertinent `nud` operator\n\t */\n\tnud(info: NudInfo<T>) {\n\t\tconst fn: NudFunction<T> | undefined = this._nuds.get(info.token.type)\n\t\tif (!fn) {\n\t\t\tconst {start} = info.token.strpos()\n\t\t\tthrow new Error(\n\t\t\t\t`Unexpected token: ${info.token.match} (at ${start.line}:${\n\t\t\t\t\tstart.column\n\t\t\t\t})`\n\t\t\t)\n\t\t}\n\t\treturn fn(info)\n\t}\n\n\t/**\n\t * Computes a token's `led` value and returns it\n\t * @param {LedInfo<T>} info The info to compute the `led` value for\n\t * @returns {any} The result of invoking the pertinent `led` operator\n\t */\n\tled(info: LedInfo<T>) {\n\t\tlet fn = this._leds.get(info.token.type)\n\t\tif (!fn) {\n\t\t\tconst {start} = info.token.strpos()\n\t\t\tthrow new Error(\n\t\t\t\t`Unexpected token: ${info.token.match} (at ${start.line}:${\n\t\t\t\t\tstart.column\n\t\t\t\t})`\n\t\t\t)\n\t\t}\n\t\treturn fn(info)\n\t}\n\n\t/**\n\t * Kicks off the Pratt parser, and returns the result\n\t * @param {ParseOpts<T>} opts The parse options\n\t * @returns {any}\n\t */\n\tparse(opts: ParseOpts<T> = {terminals: [0]}): any {\n\t\tconst stop = (opts.stop = opts.stop || createStop())\n\t\tconst check = () => {\n\t\t\tif (stop.isStopped()) return false\n\t\t\tconst t = this.lexer.peek()\n\t\t\tconst bp = this.bp(t)\n\n // @ts-ignore\n\t\t\treturn opts.terminals.reduce((canContinue, rbpOrType) => {\n\t\t\t\tif (!canContinue) return false\n // @ts-ignore\n\t\t\t\tif (typeof rbpOrType == 'number') return rbpOrType < bp\n\t\t\t\tif (typeof rbpOrType == 'string') return t.type != rbpOrType\n\t\t\t}, true)\n\t\t}\n\t\tconst mkinfo = (token: IToken<T>): NudInfo<T> => {\n\t\t\tconst bp = this.bp(token)\n // @ts-ignore\n\t\t\treturn {token, bp, stop, ctx: opts.ctx, options: opts}\n\t\t}\n\t\tif (!opts.terminals) opts.terminals = [0]\n\t\tif (opts.terminals.length == 0) opts.terminals.push(0)\n\n\t\tlet left = this.nud(mkinfo(this.lexer.next()))\n\t\twhile (check()) {\n\t\t\tconst operator = this.lexer.next()\n\t\t\tleft = this.led(Object.assign(mkinfo(operator), {left}))\n\t\t}\n\t\treturn left\n\t}\n}\n\n/**\n * Builds `led`/`nud` rules for a {@link Parser}\n */\nexport class ParserBuilder<T> {\n\tprivate _parser: Parser<T>\n\n\t/**\n\t * Constructs a ParserBuilder\n\t * See also: {@link Parser.builder}\n\t * @param {Parser<T>} parser The parser\n\t */\n\tconstructor(parser: Parser<T>) {\n\t\tthis._parser = parser\n\t}\n\n\t/**\n\t * Define `nud` for a token type\n\t * @param {T} tokenType The token type\n\t * @param {number} bp The binding power\n\t * @param {NudFunction<T>} fn The function that will parse the token\n\t * @return {ParserBuilder<T>} Returns this ParserBuilder\n\t */\n\tnud(tokenType: T, bp: BP, fn: NudFunction<T>): ParserBuilder<T> {\n\t\tthis._parser._nuds.set(tokenType, fn)\n\t\tthis.bp(tokenType, bp)\n\t\treturn this\n\t}\n\n\t/**\n\t * Define `led` for a token type\n\t * @param {T} tokenType The token type\n\t * @param {number} bp The binding power\n\t * @param {LedFunction<T>} fn The function that will parse the token\n\t * @return {ParserBuilder<T>} Returns this ParserBuilder\n\t */\n\tled(tokenType: T, bp: BP, fn: LedFunction<T>): ParserBuilder<T> {\n\t\tthis._parser._leds.set(tokenType, fn)\n\t\tthis.bp(tokenType, bp)\n\t\treturn this\n\t}\n\n\t/**\n\t * Define both `led` and `nud` for a token type at once.\n\t * The supplied `LedFunction` may be called with a null `left`\n\t * parameter when invoked from a `nud` context.\n\t * @param {strTng} tokenType The token type\n\t * @param {number} bp The binding power\n\t * @param {LedFunction<T>} fn The function that will parse the token\n\t * @return {ParserBuilder<T>} Returns this ParserBuilder\n\t */\n\teither(tokenType: T, bp: BP, fn: LedFunction<T>): ParserBuilder<T> {\n\t\treturn this.nud(tokenType, bp, inf =>\n\t\t\tfn(Object.assign(inf, {left: null}))\n\t\t).led(tokenType, bp, fn)\n\t}\n\n\t/**\n\t * Define the binding power for a token type\n\t * @param {T} tokenType The token type\n\t * @param {BP} bp The binding power\n\t * @return {ParserBuilder<T>} Returns this ParserBuilder\n\t */\n\tbp(tokenType: T, bp: BP): ParserBuilder<T> {\n\t\tthis._parser._bps.set(tokenType, bp)\n\t\treturn this\n\t}\n\n\t/**\n\t * Returns the parent {@link Parser} instance\n\t * @returns {Parser<T>}\n\t */\n\tbuild(): Parser<T> {\n\t\treturn this._parser\n\t}\n}\n\n","/**\n * This module implements the commercetools query predicate filter expression.\n * Support should be 100% complete.\n *\n * See https://docs.commercetools.com/api/predicates/query\n */\nimport { haversineDistance } from './haversine.js'\nimport { Lexer, Parser, type ITokenPosition } from './parser.js'\n\nexport class PredicateError {\n message: string\n\n constructor(message: string) {\n this.message = message\n }\n}\n\ntype MatchFunc = (target: any, variables: VariableMap) => boolean\ntype VariableMap = {\n [key: string]: any\n}\n\nexport const matchesPredicate = (\n predicate: string | string[] | undefined,\n target: any,\n variables?: VariableMap\n): boolean => {\n if (!predicate) {\n return true\n }\n\n if (Array.isArray(predicate)) {\n return predicate.every((item) => {\n const func = generateMatchFunc(item)\n return func(target, variables || {})\n })\n } else {\n const func = generateMatchFunc(predicate)\n return func(target, variables || {})\n }\n}\n\nexport const parseQueryExpression = (\n predicate: string | string[]\n): MatchFunc => {\n if (Array.isArray(predicate)) {\n const callbacks = predicate.map((item) => generateMatchFunc(item))\n return (target: any, variables: VariableMap) =>\n callbacks.every((callback) => callback(target, variables))\n } else {\n return generateMatchFunc(predicate)\n }\n}\n\ntype TypeSymbol = {\n type: 'var' | 'boolean' | 'string' | 'float' | 'int' | 'identifier'\n value: any\n pos?: ITokenPosition\n}\n\nconst validateSymbol = (val: TypeSymbol) => {\n if (!val.type) {\n throw new PredicateError('Internal error')\n }\n\n if (val.type === 'identifier') {\n const char = val.value.charAt(0)\n const line = val.pos?.start.line\n const column = val.pos?.start.column\n\n throw new PredicateError(\n `Invalid input '${char}', expected input parameter or primitive value (line ${line}, column ${column})`\n )\n }\n}\n\nconst resolveSymbol = (val: TypeSymbol, vars: VariableMap): any => {\n if (val.type === 'var') {\n if (!(val.value in vars)) {\n throw new PredicateError(`Missing parameter value for ${val.value}`)\n }\n return vars[val.value]\n }\n\n return val.value\n}\n\nconst resolveValue = (obj: any, val: TypeSymbol): any => {\n if (val.type !== 'identifier') {\n throw new PredicateError('Internal error')\n }\n\n if (!(val.value in obj)) {\n if (Array.isArray(obj)) {\n return Object.values(obj)\n .filter((v) => val.value in v)\n .map((v) => v[val.value])\n }\n throw new PredicateError(`The field '${val.value}' does not exist.`)\n }\n\n return obj[val.value]\n}\n\nconst getLexer = (value: string) =>\n new Lexer(value)\n\n .token('AND', /and(?![-_a-z0-9]+)/i)\n .token('OR', /or(?![-_a-z0-9]+)/i)\n .token('NOT', /not(?![-_a-z0-9]+)/i)\n\n .token('WITHIN', /within(?![-_a-z0-9]+)/i)\n .token('IN', /in(?![-_a-z0-9]+)/i)\n .token('MATCHES_IGNORE_CASE', /matches\\s+ignore\\s+case(?![-_a-z0-9]+)/i)\n .token('CONTAINS', /contains(?![-_a-z0-9]+)/i)\n .token('ALL', /all(?![-_a-z0-9]+)/i)\n .token('ANY', /any(?![-_a-z0-9]+)/i)\n .token('EMPTY', /empty(?![-_a-z0-9]+)/i)\n .token('IS', /is(?![-_a-z0-9]+)/i)\n .token('DEFINED', /defined(?![-_a-z0-9]+)/i)\n\n .token('FLOAT', /\\d+\\.\\d+/)\n .token('INT', /\\d+/)\n .token('VARIABLE', /:([-_A-Za-z0-9]+)/)\n .token('BOOLEAN', /(true|false)/)\n .token('IDENTIFIER', /[-_A-Za-z0-9]+/)\n .token('STRING', /\"((?:\\\\.|[^\"\\\\])*)\"/)\n .token('STRING', /'((?:\\\\.|[^'\\\\])*)'/)\n\n .token('COMMA', ',')\n .token('(', '(')\n .token(')', ')')\n .token('>=', '>=')\n .token('<=', '<=')\n .token('>', '>')\n .token('<', '<')\n .token('!=', '!=')\n .token('=', '=')\n .token('\"', '\"')\n .token('WS', /\\s+/, true) // skip\n\n/**\n * This function converts a query expression in to a callable which returns a\n * boolean to indicate if the given object matches or not.\n *\n * This currently parses the predicate each time it is called, but it should be\n * straight-forward to add a query cache (lru-cache)\n */\nconst generateMatchFunc = (predicate: string): MatchFunc => {\n const lexer = getLexer(predicate)\n const parser = new Parser(lexer)\n .builder()\n .nud(\n 'IDENTIFIER',\n 100,\n (t) =>\n ({\n type: 'identifier',\n value: t.token.match,\n pos: t.token.strpos(),\n } as TypeSymbol)\n )\n .nud(\n 'BOOLEAN',\n 1,\n (t) =>\n ({\n type: 'boolean',\n value: t.token.match === 'true' ? true : false,\n pos: t.token.strpos(),\n } as TypeSymbol)\n )\n .nud(\n 'VARIABLE',\n 100,\n (t) =>\n ({\n type: 'var',\n // @ts-ignore\n value: t.token.groups[1],\n pos: t.token.strpos(),\n } as TypeSymbol)\n )\n .nud(\n 'STRING',\n 100,\n (t) =>\n ({\n type: 'string',\n // @ts-ignore\n value: t.token.groups[1],\n pos: t.token.strpos(),\n } as TypeSymbol)\n )\n .nud(\n 'INT',\n 1,\n (t) =>\n ({\n type: 'int',\n value: parseInt(t.token.match, 10),\n pos: t.token.strpos(),\n } as TypeSymbol)\n )\n .nud(\n 'FLOAT',\n 1,\n (t) =>\n ({\n type: 'float',\n value: parseFloat(t.token.match),\n pos: t.token.strpos(),\n } as TypeSymbol)\n )\n .nud('NOT', 100, ({ bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n return (obj: any) => !expr(obj)\n })\n .nud('EMPTY', 10, ({ bp }) => 'empty')\n .nud('DEFINED', 10, ({ bp }) => 'defined')\n\n .led('AND', 5, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n return (obj: any) => left(obj) && expr(obj)\n })\n .led('OR', 5, ({ left, token, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n return (obj: any, vars: object) => left(obj, vars) || expr(obj, vars)\n })\n .led('COMMA', 1, ({ left, token, bp }) => {\n const expr: any = parser.parse({ terminals: [bp - 1] })\n if (Array.isArray(expr)) {\n return [left, ...expr]\n } else {\n return [left, expr]\n }\n })\n .nud('(', 100, (t) => {\n const expr: any = parser.parse({ terminals: [')'] })\n return expr\n })\n .led('(', 100, ({ left, bp }) => {\n const expr = parser.parse()\n lexer.expect(')')\n return (obj: any, vars: object) => {\n const value = resolveValue(obj, left)\n if (value) {\n return expr(value)\n }\n return false\n }\n })\n .bp(')', 0)\n .led('=', 20, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n validateSymbol(expr)\n\n return (obj: any, vars: VariableMap) => {\n const resolvedValue = resolveValue(obj, left)\n const resolvedSymbol = resolveSymbol(expr, vars)\n if (Array.isArray(resolvedValue)) {\n return !!resolvedValue.some((elem) => elem === resolvedSymbol)\n }\n return resolvedValue === resolvedSymbol\n }\n })\n .led('!=', 20, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n validateSymbol(expr)\n return (obj: any, vars: VariableMap) =>\n resolveValue(obj, left) !== resolveSymbol(expr, vars)\n })\n .led('>', 20, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n validateSymbol(expr)\n\n return (obj: any, vars: object) =>\n resolveValue(obj, left) > resolveSymbol(expr, vars)\n })\n .led('>=', 20, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n validateSymbol(expr)\n\n return (obj: any, vars: object) =>\n resolveValue(obj, left) >= resolveSymbol(expr, vars)\n })\n .led('<', 20, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n validateSymbol(expr)\n\n return (obj: any, vars: object) =>\n resolveValue(obj, left) < resolveSymbol(expr, vars)\n })\n .led('<=', 20, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n validateSymbol(expr)\n\n return (obj: any, vars: object) =>\n resolveValue(obj, left) <= resolveSymbol(expr, vars)\n })\n .led('IS', 20, ({ left, bp }) => {\n let invert = false\n\n // Peek if this is a `is not` statement\n const next = lexer.peek()\n if (next.type === 'NOT') {\n invert = true\n lexer.next()\n }\n\n const expr: any = parser.parse({ terminals: [bp - 1] })\n\n switch (expr) {\n case 'empty': {\n if (!invert) {\n return (obj: any, vars: VariableMap) => {\n const val = resolveValue(obj, left)\n return val.length === 0\n }\n } else {\n return (obj: any, vars: VariableMap) => {\n const val = resolveValue(obj, left)\n return val.length !== 0\n }\n }\n }\n case 'defined': {\n if (!invert) {\n return (obj: any, vars: VariableMap) => {\n const val = resolveValue(obj, left)\n return val !== undefined\n }\n } else {\n return (obj: any, vars: VariableMap) => {\n const val = resolveValue(obj, left)\n return val === undefined\n }\n }\n }\n default: {\n throw new Error('Unexpected')\n }\n }\n })\n .led('IN', 20, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n return (obj: any, vars: object) => {\n let symbols = expr\n if (!Array.isArray(symbols)) {\n symbols = [expr]\n }\n\n const inValues = symbols.map((item: TypeSymbol) =>\n resolveSymbol(item, vars)\n )\n return inValues.includes(resolveValue(obj, left))\n }\n })\n .led('MATCHES_IGNORE_CASE', 20, ({ left, bp }) => {\n const expr = parser.parse({ terminals: [bp - 1] })\n validateSymbol(expr)\n\n return (obj: any, vars: VariableMap) => {\n const value = resolveValue(obj, left)\n const other = resolveSymbol(expr, vars)\n\n if (typeof value != 'string') {\n throw new PredicateError(\n `The field '${left.value}' does not support this expression.`\n )\n }\n return value.toLowerCase() === other.toLowerCase()\n }\n })\n .led('WITHIN', 20, ({ left, bp }) => {\n const type = lexer.next()\n\n if (type.match !== 'circle') {\n throw new PredicateError(\n `Invalid input '${type.match}', expected circle`\n )\n }\n\n lexer.expect('(')\n const expr = parser.parse({ terminals: [')'] })\n\n return (obj: any, vars: object) => {\n const value = resolveValue(obj, left)\n if (!value) return false\n\n const maxDistance = resolveSymbol(expr[2], vars)\n const distance = haversineDistance(\n {\n longitude: value[0],\n latitude: value[1],\n },\n {\n longitude: resolveSymbol(expr[0], vars),\n latitude: resolveSymbol(expr[1], vars),\n }\n )\n return distance <= maxDistance\n }\n })\n .led('CONTAINS', 20, ({ left, bp }) => {\n const keyword = lexer.next()\n\n let expr = parser.parse()\n if (!Array.isArray(expr)) {\n expr = [expr]\n }\n\n return (obj: any, vars: object) => {\n const value = resolveValue(obj, left)\n\n if (!Array.isArray(value)) {\n throw new PredicateError(\n `The field '${left.value}' does not support this expression.`\n )\n }\n\n const array = expr.map((item: TypeSymbol) => resolveSymbol(item, vars))\n if (keyword.type === 'ALL') {\n return array.every((item: any) => value.includes(item))\n } else {\n return array.some((item: any) => value.includes(item))\n }\n }\n })\n\n .build()\n\n const result = parser.parse()\n\n if (typeof result !== 'function') {\n const lines = predicate.split('\\n')\n const column = lines[lines.length - 1].length\n\n throw new PredicateError(\n `Unexpected end of input, expected SphereIdentifierChar, comparison ` +\n `operator, not, in, contains, is, within or matches` +\n ` (line ${lines.length}, column ${column})`\n )\n }\n return result\n}\n","import auth from 'basic-auth'\nimport bodyParser from 'body-parser'\nimport express, { type NextFunction, type Request, type Response } from 'express'\nimport {\n InvalidTokenError,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError, InvalidRequestError } from '../exceptions.js'\nimport { InvalidClientError, UnsupportedGrantType } from './errors.js'\nimport { OAuth2Store } from './store.js'\nimport { getBearerToken } from './helpers.js'\n\nexport class OAuth2Server {\n store: OAuth2Store\n\n constructor(options: { enabled: boolean; validate: boolean }) {\n this.store = new OAuth2Store(options.validate)\n }\n\n createRouter() {\n const router = express.Router()\n router.use(bodyParser.urlencoded({ extended: true }))\n router.post('/token', this.tokenHandler.bind(this))\n return router\n }\n\n createMiddleware() {\n return async (request: Request, response: Response, next: NextFunction) => {\n const token = getBearerToken(request)\n if (!token) {\n next(\n new CommercetoolsError<InvalidTokenError>(\n {\n code: 'invalid_token',\n message:\n 'This endpoint requires an access token. You can get one from the authorization server.',\n },\n 401\n )\n )\n }\n\n if (!token || !this.store.validateToken(token)) {\n next(\n new CommercetoolsError<InvalidTokenError>(\n {\n code: 'invalid_token',\n message: 'invalid_token',\n },\n 401\n )\n )\n }\n\n next()\n }\n }\n async tokenHandler(request: Request, response: Response, next: NextFunction) {\n const authHeader = request.header('Authorization')\n if (!authHeader) {\n return next(\n new CommercetoolsError<InvalidClientError>(\n {\n code: 'invalid_client',\n message:\n 'Please provide valid client credentials using HTTP Basic Authentication.',\n },\n 401\n )\n )\n }\n const credentials = auth.parse(authHeader)\n if (!credentials) {\n return next(\n new CommercetoolsError<InvalidClientError>(\n {\n code: 'invalid_client',\n message:\n 'Please provide valid client credentials using HTTP Basic Authentication.',\n },\n 400\n )\n )\n }\n\n const grantType = request.query.grant_type || request.body.grant_type\n if (!grantType) {\n return next(\n new CommercetoolsError<InvalidRequestError>(\n {\n code: 'invalid_request',\n message: 'Missing required parameter: grant_type.',\n },\n 400\n )\n )\n }\n\n if (grantType === 'client_credentials') {\n const token = this.store.getClientToken(\n credentials.name,\n credentials.pass,\n request.query.scope?.toString()\n )\n return response.status(200).send(token)\n } else {\n return next(\n new CommercetoolsError<UnsupportedGrantType>(\n {\n code: 'unsupported_grant_type',\n message: `Invalid parameter: grant_type: Invalid grant type: ${grantType}`,\n },\n 400\n )\n )\n }\n }\n}\n","import { randomBytes } from 'crypto'\n\ntype Token = {\n access_token: string\n token_type: 'Bearer'\n expires_in: number\n scope: string\n}\n\nexport class OAuth2Store {\n tokens: Token[] = []\n validate = true\n\n constructor(validate = true) {\n this.validate = validate\n }\n\n getClientToken(clientId: string, clientSecret: string, scope?: string) {\n const token: Token = {\n access_token: randomBytes(16).toString('base64'),\n token_type: 'Bearer',\n expires_in: 172800,\n scope: scope || 'todo',\n }\n this.tokens.push(token)\n return token\n }\n\n validateToken(token: string) {\n if (!this.validate) return true\n\n const foundToken = this.tokens.find((t) => t.access_token === token)\n if (foundToken) {\n return true\n }\n return false\n }\n}\n","import { Request } from 'express'\n\nexport const getBearerToken = (request: Request): string | undefined => {\n const authHeader = request.header('Authorization')\n const match = authHeader?.match(/^Bearer\\s(?<token>[^\\s]+)$/)\n if (match) {\n return match.groups?.token\n }\n return undefined\n}\n","import { getBaseResourceProperties } from './helpers.js'\nimport { GetParams } from './repositories/abstract.js'\nimport { RepositoryMap } from './repositories/index.js'\nimport { AbstractStorage } from './storage/index.js'\nimport { ResourceMap, ResourceType } from './types.js'\n\nexport class ProjectAPI {\n private projectKey: string\n private _storage: AbstractStorage\n private _repositories: RepositoryMap\n\n constructor(\n projectKey: string,\n repositories: RepositoryMap,\n storage: AbstractStorage\n ) {\n this.projectKey = projectKey\n this._storage = storage\n this._repositories = repositories\n }\n\n add<T extends keyof RepositoryMap & keyof ResourceMap>(\n typeId: T,\n resource: ResourceMap[T]\n ) {\n const repository = this._repositories[typeId]\n if (repository) {\n this._storage.add(this.projectKey, typeId, {\n ...getBaseResourceProperties(),\n ...resource,\n })\n } else {\n throw new Error(`Service for ${typeId} not implemented yet`)\n }\n }\n\n get<RT extends ResourceType>(\n typeId: RT,\n id: string,\n params?: GetParams\n ): ResourceMap[RT] {\n return this._storage.get(\n this.projectKey,\n typeId,\n id,\n params\n ) as ResourceMap[RT]\n }\n\n // TODO: Not sure if we want to expose this...\n getRepository<RT extends keyof RepositoryMap>(typeId: RT): RepositoryMap[RT] {\n const repository = this._repositories[typeId]\n if (repository !== undefined) {\n return repository as RepositoryMap[RT]\n }\n throw new Error('No such repository')\n }\n}\n","export const copyHeaders = (headers: Record<string, string>) => {\n const validHeaders = ['accept', 'host', 'authorization']\n const result: Record<string, string> = {}\n\n Object.entries(headers).forEach(([key, value]) => {\n if (validHeaders.includes(key.toLowerCase())) {\n result[key] = value\n }\n })\n\n return result\n}\n","export const DEFAULT_API_HOSTNAME =\n /^https:\\/\\/api\\..*?\\.commercetools.com:443$/\nexport const DEFAULT_AUTH_HOSTNAME =\n /^https:\\/\\/auth\\..*?\\.commercetools.com:443$/\n","import type {\n Address,\n BaseAddress,\n CentPrecisionMoney,\n CustomFields,\n CustomFieldsDraft,\n HighPrecisionMoney,\n HighPrecisionMoneyDraft,\n InvalidJsonInputError,\n Price,\n PriceDraft,\n Reference,\n ReferencedResourceNotFoundError,\n ResourceIdentifier,\n Store,\n StoreKeyReference,\n StoreReference,\n StoreResourceIdentifier,\n Type,\n TypedMoney,\n _Money,\n} from '@commercetools/platform-sdk'\nimport type { Request } from 'express'\nimport { v4 as uuidv4 } from 'uuid'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { AbstractStorage } from '../storage/index.js'\nimport { type RepositoryContext } from './abstract.js'\n\nexport const createAddress = (\n base: BaseAddress | undefined,\n projectKey: string,\n storage: AbstractStorage\n): Address | undefined => {\n if (!base) return undefined\n\n if (!base?.country) {\n throw new Error('Country is required')\n }\n\n return {\n ...base,\n }\n}\n\nexport const createCustomFields = (\n draft: CustomFieldsDraft | undefined,\n projectKey: string,\n storage: AbstractStorage\n): CustomFields | undefined => {\n if (!draft) return undefined\n if (!draft.type) return undefined\n if (!draft.type.typeId) return undefined\n if (!draft.fields) return undefined\n const typeResource = storage.getByResourceIdentifier(\n projectKey,\n draft.type\n ) as Type\n\n if (!typeResource) {\n throw new Error(\n `No type '${draft.type.typeId}' with id=${draft.type.id} or key=${draft.type.key}`\n )\n }\n\n return {\n type: {\n typeId: draft.type.typeId,\n id: typeResource.id,\n },\n fields: draft.fields,\n }\n}\n\nexport const createPrice = (draft: PriceDraft): Price => ({\n id: uuidv4(),\n value: createTypedMoney(draft.value),\n})\n\nexport const createCentPrecisionMoney = (value: _Money): CentPrecisionMoney => {\n // Taken from https://docs.adyen.com/development-resources/currency-codes\n let fractionDigits = 2\n switch (value.currencyCode.toUpperCase()) {\n case 'BHD':\n case 'IQD':\n case 'JOD':\n case 'KWD':\n case 'LYD':\n case 'OMR':\n case 'TND':\n fractionDigits = 3\n break\n case 'CVE':\n case 'DJF':\n case 'GNF':\n case 'IDR':\n case 'JPY':\n case 'KMF':\n case 'KRW':\n case 'PYG':\n case 'RWF':\n case 'UGX':\n case 'VND':\n case 'VUV':\n case 'XAF':\n case 'XOF':\n case 'XPF':\n fractionDigits = 0\n break\n default:\n fractionDigits = 2\n }\n\n if ((value as HighPrecisionMoney & HighPrecisionMoneyDraft).preciseAmount) {\n throw new Error('HighPrecisionMoney not supported')\n }\n\n return {\n type: 'centPrecision',\n // centAmont is only optional on HighPrecisionMoney, so this should never\n // fallback to 0\n centAmount: value.centAmount ?? 0,\n currencyCode: value.currencyCode,\n fractionDigits: fractionDigits,\n }\n}\n\nexport const createTypedMoney = (value: _Money): TypedMoney => {\n const result = createCentPrecisionMoney(value)\n return result\n}\n\nexport const resolveStoreReference = (\n ref: StoreResourceIdentifier | undefined,\n projectKey: string,\n storage: AbstractStorage\n): StoreKeyReference | undefined => {\n if (!ref) return undefined\n const resource = storage.getByResourceIdentifier(projectKey, ref)\n if (!resource) {\n throw new Error('No such store')\n }\n\n const store = resource as Store\n return {\n typeId: 'store',\n key: store.key,\n }\n}\n\nexport const getReferenceFromResourceIdentifier = <T extends Reference>(\n resourceIdentifier: ResourceIdentifier,\n projectKey: string,\n storage: AbstractStorage\n): T => {\n if (!resourceIdentifier.id && !resourceIdentifier.key) {\n throw new CommercetoolsError<InvalidJsonInputError>(\n {\n code: 'InvalidJsonInput',\n message: `${resourceIdentifier.typeId}: ResourceIdentifier requires an 'id' xor a 'key'`,\n detailedErrorMessage: `ResourceIdentifier requires an 'id' xor a 'key'`,\n },\n 400\n )\n }\n\n const resource = storage.getByResourceIdentifier(\n projectKey,\n resourceIdentifier\n )\n if (!resource) {\n const errIdentifier = resourceIdentifier.key\n ? `key '${resourceIdentifier.key}'`\n : `identifier '${resourceIdentifier.key}'`\n\n throw new CommercetoolsError<ReferencedResourceNotFoundError>(\n {\n code: 'ReferencedResourceNotFound',\n // @ts-ignore\n typeId: resourceIdentifier.typeId,\n 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).`,\n },\n 400\n )\n }\n\n return {\n typeId: resourceIdentifier.typeId,\n id: resource?.id,\n } as unknown as T\n}\n\nexport const getStoreKeyReference = (\n id: StoreResourceIdentifier,\n projectKey: string,\n storage: AbstractStorage\n): StoreKeyReference => {\n if (id.key) {\n return {\n typeId: 'store',\n key: id.key,\n }\n }\n const value = getReferenceFromResourceIdentifier<StoreReference>(\n id,\n projectKey,\n storage\n )\n\n if (!value.obj?.key) {\n throw new Error('No store found for reference')\n }\n return {\n typeId: 'store',\n key: value.obj?.key,\n }\n}\n\nexport const getRepositoryContext = (request: Request): RepositoryContext => ({\n projectKey: request.params.projectKey,\n storeKey: request.params.storeKey,\n})\n","import type { Update } from '@commercetools/platform-sdk'\nimport { Request, Response, Router } from 'express'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport { ProjectRepository } from '../repositories/project.js'\n\nexport class ProjectService {\n public repository: ProjectRepository\n\n constructor(parent: Router, repository: ProjectRepository) {\n this.repository = repository\n this.registerRoutes(parent)\n }\n\n registerRoutes(parent: Router) {\n parent.get('', this.get.bind(this))\n parent.post('', this.post.bind(this))\n }\n\n get(request: Request, response: Response) {\n const project = this.repository.get(getRepositoryContext(request))\n return response.status(200).send(project)\n }\n\n post(request: Request, response: Response) {\n const updateRequest: Update = request.body\n const project = this.repository.get(getRepositoryContext(request))\n\n if (!project) {\n return response.status(404).send({})\n }\n\n const updatedResource = this.repository.processUpdateActions(\n getRepositoryContext(request),\n project,\n updateRequest.version,\n updateRequest.actions\n )\n\n return response.status(200).send(updatedResource)\n }\n}\n","import type {\n BaseResource,\n Project,\n ResourceNotFoundError,\n UpdateAction,\n} from '@commercetools/platform-sdk'\nimport deepEqual from 'deep-equal'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { cloneObject } from '../helpers.js'\nimport { AbstractStorage } from '../storage/index.js'\nimport { ResourceMap, ResourceType, ShallowWritable } from './../types.js'\nimport { checkConcurrentModification } from './errors.js'\n\nexport type QueryParams = {\n expand?: string[]\n where?: string[]\n offset?: number\n limit?: number\n}\n\nexport type GetParams = {\n expand?: string[]\n}\n\nexport type RepositoryContext = {\n projectKey: string\n storeKey?: string\n}\n\nexport abstract class AbstractRepository<R extends BaseResource | Project> {\n protected _storage: AbstractStorage\n protected actions: Partial<\n Record<\n any,\n (context: RepositoryContext, resource: any, action: any) => void\n >\n > = {}\n\n constructor(storage: AbstractStorage) {\n this._storage = storage\n }\n\n abstract saveNew({ projectKey }: RepositoryContext, resource: R): void\n\n abstract saveUpdate(\n { projectKey }: RepositoryContext,\n version: number,\n resource: R\n ): void\n\n processUpdateActions(\n context: RepositoryContext,\n resource: R,\n version: number,\n actions: UpdateAction[]\n ): R {\n // Deep-copy\n const updatedResource = cloneObject(resource) as ShallowWritable<R>\n const identifier = (resource as BaseResource).id\n ? (resource as BaseResource).id\n : (resource as Project).key\n\n actions.forEach((action) => {\n const updateFunc = this.actions[action.action]\n\n if (!updateFunc) {\n console.error(`No mock implemented for update action ${action.action}`)\n throw new Error(\n `No mock implemented for update action ${action.action}`\n )\n }\n\n const beforeUpdate = cloneObject(resource)\n updateFunc(context, updatedResource, action)\n\n // Check if the object is updated. We need to increase the version of\n // an object per action which does an actual modification.\n // This isn't the most performant method to do this (the update action\n // should return a flag) but for now the easiest.\n if (!deepEqual(beforeUpdate, updatedResource)) {\n // We only check the version when there is an actual modification to\n // be stored.\n checkConcurrentModification(resource.version, version, identifier)\n\n updatedResource.version += 1\n }\n })\n\n // If all actions succeeded we write the new version\n // to the storage.\n if (resource.version != updatedResource.version) {\n this.saveUpdate(context, version, updatedResource)\n }\n\n const result = this.postProcessResource(updatedResource)\n if (!result) {\n throw new Error('invalid post process action')\n }\n return result\n }\n\n abstract postProcessResource(resource: any): any\n}\n\nexport abstract class AbstractResourceRepository<\n T extends ResourceType\n> extends AbstractRepository<ResourceMap[T]> {\n abstract create(context: RepositoryContext, draft: any): ResourceMap[T]\n abstract getTypeId(): T\n\n constructor(storage: AbstractStorage) {\n super(storage)\n }\n\n postProcessResource(resource: ResourceMap[T]): ResourceMap[T] {\n return resource\n }\n\n query(context: RepositoryContext, params: QueryParams = {}) {\n const result = this._storage.query(context.projectKey, this.getTypeId(), {\n expand: params.expand,\n where: params.where,\n offset: params.offset,\n limit: params.limit,\n })\n\n // @ts-ignore\n result.results = result.results.map(this.postProcessResource)\n return result\n }\n\n get(\n context: RepositoryContext,\n id: string,\n params: GetParams = {}\n ): ResourceMap[T] | null {\n const resource = this._storage.get(\n context.projectKey,\n this.getTypeId(),\n id,\n params\n )\n return resource ? this.postProcessResource(resource) : null\n }\n\n getByKey(\n context: RepositoryContext,\n key: string,\n params: GetParams = {}\n ): ResourceMap[T] | null {\n const resource = this._storage.getByKey(\n context.projectKey,\n this.getTypeId(),\n key,\n params\n )\n return resource ? this.postProcessResource(resource) : null\n }\n\n delete(\n context: RepositoryContext,\n id: string,\n params: GetParams = {}\n ): ResourceMap[T] | null {\n const resource = this._storage.delete(\n context.projectKey,\n this.getTypeId(),\n id,\n params\n )\n return resource ? this.postProcessResource(resource) : null\n }\n\n saveNew(\n context: RepositoryContext,\n resource: ShallowWritable<ResourceMap[T]>\n ) {\n resource.version = 1\n this._storage.add(context.projectKey, this.getTypeId(), resource as any)\n }\n\n saveUpdate(\n context: RepositoryContext,\n version: number,\n resource: ShallowWritable<ResourceMap[T]>\n ) {\n // Check if the resource still exists.\n const current = this._storage.get(\n context.projectKey,\n this.getTypeId(),\n resource.id\n )\n if (!current) {\n throw new CommercetoolsError<ResourceNotFoundError>(\n {\n code: 'ResourceNotFound',\n message: 'Resource not found while updating',\n },\n 400\n )\n }\n\n checkConcurrentModification(current.version, version, resource.id)\n\n if (current.version === resource.version) {\n throw new Error('Internal error: no changes to save')\n }\n resource.lastModifiedAt = new Date().toISOString()\n\n this._storage.add(context.projectKey, this.getTypeId(), resource as any)\n\n return resource\n }\n}\n","import { type ConcurrentModificationError } from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from '../exceptions.js'\n\nexport const checkConcurrentModification = (\n currentVersion: number,\n expectedVersion: number,\n identifier: string\n) => {\n if (currentVersion === expectedVersion) return\n console.error(\n `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`\n )\n\n throw new CommercetoolsError<ConcurrentModificationError>(\n {\n message: `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`,\n currentVersion: currentVersion,\n code: 'ConcurrentModification',\n },\n 409\n )\n}\n","import type { AssociateRole } from '@commercetools/platform-sdk'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\n\nexport class AssociateRoleRepository extends AbstractResourceRepository<'associate-role'> {\n getTypeId() {\n return 'associate-role' as const\n }\n create(context: RepositoryContext, draft: any): AssociateRole {\n throw new Error('Method not implemented.')\n }\n}\n","import type { AttributeGroup } from '@commercetools/platform-sdk'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\n\nexport class AttributeGroupRepository extends AbstractResourceRepository<'attribute-group'> {\n getTypeId() {\n return 'attribute-group' as const\n }\n create(context: RepositoryContext, draft: any): AttributeGroup {\n throw new Error('Method not implemented.')\n }\n}\n","import type { BusinessUnit } from '@commercetools/platform-sdk'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\n\nexport class BusinessUnitRepository extends AbstractResourceRepository<'business-unit'> {\n getTypeId() {\n return 'business-unit' as const\n }\n create(context: RepositoryContext, draft: any): BusinessUnit {\n throw new Error('Method not implemented.')\n }\n}\n","import type {\n Address,\n AddressDraft,\n Cart,\n CartAddLineItemAction,\n CartChangeLineItemQuantityAction,\n CartDraft,\n CartRemoveLineItemAction,\n CartSetBillingAddressAction,\n CartSetCountryAction,\n CartSetCustomerEmailAction,\n CartSetCustomFieldAction,\n CartSetCustomTypeAction,\n CartSetLocaleAction,\n CartSetShippingAddressAction,\n CartSetShippingMethodAction,\n CustomFields,\n GeneralError,\n LineItem,\n LineItemDraft,\n Price,\n Product,\n ProductPagedQueryResponse,\n ProductVariant,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\nimport { createAddress, createCustomFields } from './helpers.js'\n\nexport class CartRepository extends AbstractResourceRepository<'cart'> {\n getTypeId() {\n return 'cart' as const\n }\n\n create(context: RepositoryContext, draft: CartDraft): Cart {\n const lineItems =\n draft.lineItems?.map((draftLineItem) =>\n this.draftLineItemtoLineItem(\n context.projectKey,\n draftLineItem,\n draft.currency,\n draft.country\n )\n ) ?? []\n\n const resource: Writable<Cart> = {\n ...getBaseResourceProperties(),\n cartState: 'Active',\n country: draft.country,\n customLineItems: [],\n directDiscounts: [],\n discountCodes: [],\n inventoryMode: 'None',\n itemShippingAddresses: [],\n lineItems,\n locale: draft.locale,\n taxCalculationMode: draft.taxCalculationMode ?? 'LineItemLevel',\n taxMode: draft.taxMode ?? 'Platform',\n taxRoundingMode: draft.taxRoundingMode ?? 'HalfEven',\n totalPrice: {\n type: 'centPrecision',\n centAmount: 0,\n currencyCode: draft.currency,\n fractionDigits: 0,\n },\n shippingMode: 'Single',\n shipping: [],\n origin: draft.origin ?? 'Customer',\n refusedGifts: [],\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n resource.totalPrice.centAmount = calculateCartTotalPrice(resource)\n\n this.saveNew(context, resource)\n return resource\n }\n\n getActiveCart(projectKey: string): Cart | undefined {\n // Get first active cart\n const results = this._storage.query(projectKey, this.getTypeId(), {\n where: [`cartState=\"Active\"`],\n })\n if (results.count > 0) {\n return results.results[0] as Cart\n }\n\n return\n }\n\n actions = {\n addLineItem: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { productId, variantId, sku, quantity = 1 }: CartAddLineItemAction\n ) => {\n let product: Product | null = null\n\n if (productId && variantId) {\n // Fetch product and variant by ID\n product = this._storage.get(\n context.projectKey,\n 'product',\n productId,\n {}\n )\n } else if (sku) {\n // Fetch product and variant by SKU\n const items = this._storage.query(context.projectKey, 'product', {\n where: [\n `masterData(current(masterVariant(sku=\"${sku}\"))) or masterData(current(variants(sku=\"${sku}\")))`,\n ],\n }) as ProductPagedQueryResponse\n\n if (items.count === 1) {\n product = items.results[0]\n }\n }\n\n if (!product) {\n // Check if product is found\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: sku\n ? `A product containing a variant with SKU '${sku}' not found.`\n : `A product with ID '${productId}' not found.`,\n })\n }\n\n // Find matching variant\n const variant: ProductVariant | undefined = [\n product.masterData.current.masterVariant,\n ...product.masterData.current.variants,\n ].find((x) => {\n if (sku) return x.sku === sku\n if (variantId) return x.id === variantId\n return false\n })\n\n if (!variant) {\n // Check if variant is found\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: sku\n ? `A variant with SKU '${sku}' for product '${product.id}' not found.`\n : `A variant with ID '${variantId}' for product '${product.id}' not found.`,\n })\n }\n\n const alreadyAdded = resource.lineItems.some(\n (x) => x.productId === product?.id && x.variant.id === variant?.id\n )\n if (alreadyAdded) {\n // increase quantity and update total price\n resource.lineItems.forEach((x) => {\n if (x.productId === product?.id && x.variant.id === variant?.id) {\n x.quantity += quantity\n x.totalPrice.centAmount = calculateLineItemTotalPrice(x)\n }\n })\n } else {\n // add line item\n if (!variant.prices?.length) {\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: `A product with ID '${productId}' doesn't have any prices.`,\n })\n }\n\n const currency = resource.totalPrice.currencyCode\n\n const price = selectPrice({\n prices: variant.prices,\n currency,\n country: resource.country,\n })\n if (!price) {\n throw new Error(\n `No valid price found for ${productId} for country ${resource.country} and currency ${currency}`\n )\n }\n resource.lineItems.push({\n id: uuidv4(),\n productId: product.id,\n productKey: product.key,\n productSlug: product.masterData.current.slug,\n productType: product.productType,\n name: product.masterData.current.name,\n variant,\n price: price,\n taxedPricePortions: [],\n perMethodTaxRate: [],\n totalPrice: {\n ...price.value,\n type: 'centPrecision',\n centAmount: price.value.centAmount * quantity,\n },\n quantity,\n discountedPricePerQuantity: [],\n lineItemMode: 'Standard',\n priceMode: 'Platform',\n state: [],\n })\n }\n\n // Update cart total price\n resource.totalPrice.centAmount = calculateCartTotalPrice(resource)\n },\n changeLineItemQuantity: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { lineItemId, lineItemKey, quantity }: CartChangeLineItemQuantityAction\n ) => {\n let lineItem: Writable<LineItem> | undefined\n\n if (lineItemId) {\n lineItem = resource.lineItems.find((x) => x.id === lineItemId)\n if (!lineItem) {\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: `A line item with ID '${lineItemId}' not found.`,\n })\n }\n } else if (lineItemKey) {\n lineItem = resource.lineItems.find((x) => x.id === lineItemId)\n if (!lineItem) {\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: `A line item with Key '${lineItemKey}' not found.`,\n })\n }\n } else {\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: `Either lineItemid or lineItemKey needs to be provided.`,\n })\n }\n\n if (quantity === 0) {\n // delete line item\n resource.lineItems = resource.lineItems.filter(\n (x) => x.id !== lineItemId\n )\n } else {\n resource.lineItems.forEach((x) => {\n if (x.id === lineItemId && quantity) {\n x.quantity = quantity\n x.totalPrice.centAmount = calculateLineItemTotalPrice(x)\n }\n })\n }\n\n // Update cart total price\n resource.totalPrice.centAmount = calculateCartTotalPrice(resource)\n },\n removeLineItem: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { lineItemId, quantity }: CartRemoveLineItemAction\n ) => {\n const lineItem = resource.lineItems.find((x) => x.id === lineItemId)\n if (!lineItem) {\n // Check if product is found\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: `A line item with ID '${lineItemId}' not found.`,\n })\n }\n\n const shouldDelete = !quantity || quantity >= lineItem.quantity\n if (shouldDelete) {\n // delete line item\n resource.lineItems = resource.lineItems.filter(\n (x) => x.id !== lineItemId\n )\n } else {\n // decrease quantity and update total price\n resource.lineItems.forEach((x) => {\n if (x.id === lineItemId && quantity) {\n x.quantity -= quantity\n x.totalPrice.centAmount = calculateLineItemTotalPrice(x)\n }\n })\n }\n\n // Update cart total price\n resource.totalPrice.centAmount = calculateCartTotalPrice(resource)\n },\n setBillingAddress: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { address }: CartSetBillingAddressAction\n ) => {\n resource.billingAddress = createAddress(\n address,\n context.projectKey,\n this._storage\n )\n },\n setShippingMethod: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { shippingMethod }: CartSetShippingMethodAction\n ) => {\n if (shippingMethod) {\n const method = this._storage.getByResourceIdentifier<'shipping-method'>(\n context.projectKey,\n shippingMethod\n )\n\n if (!method) {\n throw new Error(`Type ${shippingMethod} not found`)\n }\n\n // Based on the address we should select a shipping zone and\n // use that to define the price.\n // @ts-ignore\n resource.shippingInfo = {\n shippingMethod: {\n typeId: 'shipping-method',\n id: method.id,\n },\n shippingMethodName: method.name,\n }\n } else {\n resource.shippingInfo = undefined\n }\n },\n setCountry: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { country }: CartSetCountryAction\n ) => {\n resource.country = country\n },\n setCustomerEmail: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { email }: CartSetCustomerEmailAction\n ) => {\n resource.customerEmail = email\n },\n setCustomField: (\n context: RepositoryContext,\n resource: Cart,\n { name, value }: CartSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n throw new Error('Resource has no custom field')\n }\n resource.custom.fields[name] = value\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { type, fields }: CartSetCustomTypeAction\n ) => {\n if (!type) {\n resource.custom = undefined\n } else {\n const resolvedType = this._storage.getByResourceIdentifier(\n context.projectKey,\n type\n )\n if (!resolvedType) {\n throw new Error(`Type ${type} not found`)\n }\n\n resource.custom = {\n type: {\n typeId: 'type',\n id: resolvedType.id,\n },\n fields: fields || {}\n }\n }\n },\n setLocale: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { locale }: CartSetLocaleAction\n ) => {\n resource.locale = locale\n },\n setShippingAddress: (\n context: RepositoryContext,\n resource: Writable<Cart>,\n { address }: CartSetShippingAddressAction\n ) => {\n if (!address) {\n resource.shippingAddress = undefined\n return\n }\n\n let custom: CustomFields | undefined = undefined\n if ((address as Address & AddressDraft).custom) {\n custom = createCustomFields(\n (address as Address & AddressDraft).custom,\n context.projectKey,\n this._storage\n )\n }\n\n resource.shippingAddress = {\n ...address,\n custom: custom,\n }\n },\n }\n draftLineItemtoLineItem = (\n projectKey: string,\n draftLineItem: LineItemDraft,\n currency: string,\n country: string | undefined\n ): LineItem => {\n const { productId, quantity, variantId, sku } = draftLineItem\n\n let product: Product | null = null\n\n if (productId && variantId) {\n // Fetch product and variant by ID\n product = this._storage.get(projectKey, 'product', productId, {})\n } else if (sku) {\n // Fetch product and variant by SKU\n const items = this._storage.query(projectKey, 'product', {\n where: [\n `masterData(current(masterVariant(sku=\"${sku}\"))) or masterData(current(variants(sku=\"${sku}\")))`,\n ],\n }) as ProductPagedQueryResponse\n\n if (items.count === 1) {\n product = items.results[0]\n }\n }\n\n if (!product) {\n // Check if product is found\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: sku\n ? `A product containing a variant with SKU '${sku}' not found.`\n : `A product with ID '${productId}' not found.`,\n })\n }\n\n // Find matching variant\n const variant = [\n product.masterData.current.masterVariant,\n ...product.masterData.current.variants,\n ].find((x) => {\n if (sku) return x.sku === sku\n if (variantId) return x.id === variantId\n return false\n })\n\n if (!variant) {\n // Check if variant is found\n throw new Error(\n sku\n ? `A variant with SKU '${sku}' for product '${product.id}' not found.`\n : `A variant with ID '${variantId}' for product '${product.id}' not found.`\n )\n }\n\n const quant = quantity ?? 1\n\n const price = selectPrice({ prices: variant.prices, currency, country })\n if (!price) {\n throw new Error(\n `No valid price found for ${productId} for country ${country} and currency ${currency}`\n )\n }\n\n return {\n id: uuidv4(),\n productId: product.id,\n productKey: product.key,\n productSlug: product.masterData.current.slug,\n productType: product.productType,\n name: product.masterData.current.name,\n variant,\n price: price,\n totalPrice: {\n type: 'centPrecision',\n currencyCode: price.value.currencyCode,\n fractionDigits: price.value.fractionDigits,\n centAmount: price.value.centAmount * quant,\n },\n taxedPricePortions: [],\n perMethodTaxRate: [],\n quantity: quant,\n discountedPricePerQuantity: [],\n lineItemMode: 'Standard',\n priceMode: 'Platform',\n state: [],\n }\n }\n}\n\nconst selectPrice = ({\n prices,\n currency,\n country,\n}: {\n prices: Price[] | undefined\n currency: string\n country: string | undefined\n}): Price | undefined => {\n if (!prices) {\n return undefined\n }\n\n // Quick-and-dirty way of selecting price based on the given currency and country.\n // Can be improved later to give more priority to exact matches over\n // 'all country' matches, and include customer groups in the mix as well\n return prices.find((price) => {\n const countryMatch = !price.country || price.country === country\n const currencyMatch = price.value.currencyCode === currency\n return countryMatch && currencyMatch\n })\n}\n\nconst calculateLineItemTotalPrice = (lineItem: LineItem): number =>\n lineItem.price!.value.centAmount * lineItem.quantity\n\nconst calculateCartTotalPrice = (cart: Cart): number =>\n cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0)\n","import type {\n CartDiscount,\n CartDiscountChangeIsActiveAction,\n CartDiscountChangeSortOrderAction,\n CartDiscountDraft,\n CartDiscountSetDescriptionAction,\n CartDiscountSetKeyAction,\n CartDiscountSetValidFromAction,\n CartDiscountSetValidFromAndUntilAction,\n CartDiscountSetValidUntilAction,\n CartDiscountUpdateAction,\n CartDiscountValueAbsolute,\n CartDiscountValueDraft,\n CartDiscountValueFixed,\n CartDiscountValueGiftLineItem,\n CartDiscountValueRelative,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\nimport {\n createTypedMoney,\n getStoreKeyReference,\n} from './helpers.js'\n\nexport class CartDiscountRepository extends AbstractResourceRepository<'cart-discount'> {\n getTypeId() {\n return 'cart-discount' as const\n }\n\n create(context: RepositoryContext, draft: CartDiscountDraft): CartDiscount {\n const resource: CartDiscount = {\n ...getBaseResourceProperties(),\n key: draft.key,\n description: draft.description,\n cartPredicate: draft.cartPredicate,\n isActive: draft.isActive || false,\n name: draft.name,\n stores:\n draft.stores?.map((s) =>\n getStoreKeyReference(s, context.projectKey, this._storage)\n ) ?? [],\n references: [],\n target: draft.target,\n requiresDiscountCode: draft.requiresDiscountCode || false,\n sortOrder: draft.sortOrder,\n stackingMode: draft.stackingMode || 'Stacking',\n validFrom: draft.validFrom,\n validUntil: draft.validUntil,\n value: this.transformValueDraft(draft.value),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n private transformValueDraft(value: CartDiscountValueDraft) {\n switch (value.type) {\n case 'absolute': {\n return {\n type: 'absolute',\n money: value.money.map(createTypedMoney),\n } as CartDiscountValueAbsolute\n }\n case 'fixed': {\n return {\n type: 'fixed',\n money: value.money.map(createTypedMoney),\n } as CartDiscountValueFixed\n }\n case 'giftLineItem': {\n return {\n ...value,\n } as CartDiscountValueGiftLineItem\n }\n case 'relative': {\n return {\n ...value,\n } as CartDiscountValueRelative\n }\n }\n\n return value\n }\n\n actions: Partial<\n Record<\n CartDiscountUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<CartDiscount>,\n action: any\n ) => void\n >\n > = {\n setKey: (\n context: RepositoryContext,\n resource: Writable<CartDiscount>,\n { key }: CartDiscountSetKeyAction\n ) => {\n resource.key = key\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<CartDiscount>,\n { description }: CartDiscountSetDescriptionAction\n ) => {\n resource.description = description\n },\n setValidFrom: (\n context: RepositoryContext,\n resource: Writable<CartDiscount>,\n { validFrom }: CartDiscountSetValidFromAction\n ) => {\n resource.validFrom = validFrom\n },\n setValidUntil: (\n context: RepositoryContext,\n resource: Writable<CartDiscount>,\n { validUntil }: CartDiscountSetValidUntilAction\n ) => {\n resource.validUntil = validUntil\n },\n setValidFromAndUntil: (\n context: RepositoryContext,\n resource: Writable<CartDiscount>,\n { validFrom, validUntil }: CartDiscountSetValidFromAndUntilAction\n ) => {\n resource.validFrom = validFrom\n resource.validUntil = validUntil\n },\n changeSortOrder: (\n context: RepositoryContext,\n resource: Writable<CartDiscount>,\n { sortOrder }: CartDiscountChangeSortOrderAction\n ) => {\n resource.sortOrder = sortOrder\n },\n changeIsActive: (\n context: RepositoryContext,\n resource: Writable<CartDiscount>,\n { isActive }: CartDiscountChangeIsActiveAction\n ) => {\n resource.isActive = isActive\n },\n }\n}\n","import type {\n Category,\n CategoryChangeAssetNameAction,\n CategoryChangeSlugAction,\n CategoryDraft,\n CategorySetAssetDescriptionAction,\n CategorySetAssetSourcesAction,\n CategorySetCustomFieldAction,\n CategorySetCustomTypeAction,\n CategorySetDescriptionAction,\n CategorySetKeyAction,\n CategorySetMetaDescriptionAction,\n CategorySetMetaKeywordsAction,\n CategorySetMetaTitleAction,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\nimport { createCustomFields } from './helpers.js'\n\nexport class CategoryRepository extends AbstractResourceRepository<'category'> {\n getTypeId() {\n return 'category' as const\n }\n\n create(context: RepositoryContext, draft: CategoryDraft): Category {\n const resource: Category = {\n ...getBaseResourceProperties(),\n key: draft.key,\n name: draft.name,\n slug: draft.slug,\n orderHint: draft.orderHint || '',\n externalId: draft.externalId || '',\n parent: draft.parent\n ? { typeId: 'category', id: draft.parent.id! }\n : undefined,\n ancestors: [], // TODO\n assets:\n draft.assets?.map((d) => ({\n id: uuidv4(),\n name: d.name,\n description: d.description,\n sources: d.sources,\n tags: d.tags,\n key: d.key,\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n })) || [],\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions = {\n changeAssetName: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { assetId, assetKey, name }: CategoryChangeAssetNameAction\n ) => {\n resource.assets?.forEach((asset) => {\n if (assetId && assetId === asset.id) {\n asset.name = name\n }\n if (assetKey && assetKey === asset.key) {\n asset.name = name\n }\n })\n },\n changeSlug: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { slug }: CategoryChangeSlugAction\n ) => {\n resource.slug = slug\n },\n setKey: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { key }: CategorySetKeyAction\n ) => {\n resource.key = key\n },\n setAssetDescription: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { assetId, assetKey, description }: CategorySetAssetDescriptionAction\n ) => {\n resource.assets?.forEach((asset) => {\n if (assetId && assetId === asset.id) {\n asset.description = description\n }\n if (assetKey && assetKey === asset.key) {\n asset.description = description\n }\n })\n },\n setAssetSources: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { assetId, assetKey, sources }: CategorySetAssetSourcesAction\n ) => {\n resource.assets?.forEach((asset) => {\n if (assetId && assetId === asset.id) {\n asset.sources = sources\n }\n if (assetKey && assetKey === asset.key) {\n asset.sources = sources\n }\n })\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { description }: CategorySetDescriptionAction\n ) => {\n resource.description = description\n },\n setMetaDescription: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { metaDescription }: CategorySetMetaDescriptionAction\n ) => {\n resource.metaDescription = metaDescription\n },\n setMetaKeywords: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { metaKeywords }: CategorySetMetaKeywordsAction\n ) => {\n resource.metaKeywords = metaKeywords\n },\n setMetaTitle: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { metaTitle }: CategorySetMetaTitleAction\n ) => {\n resource.metaTitle = metaTitle\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { type, fields }: CategorySetCustomTypeAction\n ) => {\n if (type) {\n resource.custom = createCustomFields(\n { type, fields },\n context.projectKey,\n this._storage\n )\n } else {\n resource.custom = undefined\n }\n },\n setCustomField: (\n context: RepositoryContext,\n resource: Writable<Category>,\n { name, value }: CategorySetCustomFieldAction\n ) => {\n if (!resource.custom) {\n return\n }\n if (value === null) {\n delete resource.custom.fields[name]\n } else {\n resource.custom.fields[name] = value\n }\n },\n }\n}\n","import type {\n Channel,\n ChannelChangeDescriptionAction,\n ChannelChangeKeyAction,\n ChannelChangeNameAction,\n ChannelDraft,\n ChannelSetAddressAction,\n ChannelSetCustomFieldAction,\n ChannelSetCustomTypeAction,\n ChannelSetGeoLocationAction,\n ChannelUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\nimport { createAddress, createCustomFields } from './helpers.js'\n\nexport class ChannelRepository extends AbstractResourceRepository<'channel'> {\n getTypeId() {\n return 'channel' as const\n }\n\n create(context: RepositoryContext, draft: ChannelDraft): Channel {\n const resource: Channel = {\n ...getBaseResourceProperties(),\n key: draft.key,\n name: draft.name,\n description: draft.description,\n roles: draft.roles || [],\n geoLocation: draft.geoLocation,\n address: createAddress(draft.address, context.projectKey, this._storage),\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions: Partial<\n Record<\n ChannelUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Channel>,\n action: any\n ) => void\n >\n > = {\n changeKey: (\n context: RepositoryContext,\n resource: Writable<Channel>,\n { key }: ChannelChangeKeyAction\n ) => {\n resource.key = key\n },\n\n changeName: (\n context: RepositoryContext,\n resource: Writable<Channel>,\n { name }: ChannelChangeNameAction\n ) => {\n resource.name = name\n },\n\n changeDescription: (\n context: RepositoryContext,\n resource: Writable<Channel>,\n { description }: ChannelChangeDescriptionAction\n ) => {\n resource.description = description\n },\n\n setAddress: (\n context: RepositoryContext,\n resource: Writable<Channel>,\n { address }: ChannelSetAddressAction\n ) => {\n resource.address = createAddress(\n address,\n context.projectKey,\n this._storage\n )\n },\n\n setGeoLocation: (\n context: RepositoryContext,\n resource: Writable<Channel>,\n { geoLocation }: ChannelSetGeoLocationAction\n ) => {\n resource.geoLocation = geoLocation\n },\n\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<Channel>,\n { type, fields }: ChannelSetCustomTypeAction\n ) => {\n if (type) {\n resource.custom = createCustomFields(\n { type, fields },\n context.projectKey,\n this._storage\n )\n } else {\n resource.custom = undefined\n }\n },\n setCustomField: (\n context: RepositoryContext,\n resource: Writable<Channel>,\n { name, value }: ChannelSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n return\n }\n if (value === null) {\n delete resource.custom.fields[name]\n } else {\n resource.custom.fields[name] = value\n }\n },\n }\n}\n","import type {\n CustomObject,\n CustomObjectDraft,\n InvalidOperationError,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { cloneObject, getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\nimport { checkConcurrentModification } from './errors.js'\n\nexport class CustomObjectRepository extends AbstractResourceRepository<'key-value-document'> {\n getTypeId() {\n return 'key-value-document' as const\n }\n\n create(\n context: RepositoryContext,\n draft: Writable<CustomObjectDraft>\n ): CustomObject {\n const current = this.getWithContainerAndKey(\n context,\n draft.container,\n draft.key\n ) as Writable<CustomObject | undefined>\n\n if (current) {\n // Only check version if it is passed in the draft\n if (draft.version) {\n checkConcurrentModification(current.version, draft.version, current.id)\n } else {\n draft.version = current.version\n }\n\n if (draft.value !== current.value) {\n const updated = cloneObject(current) as Writable<CustomObject>\n updated.value = draft.value\n updated.version += 1\n this.saveUpdate(context, draft.version, updated)\n return updated\n }\n return current\n } else {\n // If the resource is new the only valid version is 0\n if (draft.version) {\n throw new CommercetoolsError<InvalidOperationError>(\n {\n code: 'InvalidOperation',\n message: 'version on create must be 0',\n },\n 400\n )\n }\n const baseProperties = getBaseResourceProperties()\n const resource: CustomObject = {\n ...baseProperties,\n container: draft.container,\n key: draft.key,\n value: draft.value,\n }\n\n this.saveNew(context, resource)\n return resource\n }\n }\n\n getWithContainerAndKey(\n context: RepositoryContext,\n container: string,\n key: string\n ) {\n const items = this._storage.all(context.projectKey, this.getTypeId())\n return items.find(\n (item) => item.container === container && item.key === key\n )\n }\n}\n","import type {\n Customer,\n CustomerChangeEmailAction,\n CustomerDraft,\n CustomerSetAuthenticationModeAction,\n CustomerSetCustomFieldAction,\n InvalidInputError,\n InvalidJsonInputError,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n AbstractResourceRepository,\n type RepositoryContext,\n} from './abstract.js'\n\nexport class CustomerRepository extends AbstractResourceRepository<'customer'> {\n getTypeId() {\n return 'customer' as const\n }\n\n create(context: RepositoryContext, draft: CustomerDraft): Customer {\n const resource: Customer = {\n ...getBaseResourceProperties(),\n authenticationMode: draft.authenticationMode || 'Password',\n email: draft.email,\n password: draft.password\n ? Buffer.from(draft.password).toString('base64')\n : undefined,\n isEmailVerified: draft.isEmailVerified || false,\n addresses: [],\n }\n this.saveNew(context, resource)\n return resource\n }\n\n getMe(context: RepositoryContext): Customer | undefined {\n const results = this._storage.query(\n context.projectKey,\n this.getTypeId(),\n {}\n ) // grab the first customer you can find\n if (results.count > 0) {\n return results.results[0] as Customer\n }\n\n return\n }\n\n actions = {\n changeEmail: (\n _context: RepositoryContext,\n resource: Writable<Customer>,\n { email }: CustomerChangeEmailAction\n ) => {\n resource.email = email\n },\n setAuthenticationMode: (\n _context: RepositoryContext,\n resource: Writable<Customer>,\n { authMode, password }: CustomerSetAuthenticationModeAction\n ) => {\n if (resource.authenticationMode === authMode) {\n throw new CommercetoolsError<InvalidInputError>(\n {\n code: 'InvalidInput',\n message: `The customer is already using the '${resource.authenticationMode}' authentication mode.`,\n },\n 400\n )\n }\n resource.authenticationMode = authMode\n if (authMode === 'ExternalAuth') {\n delete resource.password\n return\n }\n if (authMode === 'Password') {\n resource.password = password\n ? Buffer.from(password).toString('base64')\n : undefined\n return\n }\n throw new CommercetoolsError<InvalidJsonInputError>(\n {\n code: 'InvalidJsonInput',\n message: 'Request body does not contain valid JSON.',\n detailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`,\n },\n 400\n )\n },\n setCustomField: (\n _context: RepositoryContext,\n resource: Writable<Customer>,\n { name, value }: CustomerSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n throw new Error('Resource has no custom field')\n }\n resource.custom.fields[name] = value\n },\n }\n}\n","import type {\n CustomerGroup,\n CustomerGroupChangeNameAction,\n CustomerGroupDraft,\n CustomerGroupSetCustomFieldAction,\n CustomerGroupSetCustomTypeAction,\n CustomerGroupSetKeyAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\nimport { createCustomFields } from './helpers.js'\n\nexport class CustomerGroupRepository extends AbstractResourceRepository<'customer-group'> {\n getTypeId() {\n return 'customer-group' as const\n }\n create(context: RepositoryContext, draft: CustomerGroupDraft): CustomerGroup {\n const resource: CustomerGroup = {\n ...getBaseResourceProperties(),\n key: draft.key,\n name: draft.groupName,\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions = {\n setKey: (\n context: RepositoryContext,\n resource: Writable<CustomerGroup>,\n { key }: CustomerGroupSetKeyAction\n ) => {\n resource.key = key\n },\n changeName: (\n context: RepositoryContext,\n resource: Writable<CustomerGroup>,\n { name }: CustomerGroupChangeNameAction\n ) => {\n resource.name = name\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<CustomerGroup>,\n { type, fields }: CustomerGroupSetCustomTypeAction\n ) => {\n if (type) {\n resource.custom = createCustomFields(\n { type, fields },\n context.projectKey,\n this._storage\n )\n } else {\n resource.custom = undefined\n }\n },\n setCustomField: (\n context: RepositoryContext,\n resource: Writable<CustomerGroup>,\n { name, value }: CustomerGroupSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n return\n }\n if (value === null) {\n delete resource.custom.fields[name]\n } else {\n resource.custom.fields[name] = value\n }\n },\n }\n}\n","import type {\n CartDiscountReference,\n DiscountCode,\n DiscountCodeChangeCartDiscountsAction,\n DiscountCodeChangeIsActiveAction,\n DiscountCodeDraft,\n DiscountCodeSetCartPredicateAction,\n DiscountCodeSetCustomFieldAction,\n DiscountCodeSetCustomTypeAction,\n DiscountCodeSetDescriptionAction,\n DiscountCodeSetMaxApplicationsAction,\n DiscountCodeSetMaxApplicationsPerCustomerAction,\n DiscountCodeSetNameAction,\n DiscountCodeSetValidFromAction,\n DiscountCodeSetValidFromAndUntilAction,\n DiscountCodeSetValidUntilAction,\n DiscountCodeUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\nimport { createCustomFields } from './helpers.js'\n\nexport class DiscountCodeRepository extends AbstractResourceRepository<'discount-code'> {\n getTypeId() {\n return 'discount-code' as const\n }\n\n create(context: RepositoryContext, draft: DiscountCodeDraft): DiscountCode {\n const resource: DiscountCode = {\n ...getBaseResourceProperties(),\n applicationVersion: 1,\n cartDiscounts: draft.cartDiscounts.map(\n (obj): CartDiscountReference => ({\n typeId: 'cart-discount',\n id: obj.id!,\n })\n ),\n cartPredicate: draft.cartPredicate,\n code: draft.code,\n description: draft.description,\n groups: draft.groups || [],\n isActive: draft.isActive || true,\n name: draft.name,\n references: [],\n validFrom: draft.validFrom,\n validUntil: draft.validUntil,\n maxApplications: draft.maxApplications,\n maxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions: Partial<\n Record<\n DiscountCodeUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n action: any\n ) => void\n >\n > = {\n changeIsActive: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { isActive }: DiscountCodeChangeIsActiveAction\n ) => {\n resource.isActive = isActive\n },\n changeCartDiscounts: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { cartDiscounts }: DiscountCodeChangeCartDiscountsAction\n ) => {\n resource.cartDiscounts = cartDiscounts.map(\n (obj): CartDiscountReference => ({\n typeId: 'cart-discount',\n id: obj.id!,\n })\n )\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { description }: DiscountCodeSetDescriptionAction\n ) => {\n resource.description = description\n },\n setCartPredicate: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { cartPredicate }: DiscountCodeSetCartPredicateAction\n ) => {\n resource.cartPredicate = cartPredicate\n },\n setName: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { name }: DiscountCodeSetNameAction\n ) => {\n resource.name = name\n },\n setMaxApplications: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { maxApplications }: DiscountCodeSetMaxApplicationsAction\n ) => {\n resource.maxApplications = maxApplications\n },\n setMaxApplicationsPerCustomer: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n {\n maxApplicationsPerCustomer,\n }: DiscountCodeSetMaxApplicationsPerCustomerAction\n ) => {\n resource.maxApplicationsPerCustomer = maxApplicationsPerCustomer\n },\n setValidFrom: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { validFrom }: DiscountCodeSetValidFromAction\n ) => {\n resource.validFrom = validFrom\n },\n setValidUntil: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { validUntil }: DiscountCodeSetValidUntilAction\n ) => {\n resource.validUntil = validUntil\n },\n setValidFromAndUntil: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { validFrom, validUntil }: DiscountCodeSetValidFromAndUntilAction\n ) => {\n resource.validFrom = validFrom\n resource.validUntil = validUntil\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { type, fields }: DiscountCodeSetCustomTypeAction\n ) => {\n if (type) {\n resource.custom = createCustomFields(\n { type, fields },\n context.projectKey,\n this._storage\n )\n } else {\n resource.custom = undefined\n }\n },\n setCustomField: (\n context: RepositoryContext,\n resource: Writable<DiscountCode>,\n { name, value }: DiscountCodeSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n return\n }\n if (value === null) {\n delete resource.custom.fields[name]\n } else {\n resource.custom.fields[name] = value\n }\n },\n }\n}\n","import { cloneObject } from '../helpers.js'\n\nexport const maskSecretValue = <T>(resource: T, path: string): T => {\n const parts = path.split('.')\n const clone = cloneObject(resource) as any\n let val = clone\n\n const target = parts.pop()\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i]\n val = val[part]\n\n if (val === undefined) {\n return resource\n }\n }\n\n if (val && target && val[target]) {\n val[target] = '****'\n }\n return clone\n}\n","import type {\n Extension,\n ExtensionChangeDestinationAction,\n ExtensionChangeTriggersAction,\n ExtensionDraft,\n ExtensionSetKeyAction,\n ExtensionSetTimeoutInMsAction,\n ExtensionUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { maskSecretValue } from '../lib/masking.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\n\nexport class ExtensionRepository extends AbstractResourceRepository<'extension'> {\n getTypeId() {\n return 'extension' as const\n }\n\n postProcessResource(resource: Extension): Extension {\n if (resource) {\n const extension = resource as Extension\n if (\n extension.destination.type === 'HTTP' &&\n extension.destination.authentication?.type === 'AuthorizationHeader'\n ) {\n return maskSecretValue(\n extension,\n 'destination.authentication.headerValue'\n )\n } else if (extension.destination.type == 'AWSLambda') {\n return maskSecretValue(resource, 'destination.accessSecret')\n }\n }\n return resource\n }\n\n create(context: RepositoryContext, draft: ExtensionDraft): Extension {\n const resource: Extension = {\n ...getBaseResourceProperties(),\n key: draft.key,\n timeoutInMs: draft.timeoutInMs,\n destination: draft.destination,\n triggers: draft.triggers,\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions: Record<\n ExtensionUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Extension>,\n action: any\n ) => void\n > = {\n setKey: (\n context: RepositoryContext,\n resource: Writable<Extension>,\n { key }: ExtensionSetKeyAction\n ) => {\n resource.key = key\n },\n setTimeoutInMs: (\n context: RepositoryContext,\n resource: Writable<Extension>,\n { timeoutInMs }: ExtensionSetTimeoutInMsAction\n ) => {\n resource.timeoutInMs = timeoutInMs\n },\n changeTriggers: (\n context: RepositoryContext,\n resource: Writable<Extension>,\n { triggers }: ExtensionChangeTriggersAction\n ) => {\n resource.triggers = triggers\n },\n changeDestination: (\n context: RepositoryContext,\n resource: Writable<Extension>,\n { destination }: ExtensionChangeDestinationAction\n ) => {\n resource.destination = destination\n },\n }\n}\n","import type {\n InventoryEntry,\n InventoryEntryChangeQuantityAction,\n InventoryEntryDraft,\n InventoryEntrySetCustomFieldAction,\n InventoryEntrySetCustomTypeAction,\n InventoryEntrySetExpectedDeliveryAction,\n InventoryEntrySetRestockableInDaysAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, type RepositoryContext } from './abstract.js'\nimport { createCustomFields } from './helpers.js'\n\nexport class InventoryEntryRepository extends AbstractResourceRepository<'inventory-entry'> {\n getTypeId() {\n return 'inventory-entry' as const\n }\n\n create(\n context: RepositoryContext,\n draft: InventoryEntryDraft\n ): InventoryEntry {\n const resource: InventoryEntry = {\n ...getBaseResourceProperties(),\n sku: draft.sku,\n quantityOnStock: draft.quantityOnStock,\n availableQuantity: draft.quantityOnStock,\n expectedDelivery: draft.expectedDelivery,\n restockableInDays: draft.restockableInDays,\n supplyChannel: {\n ...draft.supplyChannel,\n typeId: 'channel',\n id: draft.supplyChannel?.id ?? '',\n },\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions = {\n changeQuantity: (\n context: RepositoryContext,\n resource: Writable<InventoryEntry>,\n { quantity }: InventoryEntryChangeQuantityAction\n ) => {\n resource.quantityOnStock = quantity\n // don't know active reservations so just set to same value\n resource.availableQuantity = quantity\n },\n setExpectedDelivery: (\n context: RepositoryContext,\n resource: Writable<InventoryEntry>,\n { expectedDelivery }: InventoryEntrySetExpectedDeliveryAction\n ) => {\n resource.expectedDelivery = new Date(expectedDelivery!).toISOString()\n },\n setCustomField: (\n context: RepositoryContext,\n resource: InventoryEntry,\n { name, value }: InventoryEntrySetCustomFieldAction\n ) => {\n if (!resource.custom) {\n throw new Error('Resource has no custom field')\n }\n resource.custom.fields[name] = value\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<InventoryEntry>,\n { type, fields }: InventoryEntrySetCustomTypeAction\n ) => {\n if (!type) {\n resource.custom = undefined\n } else {\n const resolvedType = this._storage.getByResourceIdentifier(\n context.projectKey,\n type\n )\n if (!resolvedType) {\n throw new Error(`Type ${type} not found`)\n }\n\n resource.custom = {\n type: {\n typeId: 'type',\n id: resolvedType.id,\n },\n fields: fields || {},\n }\n }\n },\n setRestockableInDays: (\n context: RepositoryContext,\n resource: Writable<InventoryEntry>,\n { restockableInDays }: InventoryEntrySetRestockableInDaysAction\n ) => {\n resource.restockableInDays = restockableInDays\n },\n }\n}\n","import type {\n CartReference,\n MyOrderFromCartDraft,\n Order,\n} from '@commercetools/platform-sdk'\nimport assert from 'assert'\nimport { type RepositoryContext } from './abstract.js'\nimport { OrderRepository } from './order.js'\n\nexport class MyOrderRepository extends OrderRepository {\n create(context: RepositoryContext, draft: MyOrderFromCartDraft): Order {\n assert(draft.id, 'draft.id is missing')\n const cartIdentifier = {\n id: draft.id,\n typeId: 'cart',\n } as CartReference\n return this.createFromCart(context, cartIdentifier)\n }\n}\n","import type {\n Cart,\n CartReference,\n CustomLineItem,\n CustomLineItemDraft,\n GeneralError,\n LineItem,\n LineItemImportDraft,\n Order,\n OrderAddPaymentAction,\n OrderChangeOrderStateAction,\n OrderChangePaymentStateAction,\n OrderFromCartDraft,\n OrderImportDraft,\n OrderSetBillingAddressAction,\n OrderSetCustomerEmailAction,\n OrderSetCustomFieldAction,\n OrderSetCustomTypeAction,\n OrderSetLocaleAction,\n OrderSetOrderNumberAction,\n OrderSetShippingAddressAction,\n OrderSetStoreAction,\n OrderTransitionStateAction,\n Product,\n ProductPagedQueryResponse,\n ProductVariant,\n State,\n Store,\n} from '@commercetools/platform-sdk'\nimport assert from 'assert'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n AbstractResourceRepository,\n type QueryParams,\n RepositoryContext,\n} from './abstract.js'\nimport {\n createAddress,\n createCentPrecisionMoney,\n createCustomFields,\n createPrice,\n createTypedMoney,\n resolveStoreReference,\n} from './helpers.js'\n\nexport class OrderRepository extends AbstractResourceRepository<'order'> {\n getTypeId() {\n return 'order' as const\n }\n\n create(context: RepositoryContext, draft: OrderFromCartDraft): Order {\n assert(draft.cart, 'draft.cart is missing')\n return this.createFromCart(\n context,\n {\n id: draft.cart.id!,\n typeId: 'cart',\n },\n draft.orderNumber\n )\n }\n\n createFromCart(\n context: RepositoryContext,\n cartReference: CartReference,\n orderNumber?: string\n ) {\n const cart = this._storage.getByResourceIdentifier(\n context.projectKey,\n cartReference\n ) as Cart | null\n if (!cart) {\n throw new Error('Cannot find cart')\n }\n\n const resource: Order = {\n ...getBaseResourceProperties(),\n orderNumber,\n cart: cartReference,\n orderState: 'Open',\n lineItems: [],\n customLineItems: [],\n totalPrice: cart.totalPrice,\n refusedGifts: [],\n origin: 'Customer',\n syncInfo: [],\n shippingMode: cart.shippingMode,\n shipping: cart.shipping,\n store: context.storeKey\n ? {\n key: context.storeKey,\n typeId: 'store',\n }\n : undefined,\n lastMessageSequenceNumber: 0,\n }\n this.saveNew(context, resource)\n return resource\n }\n\n import(context: RepositoryContext, draft: OrderImportDraft): Order {\n // TODO: Check if order with given orderNumber already exists\n assert(this, 'OrderRepository not valid')\n const resource: Order = {\n ...getBaseResourceProperties(),\n\n billingAddress: createAddress(\n draft.billingAddress,\n context.projectKey,\n this._storage\n ),\n shippingAddress: createAddress(\n draft.shippingAddress,\n context.projectKey,\n this._storage\n ),\n\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n customerEmail: draft.customerEmail,\n lastMessageSequenceNumber: 0,\n orderNumber: draft.orderNumber,\n orderState: draft.orderState || 'Open',\n origin: draft.origin || 'Customer',\n paymentState: draft.paymentState,\n refusedGifts: [],\n shippingMode: 'Single',\n shipping: [],\n\n store: resolveStoreReference(\n draft.store,\n context.projectKey,\n this._storage\n ),\n syncInfo: [],\n\n lineItems:\n draft.lineItems?.map((item) =>\n this.lineItemFromImportDraft.bind(this)(context, item)\n ) || [],\n customLineItems:\n draft.customLineItems?.map((item) =>\n this.customLineItemFromImportDraft.bind(this)(context, item)\n ) || [],\n\n totalPrice: createCentPrecisionMoney(draft.totalPrice),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n private lineItemFromImportDraft(\n context: RepositoryContext,\n draft: LineItemImportDraft\n ): LineItem {\n let product: Product\n let variant: ProductVariant | undefined\n\n if (draft.variant.sku) {\n variant = {\n id: 0,\n sku: draft.variant.sku,\n }\n\n const items = this._storage.query(context.projectKey, 'product', {\n where: [\n `masterData(current(masterVariant(sku=\"${draft.variant.sku}\"))) or masterData(current(variants(sku=\"${draft.variant.sku}\")))`,\n ],\n }) as ProductPagedQueryResponse\n\n if (items.count !== 1) {\n throw new CommercetoolsError<GeneralError>({\n code: 'General',\n message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`,\n })\n }\n\n product = items.results[0]\n if (product.masterData.current.masterVariant.sku === draft.variant.sku) {\n variant = product.masterData.current.masterVariant\n } else {\n variant = product.masterData.current.variants.find(\n (v) => v.sku === draft.variant.sku\n )\n }\n if (!variant) {\n throw new Error('Internal state error')\n }\n } else {\n throw new Error('No product found')\n }\n\n const lineItem: LineItem = {\n ...getBaseResourceProperties(),\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n discountedPricePerQuantity: [],\n lineItemMode: 'Standard',\n name: draft.name,\n price: createPrice(draft.price),\n priceMode: 'Platform',\n productId: product.id,\n productType: product.productType,\n quantity: draft.quantity,\n state: draft.state || [],\n taxRate: draft.taxRate,\n taxedPricePortions: [],\n perMethodTaxRate: [],\n totalPrice: createCentPrecisionMoney(draft.price.value),\n variant: {\n id: variant.id,\n sku: variant.sku,\n price: createPrice(draft.price),\n },\n }\n\n return lineItem\n }\n\n private customLineItemFromImportDraft(\n context: RepositoryContext,\n draft: CustomLineItemDraft\n ): CustomLineItem {\n const lineItem: CustomLineItem = {\n ...getBaseResourceProperties(),\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n discountedPricePerQuantity: [],\n money: createTypedMoney(draft.money),\n name: draft.name,\n quantity: draft.quantity ?? 0,\n perMethodTaxRate: [],\n priceMode: draft.priceMode,\n slug: draft.slug,\n state: [],\n totalPrice: createCentPrecisionMoney(draft.money),\n }\n\n return lineItem\n }\n\n getWithOrderNumber(\n context: RepositoryContext,\n orderNumber: string,\n params: QueryParams = {}\n ): Order | undefined {\n const result = this._storage.query(context.projectKey, this.getTypeId(), {\n ...params,\n where: [`orderNumber=\"${orderNumber}\"`],\n })\n if (result.count === 1) {\n return result.results[0] as Order\n }\n\n // Catch this for now, should be checked when creating/updating\n if (result.count > 1) {\n throw new Error('Duplicate order numbers')\n }\n\n return\n }\n\n actions = {\n addPayment: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { payment }: OrderAddPaymentAction\n ) => {\n const resolvedPayment = this._storage.getByResourceIdentifier(\n context.projectKey,\n payment\n )\n if (!resolvedPayment) {\n throw new Error(`Payment ${payment.id} not found`)\n }\n\n if (!resource.paymentInfo) {\n resource.paymentInfo = {\n payments: [],\n }\n }\n\n resource.paymentInfo.payments.push({\n typeId: 'payment',\n id: payment.id!,\n })\n },\n changeOrderState: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { orderState }: OrderChangeOrderStateAction\n ) => {\n resource.orderState = orderState\n },\n changePaymentState: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { paymentState }: OrderChangePaymentStateAction\n ) => {\n resource.paymentState = paymentState\n },\n transitionState: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { state }: OrderTransitionStateAction\n ) => {\n const resolvedType = this._storage.getByResourceIdentifier(\n context.projectKey,\n state\n ) as State | null\n\n if (!resolvedType) {\n throw new Error(\n `No state found with key=${state.key} or id=${state.key}`\n )\n }\n\n resource.state = {\n typeId: 'state',\n id: resolvedType.id,\n obj: { ...resolvedType, key: state.key ?? '' },\n }\n },\n setBillingAddress: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { address }: OrderSetBillingAddressAction\n ) => {\n resource.billingAddress = createAddress(\n address,\n context.projectKey,\n this._storage\n )\n },\n setCustomerEmail: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { email }: OrderSetCustomerEmailAction\n ) => {\n resource.customerEmail = email\n },\n setCustomField: (\n context: RepositoryContext,\n resource: Order,\n { name, value }: OrderSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n throw new Error('Resource has no custom field')\n }\n resource.custom.fields[name] = value\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { type, fields }: OrderSetCustomTypeAction\n ) => {\n if (!type) {\n resource.custom = undefined\n } else {\n const resolvedType = this._storage.getByResourceIdentifier(\n context.projectKey,\n type\n )\n if (!resolvedType) {\n throw new Error(`Type ${type} not found`)\n }\n\n resource.custom = {\n type: {\n typeId: 'type',\n id: resolvedType.id,\n },\n fields: fields || {},\n }\n }\n },\n setLocale: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { locale }: OrderSetLocaleAction\n ) => {\n resource.locale = locale\n },\n setOrderNumber: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { orderNumber }: OrderSetOrderNumberAction\n ) => {\n resource.orderNumber = orderNumber\n },\n setShippingAddress: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { address }: OrderSetShippingAddressAction\n ) => {\n resource.shippingAddress = createAddress(\n address,\n context.projectKey,\n this._storage\n )\n },\n setStore: (\n context: RepositoryContext,\n resource: Writable<Order>,\n { store }: OrderSetStoreAction\n ) => {\n if (!store) return\n const resolvedType = this._storage.getByResourceIdentifier(\n context.projectKey,\n store\n )\n if (!resolvedType) {\n throw new Error(`No store found with key=${store.key}`)\n }\n\n const storeReference = resolvedType as Store\n resource.store = {\n typeId: 'store',\n key: storeReference.key,\n }\n },\n }\n}\n","import type {\n OrderEdit,\n OrderEditDraft,\n OrderEditResult,\n OrderEditUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class OrderEditRepository extends AbstractResourceRepository<'order-edit'> {\n getTypeId() {\n return 'order-edit' as const\n }\n\n create(context: RepositoryContext, draft: OrderEditDraft): OrderEdit {\n const resource: OrderEdit = {\n ...getBaseResourceProperties(),\n stagedActions: draft.stagedActions ?? [],\n resource: draft.resource,\n result: {\n type: 'NotProcessed',\n } as OrderEditResult,\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions: Partial<\n Record<\n OrderEditUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<OrderEdit>,\n action: any\n ) => void\n >\n > = {}\n}\n","import type {\n Payment,\n PaymentAddTransactionAction,\n PaymentChangeTransactionStateAction,\n PaymentDraft,\n PaymentSetCustomFieldAction,\n PaymentSetCustomTypeAction,\n PaymentTransitionStateAction,\n State,\n StateReference,\n Transaction,\n TransactionDraft,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n createCentPrecisionMoney,\n createCustomFields,\n getReferenceFromResourceIdentifier,\n} from './helpers.js'\n\nexport class PaymentRepository extends AbstractResourceRepository<'payment'> {\n getTypeId() {\n return 'payment' as const\n }\n\n create(context: RepositoryContext, draft: PaymentDraft): Payment {\n const resource: Payment = {\n ...getBaseResourceProperties(),\n amountPlanned: createCentPrecisionMoney(draft.amountPlanned),\n paymentMethodInfo: draft.paymentMethodInfo!,\n paymentStatus: draft.paymentStatus\n ? {\n ...draft.paymentStatus,\n state: draft.paymentStatus.state\n ? getReferenceFromResourceIdentifier<StateReference>(\n draft.paymentStatus.state,\n context.projectKey,\n this._storage\n )\n : undefined,\n }\n : {},\n transactions: (draft.transactions || []).map((t) =>\n this.transactionFromTransactionDraft(t, context)\n ),\n interfaceInteractions: (draft.interfaceInteractions || []).map(\n (interaction) =>\n createCustomFields(interaction, context.projectKey, this._storage)!\n ),\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n\n this.saveNew(context, resource)\n return resource\n }\n\n transactionFromTransactionDraft = (\n draft: TransactionDraft,\n context: RepositoryContext\n ): Transaction => ({\n ...draft,\n id: uuidv4(),\n amount: createCentPrecisionMoney(draft.amount),\n custom: createCustomFields(draft.custom, context.projectKey, this._storage),\n state: draft.state ?? 'Initial', // Documented as default\n })\n\n actions = {\n setCustomField: (\n context: RepositoryContext,\n resource: Payment,\n { name, value }: PaymentSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n throw new Error('Resource has no custom field')\n }\n\n resource.custom.fields[name] = value\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<Payment>,\n { type, fields }: PaymentSetCustomTypeAction\n ) => {\n if (!type) {\n resource.custom = undefined\n } else {\n const resolvedType = this._storage.getByResourceIdentifier(\n context.projectKey,\n type\n )\n if (!resolvedType) {\n throw new Error(`Type ${type} not found`)\n }\n\n resource.custom = {\n type: {\n typeId: 'type',\n id: resolvedType.id,\n },\n fields: fields ?? {},\n }\n }\n },\n addTransaction: (\n context: RepositoryContext,\n resource: Writable<Payment>,\n { transaction }: PaymentAddTransactionAction\n ) => {\n resource.transactions = [\n ...resource.transactions,\n this.transactionFromTransactionDraft(transaction, context),\n ]\n },\n changeTransactionState: (\n _context: RepositoryContext,\n resource: Writable<Payment>,\n { transactionId, state }: PaymentChangeTransactionStateAction\n ) => {\n const index = resource.transactions.findIndex(\n (e: Transaction) => e.id === transactionId\n )\n const updatedTransaction: Transaction = {\n ...resource.transactions[index],\n state,\n }\n resource.transactions[index] = updatedTransaction\n },\n transitionState: (\n context: RepositoryContext,\n resource: Writable<Payment>,\n { state }: PaymentTransitionStateAction\n ) => {\n const stateObj = this._storage.getByResourceIdentifier(\n context.projectKey,\n state\n ) as State | null\n\n if (!stateObj) {\n throw new Error(`State ${state} not found`)\n }\n\n resource.paymentStatus.state = {\n typeId: 'state',\n id: stateObj.id,\n obj: stateObj,\n }\n },\n // addInterfaceInteraction: () => {},\n // changeAmountPlanned: () => {},\n // changeTransactionInteractionId: () => {},\n // changeTransactionTimestamp: () => {},\n // setAmountPaid: () => {},\n // setAmountRefunded: () => {},\n // setAnonymousId: () => {},\n // setAuthorization: () => {},\n // setCustomer: () => {},\n // setExternalId: () => {},\n // setInterfaceId: () => {},\n // setKey: () => {},\n // setMethodInfoInterface: () => {},\n // setMethodInfoMethod: () => {},\n // setMethodInfoName: () => {},\n // setStatusInterfaceCode: () => {},\n // setStatusInterfaceText: () => {},\n }\n}\n","import type {\n Price,\n PriceDraft,\n Product,\n ProductData,\n ProductDraft,\n ProductPublishAction,\n ProductSetAttributeAction,\n ProductSetDescriptionAction,\n ProductAddExternalImageAction,\n ProductRemoveImageAction,\n ProductSetKeyAction,\n ProductTypeReference,\n ProductUpdateAction,\n ProductVariant,\n ProductVariantDraft,\n ProductMoveImageToPositionAction,\n ProductChangePriceAction,\n ProductAddPriceAction,\n ProductRemovePriceAction,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport type { Writable } from '../types.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport { createTypedMoney, getReferenceFromResourceIdentifier } from './helpers.js'\nimport deepEqual from 'deep-equal'\n\nexport class ProductRepository extends AbstractResourceRepository<'product'> {\n getTypeId() {\n return 'product' as const\n }\n\n create(context: RepositoryContext, draft: ProductDraft): Product {\n if (!draft.masterVariant) {\n throw new Error('Missing master variant')\n }\n\n let productType: ProductTypeReference | undefined = undefined\n try {\n productType = getReferenceFromResourceIdentifier<ProductTypeReference>(\n draft.productType,\n context.projectKey,\n this._storage\n )\n } catch (err) {\n // For now accept missing product types (but warn)\n console.warn(\n `Error resolving product-type '${draft.productType.id}'. This will be throw an error in later releases.`\n )\n productType = {\n typeId: 'product-type',\n id: draft.productType.id || '',\n }\n }\n\n const productData: ProductData = {\n name: draft.name,\n slug: draft.slug,\n categories: [],\n masterVariant: variantFromDraft(1, draft.masterVariant),\n variants:\n draft.variants?.map((variant, index) =>\n variantFromDraft(index + 2, variant)\n ) ?? [],\n\n searchKeywords: draft.searchKeywords ?? {},\n }\n\n const resource: Product = {\n ...getBaseResourceProperties(),\n key: draft.key,\n productType: productType,\n masterData: {\n current: productData,\n staged: productData,\n hasStagedChanges: false,\n published: draft.publish ?? false,\n },\n }\n\n this.saveNew(context, resource)\n\n return resource\n }\n\n actions: Partial<\n Record<\n ProductUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Product>,\n action: any\n ) => void\n >\n > = {\n publish: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { scope }: ProductPublishAction\n ) => {\n resource.masterData.current = resource.masterData.staged\n resource.masterData.published = true\n checkForStagedChanges(resource)\n },\n unpublish: (\n context: RepositoryContext,\n resource: Writable<Product>\n // { action }: ProductUnpublishAction\n ) => {\n resource.masterData.published = false\n checkForStagedChanges(resource)\n },\n setAttribute: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { variantId, sku, name, value, staged }: ProductSetAttributeAction\n ) => {\n const setAttr = (data: Writable<ProductData>) => {\n const { variant, isMasterVariant, variantIndex } = getVariant(\n data,\n variantId,\n sku\n )\n if (!variant) {\n throw new Error(\n `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n )\n }\n\n if (!variant.attributes) {\n variant.attributes = []\n }\n\n const existingAttr = variant.attributes.find(\n (attr) => attr.name === name\n )\n if (existingAttr) {\n existingAttr.value = value\n } else {\n variant.attributes.push({\n name,\n value,\n })\n }\n if (isMasterVariant) {\n data.masterVariant = variant\n } else {\n data.variants[variantIndex] = variant\n }\n }\n\n // If true, only the staged Attribute is set. If false, both current and\n // staged Attribute is set. Default is true\n const onlyStaged = staged !== undefined ? staged : true\n\n // Write the attribute to the staged data\n setAttr(resource.masterData.staged)\n\n // Also write to published data is isStaged = false\n // if isStaged is false we set the attribute on both the staged and\n // published data.\n if (!onlyStaged) {\n setAttr(resource.masterData.current)\n }\n checkForStagedChanges(resource)\n\n return resource\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { description, staged }: ProductSetDescriptionAction\n ) => {\n const onlyStaged = staged !== undefined ? staged : true\n\n resource.masterData.staged.description = description\n if (!onlyStaged) {\n resource.masterData.current.description = description\n }\n checkForStagedChanges(resource)\n return resource\n },\n setKey: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { key }: ProductSetKeyAction\n ) => {\n resource.key = key\n return resource\n },\n addExternalImage: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { variantId, sku, image, staged }: ProductAddExternalImageAction\n ) => {\n const addImg = (data: Writable<ProductData>) => {\n const { variant, isMasterVariant, variantIndex } = getVariant(\n data,\n variantId,\n sku\n )\n if (!variant) {\n throw new Error(\n `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n )\n }\n\n if (!variant.images) {\n variant.images = []\n } else {\n const existingImage = variant.images.find((x) => x.url === image.url)\n if (existingImage) {\n throw new Error(\n `Cannot add image '${image.url}' because product '${resource.id}' already has that image.`\n )\n }\n }\n\n // Add image\n variant.images.push(image)\n\n if (isMasterVariant) {\n data.masterVariant = variant\n } else {\n data.variants[variantIndex] = variant\n }\n }\n\n // If true, only the staged Attribute is set. If false, both current and\n // staged Attribute is set. Default is true\n const onlyStaged = staged !== undefined ? staged : true\n\n // Write the attribute to the staged data\n addImg(resource.masterData.staged)\n\n // Also write to published data is isStaged = false\n // if isStaged is false we set the attribute on both the staged and\n // published data.\n if (!onlyStaged) {\n addImg(resource.masterData.current)\n }\n checkForStagedChanges(resource)\n\n return resource\n },\n removeImage: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { variantId, sku, imageUrl, staged }: ProductRemoveImageAction\n ) => {\n const removeImg = (data: Writable<ProductData>) => {\n const { variant, isMasterVariant, variantIndex } = getVariant(\n data,\n variantId,\n sku\n )\n if (!variant) {\n throw new Error(\n `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n )\n }\n\n const variantImages = variant.images ?? []\n const existingImage = variantImages.find((x) => x.url === imageUrl)\n if (!existingImage) {\n throw new Error(\n `Cannot remove image '${imageUrl}' because product '${resource.id}' does not have that image.`\n )\n }\n\n // Remove image\n variant.images = variantImages.filter((image) => image.url !== imageUrl)\n\n if (isMasterVariant) {\n data.masterVariant = variant\n } else {\n data.variants[variantIndex] = variant\n }\n }\n\n // If true, only the staged Attribute is set. If false, both current and\n // staged Attribute is set. Default is true\n const onlyStaged = staged !== undefined ? staged : true\n\n // Write the attribute to the staged data\n removeImg(resource.masterData.staged)\n\n // Also write to published data is isStaged = false\n // if isStaged is false we set the attribute on both the staged and\n // published data.\n if (!onlyStaged) {\n removeImg(resource.masterData.current)\n }\n checkForStagedChanges(resource)\n\n return resource\n },\n moveImageToPosition: (\n context: RepositoryContext,\n resource: Writable<Product>,\n {\n variantId,\n sku,\n imageUrl,\n position,\n staged,\n }: ProductMoveImageToPositionAction\n ) => {\n const moveImg = (data: Writable<ProductData>) => {\n const { variant, isMasterVariant, variantIndex } = getVariant(\n data,\n variantId,\n sku\n )\n if (!variant) {\n throw new Error(\n `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n )\n }\n\n const variantImages = variant.images ?? []\n const existingImage = variantImages.find((x) => x.url === imageUrl)\n if (!existingImage) {\n throw new Error(\n `Cannot move image '${imageUrl}' because product '${resource.id}' does not have that image.`\n )\n }\n\n if (position >= variantImages.length) {\n throw new Error(\n `Invalid position given. Position in images where the image should be moved. Must be between 0 and the total number of images minus 1.`\n )\n }\n\n // Remove image\n variant.images = variantImages.filter((image) => image.url !== imageUrl)\n\n // Re-add image to the correct position\n variant.images.splice(position, 0, existingImage)\n\n if (isMasterVariant) {\n data.masterVariant = variant\n } else {\n data.variants[variantIndex] = variant\n }\n }\n\n // If true, only the staged Attribute is set. If false, both current and\n // staged Attribute is set. Default is true\n const onlyStaged = staged !== undefined ? staged : true\n\n // Write the attribute to the staged data\n moveImg(resource.masterData.staged)\n\n // Also write to published data is isStaged = false\n // if isStaged is false we set the attribute on both the staged and\n // published data.\n if (!onlyStaged) {\n moveImg(resource.masterData.current)\n }\n checkForStagedChanges(resource)\n\n return resource\n },\n\n addPrice: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { variantId, sku, price, staged }: ProductAddPriceAction\n ) => {\n const addVariantPrice = (data: Writable<ProductData>) => {\n const { variant, isMasterVariant, variantIndex } = getVariant(\n data,\n variantId,\n sku\n )\n if (!variant) {\n throw new Error(\n `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n )\n }\n\n if (variant.prices === undefined) {\n variant.prices = [priceFromDraft(price)]\n } else {\n variant.prices.push(priceFromDraft(price))\n }\n\n if (isMasterVariant) {\n data.masterVariant = variant\n } else {\n data.variants[variantIndex] = variant\n }\n }\n\n // If true, only the staged Attribute is set. If false, both current and\n // staged Attribute is set. Default is true\n const onlyStaged = staged !== undefined ? staged : true\n\n // Write the attribute to the staged data\n addVariantPrice(resource.masterData.staged)\n\n // Also write to published data is isStaged = false\n // if isStaged is false we set the attribute on both the staged and\n // published data.\n if (!onlyStaged) {\n addVariantPrice(resource.masterData.current)\n }\n checkForStagedChanges(resource)\n\n return resource\n },\n changePrice: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { priceId, price, staged }: ProductChangePriceAction\n ) => {\n const changeVariantPrice = (data: Writable<ProductData>) => {\n const allVariants = [data.masterVariant, ...(data.variants ?? [])]\n const priceVariant = allVariants.find((variant) =>\n variant.prices?.some((x) => x.id === priceId)\n )\n if (!priceVariant) {\n throw new Error(\n `Price with id ${priceId} not found on product ${resource.id}`\n )\n }\n\n const { variant, isMasterVariant, variantIndex } = getVariant(\n data,\n priceVariant.id,\n priceVariant.sku\n )\n if (!variant) {\n throw new Error(\n `Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`\n )\n }\n\n variant.prices = variant.prices?.map((x) => {\n if (x.id === priceId) {\n return { ...x, ...price } as Price\n }\n return x\n })\n\n if (isMasterVariant) {\n data.masterVariant = variant\n } else {\n data.variants[variantIndex] = variant\n }\n }\n\n // If true, only the staged Attribute is set. If false, both current and\n // staged Attribute is set. Default is true\n const onlyStaged = staged !== undefined ? staged : true\n\n // Write the attribute to the staged data\n changeVariantPrice(resource.masterData.staged)\n\n // Also write to published data is isStaged = false\n // if isStaged is false we set the attribute on both the staged and\n // published data.\n if (!onlyStaged) {\n changeVariantPrice(resource.masterData.current)\n }\n checkForStagedChanges(resource)\n\n return resource\n },\n removePrice: (\n context: RepositoryContext,\n resource: Writable<Product>,\n { priceId, staged }: ProductRemovePriceAction\n ) => {\n const removeVariantPrice = (data: Writable<ProductData>) => {\n const allVariants = [data.masterVariant, ...(data.variants ?? [])]\n const priceVariant = allVariants.find((variant) =>\n variant.prices?.some((x) => x.id === priceId)\n )\n if (!priceVariant) {\n throw new Error(\n `Price with id ${priceId} not found on product ${resource.id}`\n )\n }\n\n const { variant, isMasterVariant, variantIndex } = getVariant(\n data,\n priceVariant.id,\n priceVariant.sku\n )\n if (!variant) {\n throw new Error(\n `Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`\n )\n }\n\n variant.prices = variant.prices?.filter((x) => x.id !== priceId)\n\n if (isMasterVariant) {\n data.masterVariant = variant\n } else {\n data.variants[variantIndex] = variant\n }\n }\n\n // If true, only the staged Attribute is set. If false, both current and\n // staged Attribute is set. Default is true\n const onlyStaged = staged !== undefined ? staged : true\n\n // Write the attribute to the staged data\n removeVariantPrice(resource.masterData.staged)\n\n // Also write to published data is isStaged = false\n // if isStaged is false we set the attribute on both the staged and\n // published data.\n if (!onlyStaged) {\n removeVariantPrice(resource.masterData.current)\n }\n checkForStagedChanges(resource)\n\n return resource\n },\n\n // 'changeName': () => {},\n // 'changeSlug': () => {},\n // 'addVariant': () => {},\n // 'removeVariant': () => {},\n // 'changeMasterVariant': () => {},\n // 'setPrices': () => {},\n // 'setProductPriceCustomType': () => {},\n // 'setProductPriceCustomField': () => {},\n // 'setDiscountedPrice': () => {},\n // 'setAttributeInAllVariants': () => {},\n // 'addToCategory': () => {},\n // 'setCategoryOrderHint': () => {},\n // 'removeFromCategory': () => {},\n // 'setTaxCategory': () => {},\n // 'setSku': () => {},\n // 'setProductVariantKey': () => {},\n // 'setImageLabel': () => {},\n // 'addAsset': () => {},\n // 'removeAsset': () => {},\n // 'setAssetKey': () => {},\n // 'changeAssetOrder': () => {},\n // 'changeAssetName': () => {},\n // 'setAssetDescription': () => {},\n // 'setAssetTags': () => {},\n // 'setAssetSources': () => {},\n // 'setAssetCustomType': () => {},\n // 'setAssetCustomField': () => {},\n // 'setSearchKeywords': () => {},\n // 'setMetaTitle': () => {},\n // 'setMetaDescription': () => {},\n // 'setMetaKeywords': () => {},\n // 'revertStagedChanges': () => {},\n // 'revertStagedVariantChanges': () => {},\n // 'transitionState': () => {},\n }\n}\n\n// Check if the product still has staged data that is different from the\n// current data.\nconst checkForStagedChanges = (product: Writable<Product>) => {\n if (!product.masterData.staged) {\n product.masterData.staged = product.masterData.current\n }\n\n if (deepEqual(product.masterData.current, product.masterData.staged)) {\n product.masterData.hasStagedChanges = false\n } else {\n product.masterData.hasStagedChanges = true\n }\n}\n\ninterface VariantResult {\n variant: Writable<ProductVariant> | undefined\n isMasterVariant: boolean\n variantIndex: number\n}\n\nconst getVariant = (\n productData: ProductData,\n variantId?: number,\n sku?: string\n): VariantResult => {\n const variants = [productData.masterVariant, ...productData.variants]\n const foundVariant = variants.find((variant: ProductVariant) => {\n if (variantId) {\n return variant.id === variantId\n }\n if (sku) {\n return variant.sku === sku\n }\n return false\n })\n\n const isMasterVariant = foundVariant === productData.masterVariant\n return {\n variant: foundVariant,\n isMasterVariant,\n variantIndex:\n !isMasterVariant && foundVariant\n ? productData.variants.indexOf(foundVariant)\n : -1,\n }\n}\n\nconst variantFromDraft = (\n variantId: number,\n variant: ProductVariantDraft\n): ProductVariant => ({\n id: variantId,\n sku: variant?.sku,\n attributes: variant?.attributes ?? [],\n prices: variant?.prices?.map(priceFromDraft),\n assets: [],\n images: [],\n})\n\nconst priceFromDraft = (draft: PriceDraft): Price => ({\n id: uuidv4(),\n country: draft.country,\n value: createTypedMoney(draft.value),\n})\n","import type {\n ProductDiscount,\n ProductDiscountChangeIsActiveAction,\n ProductDiscountChangeNameAction,\n ProductDiscountChangePredicateAction,\n ProductDiscountChangeSortOrderAction,\n ProductDiscountChangeValueAction,\n ProductDiscountDraft,\n ProductDiscountSetDescriptionAction,\n ProductDiscountSetKeyAction,\n ProductDiscountSetValidFromAction,\n ProductDiscountSetValidFromAndUntilAction,\n ProductDiscountSetValidUntilAction,\n ProductDiscountUpdateAction,\n ProductDiscountValue,\n ProductDiscountValueAbsolute,\n ProductDiscountValueDraft,\n ProductDiscountValueExternal,\n ProductDiscountValueRelative,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport { createTypedMoney } from './helpers.js'\n\nexport class ProductDiscountRepository extends AbstractResourceRepository<'product-discount'> {\n getTypeId() {\n return 'product-discount' as const\n }\n\n create(\n context: RepositoryContext,\n draft: ProductDiscountDraft\n ): ProductDiscount {\n const resource: ProductDiscount = {\n ...getBaseResourceProperties(),\n key: draft.key,\n name: draft.name,\n description: draft.description,\n value: this.transformValueDraft(draft.value),\n predicate: draft.predicate,\n sortOrder: draft.sortOrder,\n isActive: draft.isActive || false,\n validFrom: draft.validFrom,\n validUntil: draft.validUntil,\n references: [],\n }\n this.saveNew(context, resource)\n return resource\n }\n\n private transformValueDraft(\n value: ProductDiscountValueDraft\n ): ProductDiscountValue {\n switch (value.type) {\n case 'absolute': {\n return {\n type: 'absolute',\n money: value.money.map(createTypedMoney),\n } as ProductDiscountValueAbsolute\n }\n case 'external': {\n return {\n type: 'external',\n } as ProductDiscountValueExternal\n }\n case 'relative': {\n return {\n ...value,\n } as ProductDiscountValueRelative\n }\n }\n }\n\n actions: Partial<\n Record<\n ProductDiscountUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n action: any\n ) => void\n >\n > = {\n setKey: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { key }: ProductDiscountSetKeyAction\n ) => {\n resource.key = key\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { description }: ProductDiscountSetDescriptionAction\n ) => {\n if (description && Object.keys(description).length > 0) {\n resource.description = description\n } else {\n resource.description = undefined\n }\n },\n changeName: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { name }: ProductDiscountChangeNameAction\n ) => {\n resource.name = name\n },\n changeValue: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { value }: ProductDiscountChangeValueAction\n ) => {\n resource.value = this.transformValueDraft(value)\n },\n changePredicate: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { predicate }: ProductDiscountChangePredicateAction\n ) => {\n resource.predicate = predicate\n },\n changeSortOrder: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { sortOrder }: ProductDiscountChangeSortOrderAction\n ) => {\n resource.sortOrder = sortOrder\n },\n changeIsActive: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { isActive }: ProductDiscountChangeIsActiveAction\n ) => {\n resource.isActive = isActive\n },\n setValidFrom: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { validFrom }: ProductDiscountSetValidFromAction\n ) => {\n resource.validFrom = validFrom\n },\n setValidUntil: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { validUntil }: ProductDiscountSetValidUntilAction\n ) => {\n resource.validUntil = validUntil\n },\n setValidFromAndUntil: (\n context: RepositoryContext,\n resource: Writable<ProductDiscount>,\n { validFrom, validUntil }: ProductDiscountSetValidFromAndUntilAction\n ) => {\n resource.validFrom = validFrom\n resource.validUntil = validUntil\n },\n }\n}\n","/**\n * This module implements the commercetools product projection filter expression.\n */\n\nimport type { ProductProjection, ProductVariant } from '@commercetools/platform-sdk'\nimport { nestedLookup } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { Lexer, Parser } from './parser.js'\n\ntype MatchFunc = (target: any) => boolean\n\ntype ProductProjectionFilter = (\n p: Writable<ProductProjection>,\n markMatchingVariants: boolean\n) => boolean\n\ntype TypeSymbol = {\n type: 'Symbol'\n kind: 'int' | 'string' | 'any'\n value: any\n}\n\ntype RangeExpressionSet = {\n source: string\n type: 'RangeExpression'\n children?: RangeExpression[]\n}\n\ntype FilterExpressionSet = {\n source: string\n type: 'FilterExpression'\n children?: FilterExpression[]\n}\n\ntype TermExpressionSet = {\n source: string\n type: 'TermExpression'\n}\n\ntype ExpressionSet =\n | RangeExpressionSet\n | FilterExpressionSet\n | TermExpressionSet\n\nexport type RangeExpression = {\n type: 'RangeExpression'\n start?: number\n stop?: number\n match: (obj: any) => boolean\n}\n\nexport type FilterExpression = {\n type: 'FilterExpression'\n match: (obj: any) => boolean\n}\n\n/**\n * Returns a function (ProductProjectionFilter).\n * NOTE: The filter can alter the resources in-place (FIXME)\n */\nexport const parseFilterExpression = (\n filter: string\n): ProductProjectionFilter => {\n const exprFunc = generateMatchFunc(filter)\n const [source] = filter.split(':', 1)\n\n if (source.startsWith('variants.')) {\n return filterVariants(source, exprFunc)\n }\n return filterProduct(source, exprFunc)\n}\n\nconst getLexer = (value: string) =>\n new Lexer(value)\n .token('MISSING', /missing(?![-_a-z0-9]+)/i)\n .token('EXISTS', /exists(?![-_a-z0-9]+)/i)\n .token('RANGE', /range(?![-_a-z0-9]+)/i)\n .token('TO', /to(?![-_a-z0-9]+)/i)\n .token('IDENTIFIER', /[-_.a-z]+/i)\n\n .token('FLOAT', /\\d+\\.\\d+/)\n .token('INT', /\\d+/)\n .token('STRING', /\"((?:\\\\.|[^\"\\\\])*)\"/)\n .token('STRING', /'((?:\\\\.|[^'\\\\])*)'/)\n\n .token('COMMA', ',')\n .token('STAR', '*')\n .token('(', '(')\n .token(':', ':')\n .token(')', ')')\n .token('\"', '\"')\n .token('WS', /\\s+/, true) // skip\n\nconst parseFilter = (filter: string): ExpressionSet => {\n const lexer = getLexer(filter)\n const parser = new Parser(lexer)\n .builder()\n .nud('IDENTIFIER', 100, (t) => t.token.match)\n .led(':', 100, ({ left, bp }) => {\n const parsed: any = parser.parse({ terminals: [bp - 1] })\n const expressions: RangeExpression[] | FilterExpression[] | TypeSymbol[] =\n !Array.isArray(parsed) ? [parsed] : parsed\n\n // Make sure we only have one type of expression (cannot mix)\n const unique = new Set(expressions.map((expr) => expr.type))\n if (unique.size > 1) {\n throw new Error('Invalid expression')\n }\n\n // Convert plain symbols to a filter expression. For example\n // variants.attribute.foobar:4 where 4 is a Symbol should result\n // in a comparison\n if (expressions.some((expr) => expr.type == 'Symbol')) {\n return {\n source: left as string,\n type: 'FilterExpression',\n children: expressions.map((e): FilterExpression => {\n if (e.type != 'Symbol') {\n throw new Error('Invalid expression')\n }\n\n return {\n type: 'FilterExpression',\n match: (obj: any): boolean => obj === e.value,\n }\n }),\n }\n }\n\n return {\n source: left,\n type: expressions[0].type,\n children: expressions,\n }\n })\n .nud(\n 'STRING',\n 20,\n (t) =>\n ({\n type: 'Symbol',\n kind: 'string',\n // @ts-ignore\n value: t.token.groups[1],\n } as TypeSymbol)\n )\n .nud(\n 'INT',\n 5,\n (t) =>\n ({\n type: 'Symbol',\n kind: 'int',\n value: parseInt(t.token.match, 10),\n } as TypeSymbol)\n )\n .nud('STAR', 5, (_) => ({\n type: 'Symbol',\n kind: 'any',\n value: null,\n }))\n .nud(\n 'EXISTS',\n 10,\n ({ bp }) =>\n ({\n type: 'FilterExpression',\n match: (obj: any): boolean => obj !== undefined,\n } as FilterExpression)\n )\n .nud(\n 'MISSING',\n 10,\n ({ bp }) =>\n ({\n type: 'FilterExpression',\n match: (obj: any): boolean => obj === undefined,\n } as FilterExpression)\n )\n .led('COMMA', 200, ({ left, token, bp }) => {\n const expr: any = parser.parse({ terminals: [bp - 1] })\n if (Array.isArray(expr)) {\n return [left, ...expr]\n } else {\n return [left, expr]\n }\n })\n .nud('(', 100, (t) => {\n const expr: any = parser.parse({ terminals: [')'] })\n lexer.expect(')')\n return expr\n })\n .bp(')', 0)\n .led('TO', 20, ({ left, bp }) => {\n const expr: any = parser.parse({ terminals: [bp - 1] })\n return {\n start: left.value,\n stop: expr.value,\n }\n })\n .nud('RANGE', 20, ({ bp }) => {\n let ranges: any = parser.parse()\n\n // If multiple ranges are defined we receive an array of ranges. So let's\n // make sure we always have an array\n if (!Array.isArray(ranges)) {\n ranges = [ranges]\n }\n\n // Return a list of functions which matches the ranges. These functions\n // are processed as an OR clause\n return ranges.map((range: any) => {\n let func: (obj: any) => boolean\n\n if (range.start !== null && range.stop !== null) {\n func = (obj: any): boolean => obj >= range.start && obj <= range.stop\n } else if (range.start === null && range.stop !== null) {\n func = (obj: any): boolean => obj <= range.stop\n } else if (range.start !== null && range.stop === null) {\n func = (obj: any): boolean => obj >= range.start\n } else {\n func = (obj: any): boolean => true\n }\n\n return {\n type: 'RangeExpression',\n start: range.start,\n stop: range.stop,\n match: func,\n } as RangeExpression\n })\n })\n .build()\n\n return parser.parse()\n}\n\nconst generateMatchFunc = (filter: string) => {\n const result = parseFilter(filter)\n if (!result) {\n // const lines = filter.split('\\n')\n // const column = lines[lines.length - 1].length\n throw new Error(`Syntax error while parsing '${filter}'.`)\n }\n if (result.type == 'TermExpression') {\n throw new Error(`Syntax error while parsing '${filter}'.`)\n }\n\n return (obj: any) => {\n if (!result.children) return false\n return result.children.some((c) => c.match(obj))\n }\n}\n\nexport const generateFacetFunc = (filter: string): ExpressionSet => {\n if (!filter.includes(':')) {\n return {\n source: filter,\n type: 'TermExpression',\n }\n }\n return parseFilter(filter)\n}\n\nconst filterProduct =\n (source: string, exprFunc: MatchFunc): ProductProjectionFilter =>\n (p: ProductProjection, markMatchingVariants: boolean): boolean => {\n const value = nestedLookup(p, source)\n return exprFunc(value)\n }\n\nconst filterVariants =\n (source: string, exprFunc: MatchFunc): ProductProjectionFilter =>\n (p: ProductProjection, markMatchingVariants: boolean): boolean => {\n const [, ...paths] = source.split('.')\n const path = paths.join('.')\n\n const variants = getVariants(p) as Writable<ProductVariant>[]\n for (const variant of variants) {\n const value = resolveVariantValue(variant, path)\n\n if (exprFunc(value)) {\n // If markMatchingVariants parameter is true those ProductVariants that\n // match the search query have the additional field isMatchingVariant\n // set to true. For the other variants in the same product projection\n // this field is set to false.\n if (markMatchingVariants) {\n variants.forEach((v) => (v.isMatchingVariant = false))\n variant.isMatchingVariant = true\n }\n return true\n }\n }\n\n return false\n }\n\nexport const resolveVariantValue = (obj: ProductVariant, path: string): any => {\n if (path === undefined) {\n return obj\n }\n if (path.startsWith('variants.')) {\n path = path.substring(path.indexOf('.') + 1)\n }\n\n if (path.startsWith('attributes.')) {\n const [, attrName, ...rest] = path.split('.')\n if (!obj.attributes) {\n return undefined\n }\n\n for (const attr of obj.attributes) {\n if (attr.name === attrName) {\n return nestedLookup(attr.value, rest.join('.'))\n }\n }\n }\n\n if (path === 'price.centAmount') {\n return obj.prices && obj.prices.length > 0\n ? obj.prices[0].value.centAmount\n : undefined\n }\n\n return nestedLookup(obj, path)\n}\n\nexport const getVariants = (p: ProductProjection): ProductVariant[] => [\n p.masterVariant,\n ...(p.variants ?? []),\n]\n","import type {\n InvalidInputError,\n Price,\n ProductProjection,\n ProductVariant,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from './exceptions.js'\nimport type { Writable } from './types.js'\n\nexport type PriceSelector = {\n currency?: string\n country?: string\n customerGroup?: string\n channel?: string\n}\n\n/**\n * Apply the price selector on all the variants. The price selector is applied\n * on all the prices per variant and the first match per variant is stored in\n * the scopedPrice attribute\n */\nexport const applyPriceSelector = (\n products: ProductProjection[],\n selector: PriceSelector\n) => {\n validatePriceSelector(selector)\n\n for (const product of products) {\n const variants: Writable<ProductVariant>[] = [\n product.masterVariant,\n ...(product.variants ?? []),\n ].filter((x) => x != undefined)\n\n for (const variant of variants) {\n const scopedPrices =\n variant.prices?.filter((p) => priceSelectorFilter(p, selector)) ?? []\n\n if (scopedPrices.length > 0) {\n const price = scopedPrices[0]\n\n variant.scopedPriceDiscounted = false\n variant.scopedPrice = {\n ...price,\n currentValue: price.value,\n }\n }\n }\n }\n}\n\nconst validatePriceSelector = (selector: PriceSelector) => {\n if (\n (selector.country || selector.channel || selector.customerGroup) &&\n !selector.currency\n ) {\n throw new CommercetoolsError<InvalidInputError>(\n {\n code: 'InvalidInput',\n message:\n 'The price selecting parameters country, channel and customerGroup ' +\n 'cannot be used without the currency.',\n },\n 400\n )\n }\n}\n\n/**\n * Return a boolean to indicate if the price matches the selector. Price\n * selection requires that if the selector or the price has a specific value\n * then it should match.\n */\nexport const priceSelectorFilter = (\n price: Price,\n selector: PriceSelector\n): boolean => {\n if (\n (selector.country || price.country) &&\n selector.country !== price.country\n ) {\n return false\n }\n\n if (\n (selector.currency || price.value.currencyCode) &&\n selector.currency !== price.value.currencyCode\n ) {\n return false\n }\n\n if (\n (selector.channel || price.channel?.id) &&\n selector.channel !== price.channel?.id\n ) {\n return false\n }\n\n if (\n (selector.customerGroup || price.customerGroup?.id) &&\n selector.customerGroup !== price.customerGroup?.id\n ) {\n return false\n }\n\n return true\n}\n","import type {\n FacetResults,\n FilteredFacetResult,\n InvalidInputError,\n Product,\n ProductProjection,\n ProductProjectionPagedSearchResponse,\n QueryParam,\n RangeFacetResult,\n TermFacetResult,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from './exceptions.js'\nimport { nestedLookup } from './helpers.js'\nimport {\n FilterExpression,\n RangeExpression,\n generateFacetFunc,\n getVariants,\n parseFilterExpression,\n resolveVariantValue,\n} from './lib/projectionSearchFilter.js'\nimport { applyPriceSelector } from './priceSelector.js'\nimport { AbstractStorage } from './storage/index.js'\nimport type { Writable } from './types.js'\n\nexport type ProductProjectionSearchParams = {\n fuzzy?: boolean\n fuzzyLevel?: number\n markMatchingVariants?: boolean\n staged?: boolean\n filter?: string[]\n 'filter.facets'?: string[]\n 'filter.query'?: string[]\n facet?: string | string[]\n sort?: string | string[]\n limit?: number\n offset?: number\n withTotal?: boolean\n priceCurrency?: string\n priceCountry?: string\n priceCustomerGroup?: string\n priceChannel?: string\n localeProjection?: string\n storeProjection?: string\n expand?: string | string[]\n [key: string]: QueryParam\n}\n\nexport class ProductProjectionSearch {\n protected _storage: AbstractStorage\n\n constructor(storage: AbstractStorage) {\n this._storage = storage\n }\n\n search(\n projectKey: string,\n params: ProductProjectionSearchParams\n ): ProductProjectionPagedSearchResponse {\n let resources = this._storage\n .all(projectKey, 'product')\n .map((r) => this.transform(r, params.staged ?? false))\n .filter((p) => {\n if (!params.staged ?? false) {\n return p.published\n }\n return true\n })\n\n const markMatchingVariant = params.markMatchingVariants ?? false\n\n // Apply the priceSelector\n applyPriceSelector(resources, {\n country: params.priceCountry,\n channel: params.priceChannel,\n customerGroup: params.priceCustomerGroup,\n currency: params.priceCurrency,\n })\n\n // Apply filters pre facetting\n if (params.filter) {\n try {\n const filters = params.filter.map(parseFilterExpression)\n\n // Filters can modify the output. So clone the resources first.\n resources = resources.filter((resource) =>\n filters.every((f) => f(resource, markMatchingVariant))\n )\n } catch (err) {\n console.error(err)\n throw new CommercetoolsError<InvalidInputError>(\n {\n code: 'InvalidInput',\n message: (err as any).message,\n },\n 400\n )\n }\n }\n\n // TODO: Calculate facets\n const facets = this.getFacets(params, resources)\n\n // Apply filters post facetting\n if (params['filter.query']) {\n try {\n const filters = params['filter.query'].map(parseFilterExpression)\n resources = resources.filter((resource) =>\n filters.every((f) => f(resource, markMatchingVariant))\n )\n } catch (err) {\n throw new CommercetoolsError<InvalidInputError>(\n {\n code: 'InvalidInput',\n message: (err as any).message,\n },\n 400\n )\n }\n }\n\n // Expand the resources\n if (params.expand !== undefined) {\n resources = resources.map((resource) =>\n this._storage.expand(projectKey, resource, params.expand)\n )\n }\n\n // Create a slice for the pagination. If we were working with large datasets\n // then we should have done this before transforming. But that isn't the\n // goal of this library. So lets keep it simple.\n const totalResults = resources.length\n const offset = params.offset || 0\n const limit = params.limit || 20\n const results = resources.slice(offset, offset + limit)\n\n return {\n count: totalResults,\n total: results.length,\n offset: offset,\n limit: limit,\n results: results,\n facets: facets,\n }\n }\n\n transform(product: Product, staged: boolean): ProductProjection {\n const obj = !staged ? product.masterData.current : product.masterData.staged\n\n return {\n id: product.id,\n createdAt: product.createdAt,\n lastModifiedAt: product.lastModifiedAt,\n version: product.version,\n name: obj.name,\n key: product.key,\n description: obj.description,\n metaDescription: obj.metaDescription,\n slug: obj.slug,\n categories: obj.categories,\n masterVariant: obj.masterVariant,\n variants: obj.variants,\n productType: product.productType,\n hasStagedChanges: product.masterData.hasStagedChanges,\n published: product.masterData.published,\n }\n }\n\n getFacets(\n params: ProductProjectionSearchParams,\n products: ProductProjection[]\n ): FacetResults {\n if (!params.facet) return {}\n const staged = false\n const result: FacetResults = {}\n\n for (const facet of params.facet) {\n const expression = generateFacetFunc(facet)\n\n // Term Facet\n if (expression.type === 'TermExpression') {\n result[facet] = this.termFacet(expression.source, products)\n }\n\n // Range Facet\n if (expression.type === 'RangeExpression') {\n result[expression.source] = this.rangeFacet(\n expression.source,\n expression.children,\n products\n )\n }\n\n // FilteredFacet\n if (expression.type === 'FilterExpression') {\n result[expression.source] = this.filterFacet(\n expression.source,\n expression.children,\n products\n )\n }\n }\n\n return result\n }\n\n /**\n * TODO: This implemention needs the following additional features:\n * - counting products\n * - correct dataType\n */\n termFacet(facet: string, products: ProductProjection[]): TermFacetResult {\n const result: Writable<TermFacetResult> = {\n type: 'terms',\n dataType: 'text',\n missing: 0,\n total: 0,\n other: 0,\n terms: [],\n }\n const terms: Record<any, number> = {}\n\n if (facet.startsWith('variants.')) {\n products.forEach((p) => {\n const variants = getVariants(p)\n variants.forEach((v) => {\n result.total++\n\n let value = resolveVariantValue(v, facet)\n if (value === undefined) {\n result.missing++\n } else {\n if (typeof value === 'number') {\n value = Number(value).toFixed(1)\n }\n terms[value] = value in terms ? terms[value] + 1 : 1\n }\n })\n })\n } else {\n products.forEach((p) => {\n const value = nestedLookup(p, facet)\n result.total++\n if (value === undefined) {\n result.missing++\n } else {\n terms[value] = value in terms ? terms[value] + 1 : 1\n }\n })\n }\n for (const term in terms) {\n result.terms.push({\n term: term as any,\n count: terms[term],\n })\n }\n return result\n }\n\n filterFacet(\n source: string,\n filters: FilterExpression[] | undefined,\n products: ProductProjection[]\n ): FilteredFacetResult {\n let count = 0\n if (source.startsWith('variants.')) {\n for (const p of products) {\n for (const v of getVariants(p)) {\n const val = resolveVariantValue(v, source)\n if (filters?.some((f) => f.match(val))) {\n count++\n }\n }\n }\n } else {\n throw new Error('not supported')\n }\n\n return {\n type: 'filter',\n count: count,\n }\n }\n\n rangeFacet(\n source: string,\n ranges: RangeExpression[] | undefined,\n products: ProductProjection[]\n ): RangeFacetResult {\n const counts =\n ranges?.map((range) => {\n if (source.startsWith('variants.')) {\n const values = []\n for (const p of products) {\n for (const v of getVariants(p)) {\n const val = resolveVariantValue(v, source)\n if (val === undefined) {\n continue\n }\n\n if (range.match(val)) {\n values.push(val)\n }\n }\n }\n\n const numValues = values.length\n return {\n type: 'double',\n from: range.start || 0,\n fromStr: range.start !== null ? Number(range.start).toFixed(1) : '',\n to: range.stop || 0,\n toStr: range.stop !== null ? Number(range.stop).toFixed(1) : '',\n count: numValues,\n // totalCount: 0,\n total: values.reduce((a, b) => a + b, 0),\n min: numValues > 0 ? Math.min(...values) : 0,\n max: numValues > 0 ? Math.max(...values) : 0,\n mean: numValues > 0 ? mean(values) : 0,\n }\n } else {\n throw new Error('not supported')\n }\n }) || []\n const data: RangeFacetResult = {\n type: 'range',\n // @ts-ignore\n dataType: 'number',\n ranges: counts,\n }\n return data\n }\n}\n\nconst mean = (arr: number[]) => {\n let total = 0\n for (let i = 0; i < arr.length; i++) {\n total += arr[i]\n }\n return total / arr.length\n}\n","import type { ProductDraft, ProductProjection } from '@commercetools/platform-sdk'\nimport { ParsedQs } from 'qs'\nimport { QueryParamsAsArray } from '../helpers.js'\nimport { ProductProjectionSearch } from '../product-projection-search.js'\nimport { type AbstractStorage } from '../storage/index.js'\nimport {\n AbstractResourceRepository,\n type QueryParams,\n RepositoryContext,\n} from './abstract.js'\n\nexport class ProductProjectionRepository extends AbstractResourceRepository<'product-projection'> {\n protected _searchService: ProductProjectionSearch\n\n constructor(storage: AbstractStorage) {\n super(storage)\n this._searchService = new ProductProjectionSearch(storage)\n }\n\n getTypeId() {\n return 'product-projection' as const\n }\n\n create(context: RepositoryContext, draft: ProductDraft): ProductProjection {\n throw new Error('No valid action')\n }\n\n query(context: RepositoryContext, params: QueryParams = {}) {\n const response = this._storage.query(context.projectKey, 'product', {\n expand: params.expand,\n where: params.where,\n offset: params.offset,\n limit: params.limit,\n })\n\n return {\n ...response,\n results: response.results.map((r) =>\n this._searchService.transform(r, false)\n ),\n }\n }\n\n search(context: RepositoryContext, query: ParsedQs) {\n const results = this._searchService.search(context.projectKey, {\n filter: QueryParamsAsArray(query.filter),\n 'filter.query': QueryParamsAsArray(query['filter.query']),\n facet: QueryParamsAsArray(query.facet),\n offset: query.offset ? Number(query.offset) : undefined,\n limit: query.limit ? Number(query.limit) : undefined,\n expand: QueryParamsAsArray(query.expand),\n staged: query.staged === 'true',\n })\n\n return results\n }\n\n actions = {}\n}\n","import type {\n ProductSelection,\n ProductSelectionDraft,\n Review,\n ReviewUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class ProductSelectionRepository extends AbstractResourceRepository<'product-selection'> {\n getTypeId() {\n return 'product-selection' as const\n }\n\n create(\n context: RepositoryContext,\n draft: ProductSelectionDraft\n ): ProductSelection {\n const resource: ProductSelection = {\n ...getBaseResourceProperties(),\n productCount: 0,\n name: draft.name,\n type: 'individual',\n mode: 'Individual',\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions: Partial<\n Record<\n ReviewUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Review>,\n action: any\n ) => void\n >\n > = {}\n}\n","import type {\n AttributeDefinition,\n AttributeDefinitionDraft,\n AttributeType,\n ProductType,\n ProductTypeAddAttributeDefinitionAction,\n ProductTypeChangeAttributeOrderByNameAction,\n ProductTypeChangeLabelAction,\n ProductTypeChangeLocalizedEnumValueLabelAction,\n ProductTypeDraft,\n ProductTypeRemoveAttributeDefinitionAction,\n ProductTypeRemoveEnumValuesAction,\n ProductTypeUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class ProductTypeRepository extends AbstractResourceRepository<'product-type'> {\n getTypeId() {\n return 'product-type' as const\n }\n\n create(context: RepositoryContext, draft: ProductTypeDraft): ProductType {\n const resource: ProductType = {\n ...getBaseResourceProperties(),\n key: draft.key,\n name: draft.name,\n description: draft.description,\n attributes: (draft.attributes ?? []).map((a) =>\n this.attributeDefinitionFromAttributeDefinitionDraft(context, a)\n ),\n }\n\n this.saveNew(context, resource)\n return resource\n }\n\n attributeDefinitionFromAttributeDefinitionDraft = (\n _context: RepositoryContext,\n draft: AttributeDefinitionDraft\n ): AttributeDefinition => ({\n ...draft,\n attributeConstraint: draft.attributeConstraint ?? 'None',\n inputHint: draft.inputHint ?? 'SingleLine',\n inputTip:\n draft.inputTip && Object.keys(draft.inputTip).length > 0\n ? draft.inputTip\n : undefined,\n isSearchable: draft.isSearchable ?? true,\n })\n\n actions: Partial<\n Record<\n ProductTypeUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<ProductType>,\n action: any\n ) => void\n >\n > = {\n changeLocalizedEnumValueLabel: (\n context: RepositoryContext,\n resource: Writable<ProductType>,\n {\n attributeName,\n newValue,\n }: ProductTypeChangeLocalizedEnumValueLabelAction\n ) => {\n const updateAttributeType = (type: Writable<AttributeType>) => {\n switch (type.name) {\n case 'lenum':\n type.values.forEach((v) => {\n if (v.key === newValue.key) {\n v.label = newValue.label\n }\n })\n return\n case 'set':\n updateAttributeType(type.elementType)\n return\n }\n }\n\n resource.attributes?.forEach((value) => {\n if (value.name === attributeName) {\n updateAttributeType(value.type)\n }\n })\n },\n changeLabel: (\n context: RepositoryContext,\n resource: Writable<ProductType>,\n { attributeName, label }: ProductTypeChangeLabelAction\n ) => {\n resource.attributes?.forEach((value) => {\n if (value.name === attributeName) {\n value.label = label\n }\n })\n },\n addAttributeDefinition: (\n context: RepositoryContext,\n resource: Writable<ProductType>,\n { attribute }: ProductTypeAddAttributeDefinitionAction\n ) => {\n resource.attributes?.push(\n this.attributeDefinitionFromAttributeDefinitionDraft(context, attribute)\n )\n },\n changeAttributeOrderByName: (\n context: RepositoryContext,\n resource: Writable<ProductType>,\n { attributeNames }: ProductTypeChangeAttributeOrderByNameAction\n ) => {\n const attrs = new Map(\n resource.attributes?.map((item) => [item.name, item])\n )\n const result: AttributeDefinition[] = []\n let current = resource.attributes\n\n attributeNames.forEach((attrName) => {\n const attr = attrs.get(attrName)\n if (attr === undefined) {\n throw new Error('New attr')\n }\n result.push(attr)\n\n // Remove from current items\n current = current?.filter((f) => f.name !== attrName)\n })\n\n resource.attributes = result\n // Add attrs which were not specified in the order as last items. Not\n // sure if this follows commercetools\n if (current) {\n resource.attributes.push(...current)\n }\n },\n removeAttributeDefinition: (\n context: RepositoryContext,\n resource: Writable<ProductType>,\n { name }: ProductTypeRemoveAttributeDefinitionAction\n ) => {\n resource.attributes = resource.attributes?.filter((f) => f.name !== name)\n },\n removeEnumValues: (\n context: RepositoryContext,\n resource: Writable<ProductType>,\n { attributeName, keys }: ProductTypeRemoveEnumValuesAction\n ) => {\n resource.attributes?.forEach((attr) => {\n if (attr.name == attributeName) {\n if (attr.type.name == 'enum') {\n attr.type.values = attr.type.values.filter(\n (v) => !keys.includes(v.key)\n )\n }\n\n if (attr.type.name == 'set') {\n if (attr.type.elementType.name == 'enum') {\n attr.type.elementType.values =\n attr.type.elementType.values.filter(\n (v) => !keys.includes(v.key)\n )\n }\n }\n }\n })\n },\n }\n}\n","import type {\n Project,\n ProjectChangeCartsConfigurationAction,\n ProjectChangeCountriesAction,\n ProjectChangeCountryTaxRateFallbackEnabledAction,\n ProjectChangeCurrenciesAction,\n ProjectChangeLanguagesAction,\n ProjectChangeMessagesConfigurationAction,\n ProjectChangeNameAction,\n ProjectChangeOrderSearchStatusAction,\n ProjectChangeProductSearchIndexingEnabledAction,\n ProjectSetExternalOAuthAction,\n ProjectSetShippingRateInputTypeAction,\n ProjectUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { maskSecretValue } from '../lib/masking.js'\nimport type { Writable } from '../types.js'\nimport { AbstractRepository, RepositoryContext } from './abstract.js'\n\nexport class ProjectRepository extends AbstractRepository<Project> {\n get(context: RepositoryContext): Project | null {\n const resource = this._storage.getProject(context.projectKey)\n return this.postProcessResource(resource)\n }\n\n postProcessResource(resource: Project): Project {\n if (resource) {\n return maskSecretValue(resource, 'externalOAuth.authorizationHeader')\n }\n return resource\n }\n\n saveNew(context: RepositoryContext, resource: Writable<Project>) {\n resource.version = 1\n this._storage.saveProject(resource)\n }\n\n saveUpdate(context: RepositoryContext, version: number, resource: Project) {\n this._storage.saveProject(resource)\n }\n\n actions: Partial<\n Record<\n ProjectUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Project>,\n action: any\n ) => void\n >\n > = {\n changeName: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { name }: ProjectChangeNameAction\n ) => {\n resource.name = name\n },\n changeCurrencies: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { currencies }: ProjectChangeCurrenciesAction\n ) => {\n resource.currencies = currencies\n },\n changeCountries: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { countries }: ProjectChangeCountriesAction\n ) => {\n resource.countries = countries\n },\n changeLanguages: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { languages }: ProjectChangeLanguagesAction\n ) => {\n resource.languages = languages\n },\n changeMessagesConfiguration: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { messagesConfiguration }: ProjectChangeMessagesConfigurationAction\n ) => {\n resource.messages.enabled = messagesConfiguration.enabled\n resource.messages.deleteDaysAfterCreation = messagesConfiguration.deleteDaysAfterCreation\n },\n changeProductSearchIndexingEnabled: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { enabled }: ProjectChangeProductSearchIndexingEnabledAction\n ) => {\n if (!resource.searchIndexing?.products) {\n throw new Error('Invalid project state')\n }\n resource.searchIndexing.products.status = enabled\n ? 'Activated'\n : 'Deactivated'\n resource.searchIndexing.products.lastModifiedAt = new Date().toISOString()\n },\n changeOrderSearchStatus: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { status }: ProjectChangeOrderSearchStatusAction\n ) => {\n if (!resource.searchIndexing?.orders) {\n throw new Error('Invalid project state')\n }\n resource.searchIndexing.orders.status = status\n resource.searchIndexing.orders.lastModifiedAt = new Date().toISOString()\n },\n setShippingRateInputType: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { shippingRateInputType }: ProjectSetShippingRateInputTypeAction\n ) => {\n resource.shippingRateInputType = shippingRateInputType\n },\n setExternalOAuth: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { externalOAuth }: ProjectSetExternalOAuthAction\n ) => {\n resource.externalOAuth = externalOAuth\n },\n changeCountryTaxRateFallbackEnabled: (\n context: RepositoryContext,\n resource: Writable<Project>,\n {\n countryTaxRateFallbackEnabled,\n }: ProjectChangeCountryTaxRateFallbackEnabledAction\n ) => {\n resource.carts.countryTaxRateFallbackEnabled =\n countryTaxRateFallbackEnabled\n },\n changeCartsConfiguration: (\n context: RepositoryContext,\n resource: Writable<Project>,\n { cartsConfiguration }: ProjectChangeCartsConfigurationAction\n ) => {\n resource.carts = cartsConfiguration || {\n countryTaxRateFallbackEnabled: false,\n deleteDaysAfterLastModification: 90,\n }\n },\n }\n}\n","import type {\n Quote,\n QuoteDraft,\n QuoteUpdateAction,\n} from '@commercetools/platform-sdk'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class QuoteRepository extends AbstractResourceRepository<'quote'> {\n getTypeId() {\n return 'quote' as const\n }\n\n create(context: RepositoryContext, draft: QuoteDraft): Quote {\n throw new Error('not implemented')\n }\n\n actions: Partial<\n Record<\n QuoteUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Quote>,\n action: any\n ) => void\n >\n > = {}\n}\n","import type {\n QuoteRequest,\n QuoteRequestDraft,\n QuoteRequestUpdateAction,\n} from '@commercetools/platform-sdk'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class QuoteRequestRepository extends AbstractResourceRepository<'quote-request'> {\n getTypeId() {\n return 'quote-request' as const\n }\n\n create(context: RepositoryContext, draft: QuoteRequestDraft): QuoteRequest {\n throw new Error('not implemented')\n }\n\n actions: Partial<\n Record<\n QuoteRequestUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<QuoteRequest>,\n action: any\n ) => void\n >\n > = {}\n}\n","import type {\n Review,\n ReviewDraft,\n ReviewUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class ReviewRepository extends AbstractResourceRepository<'review'> {\n getTypeId() {\n return 'review' as const\n }\n\n create(context: RepositoryContext, draft: ReviewDraft): Review {\n const resource: Review = {\n ...getBaseResourceProperties(),\n includedInStatistics: false,\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions: Partial<\n Record<\n ReviewUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Review>,\n action: any\n ) => void\n >\n > = {}\n}\n","import type {\n ShippingMethod,\n ShippingMethodAddShippingRateAction,\n ShippingMethodAddZoneAction,\n ShippingMethodChangeIsDefaultAction,\n ShippingMethodChangeNameAction,\n ShippingMethodDraft,\n ShippingMethodRemoveZoneAction,\n ShippingMethodSetCustomFieldAction,\n ShippingMethodSetCustomTypeAction,\n ShippingMethodSetDescriptionAction,\n ShippingMethodSetKeyAction,\n ShippingMethodSetLocalizedDescriptionAction,\n ShippingMethodSetLocalizedNameAction,\n ShippingMethodSetPredicateAction,\n ShippingMethodUpdateAction,\n ShippingRate,\n ShippingRateDraft,\n ZoneRate,\n ZoneRateDraft,\n ZoneReference,\n} from '@commercetools/platform-sdk'\nimport deepEqual from 'deep-equal'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n createCustomFields,\n createTypedMoney,\n getReferenceFromResourceIdentifier,\n} from './helpers.js'\n\nexport class ShippingMethodRepository extends AbstractResourceRepository<'shipping-method'> {\n getTypeId() {\n return 'shipping-method' as const\n }\n\n create(\n context: RepositoryContext,\n draft: ShippingMethodDraft\n ): ShippingMethod {\n const resource: ShippingMethod = {\n ...getBaseResourceProperties(),\n ...draft,\n taxCategory: getReferenceFromResourceIdentifier(\n draft.taxCategory,\n context.projectKey,\n this._storage\n ),\n zoneRates: draft.zoneRates?.map((z) =>\n this._transformZoneRateDraft(context, z)\n ),\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n private _transformZoneRateDraft = (\n context: RepositoryContext,\n draft: ZoneRateDraft\n ): ZoneRate => ({\n ...draft,\n zone: getReferenceFromResourceIdentifier<ZoneReference>(\n draft.zone,\n context.projectKey,\n this._storage\n ),\n shippingRates: draft.shippingRates?.map(this._transformShippingRate),\n })\n\n private _transformShippingRate = (rate: ShippingRateDraft): ShippingRate => ({\n price: createTypedMoney(rate.price),\n freeAbove: rate.freeAbove && createTypedMoney(rate.freeAbove),\n tiers: rate.tiers || [],\n })\n\n actions: Partial<\n Record<\n ShippingMethodUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n action: any\n ) => void\n >\n > = {\n addShippingRate: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { shippingRate, zone }: ShippingMethodAddShippingRateAction\n ) => {\n const rate = this._transformShippingRate(shippingRate)\n\n resource.zoneRates.forEach((zoneRate) => {\n if (zoneRate.zone.id === zone.id) {\n zoneRate.shippingRates.push(rate)\n return\n }\n })\n resource.zoneRates.push({\n zone: {\n typeId: 'zone',\n id: zone.id!,\n },\n shippingRates: [rate],\n })\n },\n removeShippingRate: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { shippingRate, zone }: ShippingMethodAddShippingRateAction\n ) => {\n const rate = this._transformShippingRate(shippingRate)\n\n resource.zoneRates.forEach((zoneRate) => {\n if (zoneRate.zone.id === zone.id) {\n zoneRate.shippingRates = zoneRate.shippingRates.filter(\n (otherRate) => !deepEqual(rate, otherRate)\n )\n }\n })\n },\n addZone: (\n context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { zone }: ShippingMethodAddZoneAction\n ) => {\n const zoneReference = getReferenceFromResourceIdentifier<ZoneReference>(\n zone,\n context.projectKey,\n this._storage\n )\n\n if (resource.zoneRates === undefined) {\n resource.zoneRates = []\n }\n\n resource.zoneRates.push({\n zone: zoneReference,\n shippingRates: [],\n })\n },\n removeZone: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { zone }: ShippingMethodRemoveZoneAction\n ) => {\n resource.zoneRates = resource.zoneRates.filter(\n (zoneRate) => zoneRate.zone.id !== zone.id\n )\n },\n setKey: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { key }: ShippingMethodSetKeyAction\n ) => {\n resource.key = key\n },\n setDescription: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { description }: ShippingMethodSetDescriptionAction\n ) => {\n resource.description = description\n },\n setLocalizedDescription: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { localizedDescription }: ShippingMethodSetLocalizedDescriptionAction\n ) => {\n resource.localizedDescription = localizedDescription\n },\n setLocalizedName: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { localizedName }: ShippingMethodSetLocalizedNameAction\n ) => {\n resource.localizedName = localizedName\n },\n setPredicate: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { predicate }: ShippingMethodSetPredicateAction\n ) => {\n resource.predicate = predicate\n },\n changeIsDefault: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { isDefault }: ShippingMethodChangeIsDefaultAction\n ) => {\n resource.isDefault = isDefault\n },\n changeName: (\n _context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { name }: ShippingMethodChangeNameAction\n ) => {\n resource.name = name\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { type, fields }: ShippingMethodSetCustomTypeAction\n ) => {\n if (type) {\n resource.custom = createCustomFields(\n { type, fields },\n context.projectKey,\n this._storage\n )\n } else {\n resource.custom = undefined\n }\n },\n setCustomField: (\n context: RepositoryContext,\n resource: Writable<ShippingMethod>,\n { name, value }: ShippingMethodSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n return\n }\n if (value === null) {\n delete resource.custom.fields[name]\n } else {\n resource.custom.fields[name] = value\n }\n },\n }\n}\n","import type {\n CustomerReference,\n ShoppingList,\n ShoppingListDraft,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n createCustomFields,\n getReferenceFromResourceIdentifier,\n getStoreKeyReference,\n} from './helpers.js'\n\nexport class ShoppingListRepository extends AbstractResourceRepository<'shopping-list'> {\n getTypeId() {\n return 'shopping-list' as const\n }\n\n create(context: RepositoryContext, draft: ShoppingListDraft): ShoppingList {\n // const product =\n\n const resource: ShoppingList = {\n ...getBaseResourceProperties(),\n ...draft,\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n textLineItems: [],\n lineItems:\n draft.lineItems?.map((e) => ({\n ...getBaseResourceProperties(),\n ...e,\n addedAt: e.addedAt ?? '',\n productId: e.productId ?? '',\n name: {},\n quantity: e.quantity ?? 1,\n productType: { typeId: 'product-type', id: '' },\n custom: createCustomFields(\n e.custom,\n context.projectKey,\n this._storage\n ),\n })) ?? [],\n customer: draft.customer\n ? getReferenceFromResourceIdentifier<CustomerReference>(\n draft.customer,\n context.projectKey,\n this._storage\n )\n : undefined,\n store: draft.store\n ? getStoreKeyReference(draft.store, context.projectKey, this._storage)\n : undefined,\n }\n this.saveNew(context, resource)\n return resource\n }\n}\n","import type {\n Quote,\n StagedQuote,\n StagedQuoteDraft,\n StagedQuoteUpdateAction,\n} from '@commercetools/platform-sdk'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class StagedQuoteRepository extends AbstractResourceRepository<'staged-quote'> {\n getTypeId() {\n return 'staged-quote' as const\n }\n\n create(context: RepositoryContext, draft: StagedQuoteDraft): StagedQuote {\n throw new Error('not implemented')\n }\n\n actions: Partial<\n Record<\n StagedQuoteUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Quote>,\n action: any\n ) => void\n >\n > = {}\n}\n","import type {\n ChannelReference,\n ChannelResourceIdentifier,\n DiscountedPriceDraft,\n StandalonePrice,\n StandalonePriceChangeActiveAction,\n StandalonePriceChangeValueAction,\n StandalonePriceDraft,\n StandalonePriceSetDiscountedPriceAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport { createTypedMoney } from './helpers.js'\n\nexport class StandAlonePriceRepository extends AbstractResourceRepository<'standalone-price'> {\n getTypeId() {\n return 'standalone-price' as const\n }\n\n create(context: RepositoryContext, draft: StandalonePriceDraft): StandalonePrice {\n const resource: StandalonePrice = {\n ...getBaseResourceProperties(),\n active: draft.active? draft.active : false,\n sku: draft.sku,\n value: createTypedMoney(draft.value),\n country: draft.country,\n discounted: draft.discounted ? this.transformDiscountDraft(draft.discounted) : undefined,\n channel: draft.channel?.id ? this.transformChannelReferenceDraft(draft.channel) : undefined,\n validFrom: draft.validFrom,\n validUntil: draft.validUntil,\n }\n this.saveNew(context, resource)\n return resource\n }\n\n transformChannelReferenceDraft(channel: ChannelResourceIdentifier) : ChannelReference {\n return {\n typeId: channel.typeId,\n id: channel.id as string,\n }\n }\n\n transformDiscountDraft(discounted: DiscountedPriceDraft) {\n return {\n value: createTypedMoney(discounted.value),\n discount: discounted.discount,\n }\n }\n\n actions = {\n setActive: (\n context: RepositoryContext,\n resource: Writable<StandalonePrice>,\n action: StandalonePriceChangeActiveAction\n ) => {\n resource.active = action.active\n },\n changeValue: (\n context: RepositoryContext,\n resource: Writable<StandalonePrice>,\n action: StandalonePriceChangeValueAction\n ) => {\n resource.value = createTypedMoney(action.value)\n },\n setDiscountedPrice: (\n context: RepositoryContext,\n resource: Writable<StandalonePrice>,\n action: StandalonePriceSetDiscountedPriceAction\n ) => {\n resource.discounted = action.discounted ? this.transformDiscountDraft(action.discounted) : undefined\n }\n }\n}\n","import type {\n State,\n StateChangeInitialAction,\n StateChangeKeyAction,\n StateDraft,\n StateReference,\n StateSetDescriptionAction,\n StateSetNameAction,\n StateSetRolesAction,\n StateSetTransitionsAction,\n StateUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport { getReferenceFromResourceIdentifier } from './helpers.js'\n\nexport class StateRepository extends AbstractResourceRepository<'state'> {\n getTypeId() {\n return 'state' as const\n }\n\n create(context: RepositoryContext, draft: StateDraft): State {\n const resource: State = {\n ...getBaseResourceProperties(),\n ...draft,\n builtIn: false,\n initial: draft.initial || false,\n transitions: (draft.transitions || []).map((t) =>\n getReferenceFromResourceIdentifier(t, context.projectKey, this._storage)\n ),\n }\n\n this.saveNew(context, resource)\n return resource\n }\n\n actions: Partial<\n Record<\n StateUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<State>,\n action: any\n ) => void\n >\n > = {\n changeKey: (\n context: RepositoryContext,\n resource: Writable<State>,\n { key }: StateChangeKeyAction\n ) => {\n resource.key = key\n },\n changeInitial: (\n context: RepositoryContext,\n resource: Writable<State>,\n {initial }: StateChangeInitialAction\n ) => {\n resource.initial = initial\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<State>,\n { description }: StateSetDescriptionAction\n ) => {\n resource.description = description\n },\n setName: (\n context: RepositoryContext,\n resource: Writable<State>,\n { name }: StateSetNameAction\n ) => {\n resource.name = name\n },\n setRoles: (\n context: RepositoryContext,\n resource: Writable<State>,\n { roles }: StateSetRolesAction\n ) => {\n resource.roles = roles\n },\n setTransitions: (\n context: RepositoryContext,\n resource: Writable<State>,\n { transitions }: StateSetTransitionsAction\n ) => {\n resource.transitions = transitions?.map(\n (resourceId): StateReference => ({\n id: resourceId.id || '',\n typeId: 'state',\n })\n )\n },\n }\n}\n","import type {\n ChannelReference,\n ChannelResourceIdentifier,\n Store,\n StoreDraft,\n StoreSetCustomFieldAction,\n StoreSetCustomTypeAction,\n StoreSetDistributionChannelsAction,\n StoreSetLanguagesAction,\n StoreSetNameAction,\n StoreUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n createCustomFields,\n getReferenceFromResourceIdentifier,\n} from './helpers.js'\n\nexport class StoreRepository extends AbstractResourceRepository<'store'> {\n getTypeId() {\n return 'store' as const\n }\n\n create(context: RepositoryContext, draft: StoreDraft): Store {\n const resource: Store = {\n ...getBaseResourceProperties(),\n key: draft.key,\n name: draft.name,\n languages: draft.languages ?? [],\n countries: draft.countries ?? [],\n distributionChannels: this.transformChannels(\n context,\n draft.distributionChannels\n ),\n supplyChannels: this.transformChannels(context, draft.supplyChannels),\n productSelections: [],\n custom: createCustomFields(\n draft.custom,\n context.projectKey,\n this._storage\n ),\n }\n this.saveNew(context, resource)\n return resource\n }\n\n private transformChannels(\n context: RepositoryContext,\n channels?: ChannelResourceIdentifier[]\n ) {\n if (!channels) return []\n\n return channels.map((ref) =>\n getReferenceFromResourceIdentifier<ChannelReference>(\n ref,\n context.projectKey,\n this._storage\n )\n )\n }\n\n actions: Partial<\n Record<\n StoreUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Store>,\n action: any\n ) => void\n >\n > = {\n setName: (\n context: RepositoryContext,\n resource: Writable<Store>,\n { name }: StoreSetNameAction\n ) => {\n resource.name = name\n },\n setDistributionChannels: (\n context: RepositoryContext,\n resource: Writable<Store>,\n { distributionChannels }: StoreSetDistributionChannelsAction\n ) => {\n resource.distributionChannels = this.transformChannels(\n context,\n distributionChannels\n )\n },\n setLanguages: (\n context: RepositoryContext,\n resource: Writable<Store>,\n { languages }: StoreSetLanguagesAction\n ) => {\n resource.languages = languages ?? []\n },\n setCustomType: (\n context: RepositoryContext,\n resource: Writable<Store>,\n { type, fields }: StoreSetCustomTypeAction\n ) => {\n if (type) {\n resource.custom = createCustomFields(\n { type, fields },\n context.projectKey,\n this._storage\n )\n } else {\n resource.custom = undefined\n }\n },\n setCustomField: (\n context: RepositoryContext,\n resource: Writable<Store>,\n { name, value }: StoreSetCustomFieldAction\n ) => {\n if (!resource.custom) {\n return\n }\n if (value === null) {\n delete resource.custom.fields[name]\n } else {\n resource.custom.fields[name] = value\n }\n },\n }\n}\n","import type {\n InvalidInputError,\n Subscription,\n SubscriptionDraft,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class SubscriptionRepository extends AbstractResourceRepository<'subscription'> {\n getTypeId() {\n return 'subscription' as const\n }\n create(context: RepositoryContext, draft: SubscriptionDraft): Subscription {\n // TODO: We could actually test this here by using the aws sdk. For now\n // hardcode a failed check when account id is 0000000000\n if (draft.destination.type === 'SQS') {\n const queueURL = new URL(draft.destination.queueUrl)\n const accountId = queueURL.pathname.split('/')[1]\n if (accountId === '0000000000') {\n const dest = draft.destination\n throw new CommercetoolsError<InvalidInputError>(\n {\n code: 'InvalidInput',\n message:\n 'A test message could not be delivered to this destination: ' +\n `SQS ${dest.queueUrl} in ${dest.region} for ${dest.accessKey}. ` +\n 'Please make sure your destination is correctly configured.',\n },\n 400\n )\n }\n }\n\n const resource: Subscription = {\n ...getBaseResourceProperties(),\n changes: draft.changes || [],\n destination: draft.destination,\n format: draft.format || {\n type: 'Platform',\n },\n key: draft.key,\n messages: draft.messages || [],\n status: 'Healthy',\n }\n this.saveNew(context, resource)\n return resource\n }\n}\n","import type {\n TaxCategory,\n TaxCategoryAddTaxRateAction,\n TaxCategoryChangeNameAction,\n TaxCategoryDraft,\n TaxCategoryRemoveTaxRateAction,\n TaxCategoryReplaceTaxRateAction,\n TaxCategorySetDescriptionAction,\n TaxCategorySetKeyAction,\n TaxCategoryUpdateAction,\n TaxRate,\n TaxRateDraft,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class TaxCategoryRepository extends AbstractResourceRepository<'tax-category'> {\n getTypeId() {\n return 'tax-category' as const\n }\n\n create(context: RepositoryContext, draft: TaxCategoryDraft): TaxCategory {\n const resource: TaxCategory = {\n ...getBaseResourceProperties(),\n ...draft,\n rates: draft.rates?.map(this.taxRateFromTaxRateDraft) || [],\n }\n this.saveNew(context, resource)\n return resource\n }\n\n private taxRateFromTaxRateDraft = (draft: TaxRateDraft): TaxRate => ({\n ...draft,\n id: uuidv4(),\n amount: draft.amount || 0,\n })\n\n actions: Partial<\n Record<\n TaxCategoryUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<TaxCategory>,\n action: any\n ) => void\n >\n > = {\n addTaxRate: (\n context: RepositoryContext,\n resource: Writable<TaxCategory>,\n { taxRate }: TaxCategoryAddTaxRateAction\n ) => {\n if (resource.rates === undefined) {\n resource.rates = []\n }\n resource.rates.push(this.taxRateFromTaxRateDraft(taxRate))\n },\n removeTaxRate: (\n context: RepositoryContext,\n resource: Writable<TaxCategory>,\n { taxRateId }: TaxCategoryRemoveTaxRateAction\n ) => {\n if (resource.rates === undefined) {\n resource.rates = []\n }\n resource.rates = resource.rates.filter(\n (taxRate) => taxRate.id !== taxRateId\n )\n },\n replaceTaxRate: (\n context: RepositoryContext,\n resource: Writable<TaxCategory>,\n { taxRateId, taxRate }: TaxCategoryReplaceTaxRateAction\n ) => {\n if (resource.rates === undefined) {\n resource.rates = []\n }\n\n const taxRateObj = this.taxRateFromTaxRateDraft(taxRate)\n for (let i = 0; i < resource.rates.length; i++) {\n const rate = resource.rates[i]\n if (rate.id === taxRateId) {\n resource.rates[i] = taxRateObj\n }\n }\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<TaxCategory>,\n { description }: TaxCategorySetDescriptionAction\n ) => {\n resource.description = description\n },\n setKey: (\n context: RepositoryContext,\n resource: Writable<TaxCategory>,\n { key }: TaxCategorySetKeyAction\n ) => {\n resource.key = key\n },\n changeName: (\n context: RepositoryContext,\n resource: Writable<TaxCategory>,\n { name }: TaxCategoryChangeNameAction\n ) => {\n resource.name = name\n },\n }\n}\n","import type {\n FieldDefinition,\n InvalidOperationError,\n Type,\n TypeAddEnumValueAction,\n TypeAddFieldDefinitionAction,\n TypeChangeEnumValueLabelAction,\n TypeChangeFieldDefinitionOrderAction,\n TypeChangeNameAction,\n TypeDraft,\n TypeRemoveFieldDefinitionAction,\n TypeSetDescriptionAction,\n TypeUpdateAction,\n} from '@commercetools/platform-sdk'\nimport isEqual from 'lodash.isequal'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class TypeRepository extends AbstractResourceRepository<'type'> {\n getTypeId() {\n return 'type' as const\n }\n\n create(context: RepositoryContext, draft: TypeDraft): Type {\n const resource: Type = {\n ...getBaseResourceProperties(),\n key: draft.key,\n name: draft.name,\n resourceTypeIds: draft.resourceTypeIds,\n fieldDefinitions: draft.fieldDefinitions || [],\n description: draft.description,\n }\n this.saveNew(context, resource)\n return resource\n }\n actions: Partial<\n Record<\n TypeUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Type>,\n action: any\n ) => void\n >\n > = {\n addFieldDefinition: (\n context: RepositoryContext,\n resource: Writable<Type>,\n { fieldDefinition }: TypeAddFieldDefinitionAction\n ) => {\n resource.fieldDefinitions.push(fieldDefinition)\n },\n removeFieldDefinition: (\n context: RepositoryContext,\n resource: Writable<Type>,\n { fieldName }: TypeRemoveFieldDefinitionAction\n ) => {\n resource.fieldDefinitions = resource.fieldDefinitions.filter(\n (f) => f.name !== fieldName\n )\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<Type>,\n { description }: TypeSetDescriptionAction\n ) => {\n resource.description = description\n },\n changeName: (\n context: RepositoryContext,\n resource: Writable<Type>,\n { name }: TypeChangeNameAction\n ) => {\n resource.name = name\n },\n changeFieldDefinitionOrder: (\n context: RepositoryContext,\n resource: Writable<Type>,\n { fieldNames }: TypeChangeFieldDefinitionOrderAction\n ) => {\n const fields = new Map(\n resource.fieldDefinitions.map((item) => [item.name, item])\n )\n const result: FieldDefinition[] = []\n let current = resource.fieldDefinitions\n\n fieldNames.forEach((fieldName) => {\n const field = fields.get(fieldName)\n if (field === undefined) {\n throw new Error('New field')\n }\n result.push(field)\n\n // Remove from current items\n current = current.filter((f) => f.name !== fieldName)\n })\n\n if (\n isEqual(\n fieldNames,\n resource.fieldDefinitions.map((item) => item.name)\n )\n ) {\n throw new CommercetoolsError<InvalidOperationError>({\n code: 'InvalidOperation',\n message: \"'fieldDefinitions' has no changes.\",\n action: {\n action: 'changeFieldDefinitionOrder',\n fieldNames: fieldNames,\n },\n })\n }\n\n resource.fieldDefinitions = result\n // Add fields which were not specified in the order as last items. Not\n // sure if this follows commercetools\n resource.fieldDefinitions.push(...current)\n },\n addEnumValue: (\n context: RepositoryContext,\n resource: Writable<Type>,\n { fieldName, value }: TypeAddEnumValueAction\n ) => {\n resource.fieldDefinitions.forEach((field) => {\n if (field.name === fieldName) {\n // TODO, should be done better i suppose\n if (field.type.name === 'Enum') {\n field.type.values.push(value)\n } else if (\n field.type.name === 'Set' &&\n field.type.elementType.name === 'Enum'\n ) {\n field.type.elementType.values.push(value)\n } else {\n throw new Error('Type is not a Enum (or Set of Enum)')\n }\n }\n })\n },\n changeEnumValueLabel: (\n context: RepositoryContext,\n resource: Writable<Type>,\n { fieldName, value }: TypeChangeEnumValueLabelAction\n ) => {\n resource.fieldDefinitions.forEach((field) => {\n if (field.name === fieldName) {\n // TODO, should be done better i suppose\n if (field.type.name === 'Enum') {\n field.type.values.forEach((v) => {\n if (v.key === value.key) {\n v.label = value.label\n }\n })\n } else if (\n field.type.name === 'Set' &&\n field.type.elementType.name === 'Enum'\n ) {\n field.type.elementType.values.forEach((v) => {\n if (v.key === value.key) {\n v.label = value.label\n }\n })\n } else {\n throw new Error('Type is not a Enum (or Set of Enum)')\n }\n }\n })\n },\n }\n}\n","import type {\n Zone,\n ZoneAddLocationAction,\n ZoneChangeNameAction,\n ZoneDraft,\n ZoneRemoveLocationAction,\n ZoneSetDescriptionAction,\n ZoneSetKeyAction,\n ZoneUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class ZoneRepository extends AbstractResourceRepository<'zone'> {\n getTypeId() {\n return 'zone' as const\n }\n\n create(context: RepositoryContext, draft: ZoneDraft): Zone {\n const resource: Zone = {\n ...getBaseResourceProperties(),\n key: draft.key,\n locations: draft.locations || [],\n name: draft.name,\n description: draft.description,\n }\n this.saveNew(context, resource)\n return resource\n }\n\n actions: Partial<\n Record<\n ZoneUpdateAction['action'],\n (\n context: RepositoryContext,\n resource: Writable<Zone>,\n action: any\n ) => void\n >\n > = {\n addLocation: (\n context: RepositoryContext,\n resource: Writable<Zone>,\n { location }: ZoneAddLocationAction\n ) => {\n resource.locations.push(location)\n },\n removeLocation: (\n context: RepositoryContext,\n resource: Writable<Zone>,\n { location }: ZoneRemoveLocationAction\n ) => {\n resource.locations = resource.locations.filter(\n (loc) =>\n !(loc.country === location.country && loc.state === location.state)\n )\n },\n changeName: (\n context: RepositoryContext,\n resource: Writable<Zone>,\n { name }: ZoneChangeNameAction\n ) => {\n resource.name = name\n },\n setDescription: (\n context: RepositoryContext,\n resource: Writable<Zone>,\n { description }: ZoneSetDescriptionAction\n ) => {\n resource.description = description\n },\n setKey: (\n context: RepositoryContext,\n resource: Writable<Zone>,\n { key }: ZoneSetKeyAction\n ) => {\n resource.key = key\n },\n }\n}\n","import { AbstractStorage } from '../storage/index.js'\nimport { AssociateRoleRepository } from './associate-role.js'\nimport { AttributeGroupRepository } from './attribute-group.js'\nimport { BusinessUnitRepository } from './business-unit.js'\nimport { CartRepository } from './cart.js'\nimport { CartDiscountRepository } from './cart-discount.js'\nimport { CategoryRepository } from './category.js'\nimport { ChannelRepository } from './channel.js'\nimport { CustomObjectRepository } from './custom-object.js'\nimport { CustomerRepository } from './customer.js'\nimport { CustomerGroupRepository } from './customer-group.js'\nimport { DiscountCodeRepository } from './discount-code.js'\nimport { ExtensionRepository } from './extension.js'\nimport { InventoryEntryRepository } from './inventory-entry.js'\nimport { MyOrderRepository } from './my-order.js'\nimport { OrderRepository } from './order.js'\nimport { OrderEditRepository } from './order-edit.js'\nimport { PaymentRepository } from './payment.js'\nimport { ProductRepository } from './product.js'\nimport { ProductDiscountRepository } from './product-discount.js'\nimport { ProductProjectionRepository } from './product-projection.js'\nimport { ProductSelectionRepository } from './product-selection.js'\nimport { ProductTypeRepository } from './product-type.js'\nimport { ProjectRepository } from './project.js'\nimport { QuoteRepository } from './quote.js'\nimport { QuoteRequestRepository } from './quote-request.js'\nimport { ReviewRepository } from './review.js'\nimport { ShippingMethodRepository } from './shipping-method.js'\nimport { ShoppingListRepository } from './shopping-list.js'\nimport { StagedQuoteRepository } from './staged-quote.js'\nimport { StandAlonePriceRepository } from './standalone-price.js'\nimport { StateRepository } from './state.js'\nimport { StoreRepository } from './store.js'\nimport { SubscriptionRepository } from './subscription.js'\nimport { TaxCategoryRepository } from './tax-category.js'\nimport { TypeRepository } from './type.js'\nimport { ZoneRepository } from './zone.js'\n\nexport type RepositoryMap = ReturnType<typeof createRepositories>\n\nexport const createRepositories = (storage: AbstractStorage) => ({\n 'associate-role': new AssociateRoleRepository(storage),\n 'attribute-group': new AttributeGroupRepository(storage),\n 'business-unit': new BusinessUnitRepository(storage),\n category: new CategoryRepository(storage),\n cart: new CartRepository(storage),\n 'cart-discount': new CartDiscountRepository(storage),\n customer: new CustomerRepository(storage),\n channel: new ChannelRepository(storage),\n 'customer-group': new CustomerGroupRepository(storage),\n 'discount-code': new DiscountCodeRepository(storage),\n extension: new ExtensionRepository(storage),\n 'inventory-entry': new InventoryEntryRepository(storage),\n 'key-value-document': new CustomObjectRepository(storage),\n order: new OrderRepository(storage),\n 'order-edit': new OrderEditRepository(storage),\n payment: new PaymentRepository(storage),\n 'my-cart': new CartRepository(storage),\n 'my-order': new MyOrderRepository(storage),\n 'my-customer': new CustomerRepository(storage),\n 'my-payment': new PaymentRepository(storage),\n product: new ProductRepository(storage),\n 'product-type': new ProductTypeRepository(storage),\n 'product-discount': new ProductDiscountRepository(storage),\n 'product-projection': new ProductProjectionRepository(storage),\n 'product-selection': new ProductSelectionRepository(storage),\n project: new ProjectRepository(storage),\n review: new ReviewRepository(storage),\n quote: new QuoteRepository(storage),\n 'quote-request': new QuoteRequestRepository(storage),\n 'shipping-method': new ShippingMethodRepository(storage),\n 'shopping-list': new ShoppingListRepository(storage),\n 'staged-quote': new StagedQuoteRepository(storage),\n 'standalone-price': new StandAlonePriceRepository(storage),\n state: new StateRepository(storage),\n store: new StoreRepository(storage),\n subscription: new SubscriptionRepository(storage),\n 'tax-category': new TaxCategoryRepository(storage),\n type: new TypeRepository(storage),\n zone: new ZoneRepository(storage),\n})\n","import type { Update } from '@commercetools/platform-sdk'\nimport { type Request, type Response, Router } from 'express'\nimport { ParsedQs } from 'qs'\nimport { AbstractResourceRepository } from '../repositories/abstract.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\n\nexport default abstract class AbstractService {\n protected abstract getBasePath(): string\n public abstract repository: AbstractResourceRepository<any>\n\n createStatusCode = 201\n\n constructor(parent: Router) {\n this.registerRoutes(parent)\n }\n\n extraRoutes(router: Router) {}\n\n registerRoutes(parent: Router) {\n const basePath = this.getBasePath()\n const router = Router({ mergeParams: true })\n\n // Bind this first since the `/:id` routes are currently a bit to greedy\n this.extraRoutes(router)\n\n router.get('/', this.get.bind(this))\n router.get('/key=:key', this.getWithKey.bind(this)) // same thing goes for the key routes\n router.get('/:id', this.getWithId.bind(this))\n\n router.delete('/key=:key', this.deleteWithKey.bind(this))\n router.delete('/:id', this.deleteWithId.bind(this))\n\n router.post('/', this.post.bind(this))\n router.post('/key=:key', this.postWithKey.bind(this))\n router.post('/:id', this.postWithId.bind(this))\n\n parent.use(`/${basePath}`, router)\n }\n\n get(request: Request, response: Response) {\n const limit = this._parseParam(request.query.limit)\n const offset = this._parseParam(request.query.offset)\n\n const result = this.repository.query(getRepositoryContext(request), {\n expand: this._parseParam(request.query.expand),\n where: this._parseParam(request.query.where),\n limit: limit !== undefined ? Number(limit) : undefined,\n offset: offset !== undefined ? Number(offset) : undefined,\n })\n return response.status(200).send(result)\n }\n\n getWithId(request: Request, response: Response) {\n const result = this._expandWithId(request, request.params['id'])\n if (!result) {\n return response.status(404).send()\n }\n return response.status(200).send(result)\n }\n\n getWithKey(request: Request, response: Response) {\n const result = this.repository.getByKey(\n getRepositoryContext(request),\n request.params['key'],\n { expand: this._parseParam(request.query.expand) }\n )\n if (!result) return response.status(404).send()\n return response.status(200).send(result)\n }\n\n deleteWithId(request: Request, response: Response) {\n const result = this.repository.delete(\n getRepositoryContext(request),\n request.params['id'],\n {\n expand: this._parseParam(request.query.expand),\n }\n )\n if (!result) {\n return response.status(404).send('Not found')\n }\n return response.status(200).send(result)\n }\n\n deleteWithKey(request: Request, response: Response) {\n const resource = this.repository.getByKey(\n getRepositoryContext(request),\n request.params['key']\n )\n if (!resource) {\n return response.status(404).send('Not found')\n }\n\n const result = this.repository.delete(\n getRepositoryContext(request),\n resource.id,\n {\n expand: this._parseParam(request.query.expand),\n }\n )\n if (!result) {\n return response.status(404).send('Not found')\n }\n return response.status(200).send(result)\n }\n\n post(request: Request, response: Response) {\n const draft = request.body\n const resource = this.repository.create(\n getRepositoryContext(request),\n draft\n )\n const result = this._expandWithId(request, resource.id)\n return response.status(this.createStatusCode).send(result)\n }\n\n postWithId(request: Request, response: Response) {\n const updateRequest: Update = request.body\n const resource = this.repository.get(\n getRepositoryContext(request),\n request.params['id']\n )\n if (!resource) {\n return response.status(404).send('Not found')\n }\n\n const updatedResource = this.repository.processUpdateActions(\n getRepositoryContext(request),\n resource,\n updateRequest.version,\n updateRequest.actions\n )\n\n const result = this._expandWithId(request, updatedResource.id)\n return response.status(200).send(result)\n }\n\n postWithKey(request: Request, response: Response) {\n const updateRequest: Update = request.body\n const resource = this.repository.getByKey(\n getRepositoryContext(request),\n request.params['key']\n )\n if (!resource) {\n return response.status(404).send('Not found')\n }\n const updatedResource = this.repository.processUpdateActions(\n getRepositoryContext(request),\n resource,\n updateRequest.version,\n updateRequest.actions\n )\n\n const result = this._expandWithId(request, updatedResource.id)\n return response.status(200).send(result)\n }\n\n protected _expandWithId(request: Request, resourceId: string) {\n const result = this.repository.get(\n getRepositoryContext(request),\n resourceId,\n {\n expand: this._parseParam(request.query.expand),\n }\n )\n return result\n }\n\n // No idea what i'm doing\n private _parseParam(\n value: string | ParsedQs | string[] | ParsedQs[] | undefined\n ): string[] | undefined {\n if (Array.isArray(value)) {\n // @ts-ignore\n return value\n } else if (value !== undefined) {\n return [`${value}`]\n }\n return undefined\n }\n}\n","import type { Cart, CartDraft, Order } from '@commercetools/platform-sdk'\nimport type { Request, Response, Router } from 'express'\nimport type { CartRepository } from '../repositories/cart.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport type { OrderRepository } from '../repositories/order.js'\nimport AbstractService from './abstract.js'\n\nexport class CartService extends AbstractService {\n public repository: CartRepository\n public orderRepository: OrderRepository\n\n constructor(\n parent: Router,\n cartRepository: CartRepository,\n orderRepository: OrderRepository\n ) {\n super(parent)\n this.repository = cartRepository\n this.orderRepository = orderRepository\n }\n\n getBasePath() {\n return 'carts'\n }\n\n extraRoutes(parent: Router) {\n parent.post('/replicate', this.replicate.bind(this))\n }\n\n replicate(request: Request, response: Response) {\n const context = getRepositoryContext(request)\n\n // @ts-ignore\n const cartOrOrder: Cart | Order | null =\n request.body.reference.typeId === 'order'\n ? this.orderRepository.get(context, request.body.reference.id)\n : this.repository.get(context, request.body.reference.id)\n\n if (!cartOrOrder) {\n return response.status(400).send()\n }\n\n const cartDraft: CartDraft = {\n ...cartOrOrder,\n currency: cartOrOrder.totalPrice.currencyCode,\n discountCodes: [],\n shipping: [], // TODO: cartOrOrder.shipping,\n lineItems: cartOrOrder.lineItems.map((lineItem) => ({\n ...lineItem,\n variantId: lineItem.variant.id,\n sku: lineItem.variant.sku,\n })),\n }\n\n const newCart = this.repository.create(context, cartDraft)\n\n return response.status(200).send(newCart)\n }\n}\n","import { Router } from 'express'\nimport { CartDiscountRepository } from '../repositories/cart-discount.js'\nimport AbstractService from './abstract.js'\n\nexport class CartDiscountService extends AbstractService {\n public repository: CartDiscountRepository\n\n constructor(parent: Router, repository: CartDiscountRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'cart-discounts'\n }\n}\n","import { Router } from 'express'\nimport { CategoryRepository } from '../repositories/category.js'\nimport AbstractService from './abstract.js'\n\nexport class CategoryServices extends AbstractService {\n public repository: CategoryRepository\n\n constructor(parent: Router, repository: CategoryRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'categories'\n }\n}\n","import { Router } from 'express'\nimport { ChannelRepository } from '../repositories/channel.js'\nimport AbstractService from './abstract.js'\n\nexport class ChannelService extends AbstractService {\n public repository: ChannelRepository\n\n constructor(parent: Router, repository: ChannelRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'channels'\n }\n}\n","import type { CustomObjectDraft } from '@commercetools/platform-sdk'\nimport type { Request, Response, Router } from 'express'\nimport type { CustomObjectRepository } from '../repositories/custom-object.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport AbstractService from './abstract.js'\n\nexport class CustomObjectService extends AbstractService {\n public repository: CustomObjectRepository\n\n constructor(parent: Router, repository: CustomObjectRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'custom-objects'\n }\n\n extraRoutes(router: Router) {\n router.get('/:container/:key', this.getWithContainerAndKey.bind(this))\n router.post('/:container/:key', this.createWithContainerAndKey.bind(this))\n router.delete('/:container/:key', this.deleteWithContainerAndKey.bind(this))\n }\n\n getWithContainerAndKey(request: Request, response: Response) {\n const result = this.repository.getWithContainerAndKey(\n getRepositoryContext(request),\n request.params.container,\n request.params.key\n )\n\n if (!result) {\n return response.status(404).send('Not Found')\n }\n return response.status(200).send(result)\n }\n\n createWithContainerAndKey(request: Request, response: Response) {\n const draft: CustomObjectDraft = {\n ...request.body,\n key: request.params.key,\n container: request.params.container,\n }\n\n const result = this.repository.create(getRepositoryContext(request), draft)\n return response.status(200).send(result)\n }\n\n deleteWithContainerAndKey(request: Request, response: Response) {\n const current = this.repository.getWithContainerAndKey(\n getRepositoryContext(request),\n request.params.container,\n request.params.key\n )\n\n if (!current) {\n return response.status(404).send('Not Found')\n }\n\n const result = this.repository.delete(\n getRepositoryContext(request),\n current.id\n )\n\n return response.status(200).send(result)\n }\n}\n","import { Router } from 'express'\nimport { v4 as uuidv4 } from 'uuid'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { CustomerRepository } from '../repositories/customer.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport AbstractService from './abstract.js'\n\nexport class CustomerService extends AbstractService {\n public repository: CustomerRepository\n\n constructor(parent: Router, repository: CustomerRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'customers'\n }\n\n extraRoutes(parent: Router) {\n parent.post('/password-token', (request, response) => {\n const customer = this.repository.query(getRepositoryContext(request), {\n where: [`email=\"${request.body.email}\"`],\n })\n // @ts-ignore\n const ttlMinutes: number = request.params.ttlMinutes\n ? // @ts-ignore\n +request.params.ttlMinutes\n : 34560\n const { version, ...rest } = getBaseResourceProperties()\n\n return response.status(200).send({\n ...rest,\n customerId: customer.results[0].id,\n expiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),\n value: uuidv4(),\n })\n })\n }\n}\n","import { Router } from 'express'\nimport { CustomerGroupRepository } from '../repositories/customer-group.js'\nimport AbstractService from './abstract.js'\n\nexport class CustomerGroupService extends AbstractService {\n public repository: CustomerGroupRepository\n\n constructor(parent: Router, repository: CustomerGroupRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'customer-groups'\n }\n}\n","import { Router } from 'express'\nimport { DiscountCodeRepository } from '../repositories/discount-code.js'\nimport AbstractService from './abstract.js'\n\nexport class DiscountCodeService extends AbstractService {\n public repository: DiscountCodeRepository\n\n constructor(parent: Router, repository: DiscountCodeRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'discount-codes'\n }\n}\n","import { Router } from 'express'\nimport { ExtensionRepository } from '../repositories/extension.js'\nimport AbstractService from './abstract.js'\n\nexport class ExtensionServices extends AbstractService {\n public repository: ExtensionRepository\n\n constructor(parent: Router, repository: ExtensionRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'extensions'\n }\n}\n","import { Router } from 'express'\nimport { InventoryEntryRepository } from '../repositories/inventory-entry.js'\nimport AbstractService from './abstract.js'\n\nexport class InventoryEntryService extends AbstractService {\n public repository: InventoryEntryRepository\n\n constructor(parent: Router, repository: InventoryEntryRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'inventory'\n }\n}\n","import { Request, Response, Router } from 'express'\nimport { CartRepository } from '../repositories/cart.js'\nimport AbstractService from './abstract.js'\n\nexport class MyCartService extends AbstractService {\n public repository: CartRepository\n\n constructor(parent: Router, repository: CartRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'me'\n }\n\n registerRoutes(parent: Router) {\n // Overwrite this function to be able to handle /me/active-cart path.\n const basePath = this.getBasePath()\n const router = Router({ mergeParams: true })\n\n this.extraRoutes(router)\n\n router.get('/active-cart', this.activeCart.bind(this))\n router.get('/carts/', this.get.bind(this))\n router.get('/carts/:id', this.getWithId.bind(this))\n\n router.delete('/carts/:id', this.deleteWithId.bind(this))\n\n router.post('/carts/', this.post.bind(this))\n router.post('/carts/:id', this.postWithId.bind(this))\n\n parent.use(`/${basePath}`, router)\n }\n\n activeCart(request: Request, response: Response) {\n const resource = this.repository.getActiveCart(request.params.projectKey)\n if (!resource) {\n return response.status(404).send('Not found')\n }\n return response.status(200).send(resource)\n }\n}\n","import { Request, Response, Router } from 'express'\nimport { CustomerRepository } from '../repositories/customer.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport AbstractService from './abstract.js'\n\nexport class MyCustomerService extends AbstractService {\n public repository: CustomerRepository\n\n constructor(parent: Router, repository: CustomerRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'me'\n }\n\n registerRoutes(parent: Router) {\n // Overwrite this function to be able to handle /me path.\n const basePath = this.getBasePath()\n const router = Router({ mergeParams: true })\n\n this.extraRoutes(router)\n\n router.get('', this.getMe.bind(this))\n\n router.post('/signup', this.signUp.bind(this))\n\n router.post('/login', this.signIn.bind(this))\n\n parent.use(`/${basePath}`, router)\n }\n\n getMe(request: Request, response: Response) {\n const resource = this.repository.getMe(getRepositoryContext(request))\n if (!resource) {\n return response.status(404).send('Not found')\n }\n return response.status(200).send(resource)\n }\n\n signUp(request: Request, response: Response) {\n const draft = request.body\n const resource = this.repository.create(\n getRepositoryContext(request),\n draft\n )\n const result = this._expandWithId(request, resource.id)\n return response.status(this.createStatusCode).send({ customer: result })\n }\n\n signIn(request: Request, response: Response) {\n const { email, password } = request.body\n const encodedPassword = Buffer.from(password).toString('base64')\n\n const result = this.repository.query(getRepositoryContext(request), {\n where: [`email = \"${email}\"`, `password = \"${encodedPassword}\"`],\n })\n\n if (result.count === 0) {\n return response.status(400).send({\n message: 'Account with the given credentials not found.',\n errors: [\n {\n code: 'InvalidCredentials',\n message: 'Account with the given credentials not found.',\n },\n ],\n })\n }\n\n return response.status(200).send({ customer: result.results[0] })\n }\n}\n","import { Router } from 'express'\nimport { MyOrderRepository } from '../repositories/my-order.js'\nimport AbstractService from './abstract.js'\n\nexport class MyOrderService extends AbstractService {\n public repository: MyOrderRepository\n\n constructor(parent: Router, repository: MyOrderRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'me'\n }\n\n registerRoutes(parent: Router) {\n // Overwrite this function to be able to handle /me/active-cart path.\n const basePath = this.getBasePath()\n const router = Router({ mergeParams: true })\n\n this.extraRoutes(router)\n\n router.get('/orders/', this.get.bind(this))\n router.get('/orders/:id', this.getWithId.bind(this))\n\n router.delete('/orders/:id', this.deleteWithId.bind(this))\n\n router.post('/orders/', this.post.bind(this))\n router.post('/orders/:id', this.postWithId.bind(this))\n\n parent.use(`/${basePath}`, router)\n }\n}\n","import { Router } from 'express'\nimport { PaymentRepository } from '../repositories/payment.js'\nimport AbstractService from './abstract.js'\n\nexport class MyPaymentService extends AbstractService {\n public repository: PaymentRepository\n\n constructor(parent: Router, repository: PaymentRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'me/payments'\n }\n}\n","import { Request, Response, Router } from 'express'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport { OrderRepository } from '../repositories/order.js'\nimport AbstractService from './abstract.js'\n\nexport class OrderService extends AbstractService {\n public repository: OrderRepository\n\n constructor(parent: Router, repository: OrderRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'orders'\n }\n\n extraRoutes(router: Router) {\n router.post('/import', this.import.bind(this))\n router.get('/order-number=:orderNumber', this.getWithOrderNumber.bind(this))\n }\n\n import(request: Request, response: Response) {\n const importDraft = request.body\n const resource = this.repository.import(\n getRepositoryContext(request),\n importDraft\n )\n return response.status(200).send(resource)\n }\n\n getWithOrderNumber(request: Request, response: Response) {\n const resource = this.repository.getWithOrderNumber(\n getRepositoryContext(request),\n request.params.orderNumber,\n request.query\n )\n if (resource) {\n return response.status(200).send(resource)\n }\n return response.status(404).send('Not found')\n }\n}\n","import { Router } from 'express'\nimport { PaymentRepository } from '../repositories/payment.js'\nimport AbstractService from './abstract.js'\n\nexport class PaymentService extends AbstractService {\n public repository: PaymentRepository\n\n constructor(parent: Router, repository: PaymentRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'payments'\n }\n}\n","import { Router } from 'express'\nimport { ProductRepository } from '../repositories/product.js'\nimport AbstractService from './abstract.js'\n\nexport class ProductService extends AbstractService {\n public repository: ProductRepository\n\n constructor(parent: Router, repository: ProductRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'products'\n }\n}\n","import { Router } from 'express'\nimport { ProductDiscountRepository } from '../repositories/product-discount.js'\nimport AbstractService from './abstract.js'\n\nexport class ProductDiscountService extends AbstractService {\n public repository: ProductDiscountRepository\n\n constructor(parent: Router, repository: ProductDiscountRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'product-discounts'\n }\n}\n","import { Request, Response, Router } from 'express'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport { ProductProjectionRepository } from './../repositories/product-projection.js'\nimport AbstractService from './abstract.js'\n\nexport class ProductProjectionService extends AbstractService {\n public repository: ProductProjectionRepository\n\n constructor(parent: Router, repository: ProductProjectionRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'product-projections'\n }\n\n extraRoutes(router: Router) {\n router.get('/search', this.search.bind(this))\n }\n\n search(request: Request, response: Response) {\n const resource = this.repository.search(\n getRepositoryContext(request),\n request.query\n )\n return response.status(200).send(resource)\n }\n}\n","import { Router } from 'express'\nimport { ProductTypeRepository } from '../repositories/product-type.js'\nimport AbstractService from './abstract.js'\n\nexport class ProductTypeService extends AbstractService {\n public repository: ProductTypeRepository\n\n constructor(parent: Router, repository: ProductTypeRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'product-types'\n }\n}\n","import { Router } from 'express'\nimport { ShippingMethodRepository } from '../repositories/shipping-method.js'\nimport AbstractService from './abstract.js'\n\nexport class ShippingMethodService extends AbstractService {\n public repository: ShippingMethodRepository\n\n constructor(parent: Router, repository: ShippingMethodRepository) {\n super(parent)\n this.repository = repository\n this.registerRoutes(parent)\n }\n\n getBasePath() {\n return 'shipping-methods'\n }\n\n extraRoutes(parent: Router) {\n parent.get('/matching-cart', this.get.bind(this))\n }\n}\n","import { Router } from 'express'\nimport { ShoppingListRepository } from './../repositories/shopping-list.js'\nimport AbstractService from './abstract.js'\n\nexport class ShoppingListService extends AbstractService {\n public repository: ShoppingListRepository\n\n constructor(parent: Router, repository: ShoppingListRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'shopping-lists'\n }\n}\n","import { Router } from 'express'\nimport { StandAlonePriceRepository } from '../repositories/standalone-price.js'\nimport AbstractService from './abstract.js'\n\nexport class StandAlonePriceService extends AbstractService {\n public repository: StandAlonePriceRepository\n\n constructor(parent: Router, repository: StandAlonePriceRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'standalone-prices'\n }\n}\n","import { Router } from 'express'\nimport { StateRepository } from '../repositories/state.js'\nimport AbstractService from './abstract.js'\n\nexport class StateService extends AbstractService {\n public repository: StateRepository\n\n constructor(parent: Router, repository: StateRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'states'\n }\n}\n","import { Router } from 'express'\nimport { StoreRepository } from '../repositories/store.js'\nimport AbstractService from './abstract.js'\n\nexport class StoreService extends AbstractService {\n public repository: StoreRepository\n\n constructor(parent: Router, repository: StoreRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'stores'\n }\n}\n","import { Router } from 'express'\nimport { SubscriptionRepository } from '../repositories/subscription.js'\nimport AbstractService from './abstract.js'\n\nexport class SubscriptionService extends AbstractService {\n public repository: SubscriptionRepository\n\n constructor(parent: Router, repository: SubscriptionRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'subscriptions'\n }\n}\n","import { Router } from 'express'\nimport { TaxCategoryRepository } from '../repositories/tax-category.js'\nimport AbstractService from './abstract.js'\n\nexport class TaxCategoryService extends AbstractService {\n public repository: TaxCategoryRepository\n\n constructor(parent: Router, repository: TaxCategoryRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'tax-categories'\n }\n}\n","import { Router } from 'express'\nimport { TypeRepository } from '../repositories/type.js'\nimport AbstractService from './abstract.js'\n\nexport class TypeService extends AbstractService {\n public repository: TypeRepository\n\n constructor(parent: Router, repository: TypeRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'types'\n }\n}\n","import { Router } from 'express'\nimport { ZoneRepository } from '../repositories/zone.js'\nimport AbstractService from './abstract.js'\n\nexport class ZoneService extends AbstractService {\n public repository: ZoneRepository\n\n constructor(parent: Router, repository: ZoneRepository) {\n super(parent)\n this.repository = repository\n }\n\n getBasePath() {\n return 'zones'\n }\n}\n","import { CartService } from './cart.js'\nimport { CartDiscountService } from './cart-discount.js'\nimport { CategoryServices } from './category.js'\nimport { ChannelService } from './channel.js'\nimport { CustomObjectService } from './custom-object.js'\nimport { CustomerService } from './customer.js'\nimport { CustomerGroupService } from './customer-group.js'\nimport { DiscountCodeService } from './discount-code.js'\nimport { ExtensionServices } from './extension.js'\nimport { InventoryEntryService } from './inventory-entry.js'\nimport { MyCartService } from './my-cart.js'\nimport { MyCustomerService } from './my-customer.js'\nimport { MyOrderService } from './my-order.js'\nimport { MyPaymentService } from './my-payment.js'\nimport { OrderService } from './order.js'\nimport { PaymentService } from './payment.js'\nimport { ProductService } from './product.js'\nimport { ProductDiscountService } from './product-discount.js'\nimport { ProductProjectionService } from './product-projection.js'\nimport { ProductTypeService } from './product-type.js'\nimport { ShippingMethodService } from './shipping-method.js'\nimport { ShoppingListService } from './shopping-list.js'\nimport { StandAlonePriceService } from './standalone-price.js'\nimport { StateService } from './state.js'\nimport { StoreService } from './store.js'\nimport { SubscriptionService } from './subscription.js'\nimport { TaxCategoryService } from './tax-category.js'\nimport { TypeService } from './type.js'\nimport { ZoneService } from './zone.js'\n\nexport const createServices = (router: any, repos: any) => ({\n category: new CategoryServices(router, repos['category']),\n cart: new CartService(router, repos['cart'], repos['order']),\n 'cart-discount': new CartDiscountService(router, repos['cart-discount']),\n customer: new CustomerService(router, repos['customer']),\n channel: new ChannelService(router, repos['channel']),\n 'customer-group': new CustomerGroupService(router, repos['customer-group']),\n 'discount-code': new DiscountCodeService(router, repos['discount-code']),\n extension: new ExtensionServices(router, repos['extension']),\n 'inventory-entry': new InventoryEntryService(\n router,\n repos['inventory-entry']\n ),\n 'key-value-document': new CustomObjectService(\n router,\n repos['key-value-document']\n ),\n order: new OrderService(router, repos['order']),\n payment: new PaymentService(router, repos['payment']),\n 'standalone-price': new StandAlonePriceService(router, repos['standalone-price']),\n 'my-cart': new MyCartService(router, repos['my-cart']),\n 'my-order': new MyOrderService(router, repos['my-order']),\n 'my-customer': new MyCustomerService(router, repos['my-customer']),\n 'my-payment': new MyPaymentService(router, repos['my-payment']),\n 'shipping-method': new ShippingMethodService(\n router,\n repos['shipping-method']\n ),\n 'product-type': new ProductTypeService(router, repos['product-type']),\n product: new ProductService(router, repos['product']),\n 'product-discount': new ProductDiscountService(\n router,\n repos['product-discount']\n ),\n 'product-projection': new ProductProjectionService(\n router,\n repos['product-projection']\n ),\n 'shopping-list': new ShoppingListService(router, repos['shopping-list']),\n state: new StateService(router, repos['state']),\n store: new StoreService(router, repos['store']),\n subscription: new SubscriptionService(router, repos['subscription']),\n 'tax-category': new TaxCategoryService(router, repos['tax-category']),\n type: new TypeService(router, repos['type']),\n zone: new ZoneService(router, repos['zone']),\n})\n"],"mappings":";AAAA,OAAO,UAAU;AACjB,OAAOA,cAAkD;AACzD,OAAO,eAAe;AACtB,OAAO,YAAY;;;ACmBZ,IAAe,kBAAf,MAA+B;AAuDtC;;;ACxCA,OAAO,YAAY;;;ACjCZ,IAAM,qBAAN,cAAsD,MAAM;AAAA,EACjE;AAAA,EACA;AAAA,EAEA,YAAY,MAAS,aAAa,KAAK;AACrC,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,aAAa,cAAc;AAAA,EAClC;AACF;;;ACZA,SAAS,MAAM,cAAc;AAEtB,IAAM,4BAA4B,OAAO;AAAA,EAC9C,IAAI,OAAO;AAAA,EACX,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,EAClC,iBAAgB,oBAAI,KAAK,GAAE,YAAY;AAAA,EACvC,SAAS;AACX;AAMO,IAAM,eAAe,CAAC,KAAU,SAAsB;AAC3D,MAAI,CAAC,QAAQ,SAAS,IAAI;AACxB,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,KAAK,MAAM,GAAG;AAC5B,MAAI,MAAM;AAEV,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,OAAO,MAAM,CAAC;AACpB,QAAI,OAAO,QAAW;AACpB,aAAO;AAAA,IACT;AAEA,UAAM,IAAI,IAAI;AAAA,EAChB;AAEA,SAAO;AACT;AAEO,IAAM,qBAAqB,CAChC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assert","assert","uuidv4","uuidv4","uuidv4","deepEqual","variant","uuidv4","generateMatchFunc","getLexer","deepEqual","deepEqual","uuidv4","uuidv4","uuidv4","uuidv4","Router","Router","Router","Router","Router","Router","express"]}
1
+ {"version":3,"sources":["../src/ctMock.ts","../src/storage/abstract.ts","../src/storage/in-memory.ts","../src/exceptions.ts","../src/helpers.ts","../src/lib/expandParser.ts","../src/lib/haversine.ts","../vendor/perplex/lexer-state.ts","../vendor/perplex/token.ts","../vendor/perplex/token-types.ts","../vendor/perplex/lexer.ts","../vendor/pratt/index.ts","../src/lib/predicateParser.ts","../src/oauth/server.ts","../src/oauth/store.ts","../src/oauth/helpers.ts","../src/projectAPI.ts","../src/lib/proxy.ts","../src/constants.ts","../src/repositories/helpers.ts","../src/services/project.ts","../src/repositories/abstract.ts","../src/repositories/errors.ts","../src/repositories/associate-role.ts","../src/repositories/attribute-group.ts","../src/repositories/business-unit.ts","../src/repositories/cart.ts","../src/repositories/cart-discount.ts","../src/repositories/category.ts","../src/repositories/channel.ts","../src/repositories/custom-object.ts","../src/repositories/customer.ts","../src/repositories/customer-group.ts","../src/repositories/discount-code.ts","../src/lib/masking.ts","../src/repositories/extension.ts","../src/repositories/inventory-entry.ts","../src/repositories/my-order.ts","../src/repositories/order.ts","../src/repositories/order-edit.ts","../src/repositories/payment.ts","../src/repositories/product.ts","../src/repositories/product-discount.ts","../src/lib/projectionSearchFilter.ts","../src/priceSelector.ts","../src/product-projection-search.ts","../src/repositories/product-projection.ts","../src/repositories/product-selection.ts","../src/repositories/product-type.ts","../src/repositories/project.ts","../src/repositories/quote.ts","../src/repositories/quote-request.ts","../src/repositories/review.ts","../src/repositories/shipping-method.ts","../src/repositories/shopping-list.ts","../src/repositories/staged-quote.ts","../src/repositories/standalone-price.ts","../src/repositories/state.ts","../src/repositories/store.ts","../src/repositories/subscription.ts","../src/repositories/tax-category.ts","../src/repositories/type.ts","../src/repositories/zone.ts","../src/repositories/index.ts","../src/services/abstract.ts","../src/services/cart.ts","../src/services/cart-discount.ts","../src/services/category.ts","../src/services/channel.ts","../src/services/custom-object.ts","../src/services/customer.ts","../src/services/customer-group.ts","../src/services/discount-code.ts","../src/services/extension.ts","../src/services/inventory-entry.ts","../src/services/my-cart.ts","../src/services/my-customer.ts","../src/services/my-order.ts","../src/services/my-payment.ts","../src/services/order.ts","../src/services/payment.ts","../src/services/product.ts","../src/services/product-discount.ts","../src/services/product-projection.ts","../src/services/product-type.ts","../src/services/shipping-method.ts","../src/services/shopping-list.ts","../src/services/standalone-price.ts","../src/services/state.ts","../src/services/store.ts","../src/services/subscription.ts","../src/services/tax-category.ts","../src/services/type.ts","../src/services/zone.ts","../src/services/attribute-group.ts","../src/services/index.ts"],"sourcesContent":["import nock from 'nock'\nimport express, { NextFunction, Request, Response } from 'express'\nimport supertest from 'supertest'\nimport morgan from 'morgan'\nimport { AbstractStorage, InMemoryStorage } from './storage/index.js'\nimport { Services } from './types.js'\nimport { CommercetoolsError } from './exceptions.js'\nimport { OAuth2Server } from './oauth/server.js'\nimport { ProjectAPI } from './projectAPI.js'\nimport { copyHeaders } from './lib/proxy.js'\nimport { DEFAULT_API_HOSTNAME, DEFAULT_AUTH_HOSTNAME } from './constants.js'\n\n// Services\nimport { ProjectService } from './services/project.js'\nimport { createRepositories, RepositoryMap } from './repositories/index.js'\nimport { createServices } from './services/index.js'\nimport { ProjectRepository } from './repositories/project.js'\n\nexport type CommercetoolsMockOptions = {\n\tvalidateCredentials: boolean\n\tenableAuthentication: boolean\n\tdefaultProjectKey: string | undefined\n\tapiHost: RegExp | string\n\tauthHost: RegExp | string\n\tsilent: boolean\n}\n\ntype AppOptions = { silent?: boolean }\n\nconst DEFAULT_OPTIONS: CommercetoolsMockOptions = {\n\tenableAuthentication: false,\n\tvalidateCredentials: false,\n\tdefaultProjectKey: undefined,\n\tapiHost: DEFAULT_API_HOSTNAME,\n\tauthHost: DEFAULT_AUTH_HOSTNAME,\n\tsilent: false,\n}\n\nexport class CommercetoolsMock {\n\tpublic app: express.Express\n\tpublic options: CommercetoolsMockOptions\n\n\tprivate _storage: AbstractStorage\n\tprivate _oauth2: OAuth2Server\n\tprivate _nockScopes: {\n\t\tauth: nock.Scope | undefined\n\t\tapi: nock.Scope | undefined\n\t} = { auth: undefined, api: undefined }\n\tprivate _services: Services | null\n\tprivate _repositories: RepositoryMap | null\n\tprivate _projectService?: ProjectService\n\n\tconstructor(options: Partial<CommercetoolsMockOptions> = {}) {\n\t\tthis.options = { ...DEFAULT_OPTIONS, ...options }\n\t\tthis._services = null\n\t\tthis._repositories = null\n\t\tthis._projectService = undefined\n\n\t\tthis._storage = new InMemoryStorage()\n\t\tthis._oauth2 = new OAuth2Server({\n\t\t\tenabled: this.options.enableAuthentication,\n\t\t\tvalidate: this.options.validateCredentials,\n\t\t})\n\n\t\tthis.app = this.createApp({ silent: this.options.silent })\n\t}\n\n\tstart() {\n\t\t// Order is important here when the hostnames match\n\t\tthis.mockAuthHost()\n\t\tthis.mockApiHost()\n\t}\n\n\tstop() {\n\t\tthis._nockScopes.auth?.persist(false)\n\t\tthis._nockScopes.auth = undefined\n\n\t\tthis._nockScopes.api?.persist(false)\n\t\tthis._nockScopes.api = undefined\n\t}\n\n\tclear() {\n\t\tthis._storage.clear()\n\t}\n\n\tproject(projectKey?: string) {\n\t\tif (!projectKey && !this.options.defaultProjectKey) {\n\t\t\tthrow new Error('No projectKey passed and no default set')\n\t\t}\n\n\t\tif (this._repositories === null) {\n\t\t\tthrow new Error('repositories not initialized yet')\n\t\t}\n\n\t\treturn new ProjectAPI(\n\t\t\tprojectKey || this.options.defaultProjectKey!,\n\t\t\tthis._repositories,\n\t\t\tthis._storage\n\t\t)\n\t}\n\n\trunServer(port = 3000, options?: AppOptions) {\n\t\tconst server = this.app.listen(port, () => {\n\t\t\tconsole.info(`Mock server listening at http://localhost:${port}`)\n\t\t})\n\t\tserver.keepAliveTimeout = 60 * 1000\n\t}\n\n\tprivate createApp(options?: AppOptions): express.Express {\n\t\tthis._repositories = createRepositories(this._storage)\n\n\t\tconst app = express()\n\n\t\tconst projectRouter = express.Router({ mergeParams: true })\n\t\tprojectRouter.use(express.json())\n\n\t\tif (!options?.silent) {\n\t\t\tapp.use(morgan('tiny'))\n\t\t}\n\t\tapp.use('/oauth', this._oauth2.createRouter())\n\n\t\t// Only enable auth middleware if we have enabled this\n\t\tif (this.options.enableAuthentication) {\n\t\t\tapp.use('/:projectKey', this._oauth2.createMiddleware(), projectRouter)\n\t\t\tapp.use(\n\t\t\t\t'/:projectKey/in-store/key=:storeKey',\n\t\t\t\tthis._oauth2.createMiddleware(),\n\t\t\t\tprojectRouter\n\t\t\t)\n\t\t} else {\n\t\t\tapp.use('/:projectKey', projectRouter)\n\t\t\tapp.use('/:projectKey/in-store/key=:storeKey', projectRouter)\n\t\t}\n\n\t\t// Register the rest api services in the router\n\t\tthis._services = createServices(projectRouter, this._repositories)\n\t\tthis._projectService = new ProjectService(\n\t\t\tprojectRouter,\n\t\t\tthis._repositories.project as ProjectRepository\n\t\t)\n\n\t\tapp.use((err: Error, req: Request, resp: Response, next: NextFunction) => {\n\t\t\tif (err instanceof CommercetoolsError) {\n\t\t\t\treturn resp.status(err.statusCode).send({\n\t\t\t\t\tstatusCode: err.statusCode,\n\t\t\t\t\tmessage: err.message,\n\t\t\t\t\terrors: [err.info],\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tconsole.error(err)\n\t\t\t\treturn resp.status(500).send({\n\t\t\t\t\terror: err.message,\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\n\t\treturn app\n\t}\n\n\tprivate mockApiHost() {\n\t\tconst app = this.app\n\n\t\tthis._nockScopes.api = nock(this.options.apiHost)\n\t\t\t.persist()\n\t\t\t.get(/.*/)\n\t\t\t.reply(async function (uri) {\n\t\t\t\tconst response = await supertest(app)\n\t\t\t\t\t.get(uri)\n\t\t\t\t\t.set(copyHeaders(this.req.headers))\n\t\t\t\treturn [response.status, response.body]\n\t\t\t})\n\t\t\t.post(/.*/)\n\t\t\t.reply(async function (uri, body) {\n\t\t\t\tconst response = await supertest(app)\n\t\t\t\t\t.post(uri)\n\t\t\t\t\t.set(copyHeaders(this.req.headers))\n\t\t\t\t\t.send(body)\n\t\t\t\treturn [response.status, response.body]\n\t\t\t})\n\t\t\t.delete(/.*/)\n\t\t\t.reply(async function (uri, body) {\n\t\t\t\tconst response = await supertest(app)\n\t\t\t\t\t.delete(uri)\n\t\t\t\t\t.set(copyHeaders(this.req.headers))\n\t\t\t\t\t.send(body)\n\t\t\t\treturn [response.status, response.body]\n\t\t\t})\n\t}\n\n\tprivate mockAuthHost() {\n\t\tconst app = this.app\n\n\t\tthis._nockScopes.auth = nock(this.options.authHost)\n\t\t\t.persist()\n\t\t\t.post(/^\\/oauth\\/.*/)\n\t\t\t.reply(async function (uri, body) {\n\t\t\t\tconst response = await supertest(app)\n\t\t\t\t\t.post(uri + '?' + body)\n\t\t\t\t\t.set(copyHeaders(this.req.headers))\n\t\t\t\t\t.send()\n\t\t\t\treturn [response.status, response.body]\n\t\t\t})\n\t}\n}\n","import type {\n\tBaseResource,\n\tProject,\n\tQueryParam,\n\tResourceIdentifier,\n} from '@commercetools/platform-sdk'\nimport { PagedQueryResponseMap, ResourceMap, ResourceType } from '../types.js'\n\nexport type GetParams = {\n\texpand?: string[]\n}\n\nexport type QueryParams = {\n\texpand?: string | string[]\n\tsort?: string | string[]\n\tlimit?: number\n\toffset?: number\n\twithTotal?: boolean\n\twhere?: string | string[]\n\t[key: string]: QueryParam\n}\n\nexport abstract class AbstractStorage {\n\tabstract clear(): void\n\n\tabstract all<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT\n\t): Array<ResourceMap[RT]>\n\n\tabstract add<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tobj: ResourceMap[RT]\n\t): void\n\n\tabstract get<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tid: string,\n\t\tparams?: GetParams\n\t): ResourceMap[RT] | null\n\n\tabstract getByKey<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tkey: string,\n\t\tparams: GetParams\n\t): ResourceMap[RT] | null\n\n\tabstract addProject(projectKey: string): Project\n\tabstract getProject(projectKey: string): Project\n\tabstract saveProject(project: Project): Project\n\n\tabstract delete<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tid: string,\n\t\tparams: GetParams\n\t): ResourceMap[RT] | null\n\n\tabstract query<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tparams: QueryParams\n\t): PagedQueryResponseMap[RT]\n\n\tabstract getByResourceIdentifier<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\tidentifier: ResourceIdentifier\n\t): ResourceMap[RT] | null\n\n\tabstract expand<T>(\n\t\tprojectKey: string,\n\t\tobj: T,\n\t\tclause: undefined | string | string[]\n\t): T\n}\n\nexport type ProjectStorage = {\n\t[index in ResourceType]: Map<string, BaseResource>\n}\n","import type {\n\tAssociateRole,\n\tAttributeGroup,\n\tBusinessUnit,\n\tCart,\n\tCartDiscount,\n\tCategory,\n\tChannel,\n\tCustomer,\n\tCustomerGroup,\n\tCustomObject,\n\tDiscountCode,\n\tExtension,\n\tInvalidInputError,\n\tInventoryEntry,\n\tOrder,\n\tPagedQueryResponse,\n\tPayment,\n\tProduct,\n\tProductDiscount,\n\tProductProjection,\n\tProductType,\n\tProject,\n\tQuote,\n\tQuoteRequest,\n\tReference,\n\tResourceIdentifier,\n\tShippingMethod,\n\tShoppingList,\n\tStagedQuote,\n\tState,\n\tStore,\n\tSubscription,\n\tTaxCategory,\n\tType,\n\tZone,\n} from '@commercetools/platform-sdk'\nimport assert from 'assert'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { cloneObject } from '../helpers.js'\nimport { parseExpandClause } from '../lib/expandParser.js'\nimport { parseQueryExpression } from '../lib/predicateParser.js'\nimport {\n\tPagedQueryResponseMap,\n\tResourceMap,\n\tResourceType,\n\tWritable,\n} from '../types.js'\nimport {\n\tAbstractStorage,\n\tGetParams,\n\tProjectStorage,\n\tQueryParams,\n} from './abstract.js'\n\nexport class InMemoryStorage extends AbstractStorage {\n\tprotected resources: {\n\t\t[projectKey: string]: ProjectStorage\n\t} = {}\n\n\tprotected projects: {\n\t\t[projectKey: string]: Project\n\t} = {}\n\n\tprivate forProjectKey(projectKey: string): ProjectStorage {\n\t\tthis.addProject(projectKey)\n\n\t\tlet projectStorage = this.resources[projectKey]\n\t\tif (!projectStorage) {\n\t\t\tprojectStorage = this.resources[projectKey] = {\n\t\t\t\t'associate-role': new Map<string, AssociateRole>(),\n\t\t\t\t'attribute-group': new Map<string, AttributeGroup>(),\n\t\t\t\t'business-unit': new Map<string, BusinessUnit>(),\n\t\t\t\tcart: new Map<string, Cart>(),\n\t\t\t\t'cart-discount': new Map<string, CartDiscount>(),\n\t\t\t\tcategory: new Map<string, Category>(),\n\t\t\t\tchannel: new Map<string, Channel>(),\n\t\t\t\tcustomer: new Map<string, Customer>(),\n\t\t\t\t'customer-group': new Map<string, CustomerGroup>(),\n\t\t\t\t'discount-code': new Map<string, DiscountCode>(),\n\t\t\t\textension: new Map<string, Extension>(),\n\t\t\t\t'inventory-entry': new Map<string, InventoryEntry>(),\n\t\t\t\t'key-value-document': new Map<string, CustomObject>(),\n\t\t\t\torder: new Map<string, Order>(),\n\t\t\t\t'order-edit': new Map<string, any>(),\n\t\t\t\tpayment: new Map<string, Payment>(),\n\t\t\t\tproduct: new Map<string, Product>(),\n\t\t\t\tquote: new Map<string, Quote>(),\n\t\t\t\t'quote-request': new Map<string, QuoteRequest>(),\n\t\t\t\t'product-discount': new Map<string, ProductDiscount>(),\n\t\t\t\t'product-selection': new Map<string, any>(),\n\t\t\t\t'product-type': new Map<string, ProductType>(),\n\t\t\t\t'product-projection': new Map<string, ProductProjection>(),\n\t\t\t\treview: new Map<string, any>(),\n\t\t\t\t'shipping-method': new Map<string, ShippingMethod>(),\n\t\t\t\t'staged-quote': new Map<string, StagedQuote>(),\n\t\t\t\tstate: new Map<string, State>(),\n\t\t\t\tstore: new Map<string, Store>(),\n\t\t\t\t'shopping-list': new Map<string, ShoppingList>(),\n\t\t\t\t'standalone-price': new Map<string, any>(),\n\t\t\t\tsubscription: new Map<string, Subscription>(),\n\t\t\t\t'tax-category': new Map<string, TaxCategory>(),\n\t\t\t\ttype: new Map<string, Type>(),\n\t\t\t\tzone: new Map<string, Zone>(),\n\t\t\t}\n\t\t}\n\t\treturn projectStorage\n\t}\n\n\tclear() {\n\t\tfor (const [, projectStorage] of Object.entries(this.resources)) {\n\t\t\tfor (const [, value] of Object.entries(projectStorage)) {\n\t\t\t\tvalue?.clear()\n\t\t\t}\n\t\t}\n\t}\n\n\tall<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT\n\t): ResourceMap[RT][] {\n\t\tconst store = this.forProjectKey(projectKey)[typeId]\n\t\tif (store) {\n\t\t\treturn Array.from(store.values()).map(cloneObject) as ResourceMap[RT][]\n\t\t}\n\t\treturn []\n\t}\n\n\tadd<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tobj: ResourceMap[RT],\n\t\tparams: GetParams = {}\n\t): ResourceMap[RT] {\n\t\tconst store = this.forProjectKey(projectKey)\n\t\tstore[typeId]?.set(obj.id, obj)\n\n\t\tconst resource = this.get(projectKey, typeId, obj.id, params)\n\t\tassert(resource, `resource of type ${typeId} with id ${obj.id} not created`)\n\t\treturn cloneObject(resource)\n\t}\n\n\tget<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tid: string,\n\t\tparams: GetParams = {}\n\t): ResourceMap[RT] | null {\n\t\tconst resource = this.forProjectKey(projectKey)[typeId]?.get(id)\n\t\tif (resource) {\n\t\t\tconst clone = cloneObject(resource)\n\t\t\treturn this.expand(projectKey, clone, params.expand) as ResourceMap[RT]\n\t\t}\n\t\treturn null\n\t}\n\n\tgetByKey<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tkey: string,\n\t\tparams: GetParams = {}\n\t): ResourceMap[RT] | null {\n\t\tconst store = this.forProjectKey(projectKey)\n\t\tconst resourceStore = store[typeId]\n\t\tif (!store) {\n\t\t\tthrow new Error('No type')\n\t\t}\n\n\t\tconst resources: any[] = Array.from(resourceStore.values())\n\t\tconst resource = resources.find((e) => e.key === key)\n\t\tif (resource) {\n\t\t\tconst clone = cloneObject(resource)\n\t\t\treturn this.expand(projectKey, clone, params.expand) as ResourceMap[RT]\n\t\t}\n\t\treturn null\n\t}\n\n\tdelete<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tid: string,\n\t\tparams: GetParams = {}\n\t): ResourceMap[RT] | null {\n\t\tconst resource = this.get(projectKey, typeId, id)\n\n\t\tif (resource) {\n\t\t\tthis.forProjectKey(projectKey)[typeId]?.delete(id)\n\t\t\treturn this.expand(projectKey, resource, params.expand)\n\t\t}\n\t\treturn resource\n\t}\n\n\tquery<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\ttypeId: RT,\n\t\tparams: QueryParams\n\t): PagedQueryResponseMap[RT] {\n\t\tconst store = this.forProjectKey(projectKey)[typeId]\n\t\tif (!store) {\n\t\t\tthrow new Error('No type')\n\t\t}\n\n\t\tlet resources = this.all<RT>(projectKey, typeId)\n\n\t\t// Apply predicates\n\t\tif (params.where) {\n\t\t\ttry {\n\t\t\t\tconst filterFunc = parseQueryExpression(params.where)\n\t\t\t\tresources = resources.filter((resource) => filterFunc(resource, {}))\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidInput',\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Get the total before slicing the array\n\t\tconst totalResources = resources.length\n\n\t\t// Apply offset, limit\n\t\tconst offset = params.offset || 0\n\t\tconst limit = params.limit || 20\n\t\tresources = resources.slice(offset, offset + limit)\n\n\t\t// Expand the resources\n\t\tif (params.expand !== undefined) {\n\t\t\tresources = resources.map((resource) =>\n\t\t\t\tthis.expand(projectKey, resource, params.expand)\n\t\t\t)\n\t\t}\n\n\t\treturn {\n\t\t\tcount: totalResources,\n\t\t\ttotal: resources.length,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\tresults: resources.map(cloneObject),\n\t\t} as PagedQueryResponseMap[RT]\n\t}\n\n\tsearch(\n\t\tprojectKey: string,\n\t\ttypeId: ResourceType,\n\t\tparams: QueryParams\n\t): PagedQueryResponse {\n\t\tlet resources = this.all(projectKey, typeId)\n\n\t\t// Apply predicates\n\t\tif (params.where) {\n\t\t\ttry {\n\t\t\t\tconst filterFunc = parseQueryExpression(params.where)\n\t\t\t\tresources = resources.filter((resource) => filterFunc(resource, {}))\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidInput',\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Get the total before slicing the array\n\t\tconst totalResources = resources.length\n\n\t\t// Apply offset, limit\n\t\tconst offset = params.offset || 0\n\t\tconst limit = params.limit || 20\n\t\tresources = resources.slice(offset, offset + limit)\n\n\t\t// Expand the resources\n\t\tif (params.expand !== undefined) {\n\t\t\tresources = resources.map((resource) =>\n\t\t\t\tthis.expand(projectKey, resource, params.expand)\n\t\t\t)\n\t\t}\n\n\t\treturn {\n\t\t\tcount: totalResources,\n\t\t\ttotal: resources.length,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\tresults: resources,\n\t\t}\n\t}\n\n\tgetByResourceIdentifier<RT extends ResourceType>(\n\t\tprojectKey: string,\n\t\tidentifier: ResourceIdentifier\n\t): ResourceMap[RT] | null {\n\t\tif (identifier.id) {\n\t\t\tconst resource = this.get(projectKey, identifier.typeId, identifier.id)\n\t\t\tif (resource) {\n\t\t\t\treturn resource as ResourceMap[RT]\n\t\t\t}\n\t\t\tconsole.error(\n\t\t\t\t`No resource found with typeId=${identifier.typeId}, id=${identifier.id}`\n\t\t\t)\n\t\t\treturn null\n\t\t}\n\n\t\tif (identifier.key) {\n\t\t\tconst store = this.forProjectKey(projectKey)[identifier.typeId]\n\n\t\t\tif (store) {\n\t\t\t\t// TODO: BaseResource has no key attribute, but the subclasses should\n\t\t\t\t// have them all.\n\t\t\t\tconst resource = Array.from(store.values()).find(\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t(r) => r.key === identifier.key\n\t\t\t\t)\n\t\t\t\tif (resource) {\n\t\t\t\t\treturn resource as ResourceMap[RT]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No storage found for resource type: ${identifier.typeId}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n\n\taddProject = (projectKey: string): Project => {\n\t\tif (!this.projects[projectKey]) {\n\t\t\tthis.projects[projectKey] = {\n\t\t\t\tkey: projectKey,\n\t\t\t\tname: '',\n\t\t\t\tcountries: [],\n\t\t\t\tcurrencies: [],\n\t\t\t\tlanguages: [],\n\t\t\t\tcreatedAt: '2018-10-04T11:32:12.603Z',\n\t\t\t\ttrialUntil: '2018-12',\n\t\t\t\tcarts: {\n\t\t\t\t\tcountryTaxRateFallbackEnabled: false,\n\t\t\t\t\tdeleteDaysAfterLastModification: 90,\n\t\t\t\t},\n\t\t\t\tmessages: { enabled: false, deleteDaysAfterCreation: 15 },\n\t\t\t\tshippingRateInputType: undefined,\n\t\t\t\texternalOAuth: undefined,\n\t\t\t\tsearchIndexing: {\n\t\t\t\t\tproducts: {\n\t\t\t\t\t\tstatus: 'Deactivated',\n\t\t\t\t\t},\n\t\t\t\t\torders: {\n\t\t\t\t\t\tstatus: 'Deactivated',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tversion: 1,\n\t\t\t}\n\t\t}\n\t\treturn this.projects[projectKey]\n\t}\n\n\tsaveProject = (project: Project): Project => {\n\t\tthis.projects[project.key] = project\n\t\treturn project\n\t}\n\n\tgetProject = (projectKey: string): Project => this.addProject(projectKey)\n\n\t// Expand resolves a nested reference and injects the object in the given obj\n\tpublic expand = <T>(\n\t\tprojectKey: string,\n\t\tobj: T,\n\t\tclause: undefined | string | string[]\n\t): T => {\n\t\tif (!clause) return obj\n\t\tconst newObj = cloneObject(obj)\n\t\tif (Array.isArray(clause)) {\n\t\t\tclause.forEach((c) => {\n\t\t\t\tthis._resolveResource(projectKey, newObj, c)\n\t\t\t})\n\t\t} else {\n\t\t\tthis._resolveResource(projectKey, newObj, clause)\n\t\t}\n\t\treturn newObj\n\t}\n\n\tprivate _resolveResource = (projectKey: string, obj: any, expand: string) => {\n\t\tconst params = parseExpandClause(expand)\n\n\t\tif (!params.index) {\n\t\t\tconst reference = obj[params.element]\n\t\t\tif (reference === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis._resolveReference(projectKey, reference, params.rest)\n\t\t} else if (params.index === '*') {\n\t\t\tconst reference = obj[params.element]\n\t\t\tif (reference === undefined || !Array.isArray(reference)) return\n\t\t\treference.forEach((itemRef: Writable<Reference>) => {\n\t\t\t\tthis._resolveReference(projectKey, itemRef, params.rest)\n\t\t\t})\n\t\t} else {\n\t\t\tconst reference = obj[params.element][params.index]\n\t\t\tif (reference === undefined) return\n\t\t\tthis._resolveReference(projectKey, reference, params.rest)\n\t\t}\n\t}\n\n\tprivate _resolveReference(\n\t\tprojectKey: string,\n\t\treference: any,\n\t\texpand: string | undefined\n\t) {\n\t\tif (reference === undefined) return\n\n\t\tif (\n\t\t\treference.typeId !== undefined &&\n\t\t\t(reference.id !== undefined || reference.key !== undefined)\n\t\t) {\n\t\t\t// @ts-ignore\n\t\t\treference.obj = this.getByResourceIdentifier(projectKey, {\n\t\t\t\ttypeId: reference.typeId,\n\t\t\t\tid: reference.id,\n\t\t\t\tkey: reference.key,\n\t\t\t} as ResourceIdentifier)\n\t\t\tif (expand) {\n\t\t\t\tthis._resolveResource(projectKey, reference.obj, expand)\n\t\t\t}\n\t\t} else {\n\t\t\tif (expand) {\n\t\t\t\tthis._resolveResource(projectKey, reference, expand)\n\t\t\t}\n\t\t}\n\t}\n}\n","export abstract class BaseError {\n\tabstract message: string\n}\n\nexport class CommercetoolsError<T extends BaseError> extends Error {\n\tinfo: T\n\tstatusCode: number\n\n\tconstructor(info: T, statusCode = 400) {\n\t\tsuper(info.message)\n\t\tthis.info = info\n\t\tthis.statusCode = statusCode || 500\n\t}\n}\n\nexport interface InvalidRequestError {\n\treadonly code: 'invalid_request'\n\treadonly message: string\n}\n","import { ParsedQs } from 'qs'\nimport { v4 as uuidv4 } from 'uuid'\n\nexport const getBaseResourceProperties = () => ({\n\tid: uuidv4(),\n\tcreatedAt: new Date().toISOString(),\n\tlastModifiedAt: new Date().toISOString(),\n\tversion: 0,\n})\n\n/**\n * Do a nested lookup by using a path. For example `foo.bar.value` will\n * return obj['foo']['bar']['value']\n */\nexport const nestedLookup = (obj: any, path: string): any => {\n\tif (!path || path === '') {\n\t\treturn obj\n\t}\n\n\tconst parts = path.split('.')\n\tlet val = obj\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i]\n\t\tif (val == undefined) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tval = val[part]\n\t}\n\n\treturn val\n}\n\nexport const QueryParamsAsArray = (\n\tinput: string | ParsedQs | string[] | ParsedQs[] | undefined\n): string[] => {\n\tif (input == undefined) {\n\t\treturn []\n\t}\n\n\tif (Array.isArray(input)) {\n\t\treturn input as string[]\n\t}\n\treturn [input] as string[]\n}\n\nexport const cloneObject = <T>(o: T): T => JSON.parse(JSON.stringify(o))\n","/**\n * This module implements the reference expansion as imeplemented by\n * commercetools.\n *\n * See https://docs.commercetools.com/api/general-concepts#reference-expansion\n *\n * TODO: implement support for multi-dimensional array\n */\ntype ExpandResult = {\n\telement: string\n\tindex?: string | number\n\trest?: string\n}\n\nexport const parseExpandClause = (clause: string): ExpandResult => {\n\tconst result: ExpandResult = {\n\t\telement: clause,\n\t\tindex: undefined,\n\t\trest: undefined,\n\t}\n\n\tconst pos = clause.indexOf('.')\n\tif (pos > 0) {\n\t\tresult.element = clause.substring(0, pos)\n\t\tresult.rest = clause.substring(pos + 1)\n\t}\n\n\tconst match = result.element.match(/\\[([^\\]+])]/)\n\tif (match) {\n\t\tresult.index = match[1] === '*' ? '*' : parseInt(match[1], 10)\n\t\tresult.element = result.element.substring(0, match.index)\n\t}\n\treturn result\n}\n","export type Location = {\n\tlatitude: number\n\tlongitude: number\n}\n\n/**\n * Returns the distance between src and dst as meters\n */\nexport const haversineDistance = (src: Location, dst: Location) => {\n\tconst RADIUS_OF_EARTH_IN_KM = 6371\n\tconst toRadian = (deg: number) => deg * (Math.PI / 180)\n\n\tconst dLat = toRadian(dst.latitude - src.latitude)\n\tconst dLon = toRadian(dst.longitude - src.longitude)\n\n\tconst a =\n\t\tMath.sin(dLat / 2) * Math.sin(dLat / 2) +\n\t\tMath.cos(toRadian(src.latitude)) *\n\t\t\tMath.cos(toRadian(dst.latitude)) *\n\t\t\tMath.sin(dLon / 2) *\n\t\t\tMath.sin(dLon / 2)\n\tconst c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))\n\treturn RADIUS_OF_EARTH_IN_KM * c * 1000\n}\n","import TokenTypes from './token-types'\n\n/**\n * @private\n */\nexport default class LexerState<T> {\n\tpublic source: string\n\tpublic position: number\n\tpublic tokenTypes: TokenTypes<T>\n\n\tconstructor(source: string, position: number = 0) {\n\t\tthis.source = source\n\t\tthis.position = position\n\t}\n\n\tcopy() {\n\t\treturn new LexerState<T>(this.source, this.position)\n\t}\n}\n","import Lexer from './lexer'\n\n/**\n * @typedef {{\n * start: Position,\n * end: Position,\n * }} TokenPosition\n */\n\n/**\n * Represents a token instance\n */\nclass Token<T> {\n\ttype: T\n\tmatch: string\n\tgroups: string[]\n\tstart: number\n\tend: number\n\tlexer: Lexer<T>\n\n\t/* tslint:disable:indent */\n\t/**\n\t * Constructs a token\n\t * @param {T} type The token type\n\t * @param {string} match The string that the lexer consumed to create this token\n\t * @param {string[]} groups Any RegExp groups that accrued during the match\n\t * @param {number} start The string position where this match started\n\t * @param {number} end The string position where this match ends\n\t * @param {Lexer<T>} lexer The parent {@link Lexer}\n\t */\n\tconstructor(\n\t\ttype: T,\n\t\tmatch: string,\n\t\tgroups: string[],\n\t\tstart: number,\n\t\tend: number,\n\t\tlexer: Lexer<T>\n\t) {\n\t\t/* tslint:enable */\n\t\t/**\n\t\t * The token type\n\t\t * @type {T}\n\t\t */\n\t\tthis.type = type\n\n\t\t/**\n\t\t * The string that the lexer consumed to create this token\n\t\t * @type {string}\n\t\t */\n\t\tthis.match = match\n\n\t\t/**\n\t\t * Any RegExp groups that accrued during the match\n\t\t * @type {string[]}\n\t\t */\n\t\tthis.groups = groups\n\n\t\t/**\n\t\t * The string position where this match started\n\t\t * @type {number}\n\t\t */\n\t\tthis.start = start\n\n\t\t/**\n\t\t * The string position where this match ends\n\t\t * @type {number}\n\t\t */\n\t\tthis.end = end\n\n\t\t/**\n\t\t * The parent {@link Lexer}\n\t\t * @type {Lexer<T>}\n\t\t */\n\t\tthis.lexer = lexer\n\t}\n\n\t/**\n\t * Returns the bounds of this token, each in `{line, column}` format\n\t * @return {TokenPosition}\n\t */\n\tstrpos() {\n\t\tconst start = this.lexer.strpos(this.start)\n\t\tconst end = this.lexer.strpos(this.end)\n\t\treturn { start, end }\n\t}\n\n\t// tslint:disable-next-line prefer-function-over-method\n\tisEof() {\n\t\treturn false\n\t}\n}\n\nexport default Token\n\nexport class EOFToken<T> extends Token<T> {\n\tconstructor(lexer: Lexer<T>) {\n\t\tconst end = lexer.source.length\n\t\tsuper(null, '(eof)', [], end, end, lexer)\n\t}\n\n\t// tslint:disable-next-line prefer-function-over-method\n\tisEof() {\n\t\treturn true\n\t}\n}\n\n/**\n * @private\n */\nexport const EOF = (lexer: Lexer<any>) => new EOFToken(lexer)\n","// Thank you, http://stackoverflow.com/a/6969486\nfunction toRegExp(str: string): RegExp {\n\treturn new RegExp(str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&'))\n}\n\nfunction normalize(regex: RegExp | string): RegExp {\n\tif (typeof regex === 'string') regex = toRegExp(regex)\n\tif (!regex.source.startsWith('^'))\n\t\treturn new RegExp(`^${regex.source}`, regex.flags)\n\telse return regex\n}\n\nfunction first<T, U>(\n\tarr: T[],\n\tpredicate: (item: T, i: number) => U\n): { item: T; result: U } {\n\tlet i = 0\n\tfor (const item of arr) {\n\t\tconst result = predicate(item, i++)\n\t\tif (result) return { item, result }\n\t}\n}\n\n/**\n * @private\n */\nexport default class TokenTypes<T> {\n\tpublic tokenTypes: {\n\t\ttype: T\n\t\tregex: RegExp\n\t\tenabled: boolean\n\t\tskip: boolean\n\t}[]\n\n\tconstructor() {\n\t\tthis.tokenTypes = []\n\t}\n\n\tdisable(type: T): TokenTypes<T> {\n\t\treturn this.enable(type, false)\n\t}\n\n\tenable(type: T, enabled: boolean = true): TokenTypes<T> {\n\t\tthis.tokenTypes\n\t\t\t.filter((t) => t.type == type)\n\t\t\t.forEach((t) => (t.enabled = enabled))\n\t\treturn this\n\t}\n\n\tisEnabled(type: T) {\n\t\tconst ttypes = this.tokenTypes.filter((tt) => tt.type == type)\n\t\tif (ttypes.length == 0)\n\t\t\tthrow new Error(`Token of type ${type} does not exists`)\n\t\treturn ttypes[0].enabled\n\t}\n\n\tpeek(source: string, position: number) {\n\t\tconst s = source.substr(position)\n\t\treturn first(\n\t\t\tthis.tokenTypes.filter((tt) => tt.enabled),\n\t\t\t(tt) => {\n\t\t\t\ttt.regex.lastIndex = 0\n\t\t\t\treturn tt.regex.exec(s)\n\t\t\t}\n\t\t)\n\t}\n\n\ttoken(\n\t\ttype: T,\n\t\tpattern: RegExp | string,\n\t\tskip: boolean = false\n\t): TokenTypes<T> {\n\t\tthis.tokenTypes.push({\n\t\t\ttype,\n\t\t\tregex: normalize(pattern),\n\t\t\tenabled: true,\n\t\t\tskip,\n\t\t})\n\t\treturn this\n\t}\n}\n","import LexerState from './lexer-state'\nimport Token, { EOF } from './token'\nimport TokenTypes from './token-types'\n\n/**\n * @typedef {{\n * line: number,\n * column: number,\n * }} Position\n */\n\n/**\n * Lexes a source-string into tokens.\n *\n * @example\n * const lex = perplex('...')\n * .token('ID', /my-id-regex/)\n * .token('(', /\\(/)\n * .token(')', /\\)/)\n * .token('WS', /\\s+/, true) // true means 'skip'\n *\n * while ((let t = lex.next()).type != 'EOF') {\n * console.log(t)\n * }\n * // alternatively:\n * console.log(lex.toArray())\n * // or:\n * console.log(...lex)\n */\nclass Lexer<T> implements Iterable<Token<T>> {\n\t/* tslint:disable:variable-name */\n\tprivate _state: LexerState<T>\n\tprivate _tokenTypes: TokenTypes<T>\n\t/* tslint:enable */\n\n\t/**\n\t * Creates a new Lexer instance\n\t * @param {string} [source = ''] The source string to operate on.\n\t */\n\tconstructor(source: string = '') {\n\t\tthis._state = new LexerState<T>(source)\n\t\tthis._tokenTypes = new TokenTypes<T>()\n\t}\n\n\t//\n\t// Getters/Setters\n\t//\n\n\t/**\n\t * Gets the current lexer position\n\t * @return {number} Returns the position\n\t */\n\tget position() {\n\t\treturn this._state.position\n\t}\n\n\t/**\n\t * Sets the current lexer position\n\t * @param {number} i The position to move to\n\t */\n\tset position(i: number) {\n\t\tthis._state.position = i\n\t}\n\n\t/**\n\t * Gets the source the lexer is operating on\n\t * @return {string} Returns the source\n\t */\n\tget source() {\n\t\treturn this._state.source\n\t}\n\n\t/**\n\t * Sets the source the lexer is operating on\n\t * @param {string} s The source to set\n\t */\n\tset source(s: string) {\n\t\tthis._state = new LexerState<T>(s)\n\t}\n\n\t//\n\t// METHODS\n\t//\n\n\t/**\n\t * Attaches this lexer to another lexer's state\n\t * @param {Lexer<T>} other The other lexer to attach to\n\t */\n\tattachTo(other: Lexer<T>) {\n\t\tthis._state = other._state\n\t}\n\n\t/**\n\t * Disables a token type\n\t * @param {T} type The token type to disable\n\t * @return {Lexer<T>}\n\t */\n\tdisable(type: T) {\n\t\tthis._tokenTypes.disable(type)\n\t\treturn this\n\t}\n\n\t/**\n\t * Enables a token type\n\t * @param {T} type The token type to enalbe\n\t * @param {?boolean} [enabled=true] Whether to enable/disable the specified token type\n\t * @return {Lexer<T>}\n\t */\n\tenable(type: T, enabled?: boolean) {\n\t\tthis._tokenTypes.enable(type, enabled)\n\t\treturn this\n\t}\n\n\t/**\n\t * Like {@link next}, but throws an exception if the next token is\n\t * not of the required type.\n\t * @param {T} type The token type expected from {@link next}\n\t * @return {Token<T>} Returns the {@link Token} on success\n\t */\n\texpect(type: T): Token<T> {\n\t\tconst t = this.next()\n\t\tif (t.type != type) {\n\t\t\tconst pos = t.strpos()\n\t\t\tthrow new Error(\n\t\t\t\t'Expected ' +\n\t\t\t\t\ttype +\n\t\t\t\t\t(t ? ', got ' + t.type : '') +\n\t\t\t\t\t' at ' +\n\t\t\t\t\tpos.start.line +\n\t\t\t\t\t':' +\n\t\t\t\t\tpos.start.column\n\t\t\t)\n\t\t}\n\t\treturn t\n\t}\n\n\t/**\n\t * Looks up whether a token is enabled.\n\t * @param tokenType The token type to look up\n\t * @return {boolean} Returns whether the token is enabled\n\t */\n\tisEnabled(tokenType: T) {\n\t\treturn this._tokenTypes.isEnabled(tokenType)\n\t}\n\n\t/**\n\t * Consumes and returns the next {@link Token} in the source string.\n\t * If there are no more tokens, it returns a {@link Token} of type `$EOF`\n\t * @return {Token<T>}\n\t */\n\tnext(): Token<T> {\n\t\ttry {\n\t\t\tconst t = this.peek()\n\t\t\tthis._state.position = t.end\n\t\t\treturn t\n\t\t} catch (e) {\n\t\t\tthis._state.position = e.end\n\t\t\tthrow e\n\t\t}\n\t}\n\n\t/**\n\t * Returns the next {@link Token} in the source string, but does\n\t * not consume it.\n\t * If there are no more tokens, it returns a {@link Token} of type `$EOF`\n\t * @param {number} [position=`this.position`] The position at which to start reading\n\t * @return {Token<T>}\n\t */\n\tpeek(position: number = this._state.position): Token<T> {\n\t\tconst read = (i: number = position) => {\n\t\t\tif (i >= this._state.source.length) return EOF(this)\n\t\t\tconst n = this._tokenTypes.peek(this._state.source, i)\n\t\t\treturn n\n\t\t\t\t? n.item.skip\n\t\t\t\t\t? read(i + n.result[0].length)\n\t\t\t\t\t: new Token(\n\t\t\t\t\t\t\tn.item.type,\n\t\t\t\t\t\t\tn.result[0],\n\t\t\t\t\t\t\tn.result.map((x) => x),\n\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t\ti + n.result[0].length,\n\t\t\t\t\t\t\tthis\n\t\t\t\t\t )\n\t\t\t\t: null\n\t\t}\n\t\tconst t = read()\n\t\tif (t) return t\n\n\t\t// we did not find a match\n\t\tlet unexpected = this._state.source.substring(position, position + 1)\n\t\ttry {\n\t\t\tthis.peek(position + 1)\n\t\t} catch (e) {\n\t\t\tunexpected += e.unexpected\n\t\t}\n\t\tconst { line, column } = this.strpos(position)\n\t\tconst e = new Error(\n\t\t\t`Unexpected input: ${unexpected} at (${line}:${column})`\n\t\t)\n\t\t;(e as any).unexpected = unexpected\n\t\t;(e as any).end = position + unexpected.length\n\t\tthrow e\n\t}\n\n\t/**\n\t * Converts a string-index (relative to the source string) to a line and a column.\n\t * @param {number} i The index to compute\n\t * @return {Position}\n\t */\n\tstrpos(i: number): {\n\t\tline: number\n\t\tcolumn: number\n\t} {\n\t\tlet lines = this._state.source.substring(0, i).split(/\\r?\\n/)\n\t\tif (!Array.isArray(lines)) lines = [lines]\n\n\t\tconst line = lines.length\n\t\tconst column = lines[lines.length - 1].length + 1\n\t\treturn { line, column }\n\t}\n\n\t/**\n\t * Converts the token stream to an array of Tokens\n\t * @return {Token<T>[]} The array of tokens (not including (EOF))\n\t */\n\ttoArray(): Token<T>[] {\n\t\treturn [...this]\n\t}\n\n\t/**\n\t * Implements the Iterable protocol\n\t * Iterates lazily over the entire token stream (not including (EOF))\n\t * @return {Iterator<Token<T>>} Returns an iterator over all remaining tokens\n\t */\n\t*[Symbol.iterator]() {\n\t\tconst oldState = this._state.copy()\n\t\tthis._state.position = 0\n\n\t\tlet t\n\t\twhile (\n\t\t\t!(t = this.next()).isEof() // tslint:disable-line no-conditional-assignment\n\t\t)\n\t\t\tyield t\n\n\t\tthis._state = oldState\n\t}\n\n\t/**\n\t * Creates a new token type\n\t * @param {T} type The token type\n\t * @param {string|RegExp} pattern The pattern to match\n\t * @param {?boolean} skip Whether this type of token should be skipped\n\t * @return {Lexer<T>}\n\t */\n\ttoken(type: T, pattern: string | RegExp, skip?: boolean) {\n\t\tthis._tokenTypes.token(type, pattern, skip)\n\t\treturn this\n\t}\n\n\t/**\n\t * Creates a keyword\n\t * @param kwd The keyword to add as a token\n\t */\n\tkeyword(kwd: T) {\n\t\treturn this.token(kwd, new RegExp(`${kwd}(?=\\\\W|$)`))\n\t}\n\n\t/**\n\t * Creates an operator\n\t * @param op The operator to add as a token\n\t */\n\toperator(op: T) {\n\t\tconst sOp = new String(op).valueOf()\n\t\treturn this.token(op, sOp)\n\t}\n}\n\nexport default Lexer\nexport { EOF, Token, TokenTypes, LexerState, Lexer }\n","// From https://github.com/jrop/pratt/blob/master/src/index.ts\n\nexport interface IPosition {\n\tline: number\n\tcolumn: number\n}\nexport interface ITokenPosition {\n\tstart: IPosition\n\tend: IPosition\n}\nexport interface IToken<T> {\n\ttype: T\n\tmatch: string\n\tstrpos(): ITokenPosition\n\tisEof(): boolean\n}\nexport interface ILexer<T> {\n\tnext(): IToken<T>\n\tpeek(): IToken<T>\n}\n\nexport type BPResolver = () => number\nexport type BP = number | BPResolver\n\nexport type StopFunction = (<T>(x: T) => T) & { isStopped(): boolean }\n\nexport type NudInfo<T> = {\n\ttoken: IToken<T>\n\tbp: number\n\tstop: StopFunction\n\n\t// TODO: with the below addition of `options`\n\t// the `ctx parameter is carried through anyway\n\t// remove in a breaking API change release\n\tctx: any\n\toptions: ParseOpts<T>\n}\nexport type LedInfo<T> = NudInfo<T> & { left: any }\n\nexport type NudFunction<T> = (inf: NudInfo<T>) => any\nexport type LedFunction<T> = (inf: LedInfo<T>) => any\n\nexport type NudMap<T> = Map<T, NudFunction<T>>\nexport type LedMap<T> = Map<T, LedFunction<T>>\n\nexport type ParseOpts<T> = {\n\tctx?: any\n\tstop?: StopFunction\n\tterminals?: (number | T)[]\n}\n\nconst createStop = <T>(): StopFunction => {\n\tlet stopCalled = false\n\treturn Object.assign(\n\t\t(x: T) => {\n\t\t\tstopCalled = true\n\t\t\treturn x\n\t\t},\n\t\t{\n\t\t\tisStopped() {\n\t\t\t\treturn stopCalled\n\t\t\t},\n\t\t}\n\t) as StopFunction\n}\n\n/**\n * A Pratt parser.\n * @example\n * const lex = new perplex.Lexer('1 + -2 * 3^4')\n * .token('NUM', /\\d+/)\n * .token('+', /\\+/)\n * .token('-', /-/)\n * .token('*', new RegExp('*'))\n * .token('/', /\\//)\n * .token('^', /\\^/)\n * .token('(', /\\(/)\n * .token(')', /\\)/)\n * .token('$SKIP_WS', /\\s+/)\n *\n * const parser = new Parser(lex)\n * .builder()\n * .nud('NUM', 100, t => parseInt(t.match))\n * .nud('-', 10, (t, bp) => -parser.parse(bp))\n * .nud('(', 10, (t, bp) => {\n * const expr = parser.parse(bp)\n * lex.expect(')')\n * return expr\n * })\n * .bp(')', 0)\n *\n * .led('^', 20, (left, t, bp) => Math.pow(left, parser.parse(20 - 1)))\n * .led('+', 30, (left, t, bp) => left + parser.parse(bp))\n * .led('-', 30, (left, t, bp) => left - parser.parse(bp))\n * .led('*', 40, (left, t, bp) => left * parser.parse(bp))\n * .led('/', 40, (left, t, bp) => left / parser.parse(bp))\n * .build()\n * parser.parse()\n * // => 161\n */\nexport class Parser<T> {\n\tpublic lexer: ILexer<T>\n\t_nuds: NudMap<T>\n\t_leds: LedMap<T>\n\t_bps: Map<T, BP>\n\n\t/**\n\t * Constructs a Parser instance\n\t * @param {ILexer<T>} lexer The lexer to obtain tokens from\n\t */\n\tconstructor(lexer: ILexer<T>) {\n\t\t/**\n\t\t * The lexer that this parser is operating on.\n\t\t * @type {ILexer<T>}\n\t\t */\n\t\tthis.lexer = lexer\n\t\tthis._nuds = new Map()\n\t\tthis._leds = new Map()\n\t\tthis._bps = new Map()\n\t}\n\n\tprivate _type(tokenOrType: IToken<T> | T): T {\n\t\treturn tokenOrType && typeof (tokenOrType as IToken<T>).isEof == 'function'\n\t\t\t? (tokenOrType as IToken<T>).type\n\t\t\t: (tokenOrType as T)\n\t}\n\n\t/**\n\t * Create a {@link ParserBuilder}\n\t * @return {ParserBuilder<T>} Returns the ParserBuilder\n\t */\n\tbuilder(): ParserBuilder<T> {\n\t\treturn new ParserBuilder(this)\n\t}\n\n\t/**\n\t * Define binding power for a token-type\n\t * @param {IToken<T>|T} tokenOrType The token type to define the binding power for\n\t * @returns {number} The binding power of the specified token type\n\t */\n\tbp(tokenOrType: IToken<T> | T) {\n\t\tif (tokenOrType == null) return Number.NEGATIVE_INFINITY\n\t\tif (\n\t\t\ttokenOrType &&\n\t\t\ttypeof (tokenOrType as IToken<T>).isEof == 'function' &&\n\t\t\t(tokenOrType as IToken<T>).isEof()\n\t\t)\n\t\t\treturn Number.NEGATIVE_INFINITY\n\t\tconst type = this._type(tokenOrType)\n\t\tconst bp = this._bps.has(type)\n\t\t\t? this._bps.get(type)\n\t\t\t: Number.POSITIVE_INFINITY\n\t\treturn typeof bp == 'function' ? bp() : bp\n\t}\n\n\t/**\n\t * Computes the token's `nud` value and returns it\n\t * @param {NudInfo<T>} info The info to compute the `nud` from\n\t * @returns {any} The result of invoking the pertinent `nud` operator\n\t */\n\tnud(info: NudInfo<T>) {\n\t\tconst fn: NudFunction<T> | undefined = this._nuds.get(info.token.type)\n\t\tif (!fn) {\n\t\t\tconst { start } = info.token.strpos()\n\t\t\tthrow new Error(\n\t\t\t\t`Unexpected token: ${info.token.match} (at ${start.line}:${start.column})`\n\t\t\t)\n\t\t}\n\t\treturn fn(info)\n\t}\n\n\t/**\n\t * Computes a token's `led` value and returns it\n\t * @param {LedInfo<T>} info The info to compute the `led` value for\n\t * @returns {any} The result of invoking the pertinent `led` operator\n\t */\n\tled(info: LedInfo<T>) {\n\t\tlet fn = this._leds.get(info.token.type)\n\t\tif (!fn) {\n\t\t\tconst { start } = info.token.strpos()\n\t\t\tthrow new Error(\n\t\t\t\t`Unexpected token: ${info.token.match} (at ${start.line}:${start.column})`\n\t\t\t)\n\t\t}\n\t\treturn fn(info)\n\t}\n\n\t/**\n\t * Kicks off the Pratt parser, and returns the result\n\t * @param {ParseOpts<T>} opts The parse options\n\t * @returns {any}\n\t */\n\tparse(opts: ParseOpts<T> = { terminals: [0] }): any {\n\t\tconst stop = (opts.stop = opts.stop || createStop())\n\t\tconst check = () => {\n\t\t\tif (stop.isStopped()) return false\n\t\t\tconst t = this.lexer.peek()\n\t\t\tconst bp = this.bp(t)\n\n\t\t\t// @ts-ignore\n\t\t\treturn opts.terminals.reduce((canContinue, rbpOrType) => {\n\t\t\t\tif (!canContinue) return false\n\t\t\t\t// @ts-ignore\n\t\t\t\tif (typeof rbpOrType == 'number') return rbpOrType < bp\n\t\t\t\tif (typeof rbpOrType == 'string') return t.type != rbpOrType\n\t\t\t}, true)\n\t\t}\n\t\tconst mkinfo = (token: IToken<T>): NudInfo<T> => {\n\t\t\tconst bp = this.bp(token)\n\t\t\t// @ts-ignore\n\t\t\treturn { token, bp, stop, ctx: opts.ctx, options: opts }\n\t\t}\n\t\tif (!opts.terminals) opts.terminals = [0]\n\t\tif (opts.terminals.length == 0) opts.terminals.push(0)\n\n\t\tlet left = this.nud(mkinfo(this.lexer.next()))\n\t\twhile (check()) {\n\t\t\tconst operator = this.lexer.next()\n\t\t\tleft = this.led(Object.assign(mkinfo(operator), { left }))\n\t\t}\n\t\treturn left\n\t}\n}\n\n/**\n * Builds `led`/`nud` rules for a {@link Parser}\n */\nexport class ParserBuilder<T> {\n\tprivate _parser: Parser<T>\n\n\t/**\n\t * Constructs a ParserBuilder\n\t * See also: {@link Parser.builder}\n\t * @param {Parser<T>} parser The parser\n\t */\n\tconstructor(parser: Parser<T>) {\n\t\tthis._parser = parser\n\t}\n\n\t/**\n\t * Define `nud` for a token type\n\t * @param {T} tokenType The token type\n\t * @param {number} bp The binding power\n\t * @param {NudFunction<T>} fn The function that will parse the token\n\t * @return {ParserBuilder<T>} Returns this ParserBuilder\n\t */\n\tnud(tokenType: T, bp: BP, fn: NudFunction<T>): ParserBuilder<T> {\n\t\tthis._parser._nuds.set(tokenType, fn)\n\t\tthis.bp(tokenType, bp)\n\t\treturn this\n\t}\n\n\t/**\n\t * Define `led` for a token type\n\t * @param {T} tokenType The token type\n\t * @param {number} bp The binding power\n\t * @param {LedFunction<T>} fn The function that will parse the token\n\t * @return {ParserBuilder<T>} Returns this ParserBuilder\n\t */\n\tled(tokenType: T, bp: BP, fn: LedFunction<T>): ParserBuilder<T> {\n\t\tthis._parser._leds.set(tokenType, fn)\n\t\tthis.bp(tokenType, bp)\n\t\treturn this\n\t}\n\n\t/**\n\t * Define both `led` and `nud` for a token type at once.\n\t * The supplied `LedFunction` may be called with a null `left`\n\t * parameter when invoked from a `nud` context.\n\t * @param {strTng} tokenType The token type\n\t * @param {number} bp The binding power\n\t * @param {LedFunction<T>} fn The function that will parse the token\n\t * @return {ParserBuilder<T>} Returns this ParserBuilder\n\t */\n\teither(tokenType: T, bp: BP, fn: LedFunction<T>): ParserBuilder<T> {\n\t\treturn this.nud(tokenType, bp, (inf) =>\n\t\t\tfn(Object.assign(inf, { left: null }))\n\t\t).led(tokenType, bp, fn)\n\t}\n\n\t/**\n\t * Define the binding power for a token type\n\t * @param {T} tokenType The token type\n\t * @param {BP} bp The binding power\n\t * @return {ParserBuilder<T>} Returns this ParserBuilder\n\t */\n\tbp(tokenType: T, bp: BP): ParserBuilder<T> {\n\t\tthis._parser._bps.set(tokenType, bp)\n\t\treturn this\n\t}\n\n\t/**\n\t * Returns the parent {@link Parser} instance\n\t * @returns {Parser<T>}\n\t */\n\tbuild(): Parser<T> {\n\t\treturn this._parser\n\t}\n}\n","/**\n * This module implements the commercetools query predicate filter expression.\n * Support should be 100% complete.\n *\n * See https://docs.commercetools.com/api/predicates/query\n */\nimport { haversineDistance } from './haversine.js'\nimport { Lexer, Parser, type ITokenPosition } from './parser.js'\n\nexport class PredicateError {\n\tmessage: string\n\n\tconstructor(message: string) {\n\t\tthis.message = message\n\t}\n}\n\ntype MatchFunc = (target: any, variables: VariableMap) => boolean\ntype VariableMap = {\n\t[key: string]: any\n}\n\nexport const matchesPredicate = (\n\tpredicate: string | string[] | undefined,\n\ttarget: any,\n\tvariables?: VariableMap\n): boolean => {\n\tif (!predicate) {\n\t\treturn true\n\t}\n\n\tif (Array.isArray(predicate)) {\n\t\treturn predicate.every((item) => {\n\t\t\tconst func = generateMatchFunc(item)\n\t\t\treturn func(target, variables ?? {})\n\t\t})\n\t} else {\n\t\tconst func = generateMatchFunc(predicate)\n\t\treturn func(target, variables ?? {})\n\t}\n}\n\nexport const parseQueryExpression = (\n\tpredicate: string | string[]\n): MatchFunc => {\n\tif (Array.isArray(predicate)) {\n\t\tconst callbacks = predicate.map((item) => generateMatchFunc(item))\n\t\treturn (target: any, variables: VariableMap) =>\n\t\t\tcallbacks.every((callback) => callback(target, variables))\n\t} else {\n\t\treturn generateMatchFunc(predicate)\n\t}\n}\n\ntype TypeSymbol = {\n\ttype: 'var' | 'boolean' | 'string' | 'float' | 'int' | 'identifier'\n\tvalue: any\n\tpos?: ITokenPosition\n}\n\nconst validateSymbol = (val: TypeSymbol) => {\n\tif (!val.type) {\n\t\tthrow new PredicateError('Internal error')\n\t}\n\n\tif (val.type === 'identifier') {\n\t\tconst char = val.value.charAt(0)\n\t\tconst line = val.pos?.start.line\n\t\tconst column = val.pos?.start.column\n\n\t\tthrow new PredicateError(\n\t\t\t`Invalid input '${char}', expected input parameter or primitive value (line ${line}, column ${column})`\n\t\t)\n\t}\n}\n\nconst resolveSymbol = (val: TypeSymbol, vars: VariableMap): any => {\n\tif (val.type === 'var') {\n\t\tif (!(val.value in (vars ?? {}))) {\n\t\t\tthrow new PredicateError(`Missing parameter value for ${val.value}`)\n\t\t}\n\t\treturn vars[val.value]\n\t}\n\n\treturn val.value\n}\n\nconst resolveValue = (obj: any, val: TypeSymbol): any => {\n\tif (val.type !== 'identifier') {\n\t\tthrow new PredicateError('Internal error')\n\t}\n\n\tif (!(val.value in obj)) {\n\t\tif (Array.isArray(obj)) {\n\t\t\treturn Object.values(obj)\n\t\t\t\t.filter((v) => val.value in v)\n\t\t\t\t.map((v) => v[val.value])\n\t\t}\n\t\tthrow new PredicateError(`The field '${val.value}' does not exist.`)\n\t}\n\n\treturn obj[val.value]\n}\n\nconst getLexer = (value: string) =>\n\tnew Lexer(value)\n\n\t\t.token('AND', /and(?![-_a-z0-9]+)/i)\n\t\t.token('OR', /or(?![-_a-z0-9]+)/i)\n\t\t.token('NOT', /not(?![-_a-z0-9]+)/i)\n\n\t\t.token('WITHIN', /within(?![-_a-z0-9]+)/i)\n\t\t.token('IN', /in(?![-_a-z0-9]+)/i)\n\t\t.token('MATCHES_IGNORE_CASE', /matches\\s+ignore\\s+case(?![-_a-z0-9]+)/i)\n\t\t.token('CONTAINS', /contains(?![-_a-z0-9]+)/i)\n\t\t.token('ALL', /all(?![-_a-z0-9]+)/i)\n\t\t.token('ANY', /any(?![-_a-z0-9]+)/i)\n\t\t.token('EMPTY', /empty(?![-_a-z0-9]+)/i)\n\t\t.token('IS', /is(?![-_a-z0-9]+)/i)\n\t\t.token('DEFINED', /defined(?![-_a-z0-9]+)/i)\n\n\t\t.token('FLOAT', /\\d+\\.\\d+/)\n\t\t.token('INT', /\\d+/)\n\t\t.token('VARIABLE', /:([-_A-Za-z0-9]+)/)\n\t\t.token('BOOLEAN', /(true|false)/)\n\t\t.token('IDENTIFIER', /[-_A-Za-z0-9]+/)\n\t\t.token('STRING', /\"((?:\\\\.|[^\"\\\\])*)\"/)\n\t\t.token('STRING', /'((?:\\\\.|[^'\\\\])*)'/)\n\n\t\t.token('COMMA', ',')\n\t\t.token('(', '(')\n\t\t.token(')', ')')\n\t\t.token('>=', '>=')\n\t\t.token('<=', '<=')\n\t\t.token('>', '>')\n\t\t.token('<', '<')\n\t\t.token('!=', '!=')\n\t\t.token('=', '=')\n\t\t.token('\"', '\"')\n\t\t.token('WS', /\\s+/, true) // skip\n\n/**\n * This function converts a query expression in to a callable which returns a\n * boolean to indicate if the given object matches or not.\n *\n * This currently parses the predicate each time it is called, but it should be\n * straight-forward to add a query cache (lru-cache)\n */\nconst generateMatchFunc = (predicate: string): MatchFunc => {\n\tconst lexer = getLexer(predicate)\n\tconst parser = new Parser(lexer)\n\t\t.builder()\n\t\t.nud(\n\t\t\t'IDENTIFIER',\n\t\t\t100,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'identifier',\n\t\t\t\t\tvalue: t.token.match,\n\t\t\t\t\tpos: t.token.strpos(),\n\t\t\t\t}) as TypeSymbol\n\t\t)\n\t\t.nud(\n\t\t\t'BOOLEAN',\n\t\t\t1,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'boolean',\n\t\t\t\t\tvalue: t.token.match === 'true' ? true : false,\n\t\t\t\t\tpos: t.token.strpos(),\n\t\t\t\t}) as TypeSymbol\n\t\t)\n\t\t.nud(\n\t\t\t'VARIABLE',\n\t\t\t100,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'var',\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tvalue: t.token.groups[1],\n\t\t\t\t\tpos: t.token.strpos(),\n\t\t\t\t}) as TypeSymbol\n\t\t)\n\t\t.nud(\n\t\t\t'STRING',\n\t\t\t100,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tvalue: t.token.groups[1],\n\t\t\t\t\tpos: t.token.strpos(),\n\t\t\t\t}) as TypeSymbol\n\t\t)\n\t\t.nud(\n\t\t\t'INT',\n\t\t\t1,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'int',\n\t\t\t\t\tvalue: parseInt(t.token.match, 10),\n\t\t\t\t\tpos: t.token.strpos(),\n\t\t\t\t}) as TypeSymbol\n\t\t)\n\t\t.nud(\n\t\t\t'FLOAT',\n\t\t\t1,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'float',\n\t\t\t\t\tvalue: parseFloat(t.token.match),\n\t\t\t\t\tpos: t.token.strpos(),\n\t\t\t\t}) as TypeSymbol\n\t\t)\n\t\t.nud('NOT', 100, ({ bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\treturn (obj: any) => !expr(obj)\n\t\t})\n\t\t.nud('EMPTY', 10, ({ bp }) => 'empty')\n\t\t.nud('DEFINED', 10, ({ bp }) => 'defined')\n\n\t\t.led('AND', 5, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\treturn (obj: any) => left(obj) && expr(obj)\n\t\t})\n\t\t.led('OR', 5, ({ left, token, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\treturn (obj: any, vars: object) => left(obj, vars) || expr(obj, vars)\n\t\t})\n\t\t.led('COMMA', 1, ({ left, token, bp }) => {\n\t\t\tconst expr: any = parser.parse({ terminals: [bp - 1] })\n\t\t\tif (Array.isArray(expr)) {\n\t\t\t\treturn [left, ...expr]\n\t\t\t} else {\n\t\t\t\treturn [left, expr]\n\t\t\t}\n\t\t})\n\t\t.nud('(', 100, (t) => {\n\t\t\tconst expr: any = parser.parse({ terminals: [')'] })\n\t\t\treturn expr\n\t\t})\n\t\t.led('(', 100, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse()\n\t\t\tlexer.expect(')')\n\t\t\treturn (obj: any, vars: object) => {\n\t\t\t\tconst value = resolveValue(obj, left)\n\t\t\t\tif (value) {\n\t\t\t\t\treturn expr(value, vars)\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t})\n\t\t.bp(')', 0)\n\t\t.led('=', 20, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\tvalidateSymbol(expr)\n\n\t\t\treturn (obj: any, vars: VariableMap) => {\n\t\t\t\tconst resolvedValue = resolveValue(obj, left)\n\t\t\t\tconst resolvedSymbol = resolveSymbol(expr, vars)\n\t\t\t\tif (Array.isArray(resolvedValue)) {\n\t\t\t\t\treturn !!resolvedValue.some((elem) => elem === resolvedSymbol)\n\t\t\t\t}\n\t\t\t\treturn resolvedValue === resolvedSymbol\n\t\t\t}\n\t\t})\n\t\t.led('!=', 20, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\tvalidateSymbol(expr)\n\t\t\treturn (obj: any, vars: VariableMap) =>\n\t\t\t\tresolveValue(obj, left) !== resolveSymbol(expr, vars)\n\t\t})\n\t\t.led('>', 20, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\tvalidateSymbol(expr)\n\n\t\t\treturn (obj: any, vars: object) =>\n\t\t\t\tresolveValue(obj, left) > resolveSymbol(expr, vars)\n\t\t})\n\t\t.led('>=', 20, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\tvalidateSymbol(expr)\n\n\t\t\treturn (obj: any, vars: object) =>\n\t\t\t\tresolveValue(obj, left) >= resolveSymbol(expr, vars)\n\t\t})\n\t\t.led('<', 20, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\tvalidateSymbol(expr)\n\n\t\t\treturn (obj: any, vars: object) =>\n\t\t\t\tresolveValue(obj, left) < resolveSymbol(expr, vars)\n\t\t})\n\t\t.led('<=', 20, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\tvalidateSymbol(expr)\n\n\t\t\treturn (obj: any, vars: object) =>\n\t\t\t\tresolveValue(obj, left) <= resolveSymbol(expr, vars)\n\t\t})\n\t\t.led('IS', 20, ({ left, bp }) => {\n\t\t\tlet invert = false\n\n\t\t\t// Peek if this is a `is not` statement\n\t\t\tconst next = lexer.peek()\n\t\t\tif (next.type === 'NOT') {\n\t\t\t\tinvert = true\n\t\t\t\tlexer.next()\n\t\t\t}\n\n\t\t\tconst expr: any = parser.parse({ terminals: [bp - 1] })\n\n\t\t\tswitch (expr) {\n\t\t\t\tcase 'empty': {\n\t\t\t\t\tif (!invert) {\n\t\t\t\t\t\treturn (obj: any, vars: VariableMap) => {\n\t\t\t\t\t\t\tconst val = resolveValue(obj, left)\n\t\t\t\t\t\t\treturn val.length === 0\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn (obj: any, vars: VariableMap) => {\n\t\t\t\t\t\t\tconst val = resolveValue(obj, left)\n\t\t\t\t\t\t\treturn val.length !== 0\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcase 'defined': {\n\t\t\t\t\tif (!invert) {\n\t\t\t\t\t\treturn (obj: any, vars: VariableMap) => {\n\t\t\t\t\t\t\tconst val = resolveValue(obj, left)\n\t\t\t\t\t\t\treturn val !== undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn (obj: any, vars: VariableMap) => {\n\t\t\t\t\t\t\tconst val = resolveValue(obj, left)\n\t\t\t\t\t\t\treturn val === undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tthrow new Error('Unexpected')\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.led('IN', 20, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\treturn (obj: any, vars: object) => {\n\t\t\t\tlet symbols = expr\n\t\t\t\tif (!Array.isArray(symbols)) {\n\t\t\t\t\tsymbols = [expr]\n\t\t\t\t}\n\n\t\t\t\tconst inValues = symbols.map((item: TypeSymbol) =>\n\t\t\t\t\tresolveSymbol(item, vars)\n\t\t\t\t)\n\t\t\t\treturn inValues.includes(resolveValue(obj, left))\n\t\t\t}\n\t\t})\n\t\t.led('MATCHES_IGNORE_CASE', 20, ({ left, bp }) => {\n\t\t\tconst expr = parser.parse({ terminals: [bp - 1] })\n\t\t\tvalidateSymbol(expr)\n\n\t\t\treturn (obj: any, vars: VariableMap) => {\n\t\t\t\tconst value = resolveValue(obj, left)\n\t\t\t\tconst other = resolveSymbol(expr, vars)\n\n\t\t\t\tif (typeof value != 'string') {\n\t\t\t\t\tthrow new PredicateError(\n\t\t\t\t\t\t`The field '${left.value}' does not support this expression.`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn value.toLowerCase() === other.toLowerCase()\n\t\t\t}\n\t\t})\n\t\t.led('WITHIN', 20, ({ left, bp }) => {\n\t\t\tconst type = lexer.next()\n\n\t\t\tif (type.match !== 'circle') {\n\t\t\t\tthrow new PredicateError(\n\t\t\t\t\t`Invalid input '${type.match}', expected circle`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tlexer.expect('(')\n\t\t\tconst expr = parser.parse({ terminals: [')'] })\n\n\t\t\treturn (obj: any, vars: object) => {\n\t\t\t\tconst value = resolveValue(obj, left)\n\t\t\t\tif (!value) return false\n\n\t\t\t\tconst maxDistance = resolveSymbol(expr[2], vars)\n\t\t\t\tconst distance = haversineDistance(\n\t\t\t\t\t{\n\t\t\t\t\t\tlongitude: value[0],\n\t\t\t\t\t\tlatitude: value[1],\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tlongitude: resolveSymbol(expr[0], vars),\n\t\t\t\t\t\tlatitude: resolveSymbol(expr[1], vars),\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t\treturn distance <= maxDistance\n\t\t\t}\n\t\t})\n\t\t.led('CONTAINS', 20, ({ left, bp }) => {\n\t\t\tconst keyword = lexer.next()\n\n\t\t\tlet expr = parser.parse()\n\t\t\tif (!Array.isArray(expr)) {\n\t\t\t\texpr = [expr]\n\t\t\t}\n\n\t\t\treturn (obj: any, vars: object) => {\n\t\t\t\tconst value = resolveValue(obj, left)\n\n\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\tthrow new PredicateError(\n\t\t\t\t\t\t`The field '${left.value}' does not support this expression.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tconst array = expr.map((item: TypeSymbol) => resolveSymbol(item, vars))\n\t\t\t\tif (keyword.type === 'ALL') {\n\t\t\t\t\treturn array.every((item: any) => value.includes(item))\n\t\t\t\t} else {\n\t\t\t\t\treturn array.some((item: any) => value.includes(item))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\t.build()\n\n\tconst result = parser.parse()\n\n\tif (typeof result !== 'function') {\n\t\tconst lines = predicate.split('\\n')\n\t\tconst column = lines[lines.length - 1].length\n\n\t\tthrow new PredicateError(\n\t\t\t`Unexpected end of input, expected SphereIdentifierChar, comparison ` +\n\t\t\t\t`operator, not, in, contains, is, within or matches` +\n\t\t\t\t` (line ${lines.length}, column ${column})`\n\t\t)\n\t}\n\treturn result\n}\n","import auth from 'basic-auth'\nimport bodyParser from 'body-parser'\nimport express, {\n\ttype NextFunction,\n\ttype Request,\n\ttype Response,\n} from 'express'\nimport { InvalidTokenError } from '@commercetools/platform-sdk'\nimport { CommercetoolsError, InvalidRequestError } from '../exceptions.js'\nimport { InvalidClientError, UnsupportedGrantType } from './errors.js'\nimport { OAuth2Store } from './store.js'\nimport { getBearerToken } from './helpers.js'\n\nexport class OAuth2Server {\n\tstore: OAuth2Store\n\n\tconstructor(options: { enabled: boolean; validate: boolean }) {\n\t\tthis.store = new OAuth2Store(options.validate)\n\t}\n\n\tcreateRouter() {\n\t\tconst router = express.Router()\n\t\trouter.use(bodyParser.urlencoded({ extended: true }))\n\t\trouter.post('/token', this.tokenHandler.bind(this))\n\t\treturn router\n\t}\n\n\tcreateMiddleware() {\n\t\treturn async (request: Request, response: Response, next: NextFunction) => {\n\t\t\tconst token = getBearerToken(request)\n\t\t\tif (!token) {\n\t\t\t\tnext(\n\t\t\t\t\tnew CommercetoolsError<InvalidTokenError>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: 'invalid_token',\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t'This endpoint requires an access token. You can get one from the authorization server.',\n\t\t\t\t\t\t},\n\t\t\t\t\t\t401\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (!token || !this.store.validateToken(token)) {\n\t\t\t\tnext(\n\t\t\t\t\tnew CommercetoolsError<InvalidTokenError>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: 'invalid_token',\n\t\t\t\t\t\t\tmessage: 'invalid_token',\n\t\t\t\t\t\t},\n\t\t\t\t\t\t401\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tnext()\n\t\t}\n\t}\n\tasync tokenHandler(request: Request, response: Response, next: NextFunction) {\n\t\tconst authHeader = request.header('Authorization')\n\t\tif (!authHeader) {\n\t\t\treturn next(\n\t\t\t\tnew CommercetoolsError<InvalidClientError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'invalid_client',\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t'Please provide valid client credentials using HTTP Basic Authentication.',\n\t\t\t\t\t},\n\t\t\t\t\t401\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\tconst credentials = auth.parse(authHeader)\n\t\tif (!credentials) {\n\t\t\treturn next(\n\t\t\t\tnew CommercetoolsError<InvalidClientError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'invalid_client',\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t'Please provide valid client credentials using HTTP Basic Authentication.',\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\n\t\tconst grantType = request.query.grant_type || request.body.grant_type\n\t\tif (!grantType) {\n\t\t\treturn next(\n\t\t\t\tnew CommercetoolsError<InvalidRequestError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'invalid_request',\n\t\t\t\t\t\tmessage: 'Missing required parameter: grant_type.',\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\n\t\tif (grantType === 'client_credentials') {\n\t\t\tconst token = this.store.getClientToken(\n\t\t\t\tcredentials.name,\n\t\t\t\tcredentials.pass,\n\t\t\t\trequest.query.scope?.toString()\n\t\t\t)\n\t\t\treturn response.status(200).send(token)\n\t\t} else {\n\t\t\treturn next(\n\t\t\t\tnew CommercetoolsError<UnsupportedGrantType>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'unsupported_grant_type',\n\t\t\t\t\t\tmessage: `Invalid parameter: grant_type: Invalid grant type: ${grantType}`,\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t}\n}\n","import { randomBytes } from 'crypto'\n\ntype Token = {\n\taccess_token: string\n\ttoken_type: 'Bearer'\n\texpires_in: number\n\tscope: string\n}\n\nexport class OAuth2Store {\n\ttokens: Token[] = []\n\tvalidate = true\n\n\tconstructor(validate = true) {\n\t\tthis.validate = validate\n\t}\n\n\tgetClientToken(clientId: string, clientSecret: string, scope?: string) {\n\t\tconst token: Token = {\n\t\t\taccess_token: randomBytes(16).toString('base64'),\n\t\t\ttoken_type: 'Bearer',\n\t\t\texpires_in: 172800,\n\t\t\tscope: scope || 'todo',\n\t\t}\n\t\tthis.tokens.push(token)\n\t\treturn token\n\t}\n\n\tvalidateToken(token: string) {\n\t\tif (!this.validate) return true\n\n\t\tconst foundToken = this.tokens.find((t) => t.access_token === token)\n\t\tif (foundToken) {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}\n","import { Request } from 'express'\n\nexport const getBearerToken = (request: Request): string | undefined => {\n\tconst authHeader = request.header('Authorization')\n\tconst match = authHeader?.match(/^Bearer\\s(?<token>[^\\s]+)$/)\n\tif (match) {\n\t\treturn match.groups?.token\n\t}\n\treturn undefined\n}\n","import { getBaseResourceProperties } from './helpers.js'\nimport { GetParams } from './repositories/abstract.js'\nimport { RepositoryMap } from './repositories/index.js'\nimport { AbstractStorage } from './storage/index.js'\nimport { ResourceMap, ResourceType } from './types.js'\n\nexport class ProjectAPI {\n\tprivate projectKey: string\n\tprivate _storage: AbstractStorage\n\tprivate _repositories: RepositoryMap\n\n\tconstructor(\n\t\tprojectKey: string,\n\t\trepositories: RepositoryMap,\n\t\tstorage: AbstractStorage\n\t) {\n\t\tthis.projectKey = projectKey\n\t\tthis._storage = storage\n\t\tthis._repositories = repositories\n\t}\n\n\tadd<T extends keyof RepositoryMap & keyof ResourceMap>(\n\t\ttypeId: T,\n\t\tresource: ResourceMap[T]\n\t) {\n\t\tconst repository = this._repositories[typeId]\n\t\tif (repository) {\n\t\t\tthis._storage.add(this.projectKey, typeId, {\n\t\t\t\t...getBaseResourceProperties(),\n\t\t\t\t...resource,\n\t\t\t})\n\t\t} else {\n\t\t\tthrow new Error(`Service for ${typeId} not implemented yet`)\n\t\t}\n\t}\n\n\tget<RT extends ResourceType>(\n\t\ttypeId: RT,\n\t\tid: string,\n\t\tparams?: GetParams\n\t): ResourceMap[RT] {\n\t\treturn this._storage.get(\n\t\t\tthis.projectKey,\n\t\t\ttypeId,\n\t\t\tid,\n\t\t\tparams\n\t\t) as ResourceMap[RT]\n\t}\n\n\t// TODO: Not sure if we want to expose this...\n\tgetRepository<RT extends keyof RepositoryMap>(typeId: RT): RepositoryMap[RT] {\n\t\tconst repository = this._repositories[typeId]\n\t\tif (repository !== undefined) {\n\t\t\treturn repository as RepositoryMap[RT]\n\t\t}\n\t\tthrow new Error('No such repository')\n\t}\n}\n","export const copyHeaders = (headers: Record<string, string>) => {\n\tconst validHeaders = ['accept', 'host', 'authorization']\n\tconst result: Record<string, string> = {}\n\n\tObject.entries(headers).forEach(([key, value]) => {\n\t\tif (validHeaders.includes(key.toLowerCase())) {\n\t\t\tresult[key] = value\n\t\t}\n\t})\n\n\treturn result\n}\n","export const DEFAULT_API_HOSTNAME =\n\t/^https:\\/\\/api\\..*?\\.commercetools.com:443$/\nexport const DEFAULT_AUTH_HOSTNAME =\n\t/^https:\\/\\/auth\\..*?\\.commercetools.com:443$/\n","import type {\n\tAddress,\n\tBaseAddress,\n\tCentPrecisionMoney,\n\tCustomFields,\n\tCustomFieldsDraft,\n\tHighPrecisionMoney,\n\tHighPrecisionMoneyDraft,\n\tInvalidJsonInputError,\n\tPrice,\n\tPriceDraft,\n\tReference,\n\tReferencedResourceNotFoundError,\n\tResourceIdentifier,\n\tStore,\n\tStoreKeyReference,\n\tStoreReference,\n\tStoreResourceIdentifier,\n\tType,\n\tTypedMoney,\n\t_Money,\n} from '@commercetools/platform-sdk'\nimport type { Request } from 'express'\nimport { v4 as uuidv4 } from 'uuid'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { AbstractStorage } from '../storage/index.js'\nimport { type RepositoryContext } from './abstract.js'\n\nexport const createAddress = (\n\tbase: BaseAddress | undefined,\n\tprojectKey: string,\n\tstorage: AbstractStorage\n): Address | undefined => {\n\tif (!base) return undefined\n\n\tif (!base?.country) {\n\t\tthrow new Error('Country is required')\n\t}\n\n\treturn {\n\t\t...base,\n\t}\n}\n\nexport const createCustomFields = (\n\tdraft: CustomFieldsDraft | undefined,\n\tprojectKey: string,\n\tstorage: AbstractStorage\n): CustomFields | undefined => {\n\tif (!draft) return undefined\n\tif (!draft.type) return undefined\n\tif (!draft.type.typeId) return undefined\n\tif (!draft.fields) return undefined\n\tconst typeResource = storage.getByResourceIdentifier(\n\t\tprojectKey,\n\t\tdraft.type\n\t) as Type\n\n\tif (!typeResource) {\n\t\tthrow new Error(\n\t\t\t`No type '${draft.type.typeId}' with id=${draft.type.id} or key=${draft.type.key}`\n\t\t)\n\t}\n\n\treturn {\n\t\ttype: {\n\t\t\ttypeId: draft.type.typeId,\n\t\t\tid: typeResource.id,\n\t\t},\n\t\tfields: draft.fields,\n\t}\n}\n\nexport const createPrice = (draft: PriceDraft): Price => ({\n\tid: uuidv4(),\n\tvalue: createTypedMoney(draft.value),\n})\n\nexport const createCentPrecisionMoney = (value: _Money): CentPrecisionMoney => {\n\t// Taken from https://docs.adyen.com/development-resources/currency-codes\n\tlet fractionDigits = 2\n\tswitch (value.currencyCode.toUpperCase()) {\n\t\tcase 'BHD':\n\t\tcase 'IQD':\n\t\tcase 'JOD':\n\t\tcase 'KWD':\n\t\tcase 'LYD':\n\t\tcase 'OMR':\n\t\tcase 'TND':\n\t\t\tfractionDigits = 3\n\t\t\tbreak\n\t\tcase 'CVE':\n\t\tcase 'DJF':\n\t\tcase 'GNF':\n\t\tcase 'IDR':\n\t\tcase 'JPY':\n\t\tcase 'KMF':\n\t\tcase 'KRW':\n\t\tcase 'PYG':\n\t\tcase 'RWF':\n\t\tcase 'UGX':\n\t\tcase 'VND':\n\t\tcase 'VUV':\n\t\tcase 'XAF':\n\t\tcase 'XOF':\n\t\tcase 'XPF':\n\t\t\tfractionDigits = 0\n\t\t\tbreak\n\t\tdefault:\n\t\t\tfractionDigits = 2\n\t}\n\n\tif ((value as HighPrecisionMoney & HighPrecisionMoneyDraft).preciseAmount) {\n\t\tthrow new Error('HighPrecisionMoney not supported')\n\t}\n\n\treturn {\n\t\ttype: 'centPrecision',\n\t\t// centAmont is only optional on HighPrecisionMoney, so this should never\n\t\t// fallback to 0\n\t\tcentAmount: value.centAmount ?? 0,\n\t\tcurrencyCode: value.currencyCode,\n\t\tfractionDigits: fractionDigits,\n\t}\n}\n\nexport const createTypedMoney = (value: _Money): TypedMoney => {\n\tconst result = createCentPrecisionMoney(value)\n\treturn result\n}\n\nexport const resolveStoreReference = (\n\tref: StoreResourceIdentifier | undefined,\n\tprojectKey: string,\n\tstorage: AbstractStorage\n): StoreKeyReference | undefined => {\n\tif (!ref) return undefined\n\tconst resource = storage.getByResourceIdentifier(projectKey, ref)\n\tif (!resource) {\n\t\tthrow new Error('No such store')\n\t}\n\n\tconst store = resource as Store\n\treturn {\n\t\ttypeId: 'store',\n\t\tkey: store.key,\n\t}\n}\n\nexport const getReferenceFromResourceIdentifier = <T extends Reference>(\n\tresourceIdentifier: ResourceIdentifier,\n\tprojectKey: string,\n\tstorage: AbstractStorage\n): T => {\n\tif (!resourceIdentifier.id && !resourceIdentifier.key) {\n\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t{\n\t\t\t\tcode: 'InvalidJsonInput',\n\t\t\t\tmessage: `${resourceIdentifier.typeId}: ResourceIdentifier requires an 'id' xor a 'key'`,\n\t\t\t\tdetailedErrorMessage: `ResourceIdentifier requires an 'id' xor a 'key'`,\n\t\t\t},\n\t\t\t400\n\t\t)\n\t}\n\n\tconst resource = storage.getByResourceIdentifier(\n\t\tprojectKey,\n\t\tresourceIdentifier\n\t)\n\tif (!resource) {\n\t\tconst errIdentifier = resourceIdentifier.key\n\t\t\t? `key '${resourceIdentifier.key}'`\n\t\t\t: `identifier '${resourceIdentifier.key}'`\n\n\t\tthrow new CommercetoolsError<ReferencedResourceNotFoundError>(\n\t\t\t{\n\t\t\t\tcode: 'ReferencedResourceNotFound',\n\t\t\t\t// @ts-ignore\n\t\t\t\ttypeId: resourceIdentifier.typeId,\n\t\t\t\tmessage: `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).`,\n\t\t\t},\n\t\t\t400\n\t\t)\n\t}\n\n\treturn {\n\t\ttypeId: resourceIdentifier.typeId,\n\t\tid: resource?.id,\n\t} as unknown as T\n}\n\nexport const getStoreKeyReference = (\n\tid: StoreResourceIdentifier,\n\tprojectKey: string,\n\tstorage: AbstractStorage\n): StoreKeyReference => {\n\tif (id.key) {\n\t\treturn {\n\t\t\ttypeId: 'store',\n\t\t\tkey: id.key,\n\t\t}\n\t}\n\tconst value = getReferenceFromResourceIdentifier<StoreReference>(\n\t\tid,\n\t\tprojectKey,\n\t\tstorage\n\t)\n\n\tif (!value.obj?.key) {\n\t\tthrow new Error('No store found for reference')\n\t}\n\treturn {\n\t\ttypeId: 'store',\n\t\tkey: value.obj?.key,\n\t}\n}\n\nexport const getRepositoryContext = (request: Request): RepositoryContext => ({\n\tprojectKey: request.params.projectKey,\n\tstoreKey: request.params.storeKey,\n})\n","import type { Update } from '@commercetools/platform-sdk'\nimport { Request, Response, Router } from 'express'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport { ProjectRepository } from '../repositories/project.js'\n\nexport class ProjectService {\n\tpublic repository: ProjectRepository\n\n\tconstructor(parent: Router, repository: ProjectRepository) {\n\t\tthis.repository = repository\n\t\tthis.registerRoutes(parent)\n\t}\n\n\tregisterRoutes(parent: Router) {\n\t\tparent.get('', this.get.bind(this))\n\t\tparent.post('', this.post.bind(this))\n\t}\n\n\tget(request: Request, response: Response) {\n\t\tconst project = this.repository.get(getRepositoryContext(request))\n\t\treturn response.status(200).send(project)\n\t}\n\n\tpost(request: Request, response: Response) {\n\t\tconst updateRequest: Update = request.body\n\t\tconst project = this.repository.get(getRepositoryContext(request))\n\n\t\tif (!project) {\n\t\t\treturn response.status(404).send({})\n\t\t}\n\n\t\tconst updatedResource = this.repository.processUpdateActions(\n\t\t\tgetRepositoryContext(request),\n\t\t\tproject,\n\t\t\tupdateRequest.version,\n\t\t\tupdateRequest.actions\n\t\t)\n\n\t\treturn response.status(200).send(updatedResource)\n\t}\n}\n","import type {\n\tBaseResource,\n\tProject,\n\tResourceNotFoundError,\n\tUpdateAction,\n} from '@commercetools/platform-sdk'\nimport deepEqual from 'deep-equal'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { cloneObject } from '../helpers.js'\nimport { AbstractStorage } from '../storage/index.js'\nimport { ResourceMap, ResourceType, ShallowWritable } from './../types.js'\nimport { checkConcurrentModification } from './errors.js'\n\nexport type QueryParams = {\n\texpand?: string[]\n\twhere?: string[]\n\toffset?: number\n\tlimit?: number\n}\n\nexport type GetParams = {\n\texpand?: string[]\n}\n\nexport type RepositoryContext = {\n\tprojectKey: string\n\tstoreKey?: string\n}\n\nexport abstract class AbstractRepository<R extends BaseResource | Project> {\n\tprotected _storage: AbstractStorage\n\tprotected actions: Partial<\n\t\tRecord<\n\t\t\tany,\n\t\t\t(context: RepositoryContext, resource: any, action: any) => void\n\t\t>\n\t> = {}\n\n\tconstructor(storage: AbstractStorage) {\n\t\tthis._storage = storage\n\t}\n\n\tabstract saveNew({ projectKey }: RepositoryContext, resource: R): void\n\n\tabstract saveUpdate(\n\t\t{ projectKey }: RepositoryContext,\n\t\tversion: number,\n\t\tresource: R\n\t): void\n\n\tprocessUpdateActions(\n\t\tcontext: RepositoryContext,\n\t\tresource: R,\n\t\tversion: number,\n\t\tactions: UpdateAction[]\n\t): R {\n\t\t// Deep-copy\n\t\tconst updatedResource = cloneObject(resource) as ShallowWritable<R>\n\t\tconst identifier = (resource as BaseResource).id\n\t\t\t? (resource as BaseResource).id\n\t\t\t: (resource as Project).key\n\n\t\tactions.forEach((action) => {\n\t\t\tconst updateFunc = this.actions[action.action]\n\n\t\t\tif (!updateFunc) {\n\t\t\t\tconsole.error(`No mock implemented for update action ${action.action}`)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No mock implemented for update action ${action.action}`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst beforeUpdate = cloneObject(resource)\n\t\t\tupdateFunc(context, updatedResource, action)\n\n\t\t\t// Check if the object is updated. We need to increase the version of\n\t\t\t// an object per action which does an actual modification.\n\t\t\t// This isn't the most performant method to do this (the update action\n\t\t\t// should return a flag) but for now the easiest.\n\t\t\tif (!deepEqual(beforeUpdate, updatedResource)) {\n\t\t\t\t// We only check the version when there is an actual modification to\n\t\t\t\t// be stored.\n\t\t\t\tcheckConcurrentModification(resource.version, version, identifier)\n\n\t\t\t\tupdatedResource.version += 1\n\t\t\t}\n\t\t})\n\n\t\t// If all actions succeeded we write the new version\n\t\t// to the storage.\n\t\tif (resource.version != updatedResource.version) {\n\t\t\tthis.saveUpdate(context, version, updatedResource)\n\t\t}\n\n\t\tconst result = this.postProcessResource(updatedResource)\n\t\tif (!result) {\n\t\t\tthrow new Error('invalid post process action')\n\t\t}\n\t\treturn result\n\t}\n\n\tabstract postProcessResource(resource: any): any\n}\n\nexport abstract class AbstractResourceRepository<\n\tT extends ResourceType,\n> extends AbstractRepository<ResourceMap[T]> {\n\tabstract create(context: RepositoryContext, draft: any): ResourceMap[T]\n\tabstract getTypeId(): T\n\n\tconstructor(storage: AbstractStorage) {\n\t\tsuper(storage)\n\t}\n\n\tpostProcessResource(resource: ResourceMap[T]): ResourceMap[T] {\n\t\treturn resource\n\t}\n\n\tquery(context: RepositoryContext, params: QueryParams = {}) {\n\t\tconst result = this._storage.query(context.projectKey, this.getTypeId(), {\n\t\t\texpand: params.expand,\n\t\t\twhere: params.where,\n\t\t\toffset: params.offset,\n\t\t\tlimit: params.limit,\n\t\t})\n\n\t\t// @ts-ignore\n\t\tresult.results = result.results.map(this.postProcessResource)\n\t\treturn result\n\t}\n\n\tget(\n\t\tcontext: RepositoryContext,\n\t\tid: string,\n\t\tparams: GetParams = {}\n\t): ResourceMap[T] | null {\n\t\tconst resource = this._storage.get(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tid,\n\t\t\tparams\n\t\t)\n\t\treturn resource ? this.postProcessResource(resource) : null\n\t}\n\n\tgetByKey(\n\t\tcontext: RepositoryContext,\n\t\tkey: string,\n\t\tparams: GetParams = {}\n\t): ResourceMap[T] | null {\n\t\tconst resource = this._storage.getByKey(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tkey,\n\t\t\tparams\n\t\t)\n\t\treturn resource ? this.postProcessResource(resource) : null\n\t}\n\n\tdelete(\n\t\tcontext: RepositoryContext,\n\t\tid: string,\n\t\tparams: GetParams = {}\n\t): ResourceMap[T] | null {\n\t\tconst resource = this._storage.delete(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tid,\n\t\t\tparams\n\t\t)\n\t\treturn resource ? this.postProcessResource(resource) : null\n\t}\n\n\tsaveNew(\n\t\tcontext: RepositoryContext,\n\t\tresource: ShallowWritable<ResourceMap[T]>\n\t) {\n\t\tresource.version = 1\n\t\tthis._storage.add(context.projectKey, this.getTypeId(), resource as any)\n\t}\n\n\tsaveUpdate(\n\t\tcontext: RepositoryContext,\n\t\tversion: number,\n\t\tresource: ShallowWritable<ResourceMap[T]>\n\t) {\n\t\t// Check if the resource still exists.\n\t\tconst current = this._storage.get(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\tresource.id\n\t\t)\n\t\tif (!current) {\n\t\t\tthrow new CommercetoolsError<ResourceNotFoundError>(\n\t\t\t\t{\n\t\t\t\t\tcode: 'ResourceNotFound',\n\t\t\t\t\tmessage: 'Resource not found while updating',\n\t\t\t\t},\n\t\t\t\t400\n\t\t\t)\n\t\t}\n\n\t\tcheckConcurrentModification(current.version, version, resource.id)\n\n\t\tif (current.version === resource.version) {\n\t\t\tthrow new Error('Internal error: no changes to save')\n\t\t}\n\t\tresource.lastModifiedAt = new Date().toISOString()\n\n\t\tthis._storage.add(context.projectKey, this.getTypeId(), resource as any)\n\n\t\treturn resource\n\t}\n}\n","import { type ConcurrentModificationError } from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from '../exceptions.js'\n\nexport const checkConcurrentModification = (\n\tcurrentVersion: number,\n\texpectedVersion: number,\n\tidentifier: string\n) => {\n\tif (currentVersion === expectedVersion) return\n\tconsole.error(\n\t\t`Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`\n\t)\n\n\tthrow new CommercetoolsError<ConcurrentModificationError>(\n\t\t{\n\t\t\tmessage: `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`,\n\t\t\tcurrentVersion: currentVersion,\n\t\t\tcode: 'ConcurrentModification',\n\t\t},\n\t\t409\n\t)\n}\n","import type { AssociateRole } from '@commercetools/platform-sdk'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\n\nexport class AssociateRoleRepository extends AbstractResourceRepository<'associate-role'> {\n\tgetTypeId() {\n\t\treturn 'associate-role' as const\n\t}\n\tcreate(context: RepositoryContext, draft: any): AssociateRole {\n\t\tthrow new Error('Method not implemented.')\n\t}\n}\n","import type {\n\tAttributeGroup,\n\tAttributeGroupChangeNameAction,\n\tAttributeGroupDraft,\n\tAttributeGroupSetAttributesAction,\n\tAttributeGroupSetDescriptionAction,\n\tAttributeGroupSetKeyAction,\n} from '@commercetools/platform-sdk'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { Writable } from '../types.js'\n\nexport class AttributeGroupRepository extends AbstractResourceRepository<'attribute-group'> {\n\tgetTypeId() {\n\t\treturn 'attribute-group' as const\n\t}\n\n\tcreate(\n\t\tcontext: RepositoryContext,\n\t\tdraft: AttributeGroupDraft\n\t): AttributeGroup {\n\t\tconst resource: AttributeGroup = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\tkey: draft.key,\n\t\t\tattributes: draft.attributes,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions = {\n\t\tsetAttributes: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<AttributeGroup>,\n\t\t\t{ attributes }: AttributeGroupSetAttributesAction\n\t\t) => {\n\t\t\tresource.attributes = attributes\n\t\t},\n\t\tchangeName: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<AttributeGroup>,\n\t\t\t{ name }: AttributeGroupChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tsetDescription: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<AttributeGroup>,\n\t\t\t{ description }: AttributeGroupSetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tsetKey: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<AttributeGroup>,\n\t\t\t{ key }: AttributeGroupSetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t}\n}\n","import type { BusinessUnit } from '@commercetools/platform-sdk'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\n\nexport class BusinessUnitRepository extends AbstractResourceRepository<'business-unit'> {\n\tgetTypeId() {\n\t\treturn 'business-unit' as const\n\t}\n\tcreate(context: RepositoryContext, draft: any): BusinessUnit {\n\t\tthrow new Error('Method not implemented.')\n\t}\n}\n","import type {\n\tAddress,\n\tAddressDraft,\n\tCart,\n\tCartAddLineItemAction,\n\tCartChangeLineItemQuantityAction,\n\tCartDraft,\n\tCartRemoveLineItemAction,\n\tCartSetBillingAddressAction,\n\tCartSetCountryAction,\n\tCartSetCustomerEmailAction,\n\tCartSetCustomFieldAction,\n\tCartSetCustomTypeAction,\n\tCartSetLocaleAction,\n\tCartSetShippingAddressAction,\n\tCartSetShippingMethodAction,\n\tCustomFields,\n\tGeneralError,\n\tLineItem,\n\tLineItemDraft,\n\tPrice,\n\tProduct,\n\tProductPagedQueryResponse,\n\tProductVariant,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { createAddress, createCustomFields } from './helpers.js'\n\nexport class CartRepository extends AbstractResourceRepository<'cart'> {\n\tgetTypeId() {\n\t\treturn 'cart' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: CartDraft): Cart {\n\t\tconst lineItems =\n\t\t\tdraft.lineItems?.map((draftLineItem) =>\n\t\t\t\tthis.draftLineItemtoLineItem(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tdraftLineItem,\n\t\t\t\t\tdraft.currency,\n\t\t\t\t\tdraft.country\n\t\t\t\t)\n\t\t\t) ?? []\n\n\t\tconst resource: Writable<Cart> = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tcartState: 'Active',\n\t\t\tcountry: draft.country,\n\t\t\tcustomLineItems: [],\n\t\t\tdirectDiscounts: [],\n\t\t\tdiscountCodes: [],\n\t\t\tinventoryMode: 'None',\n\t\t\titemShippingAddresses: [],\n\t\t\tlineItems,\n\t\t\tlocale: draft.locale,\n\t\t\ttaxCalculationMode: draft.taxCalculationMode ?? 'LineItemLevel',\n\t\t\ttaxMode: draft.taxMode ?? 'Platform',\n\t\t\ttaxRoundingMode: draft.taxRoundingMode ?? 'HalfEven',\n\t\t\ttotalPrice: {\n\t\t\t\ttype: 'centPrecision',\n\t\t\t\tcentAmount: 0,\n\t\t\t\tcurrencyCode: draft.currency,\n\t\t\t\tfractionDigits: 0,\n\t\t\t},\n\t\t\tshippingMode: 'Single',\n\t\t\tshipping: [],\n\t\t\torigin: draft.origin ?? 'Customer',\n\t\t\trefusedGifts: [],\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource)\n\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tgetActiveCart(projectKey: string): Cart | undefined {\n\t\t// Get first active cart\n\t\tconst results = this._storage.query(projectKey, this.getTypeId(), {\n\t\t\twhere: [`cartState=\"Active\"`],\n\t\t})\n\t\tif (results.count > 0) {\n\t\t\treturn results.results[0] as Cart\n\t\t}\n\n\t\treturn\n\t}\n\n\tactions = {\n\t\taddLineItem: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ productId, variantId, sku, quantity = 1 }: CartAddLineItemAction\n\t\t) => {\n\t\t\tlet product: Product | null = null\n\n\t\t\tif (productId && variantId) {\n\t\t\t\t// Fetch product and variant by ID\n\t\t\t\tproduct = this._storage.get(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t'product',\n\t\t\t\t\tproductId,\n\t\t\t\t\t{}\n\t\t\t\t)\n\t\t\t} else if (sku) {\n\t\t\t\t// Fetch product and variant by SKU\n\t\t\t\tconst items = this._storage.query(context.projectKey, 'product', {\n\t\t\t\t\twhere: [\n\t\t\t\t\t\t`masterData(current(masterVariant(sku=\"${sku}\"))) or masterData(current(variants(sku=\"${sku}\")))`,\n\t\t\t\t\t],\n\t\t\t\t}) as ProductPagedQueryResponse\n\n\t\t\t\tif (items.count === 1) {\n\t\t\t\t\tproduct = items.results[0]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!product) {\n\t\t\t\t// Check if product is found\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: 'General',\n\t\t\t\t\tmessage: sku\n\t\t\t\t\t\t? `A product containing a variant with SKU '${sku}' not found.`\n\t\t\t\t\t\t: `A product with ID '${productId}' not found.`,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Find matching variant\n\t\t\tconst variant: ProductVariant | undefined = [\n\t\t\t\tproduct.masterData.current.masterVariant,\n\t\t\t\t...product.masterData.current.variants,\n\t\t\t].find((x) => {\n\t\t\t\tif (sku) return x.sku === sku\n\t\t\t\tif (variantId) return x.id === variantId\n\t\t\t\treturn false\n\t\t\t})\n\n\t\t\tif (!variant) {\n\t\t\t\t// Check if variant is found\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: 'General',\n\t\t\t\t\tmessage: sku\n\t\t\t\t\t\t? `A variant with SKU '${sku}' for product '${product.id}' not found.`\n\t\t\t\t\t\t: `A variant with ID '${variantId}' for product '${product.id}' not found.`,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst alreadyAdded = resource.lineItems.some(\n\t\t\t\t(x) => x.productId === product?.id && x.variant.id === variant?.id\n\t\t\t)\n\t\t\tif (alreadyAdded) {\n\t\t\t\t// increase quantity and update total price\n\t\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\t\tif (x.productId === product?.id && x.variant.id === variant?.id) {\n\t\t\t\t\t\tx.quantity += quantity\n\t\t\t\t\t\tx.totalPrice.centAmount = calculateLineItemTotalPrice(x)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\t// add line item\n\t\t\t\tif (!variant.prices?.length) {\n\t\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\t\tcode: 'General',\n\t\t\t\t\t\tmessage: `A product with ID '${productId}' doesn't have any prices.`,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tconst currency = resource.totalPrice.currencyCode\n\n\t\t\t\tconst price = selectPrice({\n\t\t\t\t\tprices: variant.prices,\n\t\t\t\t\tcurrency,\n\t\t\t\t\tcountry: resource.country,\n\t\t\t\t})\n\t\t\t\tif (!price) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`No valid price found for ${productId} for country ${resource.country} and currency ${currency}`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tresource.lineItems.push({\n\t\t\t\t\tid: uuidv4(),\n\t\t\t\t\tproductId: product.id,\n\t\t\t\t\tproductKey: product.key,\n\t\t\t\t\tproductSlug: product.masterData.current.slug,\n\t\t\t\t\tproductType: product.productType,\n\t\t\t\t\tname: product.masterData.current.name,\n\t\t\t\t\tvariant,\n\t\t\t\t\tprice: price,\n\t\t\t\t\ttaxedPricePortions: [],\n\t\t\t\t\tperMethodTaxRate: [],\n\t\t\t\t\ttotalPrice: {\n\t\t\t\t\t\t...price.value,\n\t\t\t\t\t\ttype: 'centPrecision',\n\t\t\t\t\t\tcentAmount: price.value.centAmount * quantity,\n\t\t\t\t\t},\n\t\t\t\t\tquantity,\n\t\t\t\t\tdiscountedPricePerQuantity: [],\n\t\t\t\t\tlineItemMode: 'Standard',\n\t\t\t\t\tpriceMode: 'Platform',\n\t\t\t\t\tstate: [],\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Update cart total price\n\t\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource)\n\t\t},\n\t\tchangeLineItemQuantity: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ lineItemId, lineItemKey, quantity }: CartChangeLineItemQuantityAction\n\t\t) => {\n\t\t\tlet lineItem: Writable<LineItem> | undefined\n\n\t\t\tif (lineItemId) {\n\t\t\t\tlineItem = resource.lineItems.find((x) => x.id === lineItemId)\n\t\t\t\tif (!lineItem) {\n\t\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\t\tcode: 'General',\n\t\t\t\t\t\tmessage: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else if (lineItemKey) {\n\t\t\t\tlineItem = resource.lineItems.find((x) => x.id === lineItemId)\n\t\t\t\tif (!lineItem) {\n\t\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\t\tcode: 'General',\n\t\t\t\t\t\tmessage: `A line item with Key '${lineItemKey}' not found.`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: 'General',\n\t\t\t\t\tmessage: `Either lineItemid or lineItemKey needs to be provided.`,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (quantity === 0) {\n\t\t\t\t// delete line item\n\t\t\t\tresource.lineItems = resource.lineItems.filter(\n\t\t\t\t\t(x) => x.id !== lineItemId\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\t\tif (x.id === lineItemId && quantity) {\n\t\t\t\t\t\tx.quantity = quantity\n\t\t\t\t\t\tx.totalPrice.centAmount = calculateLineItemTotalPrice(x)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Update cart total price\n\t\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource)\n\t\t},\n\t\tremoveLineItem: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ lineItemId, quantity }: CartRemoveLineItemAction\n\t\t) => {\n\t\t\tconst lineItem = resource.lineItems.find((x) => x.id === lineItemId)\n\t\t\tif (!lineItem) {\n\t\t\t\t// Check if product is found\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: 'General',\n\t\t\t\t\tmessage: `A line item with ID '${lineItemId}' not found.`,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst shouldDelete = !quantity || quantity >= lineItem.quantity\n\t\t\tif (shouldDelete) {\n\t\t\t\t// delete line item\n\t\t\t\tresource.lineItems = resource.lineItems.filter(\n\t\t\t\t\t(x) => x.id !== lineItemId\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\t// decrease quantity and update total price\n\t\t\t\tresource.lineItems.forEach((x) => {\n\t\t\t\t\tif (x.id === lineItemId && quantity) {\n\t\t\t\t\t\tx.quantity -= quantity\n\t\t\t\t\t\tx.totalPrice.centAmount = calculateLineItemTotalPrice(x)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Update cart total price\n\t\t\tresource.totalPrice.centAmount = calculateCartTotalPrice(resource)\n\t\t},\n\t\tsetBillingAddress: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ address }: CartSetBillingAddressAction\n\t\t) => {\n\t\t\tresource.billingAddress = createAddress(\n\t\t\t\taddress,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t)\n\t\t},\n\t\tsetShippingMethod: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ shippingMethod }: CartSetShippingMethodAction\n\t\t) => {\n\t\t\tif (shippingMethod) {\n\t\t\t\tconst method = this._storage.getByResourceIdentifier<'shipping-method'>(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tshippingMethod\n\t\t\t\t)\n\n\t\t\t\tif (!method) {\n\t\t\t\t\tthrow new Error(`Type ${shippingMethod} not found`)\n\t\t\t\t}\n\n\t\t\t\t// Based on the address we should select a shipping zone and\n\t\t\t\t// use that to define the price.\n\t\t\t\t// @ts-ignore\n\t\t\t\tresource.shippingInfo = {\n\t\t\t\t\tshippingMethod: {\n\t\t\t\t\t\ttypeId: 'shipping-method',\n\t\t\t\t\t\tid: method.id,\n\t\t\t\t\t},\n\t\t\t\t\tshippingMethodName: method.name,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresource.shippingInfo = undefined\n\t\t\t}\n\t\t},\n\t\tsetCountry: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ country }: CartSetCountryAction\n\t\t) => {\n\t\t\tresource.country = country\n\t\t},\n\t\tsetCustomerEmail: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ email }: CartSetCustomerEmailAction\n\t\t) => {\n\t\t\tresource.customerEmail = email\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Cart,\n\t\t\t{ name, value }: CartSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\tthrow new Error('Resource has no custom field')\n\t\t\t}\n\t\t\tresource.custom.fields[name] = value\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ type, fields }: CartSetCustomTypeAction\n\t\t) => {\n\t\t\tif (!type) {\n\t\t\t\tresource.custom = undefined\n\t\t\t} else {\n\t\t\t\tconst resolvedType = this._storage.getByResourceIdentifier(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\ttype\n\t\t\t\t)\n\t\t\t\tif (!resolvedType) {\n\t\t\t\t\tthrow new Error(`Type ${type} not found`)\n\t\t\t\t}\n\n\t\t\t\tresource.custom = {\n\t\t\t\t\ttype: {\n\t\t\t\t\t\ttypeId: 'type',\n\t\t\t\t\t\tid: resolvedType.id,\n\t\t\t\t\t},\n\t\t\t\t\tfields: fields || {},\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tsetLocale: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ locale }: CartSetLocaleAction\n\t\t) => {\n\t\t\tresource.locale = locale\n\t\t},\n\t\tsetShippingAddress: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Cart>,\n\t\t\t{ address }: CartSetShippingAddressAction\n\t\t) => {\n\t\t\tif (!address) {\n\t\t\t\tresource.shippingAddress = undefined\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlet custom: CustomFields | undefined = undefined\n\t\t\tif ((address as Address & AddressDraft).custom) {\n\t\t\t\tcustom = createCustomFields(\n\t\t\t\t\t(address as Address & AddressDraft).custom,\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tresource.shippingAddress = {\n\t\t\t\t...address,\n\t\t\t\tcustom: custom,\n\t\t\t}\n\t\t},\n\t}\n\tdraftLineItemtoLineItem = (\n\t\tprojectKey: string,\n\t\tdraftLineItem: LineItemDraft,\n\t\tcurrency: string,\n\t\tcountry: string | undefined\n\t): LineItem => {\n\t\tconst { productId, quantity, variantId, sku } = draftLineItem\n\n\t\tlet product: Product | null = null\n\n\t\tif (productId && variantId) {\n\t\t\t// Fetch product and variant by ID\n\t\t\tproduct = this._storage.get(projectKey, 'product', productId, {})\n\t\t} else if (sku) {\n\t\t\t// Fetch product and variant by SKU\n\t\t\tconst items = this._storage.query(projectKey, 'product', {\n\t\t\t\twhere: [\n\t\t\t\t\t`masterData(current(masterVariant(sku=\"${sku}\"))) or masterData(current(variants(sku=\"${sku}\")))`,\n\t\t\t\t],\n\t\t\t}) as ProductPagedQueryResponse\n\n\t\t\tif (items.count === 1) {\n\t\t\t\tproduct = items.results[0]\n\t\t\t}\n\t\t}\n\n\t\tif (!product) {\n\t\t\t// Check if product is found\n\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\tcode: 'General',\n\t\t\t\tmessage: sku\n\t\t\t\t\t? `A product containing a variant with SKU '${sku}' not found.`\n\t\t\t\t\t: `A product with ID '${productId}' not found.`,\n\t\t\t})\n\t\t}\n\n\t\t// Find matching variant\n\t\tconst variant = [\n\t\t\tproduct.masterData.current.masterVariant,\n\t\t\t...product.masterData.current.variants,\n\t\t].find((x) => {\n\t\t\tif (sku) return x.sku === sku\n\t\t\tif (variantId) return x.id === variantId\n\t\t\treturn false\n\t\t})\n\n\t\tif (!variant) {\n\t\t\t// Check if variant is found\n\t\t\tthrow new Error(\n\t\t\t\tsku\n\t\t\t\t\t? `A variant with SKU '${sku}' for product '${product.id}' not found.`\n\t\t\t\t\t: `A variant with ID '${variantId}' for product '${product.id}' not found.`\n\t\t\t)\n\t\t}\n\n\t\tconst quant = quantity ?? 1\n\n\t\tconst price = selectPrice({ prices: variant.prices, currency, country })\n\t\tif (!price) {\n\t\t\tthrow new Error(\n\t\t\t\t`No valid price found for ${productId} for country ${country} and currency ${currency}`\n\t\t\t)\n\t\t}\n\n\t\treturn {\n\t\t\tid: uuidv4(),\n\t\t\tproductId: product.id,\n\t\t\tproductKey: product.key,\n\t\t\tproductSlug: product.masterData.current.slug,\n\t\t\tproductType: product.productType,\n\t\t\tname: product.masterData.current.name,\n\t\t\tvariant,\n\t\t\tprice: price,\n\t\t\ttotalPrice: {\n\t\t\t\ttype: 'centPrecision',\n\t\t\t\tcurrencyCode: price.value.currencyCode,\n\t\t\t\tfractionDigits: price.value.fractionDigits,\n\t\t\t\tcentAmount: price.value.centAmount * quant,\n\t\t\t},\n\t\t\ttaxedPricePortions: [],\n\t\t\tperMethodTaxRate: [],\n\t\t\tquantity: quant,\n\t\t\tdiscountedPricePerQuantity: [],\n\t\t\tlineItemMode: 'Standard',\n\t\t\tpriceMode: 'Platform',\n\t\t\tstate: [],\n\t\t}\n\t}\n}\n\nconst selectPrice = ({\n\tprices,\n\tcurrency,\n\tcountry,\n}: {\n\tprices: Price[] | undefined\n\tcurrency: string\n\tcountry: string | undefined\n}): Price | undefined => {\n\tif (!prices) {\n\t\treturn undefined\n\t}\n\n\t// Quick-and-dirty way of selecting price based on the given currency and country.\n\t// Can be improved later to give more priority to exact matches over\n\t// 'all country' matches, and include customer groups in the mix as well\n\treturn prices.find((price) => {\n\t\tconst countryMatch = !price.country || price.country === country\n\t\tconst currencyMatch = price.value.currencyCode === currency\n\t\treturn countryMatch && currencyMatch\n\t})\n}\n\nconst calculateLineItemTotalPrice = (lineItem: LineItem): number =>\n\tlineItem.price!.value.centAmount * lineItem.quantity\n\nconst calculateCartTotalPrice = (cart: Cart): number =>\n\tcart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0)\n","import type {\n\tCartDiscount,\n\tCartDiscountChangeIsActiveAction,\n\tCartDiscountChangeSortOrderAction,\n\tCartDiscountDraft,\n\tCartDiscountSetDescriptionAction,\n\tCartDiscountSetKeyAction,\n\tCartDiscountSetValidFromAction,\n\tCartDiscountSetValidFromAndUntilAction,\n\tCartDiscountSetValidUntilAction,\n\tCartDiscountUpdateAction,\n\tCartDiscountValueAbsolute,\n\tCartDiscountValueDraft,\n\tCartDiscountValueFixed,\n\tCartDiscountValueGiftLineItem,\n\tCartDiscountValueRelative,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { createTypedMoney, getStoreKeyReference } from './helpers.js'\n\nexport class CartDiscountRepository extends AbstractResourceRepository<'cart-discount'> {\n\tgetTypeId() {\n\t\treturn 'cart-discount' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: CartDiscountDraft): CartDiscount {\n\t\tconst resource: CartDiscount = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tdescription: draft.description,\n\t\t\tcartPredicate: draft.cartPredicate,\n\t\t\tisActive: draft.isActive || false,\n\t\t\tname: draft.name,\n\t\t\tstores:\n\t\t\t\tdraft.stores?.map((s) =>\n\t\t\t\t\tgetStoreKeyReference(s, context.projectKey, this._storage)\n\t\t\t\t) ?? [],\n\t\t\treferences: [],\n\t\t\ttarget: draft.target,\n\t\t\trequiresDiscountCode: draft.requiresDiscountCode || false,\n\t\t\tsortOrder: draft.sortOrder,\n\t\t\tstackingMode: draft.stackingMode || 'Stacking',\n\t\t\tvalidFrom: draft.validFrom,\n\t\t\tvalidUntil: draft.validUntil,\n\t\t\tvalue: this.transformValueDraft(draft.value),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tprivate transformValueDraft(value: CartDiscountValueDraft) {\n\t\tswitch (value.type) {\n\t\t\tcase 'absolute': {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'absolute',\n\t\t\t\t\tmoney: value.money.map(createTypedMoney),\n\t\t\t\t} as CartDiscountValueAbsolute\n\t\t\t}\n\t\t\tcase 'fixed': {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'fixed',\n\t\t\t\t\tmoney: value.money.map(createTypedMoney),\n\t\t\t\t} as CartDiscountValueFixed\n\t\t\t}\n\t\t\tcase 'giftLineItem': {\n\t\t\t\treturn {\n\t\t\t\t\t...value,\n\t\t\t\t} as CartDiscountValueGiftLineItem\n\t\t\t}\n\t\t\tcase 'relative': {\n\t\t\t\treturn {\n\t\t\t\t\t...value,\n\t\t\t\t} as CartDiscountValueRelative\n\t\t\t}\n\t\t}\n\n\t\treturn value\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tCartDiscountUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<CartDiscount>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tsetKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CartDiscount>,\n\t\t\t{ key }: CartDiscountSetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CartDiscount>,\n\t\t\t{ description }: CartDiscountSetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tsetValidFrom: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CartDiscount>,\n\t\t\t{ validFrom }: CartDiscountSetValidFromAction\n\t\t) => {\n\t\t\tresource.validFrom = validFrom\n\t\t},\n\t\tsetValidUntil: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CartDiscount>,\n\t\t\t{ validUntil }: CartDiscountSetValidUntilAction\n\t\t) => {\n\t\t\tresource.validUntil = validUntil\n\t\t},\n\t\tsetValidFromAndUntil: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CartDiscount>,\n\t\t\t{ validFrom, validUntil }: CartDiscountSetValidFromAndUntilAction\n\t\t) => {\n\t\t\tresource.validFrom = validFrom\n\t\t\tresource.validUntil = validUntil\n\t\t},\n\t\tchangeSortOrder: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CartDiscount>,\n\t\t\t{ sortOrder }: CartDiscountChangeSortOrderAction\n\t\t) => {\n\t\t\tresource.sortOrder = sortOrder\n\t\t},\n\t\tchangeIsActive: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CartDiscount>,\n\t\t\t{ isActive }: CartDiscountChangeIsActiveAction\n\t\t) => {\n\t\t\tresource.isActive = isActive\n\t\t},\n\t}\n}\n","import type {\n\tCategory,\n\tCategoryChangeAssetNameAction,\n\tCategoryChangeSlugAction,\n\tCategoryDraft,\n\tCategorySetAssetDescriptionAction,\n\tCategorySetAssetSourcesAction,\n\tCategorySetCustomFieldAction,\n\tCategorySetCustomTypeAction,\n\tCategorySetDescriptionAction,\n\tCategorySetKeyAction,\n\tCategorySetMetaDescriptionAction,\n\tCategorySetMetaKeywordsAction,\n\tCategorySetMetaTitleAction,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { createCustomFields } from './helpers.js'\n\nexport class CategoryRepository extends AbstractResourceRepository<'category'> {\n\tgetTypeId() {\n\t\treturn 'category' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: CategoryDraft): Category {\n\t\tconst resource: Category = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tslug: draft.slug,\n\t\t\torderHint: draft.orderHint || '',\n\t\t\texternalId: draft.externalId || '',\n\t\t\tparent: draft.parent\n\t\t\t\t? { typeId: 'category', id: draft.parent.id! }\n\t\t\t\t: undefined,\n\t\t\tancestors: [], // TODO\n\t\t\tassets:\n\t\t\t\tdraft.assets?.map((d) => ({\n\t\t\t\t\tid: uuidv4(),\n\t\t\t\t\tname: d.name,\n\t\t\t\t\tdescription: d.description,\n\t\t\t\t\tsources: d.sources,\n\t\t\t\t\ttags: d.tags,\n\t\t\t\t\tkey: d.key,\n\t\t\t\t\tcustom: createCustomFields(\n\t\t\t\t\t\tdraft.custom,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage\n\t\t\t\t\t),\n\t\t\t\t})) || [],\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions = {\n\t\tchangeAssetName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ assetId, assetKey, name }: CategoryChangeAssetNameAction\n\t\t) => {\n\t\t\tresource.assets?.forEach((asset) => {\n\t\t\t\tif (assetId && assetId === asset.id) {\n\t\t\t\t\tasset.name = name\n\t\t\t\t}\n\t\t\t\tif (assetKey && assetKey === asset.key) {\n\t\t\t\t\tasset.name = name\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\tchangeSlug: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ slug }: CategoryChangeSlugAction\n\t\t) => {\n\t\t\tresource.slug = slug\n\t\t},\n\t\tsetKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ key }: CategorySetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t\tsetAssetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ assetId, assetKey, description }: CategorySetAssetDescriptionAction\n\t\t) => {\n\t\t\tresource.assets?.forEach((asset) => {\n\t\t\t\tif (assetId && assetId === asset.id) {\n\t\t\t\t\tasset.description = description\n\t\t\t\t}\n\t\t\t\tif (assetKey && assetKey === asset.key) {\n\t\t\t\t\tasset.description = description\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\tsetAssetSources: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ assetId, assetKey, sources }: CategorySetAssetSourcesAction\n\t\t) => {\n\t\t\tresource.assets?.forEach((asset) => {\n\t\t\t\tif (assetId && assetId === asset.id) {\n\t\t\t\t\tasset.sources = sources\n\t\t\t\t}\n\t\t\t\tif (assetKey && assetKey === asset.key) {\n\t\t\t\t\tasset.sources = sources\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ description }: CategorySetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tsetMetaDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ metaDescription }: CategorySetMetaDescriptionAction\n\t\t) => {\n\t\t\tresource.metaDescription = metaDescription\n\t\t},\n\t\tsetMetaKeywords: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ metaKeywords }: CategorySetMetaKeywordsAction\n\t\t) => {\n\t\t\tresource.metaKeywords = metaKeywords\n\t\t},\n\t\tsetMetaTitle: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ metaTitle }: CategorySetMetaTitleAction\n\t\t) => {\n\t\t\tresource.metaTitle = metaTitle\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ type, fields }: CategorySetCustomTypeAction\n\t\t) => {\n\t\t\tif (type) {\n\t\t\t\tresource.custom = createCustomFields(\n\t\t\t\t\t{ type, fields },\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tresource.custom = undefined\n\t\t\t}\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Category>,\n\t\t\t{ name, value }: CategorySetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (value === null) {\n\t\t\t\tdelete resource.custom.fields[name]\n\t\t\t} else {\n\t\t\t\tresource.custom.fields[name] = value\n\t\t\t}\n\t\t},\n\t}\n}\n","import type {\n\tChannel,\n\tChannelChangeDescriptionAction,\n\tChannelChangeKeyAction,\n\tChannelChangeNameAction,\n\tChannelDraft,\n\tChannelSetAddressAction,\n\tChannelSetCustomFieldAction,\n\tChannelSetCustomTypeAction,\n\tChannelSetGeoLocationAction,\n\tChannelUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { createAddress, createCustomFields } from './helpers.js'\n\nexport class ChannelRepository extends AbstractResourceRepository<'channel'> {\n\tgetTypeId() {\n\t\treturn 'channel' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: ChannelDraft): Channel {\n\t\tconst resource: Channel = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\troles: draft.roles || [],\n\t\t\tgeoLocation: draft.geoLocation,\n\t\t\taddress: createAddress(draft.address, context.projectKey, this._storage),\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tChannelUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Channel>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tchangeKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Channel>,\n\t\t\t{ key }: ChannelChangeKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\n\t\tchangeName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Channel>,\n\t\t\t{ name }: ChannelChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\n\t\tchangeDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Channel>,\n\t\t\t{ description }: ChannelChangeDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\n\t\tsetAddress: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Channel>,\n\t\t\t{ address }: ChannelSetAddressAction\n\t\t) => {\n\t\t\tresource.address = createAddress(\n\t\t\t\taddress,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t)\n\t\t},\n\n\t\tsetGeoLocation: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Channel>,\n\t\t\t{ geoLocation }: ChannelSetGeoLocationAction\n\t\t) => {\n\t\t\tresource.geoLocation = geoLocation\n\t\t},\n\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Channel>,\n\t\t\t{ type, fields }: ChannelSetCustomTypeAction\n\t\t) => {\n\t\t\tif (type) {\n\t\t\t\tresource.custom = createCustomFields(\n\t\t\t\t\t{ type, fields },\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tresource.custom = undefined\n\t\t\t}\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Channel>,\n\t\t\t{ name, value }: ChannelSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (value === null) {\n\t\t\t\tdelete resource.custom.fields[name]\n\t\t\t} else {\n\t\t\t\tresource.custom.fields[name] = value\n\t\t\t}\n\t\t},\n\t}\n}\n","import type {\n\tCustomObject,\n\tCustomObjectDraft,\n\tInvalidOperationError,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { cloneObject, getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { checkConcurrentModification } from './errors.js'\n\nexport class CustomObjectRepository extends AbstractResourceRepository<'key-value-document'> {\n\tgetTypeId() {\n\t\treturn 'key-value-document' as const\n\t}\n\n\tcreate(\n\t\tcontext: RepositoryContext,\n\t\tdraft: Writable<CustomObjectDraft>\n\t): CustomObject {\n\t\tconst current = this.getWithContainerAndKey(\n\t\t\tcontext,\n\t\t\tdraft.container,\n\t\t\tdraft.key\n\t\t) as Writable<CustomObject | undefined>\n\n\t\tif (current) {\n\t\t\t// Only check version if it is passed in the draft\n\t\t\tif (draft.version) {\n\t\t\t\tcheckConcurrentModification(current.version, draft.version, current.id)\n\t\t\t} else {\n\t\t\t\tdraft.version = current.version\n\t\t\t}\n\n\t\t\tif (draft.value !== current.value) {\n\t\t\t\tconst updated = cloneObject(current) as Writable<CustomObject>\n\t\t\t\tupdated.value = draft.value\n\t\t\t\tupdated.version += 1\n\t\t\t\tthis.saveUpdate(context, draft.version, updated)\n\t\t\t\treturn updated\n\t\t\t}\n\t\t\treturn current\n\t\t} else {\n\t\t\t// If the resource is new the only valid version is 0\n\t\t\tif (draft.version) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidOperation',\n\t\t\t\t\t\tmessage: 'version on create must be 0',\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst baseProperties = getBaseResourceProperties()\n\t\t\tconst resource: CustomObject = {\n\t\t\t\t...baseProperties,\n\t\t\t\tcontainer: draft.container,\n\t\t\t\tkey: draft.key,\n\t\t\t\tvalue: draft.value,\n\t\t\t}\n\n\t\t\tthis.saveNew(context, resource)\n\t\t\treturn resource\n\t\t}\n\t}\n\n\tgetWithContainerAndKey(\n\t\tcontext: RepositoryContext,\n\t\tcontainer: string,\n\t\tkey: string\n\t) {\n\t\tconst items = this._storage.all(context.projectKey, this.getTypeId())\n\t\treturn items.find(\n\t\t\t(item) => item.container === container && item.key === key\n\t\t)\n\t}\n}\n","import type {\n\tCustomer,\n\tCustomerChangeEmailAction,\n\tCustomerDraft,\n\tCustomerSetAuthenticationModeAction,\n\tCustomerSetCustomFieldAction,\n\tInvalidInputError,\n\tInvalidJsonInputError,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\n\nexport class CustomerRepository extends AbstractResourceRepository<'customer'> {\n\tgetTypeId() {\n\t\treturn 'customer' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: CustomerDraft): Customer {\n\t\tconst resource: Customer = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tauthenticationMode: draft.authenticationMode || 'Password',\n\t\t\temail: draft.email,\n\t\t\tpassword: draft.password\n\t\t\t\t? Buffer.from(draft.password).toString('base64')\n\t\t\t\t: undefined,\n\t\t\tisEmailVerified: draft.isEmailVerified || false,\n\t\t\taddresses: [],\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tgetMe(context: RepositoryContext): Customer | undefined {\n\t\tconst results = this._storage.query(\n\t\t\tcontext.projectKey,\n\t\t\tthis.getTypeId(),\n\t\t\t{}\n\t\t) // grab the first customer you can find\n\t\tif (results.count > 0) {\n\t\t\treturn results.results[0] as Customer\n\t\t}\n\n\t\treturn\n\t}\n\n\tactions = {\n\t\tchangeEmail: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<Customer>,\n\t\t\t{ email }: CustomerChangeEmailAction\n\t\t) => {\n\t\t\tresource.email = email\n\t\t},\n\t\tsetAuthenticationMode: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<Customer>,\n\t\t\t{ authMode, password }: CustomerSetAuthenticationModeAction\n\t\t) => {\n\t\t\tif (resource.authenticationMode === authMode) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidInput',\n\t\t\t\t\t\tmessage: `The customer is already using the '${resource.authenticationMode}' authentication mode.`,\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t}\n\t\t\tresource.authenticationMode = authMode\n\t\t\tif (authMode === 'ExternalAuth') {\n\t\t\t\tdelete resource.password\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (authMode === 'Password') {\n\t\t\t\tresource.password = password\n\t\t\t\t\t? Buffer.from(password).toString('base64')\n\t\t\t\t\t: undefined\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthrow new CommercetoolsError<InvalidJsonInputError>(\n\t\t\t\t{\n\t\t\t\t\tcode: 'InvalidJsonInput',\n\t\t\t\t\tmessage: 'Request body does not contain valid JSON.',\n\t\t\t\t\tdetailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`,\n\t\t\t\t},\n\t\t\t\t400\n\t\t\t)\n\t\t},\n\t\tsetCustomField: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<Customer>,\n\t\t\t{ name, value }: CustomerSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\tthrow new Error('Resource has no custom field')\n\t\t\t}\n\t\t\tresource.custom.fields[name] = value\n\t\t},\n\t}\n}\n","import type {\n\tCustomerGroup,\n\tCustomerGroupChangeNameAction,\n\tCustomerGroupDraft,\n\tCustomerGroupSetCustomFieldAction,\n\tCustomerGroupSetCustomTypeAction,\n\tCustomerGroupSetKeyAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { createCustomFields } from './helpers.js'\n\nexport class CustomerGroupRepository extends AbstractResourceRepository<'customer-group'> {\n\tgetTypeId() {\n\t\treturn 'customer-group' as const\n\t}\n\tcreate(context: RepositoryContext, draft: CustomerGroupDraft): CustomerGroup {\n\t\tconst resource: CustomerGroup = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.groupName,\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions = {\n\t\tsetKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CustomerGroup>,\n\t\t\t{ key }: CustomerGroupSetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t\tchangeName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CustomerGroup>,\n\t\t\t{ name }: CustomerGroupChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CustomerGroup>,\n\t\t\t{ type, fields }: CustomerGroupSetCustomTypeAction\n\t\t) => {\n\t\t\tif (type) {\n\t\t\t\tresource.custom = createCustomFields(\n\t\t\t\t\t{ type, fields },\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tresource.custom = undefined\n\t\t\t}\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<CustomerGroup>,\n\t\t\t{ name, value }: CustomerGroupSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (value === null) {\n\t\t\t\tdelete resource.custom.fields[name]\n\t\t\t} else {\n\t\t\t\tresource.custom.fields[name] = value\n\t\t\t}\n\t\t},\n\t}\n}\n","import type {\n\tCartDiscountReference,\n\tDiscountCode,\n\tDiscountCodeChangeCartDiscountsAction,\n\tDiscountCodeChangeIsActiveAction,\n\tDiscountCodeDraft,\n\tDiscountCodeSetCartPredicateAction,\n\tDiscountCodeSetCustomFieldAction,\n\tDiscountCodeSetCustomTypeAction,\n\tDiscountCodeSetDescriptionAction,\n\tDiscountCodeSetMaxApplicationsAction,\n\tDiscountCodeSetMaxApplicationsPerCustomerAction,\n\tDiscountCodeSetNameAction,\n\tDiscountCodeSetValidFromAction,\n\tDiscountCodeSetValidFromAndUntilAction,\n\tDiscountCodeSetValidUntilAction,\n\tDiscountCodeUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { createCustomFields } from './helpers.js'\n\nexport class DiscountCodeRepository extends AbstractResourceRepository<'discount-code'> {\n\tgetTypeId() {\n\t\treturn 'discount-code' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: DiscountCodeDraft): DiscountCode {\n\t\tconst resource: DiscountCode = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tapplicationVersion: 1,\n\t\t\tcartDiscounts: draft.cartDiscounts.map(\n\t\t\t\t(obj): CartDiscountReference => ({\n\t\t\t\t\ttypeId: 'cart-discount',\n\t\t\t\t\tid: obj.id!,\n\t\t\t\t})\n\t\t\t),\n\t\t\tcartPredicate: draft.cartPredicate,\n\t\t\tcode: draft.code,\n\t\t\tdescription: draft.description,\n\t\t\tgroups: draft.groups || [],\n\t\t\tisActive: draft.isActive || true,\n\t\t\tname: draft.name,\n\t\t\treferences: [],\n\t\t\tvalidFrom: draft.validFrom,\n\t\t\tvalidUntil: draft.validUntil,\n\t\t\tmaxApplications: draft.maxApplications,\n\t\t\tmaxApplicationsPerCustomer: draft.maxApplicationsPerCustomer,\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tDiscountCodeUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<DiscountCode>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tchangeIsActive: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ isActive }: DiscountCodeChangeIsActiveAction\n\t\t) => {\n\t\t\tresource.isActive = isActive\n\t\t},\n\t\tchangeCartDiscounts: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ cartDiscounts }: DiscountCodeChangeCartDiscountsAction\n\t\t) => {\n\t\t\tresource.cartDiscounts = cartDiscounts.map(\n\t\t\t\t(obj): CartDiscountReference => ({\n\t\t\t\t\ttypeId: 'cart-discount',\n\t\t\t\t\tid: obj.id!,\n\t\t\t\t})\n\t\t\t)\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ description }: DiscountCodeSetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tsetCartPredicate: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ cartPredicate }: DiscountCodeSetCartPredicateAction\n\t\t) => {\n\t\t\tresource.cartPredicate = cartPredicate\n\t\t},\n\t\tsetName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ name }: DiscountCodeSetNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tsetMaxApplications: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ maxApplications }: DiscountCodeSetMaxApplicationsAction\n\t\t) => {\n\t\t\tresource.maxApplications = maxApplications\n\t\t},\n\t\tsetMaxApplicationsPerCustomer: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{\n\t\t\t\tmaxApplicationsPerCustomer,\n\t\t\t}: DiscountCodeSetMaxApplicationsPerCustomerAction\n\t\t) => {\n\t\t\tresource.maxApplicationsPerCustomer = maxApplicationsPerCustomer\n\t\t},\n\t\tsetValidFrom: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ validFrom }: DiscountCodeSetValidFromAction\n\t\t) => {\n\t\t\tresource.validFrom = validFrom\n\t\t},\n\t\tsetValidUntil: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ validUntil }: DiscountCodeSetValidUntilAction\n\t\t) => {\n\t\t\tresource.validUntil = validUntil\n\t\t},\n\t\tsetValidFromAndUntil: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ validFrom, validUntil }: DiscountCodeSetValidFromAndUntilAction\n\t\t) => {\n\t\t\tresource.validFrom = validFrom\n\t\t\tresource.validUntil = validUntil\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ type, fields }: DiscountCodeSetCustomTypeAction\n\t\t) => {\n\t\t\tif (type) {\n\t\t\t\tresource.custom = createCustomFields(\n\t\t\t\t\t{ type, fields },\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tresource.custom = undefined\n\t\t\t}\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<DiscountCode>,\n\t\t\t{ name, value }: DiscountCodeSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (value === null) {\n\t\t\t\tdelete resource.custom.fields[name]\n\t\t\t} else {\n\t\t\t\tresource.custom.fields[name] = value\n\t\t\t}\n\t\t},\n\t}\n}\n","import { cloneObject } from '../helpers.js'\n\nexport const maskSecretValue = <T>(resource: T, path: string): T => {\n\tconst parts = path.split('.')\n\tconst clone = cloneObject(resource) as any\n\tlet val = clone\n\n\tconst target = parts.pop()\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i]\n\t\tval = val[part]\n\n\t\tif (val === undefined) {\n\t\t\treturn resource\n\t\t}\n\t}\n\n\tif (val && target && val[target]) {\n\t\tval[target] = '****'\n\t}\n\treturn clone\n}\n","import type {\n\tExtension,\n\tExtensionChangeDestinationAction,\n\tExtensionChangeTriggersAction,\n\tExtensionDraft,\n\tExtensionSetKeyAction,\n\tExtensionSetTimeoutInMsAction,\n\tExtensionUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { maskSecretValue } from '../lib/masking.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\n\nexport class ExtensionRepository extends AbstractResourceRepository<'extension'> {\n\tgetTypeId() {\n\t\treturn 'extension' as const\n\t}\n\n\tpostProcessResource(resource: Extension): Extension {\n\t\tif (resource) {\n\t\t\tconst extension = resource as Extension\n\t\t\tif (\n\t\t\t\textension.destination.type === 'HTTP' &&\n\t\t\t\textension.destination.authentication?.type === 'AuthorizationHeader'\n\t\t\t) {\n\t\t\t\treturn maskSecretValue(\n\t\t\t\t\textension,\n\t\t\t\t\t'destination.authentication.headerValue'\n\t\t\t\t)\n\t\t\t} else if (extension.destination.type == 'AWSLambda') {\n\t\t\t\treturn maskSecretValue(resource, 'destination.accessSecret')\n\t\t\t}\n\t\t}\n\t\treturn resource\n\t}\n\n\tcreate(context: RepositoryContext, draft: ExtensionDraft): Extension {\n\t\tconst resource: Extension = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\ttimeoutInMs: draft.timeoutInMs,\n\t\t\tdestination: draft.destination,\n\t\t\ttriggers: draft.triggers,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions: Record<\n\t\tExtensionUpdateAction['action'],\n\t\t(\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Extension>,\n\t\t\taction: any\n\t\t) => void\n\t> = {\n\t\tsetKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Extension>,\n\t\t\t{ key }: ExtensionSetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t\tsetTimeoutInMs: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Extension>,\n\t\t\t{ timeoutInMs }: ExtensionSetTimeoutInMsAction\n\t\t) => {\n\t\t\tresource.timeoutInMs = timeoutInMs\n\t\t},\n\t\tchangeTriggers: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Extension>,\n\t\t\t{ triggers }: ExtensionChangeTriggersAction\n\t\t) => {\n\t\t\tresource.triggers = triggers\n\t\t},\n\t\tchangeDestination: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Extension>,\n\t\t\t{ destination }: ExtensionChangeDestinationAction\n\t\t) => {\n\t\t\tresource.destination = destination\n\t\t},\n\t}\n}\n","import type {\n\tInventoryEntry,\n\tInventoryEntryChangeQuantityAction,\n\tInventoryEntryDraft,\n\tInventoryEntrySetCustomFieldAction,\n\tInventoryEntrySetCustomTypeAction,\n\tInventoryEntrySetExpectedDeliveryAction,\n\tInventoryEntrySetRestockableInDaysAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype RepositoryContext,\n} from './abstract.js'\nimport { createCustomFields } from './helpers.js'\n\nexport class InventoryEntryRepository extends AbstractResourceRepository<'inventory-entry'> {\n\tgetTypeId() {\n\t\treturn 'inventory-entry' as const\n\t}\n\n\tcreate(\n\t\tcontext: RepositoryContext,\n\t\tdraft: InventoryEntryDraft\n\t): InventoryEntry {\n\t\tconst resource: InventoryEntry = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tsku: draft.sku,\n\t\t\tquantityOnStock: draft.quantityOnStock,\n\t\t\tavailableQuantity: draft.quantityOnStock,\n\t\t\texpectedDelivery: draft.expectedDelivery,\n\t\t\trestockableInDays: draft.restockableInDays,\n\t\t\tsupplyChannel: {\n\t\t\t\t...draft.supplyChannel,\n\t\t\t\ttypeId: 'channel',\n\t\t\t\tid: draft.supplyChannel?.id ?? '',\n\t\t\t},\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions = {\n\t\tchangeQuantity: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<InventoryEntry>,\n\t\t\t{ quantity }: InventoryEntryChangeQuantityAction\n\t\t) => {\n\t\t\tresource.quantityOnStock = quantity\n\t\t\t// don't know active reservations so just set to same value\n\t\t\tresource.availableQuantity = quantity\n\t\t},\n\t\tsetExpectedDelivery: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<InventoryEntry>,\n\t\t\t{ expectedDelivery }: InventoryEntrySetExpectedDeliveryAction\n\t\t) => {\n\t\t\tresource.expectedDelivery = new Date(expectedDelivery!).toISOString()\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: InventoryEntry,\n\t\t\t{ name, value }: InventoryEntrySetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\tthrow new Error('Resource has no custom field')\n\t\t\t}\n\t\t\tresource.custom.fields[name] = value\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<InventoryEntry>,\n\t\t\t{ type, fields }: InventoryEntrySetCustomTypeAction\n\t\t) => {\n\t\t\tif (!type) {\n\t\t\t\tresource.custom = undefined\n\t\t\t} else {\n\t\t\t\tconst resolvedType = this._storage.getByResourceIdentifier(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\ttype\n\t\t\t\t)\n\t\t\t\tif (!resolvedType) {\n\t\t\t\t\tthrow new Error(`Type ${type} not found`)\n\t\t\t\t}\n\n\t\t\t\tresource.custom = {\n\t\t\t\t\ttype: {\n\t\t\t\t\t\ttypeId: 'type',\n\t\t\t\t\t\tid: resolvedType.id,\n\t\t\t\t\t},\n\t\t\t\t\tfields: fields || {},\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tsetRestockableInDays: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<InventoryEntry>,\n\t\t\t{ restockableInDays }: InventoryEntrySetRestockableInDaysAction\n\t\t) => {\n\t\t\tresource.restockableInDays = restockableInDays\n\t\t},\n\t}\n}\n","import type {\n\tCartReference,\n\tMyOrderFromCartDraft,\n\tOrder,\n} from '@commercetools/platform-sdk'\nimport assert from 'assert'\nimport { type RepositoryContext } from './abstract.js'\nimport { OrderRepository } from './order.js'\n\nexport class MyOrderRepository extends OrderRepository {\n\tcreate(context: RepositoryContext, draft: MyOrderFromCartDraft): Order {\n\t\tassert(draft.id, 'draft.id is missing')\n\t\tconst cartIdentifier = {\n\t\t\tid: draft.id,\n\t\t\ttypeId: 'cart',\n\t\t} as CartReference\n\t\treturn this.createFromCart(context, cartIdentifier)\n\t}\n}\n","import type {\n\tCart,\n\tCartReference,\n\tCustomLineItem,\n\tCustomLineItemDraft,\n\tGeneralError,\n\tLineItem,\n\tLineItemImportDraft,\n\tOrder,\n\tOrderAddPaymentAction,\n\tOrderChangeOrderStateAction,\n\tOrderChangePaymentStateAction,\n\tOrderFromCartDraft,\n\tOrderImportDraft,\n\tOrderSetBillingAddressAction,\n\tOrderSetCustomerEmailAction,\n\tOrderSetCustomFieldAction,\n\tOrderSetCustomTypeAction,\n\tOrderSetLocaleAction,\n\tOrderSetOrderNumberAction,\n\tOrderSetShippingAddressAction,\n\tOrderSetStoreAction,\n\tOrderTransitionStateAction,\n\tProduct,\n\tProductPagedQueryResponse,\n\tProductVariant,\n\tState,\n\tStore,\n} from '@commercetools/platform-sdk'\nimport assert from 'assert'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport {\n\tAbstractResourceRepository,\n\ttype QueryParams,\n\tRepositoryContext,\n} from './abstract.js'\nimport {\n\tcreateAddress,\n\tcreateCentPrecisionMoney,\n\tcreateCustomFields,\n\tcreatePrice,\n\tcreateTypedMoney,\n\tresolveStoreReference,\n} from './helpers.js'\n\nexport class OrderRepository extends AbstractResourceRepository<'order'> {\n\tgetTypeId() {\n\t\treturn 'order' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: OrderFromCartDraft): Order {\n\t\tassert(draft.cart, 'draft.cart is missing')\n\t\treturn this.createFromCart(\n\t\t\tcontext,\n\t\t\t{\n\t\t\t\tid: draft.cart.id!,\n\t\t\t\ttypeId: 'cart',\n\t\t\t},\n\t\t\tdraft.orderNumber\n\t\t)\n\t}\n\n\tcreateFromCart(\n\t\tcontext: RepositoryContext,\n\t\tcartReference: CartReference,\n\t\torderNumber?: string\n\t) {\n\t\tconst cart = this._storage.getByResourceIdentifier(\n\t\t\tcontext.projectKey,\n\t\t\tcartReference\n\t\t) as Cart | null\n\t\tif (!cart) {\n\t\t\tthrow new Error('Cannot find cart')\n\t\t}\n\n\t\tconst resource: Order = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\torderNumber,\n\t\t\tcart: cartReference,\n\t\t\torderState: 'Open',\n\t\t\tlineItems: [],\n\t\t\tcustomLineItems: [],\n\t\t\ttotalPrice: cart.totalPrice,\n\t\t\trefusedGifts: [],\n\t\t\torigin: 'Customer',\n\t\t\tsyncInfo: [],\n\t\t\tshippingMode: cart.shippingMode,\n\t\t\tshipping: cart.shipping,\n\t\t\tstore: context.storeKey\n\t\t\t\t? {\n\t\t\t\t\t\tkey: context.storeKey,\n\t\t\t\t\t\ttypeId: 'store',\n\t\t\t\t }\n\t\t\t\t: undefined,\n\t\t\tlastMessageSequenceNumber: 0,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\timport(context: RepositoryContext, draft: OrderImportDraft): Order {\n\t\t// TODO: Check if order with given orderNumber already exists\n\t\tassert(this, 'OrderRepository not valid')\n\t\tconst resource: Order = {\n\t\t\t...getBaseResourceProperties(),\n\n\t\t\tbillingAddress: createAddress(\n\t\t\t\tdraft.billingAddress,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t\tshippingAddress: createAddress(\n\t\t\t\tdraft.shippingAddress,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t\tcustomerEmail: draft.customerEmail,\n\t\t\tlastMessageSequenceNumber: 0,\n\t\t\torderNumber: draft.orderNumber,\n\t\t\torderState: draft.orderState || 'Open',\n\t\t\torigin: draft.origin || 'Customer',\n\t\t\tpaymentState: draft.paymentState,\n\t\t\trefusedGifts: [],\n\t\t\tshippingMode: 'Single',\n\t\t\tshipping: [],\n\n\t\t\tstore: resolveStoreReference(\n\t\t\t\tdraft.store,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t\tsyncInfo: [],\n\n\t\t\tlineItems:\n\t\t\t\tdraft.lineItems?.map((item) =>\n\t\t\t\t\tthis.lineItemFromImportDraft.bind(this)(context, item)\n\t\t\t\t) || [],\n\t\t\tcustomLineItems:\n\t\t\t\tdraft.customLineItems?.map((item) =>\n\t\t\t\t\tthis.customLineItemFromImportDraft.bind(this)(context, item)\n\t\t\t\t) || [],\n\n\t\t\ttotalPrice: createCentPrecisionMoney(draft.totalPrice),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tprivate lineItemFromImportDraft(\n\t\tcontext: RepositoryContext,\n\t\tdraft: LineItemImportDraft\n\t): LineItem {\n\t\tlet product: Product\n\t\tlet variant: ProductVariant | undefined\n\n\t\tif (draft.variant.sku) {\n\t\t\tvariant = {\n\t\t\t\tid: 0,\n\t\t\t\tsku: draft.variant.sku,\n\t\t\t}\n\n\t\t\tconst items = this._storage.query(context.projectKey, 'product', {\n\t\t\t\twhere: [\n\t\t\t\t\t`masterData(current(masterVariant(sku=\"${draft.variant.sku}\"))) or masterData(current(variants(sku=\"${draft.variant.sku}\")))`,\n\t\t\t\t],\n\t\t\t}) as ProductPagedQueryResponse\n\n\t\t\tif (items.count !== 1) {\n\t\t\t\tthrow new CommercetoolsError<GeneralError>({\n\t\t\t\t\tcode: 'General',\n\t\t\t\t\tmessage: `A product containing a variant with SKU '${draft.variant.sku}' not found.`,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tproduct = items.results[0]\n\t\t\tif (product.masterData.current.masterVariant.sku === draft.variant.sku) {\n\t\t\t\tvariant = product.masterData.current.masterVariant\n\t\t\t} else {\n\t\t\t\tvariant = product.masterData.current.variants.find(\n\t\t\t\t\t(v) => v.sku === draft.variant.sku\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!variant) {\n\t\t\t\tthrow new Error('Internal state error')\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new Error('No product found')\n\t\t}\n\n\t\tconst lineItem: LineItem = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t\tdiscountedPricePerQuantity: [],\n\t\t\tlineItemMode: 'Standard',\n\t\t\tname: draft.name,\n\t\t\tprice: createPrice(draft.price),\n\t\t\tpriceMode: 'Platform',\n\t\t\tproductId: product.id,\n\t\t\tproductType: product.productType,\n\t\t\tquantity: draft.quantity,\n\t\t\tstate: draft.state || [],\n\t\t\ttaxRate: draft.taxRate,\n\t\t\ttaxedPricePortions: [],\n\t\t\tperMethodTaxRate: [],\n\t\t\ttotalPrice: createCentPrecisionMoney(draft.price.value),\n\t\t\tvariant: {\n\t\t\t\tid: variant.id,\n\t\t\t\tsku: variant.sku,\n\t\t\t\tprice: createPrice(draft.price),\n\t\t\t},\n\t\t}\n\n\t\treturn lineItem\n\t}\n\n\tprivate customLineItemFromImportDraft(\n\t\tcontext: RepositoryContext,\n\t\tdraft: CustomLineItemDraft\n\t): CustomLineItem {\n\t\tconst lineItem: CustomLineItem = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t\tdiscountedPricePerQuantity: [],\n\t\t\tmoney: createTypedMoney(draft.money),\n\t\t\tname: draft.name,\n\t\t\tquantity: draft.quantity ?? 0,\n\t\t\tperMethodTaxRate: [],\n\t\t\tpriceMode: draft.priceMode,\n\t\t\tslug: draft.slug,\n\t\t\tstate: [],\n\t\t\ttotalPrice: createCentPrecisionMoney(draft.money),\n\t\t}\n\n\t\treturn lineItem\n\t}\n\n\tgetWithOrderNumber(\n\t\tcontext: RepositoryContext,\n\t\torderNumber: string,\n\t\tparams: QueryParams = {}\n\t): Order | undefined {\n\t\tconst result = this._storage.query(context.projectKey, this.getTypeId(), {\n\t\t\t...params,\n\t\t\twhere: [`orderNumber=\"${orderNumber}\"`],\n\t\t})\n\t\tif (result.count === 1) {\n\t\t\treturn result.results[0] as Order\n\t\t}\n\n\t\t// Catch this for now, should be checked when creating/updating\n\t\tif (result.count > 1) {\n\t\t\tthrow new Error('Duplicate order numbers')\n\t\t}\n\n\t\treturn\n\t}\n\n\tactions = {\n\t\taddPayment: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ payment }: OrderAddPaymentAction\n\t\t) => {\n\t\t\tconst resolvedPayment = this._storage.getByResourceIdentifier(\n\t\t\t\tcontext.projectKey,\n\t\t\t\tpayment\n\t\t\t)\n\t\t\tif (!resolvedPayment) {\n\t\t\t\tthrow new Error(`Payment ${payment.id} not found`)\n\t\t\t}\n\n\t\t\tif (!resource.paymentInfo) {\n\t\t\t\tresource.paymentInfo = {\n\t\t\t\t\tpayments: [],\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresource.paymentInfo.payments.push({\n\t\t\t\ttypeId: 'payment',\n\t\t\t\tid: payment.id!,\n\t\t\t})\n\t\t},\n\t\tchangeOrderState: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ orderState }: OrderChangeOrderStateAction\n\t\t) => {\n\t\t\tresource.orderState = orderState\n\t\t},\n\t\tchangePaymentState: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ paymentState }: OrderChangePaymentStateAction\n\t\t) => {\n\t\t\tresource.paymentState = paymentState\n\t\t},\n\t\ttransitionState: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ state }: OrderTransitionStateAction\n\t\t) => {\n\t\t\tconst resolvedType = this._storage.getByResourceIdentifier(\n\t\t\t\tcontext.projectKey,\n\t\t\t\tstate\n\t\t\t) as State | null\n\n\t\t\tif (!resolvedType) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No state found with key=${state.key} or id=${state.key}`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tresource.state = {\n\t\t\t\ttypeId: 'state',\n\t\t\t\tid: resolvedType.id,\n\t\t\t\tobj: { ...resolvedType, key: state.key ?? '' },\n\t\t\t}\n\t\t},\n\t\tsetBillingAddress: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ address }: OrderSetBillingAddressAction\n\t\t) => {\n\t\t\tresource.billingAddress = createAddress(\n\t\t\t\taddress,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t)\n\t\t},\n\t\tsetCustomerEmail: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ email }: OrderSetCustomerEmailAction\n\t\t) => {\n\t\t\tresource.customerEmail = email\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Order,\n\t\t\t{ name, value }: OrderSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\tthrow new Error('Resource has no custom field')\n\t\t\t}\n\t\t\tresource.custom.fields[name] = value\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ type, fields }: OrderSetCustomTypeAction\n\t\t) => {\n\t\t\tif (!type) {\n\t\t\t\tresource.custom = undefined\n\t\t\t} else {\n\t\t\t\tconst resolvedType = this._storage.getByResourceIdentifier(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\ttype\n\t\t\t\t)\n\t\t\t\tif (!resolvedType) {\n\t\t\t\t\tthrow new Error(`Type ${type} not found`)\n\t\t\t\t}\n\n\t\t\t\tresource.custom = {\n\t\t\t\t\ttype: {\n\t\t\t\t\t\ttypeId: 'type',\n\t\t\t\t\t\tid: resolvedType.id,\n\t\t\t\t\t},\n\t\t\t\t\tfields: fields || {},\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tsetLocale: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ locale }: OrderSetLocaleAction\n\t\t) => {\n\t\t\tresource.locale = locale\n\t\t},\n\t\tsetOrderNumber: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ orderNumber }: OrderSetOrderNumberAction\n\t\t) => {\n\t\t\tresource.orderNumber = orderNumber\n\t\t},\n\t\tsetShippingAddress: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ address }: OrderSetShippingAddressAction\n\t\t) => {\n\t\t\tresource.shippingAddress = createAddress(\n\t\t\t\taddress,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t)\n\t\t},\n\t\tsetStore: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Order>,\n\t\t\t{ store }: OrderSetStoreAction\n\t\t) => {\n\t\t\tif (!store) return\n\t\t\tconst resolvedType = this._storage.getByResourceIdentifier(\n\t\t\t\tcontext.projectKey,\n\t\t\t\tstore\n\t\t\t)\n\t\t\tif (!resolvedType) {\n\t\t\t\tthrow new Error(`No store found with key=${store.key}`)\n\t\t\t}\n\n\t\t\tconst storeReference = resolvedType as Store\n\t\t\tresource.store = {\n\t\t\t\ttypeId: 'store',\n\t\t\t\tkey: storeReference.key,\n\t\t\t}\n\t\t},\n\t}\n}\n","import type {\n\tOrderEdit,\n\tOrderEditDraft,\n\tOrderEditResult,\n\tOrderEditUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class OrderEditRepository extends AbstractResourceRepository<'order-edit'> {\n\tgetTypeId() {\n\t\treturn 'order-edit' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: OrderEditDraft): OrderEdit {\n\t\tconst resource: OrderEdit = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tstagedActions: draft.stagedActions ?? [],\n\t\t\tresource: draft.resource,\n\t\t\tresult: {\n\t\t\t\ttype: 'NotProcessed',\n\t\t\t} as OrderEditResult,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tOrderEditUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<OrderEdit>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {}\n}\n","import type {\n\tPayment,\n\tPaymentAddTransactionAction,\n\tPaymentChangeTransactionStateAction,\n\tPaymentDraft,\n\tPaymentSetCustomFieldAction,\n\tPaymentSetCustomTypeAction,\n\tPaymentTransitionStateAction,\n\tState,\n\tStateReference,\n\tTransaction,\n\tTransactionDraft,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n\tcreateCentPrecisionMoney,\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from './helpers.js'\n\nexport class PaymentRepository extends AbstractResourceRepository<'payment'> {\n\tgetTypeId() {\n\t\treturn 'payment' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: PaymentDraft): Payment {\n\t\tconst resource: Payment = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tamountPlanned: createCentPrecisionMoney(draft.amountPlanned),\n\t\t\tpaymentMethodInfo: draft.paymentMethodInfo!,\n\t\t\tpaymentStatus: draft.paymentStatus\n\t\t\t\t? {\n\t\t\t\t\t\t...draft.paymentStatus,\n\t\t\t\t\t\tstate: draft.paymentStatus.state\n\t\t\t\t\t\t\t? getReferenceFromResourceIdentifier<StateReference>(\n\t\t\t\t\t\t\t\t\tdraft.paymentStatus.state,\n\t\t\t\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\t\t\t\tthis._storage\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t }\n\t\t\t\t: {},\n\t\t\ttransactions: (draft.transactions || []).map((t) =>\n\t\t\t\tthis.transactionFromTransactionDraft(t, context)\n\t\t\t),\n\t\t\tinterfaceInteractions: (draft.interfaceInteractions || []).map(\n\t\t\t\t(interaction) =>\n\t\t\t\t\tcreateCustomFields(interaction, context.projectKey, this._storage)!\n\t\t\t),\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\ttransactionFromTransactionDraft = (\n\t\tdraft: TransactionDraft,\n\t\tcontext: RepositoryContext\n\t): Transaction => ({\n\t\t...draft,\n\t\tid: uuidv4(),\n\t\tamount: createCentPrecisionMoney(draft.amount),\n\t\tcustom: createCustomFields(draft.custom, context.projectKey, this._storage),\n\t\tstate: draft.state ?? 'Initial', // Documented as default\n\t})\n\n\tactions = {\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Payment,\n\t\t\t{ name, value }: PaymentSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\tthrow new Error('Resource has no custom field')\n\t\t\t}\n\n\t\t\tresource.custom.fields[name] = value\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Payment>,\n\t\t\t{ type, fields }: PaymentSetCustomTypeAction\n\t\t) => {\n\t\t\tif (!type) {\n\t\t\t\tresource.custom = undefined\n\t\t\t} else {\n\t\t\t\tconst resolvedType = this._storage.getByResourceIdentifier(\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\ttype\n\t\t\t\t)\n\t\t\t\tif (!resolvedType) {\n\t\t\t\t\tthrow new Error(`Type ${type} not found`)\n\t\t\t\t}\n\n\t\t\t\tresource.custom = {\n\t\t\t\t\ttype: {\n\t\t\t\t\t\ttypeId: 'type',\n\t\t\t\t\t\tid: resolvedType.id,\n\t\t\t\t\t},\n\t\t\t\t\tfields: fields ?? {},\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\taddTransaction: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Payment>,\n\t\t\t{ transaction }: PaymentAddTransactionAction\n\t\t) => {\n\t\t\tresource.transactions = [\n\t\t\t\t...resource.transactions,\n\t\t\t\tthis.transactionFromTransactionDraft(transaction, context),\n\t\t\t]\n\t\t},\n\t\tchangeTransactionState: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<Payment>,\n\t\t\t{ transactionId, state }: PaymentChangeTransactionStateAction\n\t\t) => {\n\t\t\tconst index = resource.transactions.findIndex(\n\t\t\t\t(e: Transaction) => e.id === transactionId\n\t\t\t)\n\t\t\tconst updatedTransaction: Transaction = {\n\t\t\t\t...resource.transactions[index],\n\t\t\t\tstate,\n\t\t\t}\n\t\t\tresource.transactions[index] = updatedTransaction\n\t\t},\n\t\ttransitionState: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Payment>,\n\t\t\t{ state }: PaymentTransitionStateAction\n\t\t) => {\n\t\t\tconst stateObj = this._storage.getByResourceIdentifier(\n\t\t\t\tcontext.projectKey,\n\t\t\t\tstate\n\t\t\t) as State | null\n\n\t\t\tif (!stateObj) {\n\t\t\t\tthrow new Error(`State ${state} not found`)\n\t\t\t}\n\n\t\t\tresource.paymentStatus.state = {\n\t\t\t\ttypeId: 'state',\n\t\t\t\tid: stateObj.id,\n\t\t\t\tobj: stateObj,\n\t\t\t}\n\t\t},\n\t\t// addInterfaceInteraction: () => {},\n\t\t// changeAmountPlanned: () => {},\n\t\t// changeTransactionInteractionId: () => {},\n\t\t// changeTransactionTimestamp: () => {},\n\t\t// setAmountPaid: () => {},\n\t\t// setAmountRefunded: () => {},\n\t\t// setAnonymousId: () => {},\n\t\t// setAuthorization: () => {},\n\t\t// setCustomer: () => {},\n\t\t// setExternalId: () => {},\n\t\t// setInterfaceId: () => {},\n\t\t// setKey: () => {},\n\t\t// setMethodInfoInterface: () => {},\n\t\t// setMethodInfoMethod: () => {},\n\t\t// setMethodInfoName: () => {},\n\t\t// setStatusInterfaceCode: () => {},\n\t\t// setStatusInterfaceText: () => {},\n\t}\n}\n","import type {\n\tPrice,\n\tPriceDraft,\n\tProduct,\n\tProductData,\n\tProductDraft,\n\tProductPublishAction,\n\tProductSetAttributeAction,\n\tProductSetDescriptionAction,\n\tProductAddExternalImageAction,\n\tProductRemoveImageAction,\n\tProductSetKeyAction,\n\tProductTypeReference,\n\tProductUpdateAction,\n\tProductVariant,\n\tProductVariantDraft,\n\tProductMoveImageToPositionAction,\n\tProductChangePriceAction,\n\tProductAddPriceAction,\n\tProductRemovePriceAction,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport type { Writable } from '../types.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n\tcreateTypedMoney,\n\tgetReferenceFromResourceIdentifier,\n} from './helpers.js'\nimport deepEqual from 'deep-equal'\n\nexport class ProductRepository extends AbstractResourceRepository<'product'> {\n\tgetTypeId() {\n\t\treturn 'product' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: ProductDraft): Product {\n\t\tif (!draft.masterVariant) {\n\t\t\tthrow new Error('Missing master variant')\n\t\t}\n\n\t\tlet productType: ProductTypeReference | undefined = undefined\n\t\ttry {\n\t\t\tproductType = getReferenceFromResourceIdentifier<ProductTypeReference>(\n\t\t\t\tdraft.productType,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t)\n\t\t} catch (err) {\n\t\t\t// For now accept missing product types (but warn)\n\t\t\tconsole.warn(\n\t\t\t\t`Error resolving product-type '${draft.productType.id}'. This will be throw an error in later releases.`\n\t\t\t)\n\t\t\tproductType = {\n\t\t\t\ttypeId: 'product-type',\n\t\t\t\tid: draft.productType.id || '',\n\t\t\t}\n\t\t}\n\n\t\tconst productData: ProductData = {\n\t\t\tname: draft.name,\n\t\t\tslug: draft.slug,\n\t\t\tcategories: [],\n\t\t\tmasterVariant: variantFromDraft(1, draft.masterVariant),\n\t\t\tvariants:\n\t\t\t\tdraft.variants?.map((variant, index) =>\n\t\t\t\t\tvariantFromDraft(index + 2, variant)\n\t\t\t\t) ?? [],\n\n\t\t\tsearchKeywords: draft.searchKeywords ?? {},\n\t\t}\n\n\t\tconst resource: Product = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tproductType: productType,\n\t\t\tmasterData: {\n\t\t\t\tcurrent: productData,\n\t\t\t\tstaged: productData,\n\t\t\t\thasStagedChanges: false,\n\t\t\t\tpublished: draft.publish ?? false,\n\t\t\t},\n\t\t}\n\n\t\tthis.saveNew(context, resource)\n\n\t\treturn resource\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tProductUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Product>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tpublish: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ scope }: ProductPublishAction\n\t\t) => {\n\t\t\tresource.masterData.current = resource.masterData.staged\n\t\t\tresource.masterData.published = true\n\t\t\tcheckForStagedChanges(resource)\n\t\t},\n\t\tunpublish: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>\n\t\t\t// { action }: ProductUnpublishAction\n\t\t) => {\n\t\t\tresource.masterData.published = false\n\t\t\tcheckForStagedChanges(resource)\n\t\t},\n\t\tsetAttribute: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ variantId, sku, name, value, staged }: ProductSetAttributeAction\n\t\t) => {\n\t\t\tconst setAttr = (data: Writable<ProductData>) => {\n\t\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\t\tdata,\n\t\t\t\t\tvariantId,\n\t\t\t\t\tsku\n\t\t\t\t)\n\t\t\t\tif (!variant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (!variant.attributes) {\n\t\t\t\t\tvariant.attributes = []\n\t\t\t\t}\n\n\t\t\t\tconst existingAttr = variant.attributes.find(\n\t\t\t\t\t(attr) => attr.name === name\n\t\t\t\t)\n\t\t\t\tif (existingAttr) {\n\t\t\t\t\texistingAttr.value = value\n\t\t\t\t} else {\n\t\t\t\t\tvariant.attributes.push({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (isMasterVariant) {\n\t\t\t\t\tdata.masterVariant = variant\n\t\t\t\t} else {\n\t\t\t\t\tdata.variants[variantIndex] = variant\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t\t// staged Attribute is set. Default is true\n\t\t\tconst onlyStaged = staged !== undefined ? staged : true\n\n\t\t\t// Write the attribute to the staged data\n\t\t\tsetAttr(resource.masterData.staged)\n\n\t\t\t// Also write to published data is isStaged = false\n\t\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t\t// published data.\n\t\t\tif (!onlyStaged) {\n\t\t\t\tsetAttr(resource.masterData.current)\n\t\t\t}\n\t\t\tcheckForStagedChanges(resource)\n\n\t\t\treturn resource\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ description, staged }: ProductSetDescriptionAction\n\t\t) => {\n\t\t\tconst onlyStaged = staged !== undefined ? staged : true\n\n\t\t\tresource.masterData.staged.description = description\n\t\t\tif (!onlyStaged) {\n\t\t\t\tresource.masterData.current.description = description\n\t\t\t}\n\t\t\tcheckForStagedChanges(resource)\n\t\t\treturn resource\n\t\t},\n\t\tsetKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ key }: ProductSetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t\treturn resource\n\t\t},\n\t\taddExternalImage: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ variantId, sku, image, staged }: ProductAddExternalImageAction\n\t\t) => {\n\t\t\tconst addImg = (data: Writable<ProductData>) => {\n\t\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\t\tdata,\n\t\t\t\t\tvariantId,\n\t\t\t\t\tsku\n\t\t\t\t)\n\t\t\t\tif (!variant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (!variant.images) {\n\t\t\t\t\tvariant.images = []\n\t\t\t\t} else {\n\t\t\t\t\tconst existingImage = variant.images.find((x) => x.url === image.url)\n\t\t\t\t\tif (existingImage) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Cannot add image '${image.url}' because product '${resource.id}' already has that image.`\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Add image\n\t\t\t\tvariant.images.push(image)\n\n\t\t\t\tif (isMasterVariant) {\n\t\t\t\t\tdata.masterVariant = variant\n\t\t\t\t} else {\n\t\t\t\t\tdata.variants[variantIndex] = variant\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t\t// staged Attribute is set. Default is true\n\t\t\tconst onlyStaged = staged !== undefined ? staged : true\n\n\t\t\t// Write the attribute to the staged data\n\t\t\taddImg(resource.masterData.staged)\n\n\t\t\t// Also write to published data is isStaged = false\n\t\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t\t// published data.\n\t\t\tif (!onlyStaged) {\n\t\t\t\taddImg(resource.masterData.current)\n\t\t\t}\n\t\t\tcheckForStagedChanges(resource)\n\n\t\t\treturn resource\n\t\t},\n\t\tremoveImage: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ variantId, sku, imageUrl, staged }: ProductRemoveImageAction\n\t\t) => {\n\t\t\tconst removeImg = (data: Writable<ProductData>) => {\n\t\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\t\tdata,\n\t\t\t\t\tvariantId,\n\t\t\t\t\tsku\n\t\t\t\t)\n\t\t\t\tif (!variant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tconst variantImages = variant.images ?? []\n\t\t\t\tconst existingImage = variantImages.find((x) => x.url === imageUrl)\n\t\t\t\tif (!existingImage) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Cannot remove image '${imageUrl}' because product '${resource.id}' does not have that image.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// Remove image\n\t\t\t\tvariant.images = variantImages.filter((image) => image.url !== imageUrl)\n\n\t\t\t\tif (isMasterVariant) {\n\t\t\t\t\tdata.masterVariant = variant\n\t\t\t\t} else {\n\t\t\t\t\tdata.variants[variantIndex] = variant\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t\t// staged Attribute is set. Default is true\n\t\t\tconst onlyStaged = staged !== undefined ? staged : true\n\n\t\t\t// Write the attribute to the staged data\n\t\t\tremoveImg(resource.masterData.staged)\n\n\t\t\t// Also write to published data is isStaged = false\n\t\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t\t// published data.\n\t\t\tif (!onlyStaged) {\n\t\t\t\tremoveImg(resource.masterData.current)\n\t\t\t}\n\t\t\tcheckForStagedChanges(resource)\n\n\t\t\treturn resource\n\t\t},\n\t\tmoveImageToPosition: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{\n\t\t\t\tvariantId,\n\t\t\t\tsku,\n\t\t\t\timageUrl,\n\t\t\t\tposition,\n\t\t\t\tstaged,\n\t\t\t}: ProductMoveImageToPositionAction\n\t\t) => {\n\t\t\tconst moveImg = (data: Writable<ProductData>) => {\n\t\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\t\tdata,\n\t\t\t\t\tvariantId,\n\t\t\t\t\tsku\n\t\t\t\t)\n\t\t\t\tif (!variant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tconst variantImages = variant.images ?? []\n\t\t\t\tconst existingImage = variantImages.find((x) => x.url === imageUrl)\n\t\t\t\tif (!existingImage) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Cannot move image '${imageUrl}' because product '${resource.id}' does not have that image.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (position >= variantImages.length) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Invalid position given. Position in images where the image should be moved. Must be between 0 and the total number of images minus 1.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// Remove image\n\t\t\t\tvariant.images = variantImages.filter((image) => image.url !== imageUrl)\n\n\t\t\t\t// Re-add image to the correct position\n\t\t\t\tvariant.images.splice(position, 0, existingImage)\n\n\t\t\t\tif (isMasterVariant) {\n\t\t\t\t\tdata.masterVariant = variant\n\t\t\t\t} else {\n\t\t\t\t\tdata.variants[variantIndex] = variant\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t\t// staged Attribute is set. Default is true\n\t\t\tconst onlyStaged = staged !== undefined ? staged : true\n\n\t\t\t// Write the attribute to the staged data\n\t\t\tmoveImg(resource.masterData.staged)\n\n\t\t\t// Also write to published data is isStaged = false\n\t\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t\t// published data.\n\t\t\tif (!onlyStaged) {\n\t\t\t\tmoveImg(resource.masterData.current)\n\t\t\t}\n\t\t\tcheckForStagedChanges(resource)\n\n\t\t\treturn resource\n\t\t},\n\n\t\taddPrice: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ variantId, sku, price, staged }: ProductAddPriceAction\n\t\t) => {\n\t\t\tconst addVariantPrice = (data: Writable<ProductData>) => {\n\t\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\t\tdata,\n\t\t\t\t\tvariantId,\n\t\t\t\t\tsku\n\t\t\t\t)\n\t\t\t\tif (!variant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif (variant.prices === undefined) {\n\t\t\t\t\tvariant.prices = [priceFromDraft(price)]\n\t\t\t\t} else {\n\t\t\t\t\tvariant.prices.push(priceFromDraft(price))\n\t\t\t\t}\n\n\t\t\t\tif (isMasterVariant) {\n\t\t\t\t\tdata.masterVariant = variant\n\t\t\t\t} else {\n\t\t\t\t\tdata.variants[variantIndex] = variant\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t\t// staged Attribute is set. Default is true\n\t\t\tconst onlyStaged = staged !== undefined ? staged : true\n\n\t\t\t// Write the attribute to the staged data\n\t\t\taddVariantPrice(resource.masterData.staged)\n\n\t\t\t// Also write to published data is isStaged = false\n\t\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t\t// published data.\n\t\t\tif (!onlyStaged) {\n\t\t\t\taddVariantPrice(resource.masterData.current)\n\t\t\t}\n\t\t\tcheckForStagedChanges(resource)\n\n\t\t\treturn resource\n\t\t},\n\t\tchangePrice: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ priceId, price, staged }: ProductChangePriceAction\n\t\t) => {\n\t\t\tconst changeVariantPrice = (data: Writable<ProductData>) => {\n\t\t\t\tconst allVariants = [data.masterVariant, ...(data.variants ?? [])]\n\t\t\t\tconst priceVariant = allVariants.find(\n\t\t\t\t\t(variant) => variant.prices?.some((x) => x.id === priceId)\n\t\t\t\t)\n\t\t\t\tif (!priceVariant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Price with id ${priceId} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\t\tdata,\n\t\t\t\t\tpriceVariant.id,\n\t\t\t\t\tpriceVariant.sku\n\t\t\t\t)\n\t\t\t\tif (!variant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tvariant.prices = variant.prices?.map((x) => {\n\t\t\t\t\tif (x.id === priceId) {\n\t\t\t\t\t\treturn { ...x, ...price } as Price\n\t\t\t\t\t}\n\t\t\t\t\treturn x\n\t\t\t\t})\n\n\t\t\t\tif (isMasterVariant) {\n\t\t\t\t\tdata.masterVariant = variant\n\t\t\t\t} else {\n\t\t\t\t\tdata.variants[variantIndex] = variant\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t\t// staged Attribute is set. Default is true\n\t\t\tconst onlyStaged = staged !== undefined ? staged : true\n\n\t\t\t// Write the attribute to the staged data\n\t\t\tchangeVariantPrice(resource.masterData.staged)\n\n\t\t\t// Also write to published data is isStaged = false\n\t\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t\t// published data.\n\t\t\tif (!onlyStaged) {\n\t\t\t\tchangeVariantPrice(resource.masterData.current)\n\t\t\t}\n\t\t\tcheckForStagedChanges(resource)\n\n\t\t\treturn resource\n\t\t},\n\t\tremovePrice: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Product>,\n\t\t\t{ priceId, staged }: ProductRemovePriceAction\n\t\t) => {\n\t\t\tconst removeVariantPrice = (data: Writable<ProductData>) => {\n\t\t\t\tconst allVariants = [data.masterVariant, ...(data.variants ?? [])]\n\t\t\t\tconst priceVariant = allVariants.find(\n\t\t\t\t\t(variant) => variant.prices?.some((x) => x.id === priceId)\n\t\t\t\t)\n\t\t\t\tif (!priceVariant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Price with id ${priceId} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tconst { variant, isMasterVariant, variantIndex } = getVariant(\n\t\t\t\t\tdata,\n\t\t\t\t\tpriceVariant.id,\n\t\t\t\t\tpriceVariant.sku\n\t\t\t\t)\n\t\t\t\tif (!variant) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Variant with id ${priceVariant.id} or sku ${priceVariant.sku} not found on product ${resource.id}`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tvariant.prices = variant.prices?.filter((x) => x.id !== priceId)\n\n\t\t\t\tif (isMasterVariant) {\n\t\t\t\t\tdata.masterVariant = variant\n\t\t\t\t} else {\n\t\t\t\t\tdata.variants[variantIndex] = variant\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If true, only the staged Attribute is set. If false, both current and\n\t\t\t// staged Attribute is set. Default is true\n\t\t\tconst onlyStaged = staged !== undefined ? staged : true\n\n\t\t\t// Write the attribute to the staged data\n\t\t\tremoveVariantPrice(resource.masterData.staged)\n\n\t\t\t// Also write to published data is isStaged = false\n\t\t\t// if isStaged is false we set the attribute on both the staged and\n\t\t\t// published data.\n\t\t\tif (!onlyStaged) {\n\t\t\t\tremoveVariantPrice(resource.masterData.current)\n\t\t\t}\n\t\t\tcheckForStagedChanges(resource)\n\n\t\t\treturn resource\n\t\t},\n\n\t\t// 'changeName': () => {},\n\t\t// 'changeSlug': () => {},\n\t\t// 'addVariant': () => {},\n\t\t// 'removeVariant': () => {},\n\t\t// 'changeMasterVariant': () => {},\n\t\t// 'setPrices': () => {},\n\t\t// 'setProductPriceCustomType': () => {},\n\t\t// 'setProductPriceCustomField': () => {},\n\t\t// 'setDiscountedPrice': () => {},\n\t\t// 'setAttributeInAllVariants': () => {},\n\t\t// 'addToCategory': () => {},\n\t\t// 'setCategoryOrderHint': () => {},\n\t\t// 'removeFromCategory': () => {},\n\t\t// 'setTaxCategory': () => {},\n\t\t// 'setSku': () => {},\n\t\t// 'setProductVariantKey': () => {},\n\t\t// 'setImageLabel': () => {},\n\t\t// 'addAsset': () => {},\n\t\t// 'removeAsset': () => {},\n\t\t// 'setAssetKey': () => {},\n\t\t// 'changeAssetOrder': () => {},\n\t\t// 'changeAssetName': () => {},\n\t\t// 'setAssetDescription': () => {},\n\t\t// 'setAssetTags': () => {},\n\t\t// 'setAssetSources': () => {},\n\t\t// 'setAssetCustomType': () => {},\n\t\t// 'setAssetCustomField': () => {},\n\t\t// 'setSearchKeywords': () => {},\n\t\t// 'setMetaTitle': () => {},\n\t\t// 'setMetaDescription': () => {},\n\t\t// 'setMetaKeywords': () => {},\n\t\t// 'revertStagedChanges': () => {},\n\t\t// 'revertStagedVariantChanges': () => {},\n\t\t// 'transitionState': () => {},\n\t}\n}\n\n// Check if the product still has staged data that is different from the\n// current data.\nconst checkForStagedChanges = (product: Writable<Product>) => {\n\tif (!product.masterData.staged) {\n\t\tproduct.masterData.staged = product.masterData.current\n\t}\n\n\tif (deepEqual(product.masterData.current, product.masterData.staged)) {\n\t\tproduct.masterData.hasStagedChanges = false\n\t} else {\n\t\tproduct.masterData.hasStagedChanges = true\n\t}\n}\n\ninterface VariantResult {\n\tvariant: Writable<ProductVariant> | undefined\n\tisMasterVariant: boolean\n\tvariantIndex: number\n}\n\nconst getVariant = (\n\tproductData: ProductData,\n\tvariantId?: number,\n\tsku?: string\n): VariantResult => {\n\tconst variants = [productData.masterVariant, ...productData.variants]\n\tconst foundVariant = variants.find((variant: ProductVariant) => {\n\t\tif (variantId) {\n\t\t\treturn variant.id === variantId\n\t\t}\n\t\tif (sku) {\n\t\t\treturn variant.sku === sku\n\t\t}\n\t\treturn false\n\t})\n\n\tconst isMasterVariant = foundVariant === productData.masterVariant\n\treturn {\n\t\tvariant: foundVariant,\n\t\tisMasterVariant,\n\t\tvariantIndex:\n\t\t\t!isMasterVariant && foundVariant\n\t\t\t\t? productData.variants.indexOf(foundVariant)\n\t\t\t\t: -1,\n\t}\n}\n\nconst variantFromDraft = (\n\tvariantId: number,\n\tvariant: ProductVariantDraft\n): ProductVariant => ({\n\tid: variantId,\n\tsku: variant?.sku,\n\tattributes: variant?.attributes ?? [],\n\tprices: variant?.prices?.map(priceFromDraft),\n\tassets: [],\n\timages: [],\n})\n\nconst priceFromDraft = (draft: PriceDraft): Price => ({\n\tid: uuidv4(),\n\tcountry: draft.country,\n\tvalue: createTypedMoney(draft.value),\n})\n","import type {\n\tProductDiscount,\n\tProductDiscountChangeIsActiveAction,\n\tProductDiscountChangeNameAction,\n\tProductDiscountChangePredicateAction,\n\tProductDiscountChangeSortOrderAction,\n\tProductDiscountChangeValueAction,\n\tProductDiscountDraft,\n\tProductDiscountSetDescriptionAction,\n\tProductDiscountSetKeyAction,\n\tProductDiscountSetValidFromAction,\n\tProductDiscountSetValidFromAndUntilAction,\n\tProductDiscountSetValidUntilAction,\n\tProductDiscountUpdateAction,\n\tProductDiscountValue,\n\tProductDiscountValueAbsolute,\n\tProductDiscountValueDraft,\n\tProductDiscountValueExternal,\n\tProductDiscountValueRelative,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport { createTypedMoney } from './helpers.js'\n\nexport class ProductDiscountRepository extends AbstractResourceRepository<'product-discount'> {\n\tgetTypeId() {\n\t\treturn 'product-discount' as const\n\t}\n\n\tcreate(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ProductDiscountDraft\n\t): ProductDiscount {\n\t\tconst resource: ProductDiscount = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\tvalue: this.transformValueDraft(draft.value),\n\t\t\tpredicate: draft.predicate,\n\t\t\tsortOrder: draft.sortOrder,\n\t\t\tisActive: draft.isActive || false,\n\t\t\tvalidFrom: draft.validFrom,\n\t\t\tvalidUntil: draft.validUntil,\n\t\t\treferences: [],\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tprivate transformValueDraft(\n\t\tvalue: ProductDiscountValueDraft\n\t): ProductDiscountValue {\n\t\tswitch (value.type) {\n\t\t\tcase 'absolute': {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'absolute',\n\t\t\t\t\tmoney: value.money.map(createTypedMoney),\n\t\t\t\t} as ProductDiscountValueAbsolute\n\t\t\t}\n\t\t\tcase 'external': {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'external',\n\t\t\t\t} as ProductDiscountValueExternal\n\t\t\t}\n\t\t\tcase 'relative': {\n\t\t\t\treturn {\n\t\t\t\t\t...value,\n\t\t\t\t} as ProductDiscountValueRelative\n\t\t\t}\n\t\t}\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tProductDiscountUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tsetKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ key }: ProductDiscountSetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ description }: ProductDiscountSetDescriptionAction\n\t\t) => {\n\t\t\tif (description && Object.keys(description).length > 0) {\n\t\t\t\tresource.description = description\n\t\t\t} else {\n\t\t\t\tresource.description = undefined\n\t\t\t}\n\t\t},\n\t\tchangeName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ name }: ProductDiscountChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tchangeValue: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ value }: ProductDiscountChangeValueAction\n\t\t) => {\n\t\t\tresource.value = this.transformValueDraft(value)\n\t\t},\n\t\tchangePredicate: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ predicate }: ProductDiscountChangePredicateAction\n\t\t) => {\n\t\t\tresource.predicate = predicate\n\t\t},\n\t\tchangeSortOrder: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ sortOrder }: ProductDiscountChangeSortOrderAction\n\t\t) => {\n\t\t\tresource.sortOrder = sortOrder\n\t\t},\n\t\tchangeIsActive: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ isActive }: ProductDiscountChangeIsActiveAction\n\t\t) => {\n\t\t\tresource.isActive = isActive\n\t\t},\n\t\tsetValidFrom: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ validFrom }: ProductDiscountSetValidFromAction\n\t\t) => {\n\t\t\tresource.validFrom = validFrom\n\t\t},\n\t\tsetValidUntil: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ validUntil }: ProductDiscountSetValidUntilAction\n\t\t) => {\n\t\t\tresource.validUntil = validUntil\n\t\t},\n\t\tsetValidFromAndUntil: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductDiscount>,\n\t\t\t{ validFrom, validUntil }: ProductDiscountSetValidFromAndUntilAction\n\t\t) => {\n\t\t\tresource.validFrom = validFrom\n\t\t\tresource.validUntil = validUntil\n\t\t},\n\t}\n}\n","/**\n * This module implements the commercetools product projection filter expression.\n */\n\nimport type {\n\tProductProjection,\n\tProductVariant,\n} from '@commercetools/platform-sdk'\nimport { nestedLookup } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { Lexer, Parser } from './parser.js'\n\ntype MatchFunc = (target: any) => boolean\n\ntype ProductProjectionFilter = (\n\tp: Writable<ProductProjection>,\n\tmarkMatchingVariants: boolean\n) => boolean\n\ntype TypeSymbol = {\n\ttype: 'Symbol'\n\tkind: 'int' | 'string' | 'any'\n\tvalue: any\n}\n\ntype RangeExpressionSet = {\n\tsource: string\n\ttype: 'RangeExpression'\n\tchildren?: RangeExpression[]\n}\n\ntype FilterExpressionSet = {\n\tsource: string\n\ttype: 'FilterExpression'\n\tchildren?: FilterExpression[]\n}\n\ntype TermExpressionSet = {\n\tsource: string\n\ttype: 'TermExpression'\n}\n\ntype ExpressionSet =\n\t| RangeExpressionSet\n\t| FilterExpressionSet\n\t| TermExpressionSet\n\nexport type RangeExpression = {\n\ttype: 'RangeExpression'\n\tstart?: number\n\tstop?: number\n\tmatch: (obj: any) => boolean\n}\n\nexport type FilterExpression = {\n\ttype: 'FilterExpression'\n\tmatch: (obj: any) => boolean\n}\n\n/**\n * Returns a function (ProductProjectionFilter).\n * NOTE: The filter can alter the resources in-place (FIXME)\n */\nexport const parseFilterExpression = (\n\tfilter: string\n): ProductProjectionFilter => {\n\tconst exprFunc = generateMatchFunc(filter)\n\tconst [source] = filter.split(':', 1)\n\n\tif (source.startsWith('variants.')) {\n\t\treturn filterVariants(source, exprFunc)\n\t}\n\treturn filterProduct(source, exprFunc)\n}\n\nconst getLexer = (value: string) =>\n\tnew Lexer(value)\n\t\t.token('MISSING', /missing(?![-_a-z0-9]+)/i)\n\t\t.token('EXISTS', /exists(?![-_a-z0-9]+)/i)\n\t\t.token('RANGE', /range(?![-_a-z0-9]+)/i)\n\t\t.token('TO', /to(?![-_a-z0-9]+)/i)\n\t\t.token('IDENTIFIER', /[-_.a-z]+/i)\n\n\t\t.token('FLOAT', /\\d+\\.\\d+/)\n\t\t.token('INT', /\\d+/)\n\t\t.token('STRING', /\"((?:\\\\.|[^\"\\\\])*)\"/)\n\t\t.token('STRING', /'((?:\\\\.|[^'\\\\])*)'/)\n\n\t\t.token('COMMA', ',')\n\t\t.token('STAR', '*')\n\t\t.token('(', '(')\n\t\t.token(':', ':')\n\t\t.token(')', ')')\n\t\t.token('\"', '\"')\n\t\t.token('WS', /\\s+/, true) // skip\n\nconst parseFilter = (filter: string): ExpressionSet => {\n\tconst lexer = getLexer(filter)\n\tconst parser = new Parser(lexer)\n\t\t.builder()\n\t\t.nud('IDENTIFIER', 100, (t) => t.token.match)\n\t\t.led(':', 100, ({ left, bp }) => {\n\t\t\tconst parsed: any = parser.parse({ terminals: [bp - 1] })\n\t\t\tconst expressions: RangeExpression[] | FilterExpression[] | TypeSymbol[] =\n\t\t\t\t!Array.isArray(parsed) ? [parsed] : parsed\n\n\t\t\t// Make sure we only have one type of expression (cannot mix)\n\t\t\tconst unique = new Set(expressions.map((expr) => expr.type))\n\t\t\tif (unique.size > 1) {\n\t\t\t\tthrow new Error('Invalid expression')\n\t\t\t}\n\n\t\t\t// Convert plain symbols to a filter expression. For example\n\t\t\t// variants.attribute.foobar:4 where 4 is a Symbol should result\n\t\t\t// in a comparison\n\t\t\tif (expressions.some((expr) => expr.type == 'Symbol')) {\n\t\t\t\treturn {\n\t\t\t\t\tsource: left as string,\n\t\t\t\t\ttype: 'FilterExpression',\n\t\t\t\t\tchildren: expressions.map((e): FilterExpression => {\n\t\t\t\t\t\tif (e.type != 'Symbol') {\n\t\t\t\t\t\t\tthrow new Error('Invalid expression')\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: 'FilterExpression',\n\t\t\t\t\t\t\tmatch: (obj: any): boolean => obj === e.value,\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tsource: left,\n\t\t\t\ttype: expressions[0].type,\n\t\t\t\tchildren: expressions,\n\t\t\t}\n\t\t})\n\t\t.nud(\n\t\t\t'STRING',\n\t\t\t20,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'Symbol',\n\t\t\t\t\tkind: 'string',\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tvalue: t.token.groups[1],\n\t\t\t\t}) as TypeSymbol\n\t\t)\n\t\t.nud(\n\t\t\t'INT',\n\t\t\t5,\n\t\t\t(t) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'Symbol',\n\t\t\t\t\tkind: 'int',\n\t\t\t\t\tvalue: parseInt(t.token.match, 10),\n\t\t\t\t}) as TypeSymbol\n\t\t)\n\t\t.nud('STAR', 5, (_) => ({\n\t\t\ttype: 'Symbol',\n\t\t\tkind: 'any',\n\t\t\tvalue: null,\n\t\t}))\n\t\t.nud(\n\t\t\t'EXISTS',\n\t\t\t10,\n\t\t\t({ bp }) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'FilterExpression',\n\t\t\t\t\tmatch: (obj: any): boolean => obj !== undefined,\n\t\t\t\t}) as FilterExpression\n\t\t)\n\t\t.nud(\n\t\t\t'MISSING',\n\t\t\t10,\n\t\t\t({ bp }) =>\n\t\t\t\t({\n\t\t\t\t\ttype: 'FilterExpression',\n\t\t\t\t\tmatch: (obj: any): boolean => obj === undefined,\n\t\t\t\t}) as FilterExpression\n\t\t)\n\t\t.led('COMMA', 200, ({ left, token, bp }) => {\n\t\t\tconst expr: any = parser.parse({ terminals: [bp - 1] })\n\t\t\tif (Array.isArray(expr)) {\n\t\t\t\treturn [left, ...expr]\n\t\t\t} else {\n\t\t\t\treturn [left, expr]\n\t\t\t}\n\t\t})\n\t\t.nud('(', 100, (t) => {\n\t\t\tconst expr: any = parser.parse({ terminals: [')'] })\n\t\t\tlexer.expect(')')\n\t\t\treturn expr\n\t\t})\n\t\t.bp(')', 0)\n\t\t.led('TO', 20, ({ left, bp }) => {\n\t\t\tconst expr: any = parser.parse({ terminals: [bp - 1] })\n\t\t\treturn {\n\t\t\t\tstart: left.value,\n\t\t\t\tstop: expr.value,\n\t\t\t}\n\t\t})\n\t\t.nud('RANGE', 20, ({ bp }) => {\n\t\t\tlet ranges: any = parser.parse()\n\n\t\t\t// If multiple ranges are defined we receive an array of ranges. So let's\n\t\t\t// make sure we always have an array\n\t\t\tif (!Array.isArray(ranges)) {\n\t\t\t\tranges = [ranges]\n\t\t\t}\n\n\t\t\t// Return a list of functions which matches the ranges. These functions\n\t\t\t// are processed as an OR clause\n\t\t\treturn ranges.map((range: any) => {\n\t\t\t\tlet func: (obj: any) => boolean\n\n\t\t\t\tif (range.start !== null && range.stop !== null) {\n\t\t\t\t\tfunc = (obj: any): boolean => obj >= range.start && obj <= range.stop\n\t\t\t\t} else if (range.start === null && range.stop !== null) {\n\t\t\t\t\tfunc = (obj: any): boolean => obj <= range.stop\n\t\t\t\t} else if (range.start !== null && range.stop === null) {\n\t\t\t\t\tfunc = (obj: any): boolean => obj >= range.start\n\t\t\t\t} else {\n\t\t\t\t\tfunc = (obj: any): boolean => true\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'RangeExpression',\n\t\t\t\t\tstart: range.start,\n\t\t\t\t\tstop: range.stop,\n\t\t\t\t\tmatch: func,\n\t\t\t\t} as RangeExpression\n\t\t\t})\n\t\t})\n\t\t.build()\n\n\treturn parser.parse()\n}\n\nconst generateMatchFunc = (filter: string) => {\n\tconst result = parseFilter(filter)\n\tif (!result) {\n\t\t// const lines = filter.split('\\n')\n\t\t// const column = lines[lines.length - 1].length\n\t\tthrow new Error(`Syntax error while parsing '${filter}'.`)\n\t}\n\tif (result.type == 'TermExpression') {\n\t\tthrow new Error(`Syntax error while parsing '${filter}'.`)\n\t}\n\n\treturn (obj: any) => {\n\t\tif (!result.children) return false\n\t\treturn result.children.some((c) => c.match(obj))\n\t}\n}\n\nexport const generateFacetFunc = (filter: string): ExpressionSet => {\n\tif (!filter.includes(':')) {\n\t\treturn {\n\t\t\tsource: filter,\n\t\t\ttype: 'TermExpression',\n\t\t}\n\t}\n\treturn parseFilter(filter)\n}\n\nconst filterProduct =\n\t(source: string, exprFunc: MatchFunc): ProductProjectionFilter =>\n\t(p: ProductProjection, markMatchingVariants: boolean): boolean => {\n\t\tconst value = nestedLookup(p, source)\n\t\treturn exprFunc(value)\n\t}\n\nconst filterVariants =\n\t(source: string, exprFunc: MatchFunc): ProductProjectionFilter =>\n\t(p: ProductProjection, markMatchingVariants: boolean): boolean => {\n\t\tconst [, ...paths] = source.split('.')\n\t\tconst path = paths.join('.')\n\n\t\tconst variants = getVariants(p) as Writable<ProductVariant>[]\n\t\tfor (const variant of variants) {\n\t\t\tconst value = resolveVariantValue(variant, path)\n\n\t\t\tif (exprFunc(value)) {\n\t\t\t\t// If markMatchingVariants parameter is true those ProductVariants that\n\t\t\t\t// match the search query have the additional field isMatchingVariant\n\t\t\t\t// set to true. For the other variants in the same product projection\n\t\t\t\t// this field is set to false.\n\t\t\t\tif (markMatchingVariants) {\n\t\t\t\t\tvariants.forEach((v) => (v.isMatchingVariant = false))\n\t\t\t\t\tvariant.isMatchingVariant = true\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\nexport const resolveVariantValue = (obj: ProductVariant, path: string): any => {\n\tif (path === undefined) {\n\t\treturn obj\n\t}\n\tif (path.startsWith('variants.')) {\n\t\tpath = path.substring(path.indexOf('.') + 1)\n\t}\n\n\tif (path.startsWith('attributes.')) {\n\t\tconst [, attrName, ...rest] = path.split('.')\n\t\tif (!obj.attributes) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tfor (const attr of obj.attributes) {\n\t\t\tif (attr.name === attrName) {\n\t\t\t\treturn nestedLookup(attr.value, rest.join('.'))\n\t\t\t}\n\t\t}\n\t}\n\n\tif (path === 'price.centAmount') {\n\t\treturn obj.prices && obj.prices.length > 0\n\t\t\t? obj.prices[0].value.centAmount\n\t\t\t: undefined\n\t}\n\n\treturn nestedLookup(obj, path)\n}\n\nexport const getVariants = (p: ProductProjection): ProductVariant[] => [\n\tp.masterVariant,\n\t...(p.variants ?? []),\n]\n","import type {\n\tInvalidInputError,\n\tPrice,\n\tProductProjection,\n\tProductVariant,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from './exceptions.js'\nimport type { Writable } from './types.js'\n\nexport type PriceSelector = {\n\tcurrency?: string\n\tcountry?: string\n\tcustomerGroup?: string\n\tchannel?: string\n}\n\n/**\n * Apply the price selector on all the variants. The price selector is applied\n * on all the prices per variant and the first match per variant is stored in\n * the scopedPrice attribute\n */\nexport const applyPriceSelector = (\n\tproducts: ProductProjection[],\n\tselector: PriceSelector\n) => {\n\tvalidatePriceSelector(selector)\n\n\tfor (const product of products) {\n\t\tconst variants: Writable<ProductVariant>[] = [\n\t\t\tproduct.masterVariant,\n\t\t\t...(product.variants ?? []),\n\t\t].filter((x) => x != undefined)\n\n\t\tfor (const variant of variants) {\n\t\t\tconst scopedPrices =\n\t\t\t\tvariant.prices?.filter((p) => priceSelectorFilter(p, selector)) ?? []\n\n\t\t\tif (scopedPrices.length > 0) {\n\t\t\t\tconst price = scopedPrices[0]\n\n\t\t\t\tvariant.scopedPriceDiscounted = false\n\t\t\t\tvariant.scopedPrice = {\n\t\t\t\t\t...price,\n\t\t\t\t\tcurrentValue: price.value,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst validatePriceSelector = (selector: PriceSelector) => {\n\tif (\n\t\t(selector.country || selector.channel || selector.customerGroup) &&\n\t\t!selector.currency\n\t) {\n\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t{\n\t\t\t\tcode: 'InvalidInput',\n\t\t\t\tmessage:\n\t\t\t\t\t'The price selecting parameters country, channel and customerGroup ' +\n\t\t\t\t\t'cannot be used without the currency.',\n\t\t\t},\n\t\t\t400\n\t\t)\n\t}\n}\n\n/**\n * Return a boolean to indicate if the price matches the selector. Price\n * selection requires that if the selector or the price has a specific value\n * then it should match.\n */\nexport const priceSelectorFilter = (\n\tprice: Price,\n\tselector: PriceSelector\n): boolean => {\n\tif (\n\t\t(selector.country || price.country) &&\n\t\tselector.country !== price.country\n\t) {\n\t\treturn false\n\t}\n\n\tif (\n\t\t(selector.currency || price.value.currencyCode) &&\n\t\tselector.currency !== price.value.currencyCode\n\t) {\n\t\treturn false\n\t}\n\n\tif (\n\t\t(selector.channel || price.channel?.id) &&\n\t\tselector.channel !== price.channel?.id\n\t) {\n\t\treturn false\n\t}\n\n\tif (\n\t\t(selector.customerGroup || price.customerGroup?.id) &&\n\t\tselector.customerGroup !== price.customerGroup?.id\n\t) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n","import type {\n\tFacetResults,\n\tFilteredFacetResult,\n\tInvalidInputError,\n\tProduct,\n\tProductProjection,\n\tProductProjectionPagedSearchResponse,\n\tQueryParam,\n\tRangeFacetResult,\n\tTermFacetResult,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from './exceptions.js'\nimport { nestedLookup } from './helpers.js'\nimport {\n\tFilterExpression,\n\tRangeExpression,\n\tgenerateFacetFunc,\n\tgetVariants,\n\tparseFilterExpression,\n\tresolveVariantValue,\n} from './lib/projectionSearchFilter.js'\nimport { applyPriceSelector } from './priceSelector.js'\nimport { AbstractStorage } from './storage/index.js'\nimport type { Writable } from './types.js'\n\nexport type ProductProjectionSearchParams = {\n\tfuzzy?: boolean\n\tfuzzyLevel?: number\n\tmarkMatchingVariants?: boolean\n\tstaged?: boolean\n\tfilter?: string[]\n\t'filter.facets'?: string[]\n\t'filter.query'?: string[]\n\tfacet?: string | string[]\n\tsort?: string | string[]\n\tlimit?: number\n\toffset?: number\n\twithTotal?: boolean\n\tpriceCurrency?: string\n\tpriceCountry?: string\n\tpriceCustomerGroup?: string\n\tpriceChannel?: string\n\tlocaleProjection?: string\n\tstoreProjection?: string\n\texpand?: string | string[]\n\t[key: string]: QueryParam\n}\n\nexport class ProductProjectionSearch {\n\tprotected _storage: AbstractStorage\n\n\tconstructor(storage: AbstractStorage) {\n\t\tthis._storage = storage\n\t}\n\n\tsearch(\n\t\tprojectKey: string,\n\t\tparams: ProductProjectionSearchParams\n\t): ProductProjectionPagedSearchResponse {\n\t\tlet resources = this._storage\n\t\t\t.all(projectKey, 'product')\n\t\t\t.map((r) => this.transform(r, params.staged ?? false))\n\t\t\t.filter((p) => {\n\t\t\t\tif (!params.staged ?? false) {\n\t\t\t\t\treturn p.published\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t})\n\n\t\tconst markMatchingVariant = params.markMatchingVariants ?? false\n\n\t\t// Apply the priceSelector\n\t\tapplyPriceSelector(resources, {\n\t\t\tcountry: params.priceCountry,\n\t\t\tchannel: params.priceChannel,\n\t\t\tcustomerGroup: params.priceCustomerGroup,\n\t\t\tcurrency: params.priceCurrency,\n\t\t})\n\n\t\t// Apply filters pre facetting\n\t\tif (params.filter) {\n\t\t\ttry {\n\t\t\t\tconst filters = params.filter.map(parseFilterExpression)\n\n\t\t\t\t// Filters can modify the output. So clone the resources first.\n\t\t\t\tresources = resources.filter((resource) =>\n\t\t\t\t\tfilters.every((f) => f(resource, markMatchingVariant))\n\t\t\t\t)\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(err)\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidInput',\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// TODO: Calculate facets\n\t\tconst facets = this.getFacets(params, resources)\n\n\t\t// Apply filters post facetting\n\t\tif (params['filter.query']) {\n\t\t\ttry {\n\t\t\t\tconst filters = params['filter.query'].map(parseFilterExpression)\n\t\t\t\tresources = resources.filter((resource) =>\n\t\t\t\t\tfilters.every((f) => f(resource, markMatchingVariant))\n\t\t\t\t)\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidInput',\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Expand the resources\n\t\tif (params.expand !== undefined) {\n\t\t\tresources = resources.map((resource) =>\n\t\t\t\tthis._storage.expand(projectKey, resource, params.expand)\n\t\t\t)\n\t\t}\n\n\t\t// Create a slice for the pagination. If we were working with large datasets\n\t\t// then we should have done this before transforming. But that isn't the\n\t\t// goal of this library. So lets keep it simple.\n\t\tconst totalResults = resources.length\n\t\tconst offset = params.offset || 0\n\t\tconst limit = params.limit || 20\n\t\tconst results = resources.slice(offset, offset + limit)\n\n\t\treturn {\n\t\t\tcount: totalResults,\n\t\t\ttotal: results.length,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\tresults: results,\n\t\t\tfacets: facets,\n\t\t}\n\t}\n\n\ttransform(product: Product, staged: boolean): ProductProjection {\n\t\tconst obj = !staged ? product.masterData.current : product.masterData.staged\n\n\t\treturn {\n\t\t\tid: product.id,\n\t\t\tcreatedAt: product.createdAt,\n\t\t\tlastModifiedAt: product.lastModifiedAt,\n\t\t\tversion: product.version,\n\t\t\tname: obj.name,\n\t\t\tkey: product.key,\n\t\t\tdescription: obj.description,\n\t\t\tmetaDescription: obj.metaDescription,\n\t\t\tslug: obj.slug,\n\t\t\tcategories: obj.categories,\n\t\t\tmasterVariant: obj.masterVariant,\n\t\t\tvariants: obj.variants,\n\t\t\tproductType: product.productType,\n\t\t\thasStagedChanges: product.masterData.hasStagedChanges,\n\t\t\tpublished: product.masterData.published,\n\t\t}\n\t}\n\n\tgetFacets(\n\t\tparams: ProductProjectionSearchParams,\n\t\tproducts: ProductProjection[]\n\t): FacetResults {\n\t\tif (!params.facet) return {}\n\t\tconst staged = false\n\t\tconst result: FacetResults = {}\n\n\t\tfor (const facet of params.facet) {\n\t\t\tconst expression = generateFacetFunc(facet)\n\n\t\t\t// Term Facet\n\t\t\tif (expression.type === 'TermExpression') {\n\t\t\t\tresult[facet] = this.termFacet(expression.source, products)\n\t\t\t}\n\n\t\t\t// Range Facet\n\t\t\tif (expression.type === 'RangeExpression') {\n\t\t\t\tresult[expression.source] = this.rangeFacet(\n\t\t\t\t\texpression.source,\n\t\t\t\t\texpression.children,\n\t\t\t\t\tproducts\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// FilteredFacet\n\t\t\tif (expression.type === 'FilterExpression') {\n\t\t\t\tresult[expression.source] = this.filterFacet(\n\t\t\t\t\texpression.source,\n\t\t\t\t\texpression.children,\n\t\t\t\t\tproducts\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/**\n\t * TODO: This implemention needs the following additional features:\n\t * - counting products\n\t * - correct dataType\n\t */\n\ttermFacet(facet: string, products: ProductProjection[]): TermFacetResult {\n\t\tconst result: Writable<TermFacetResult> = {\n\t\t\ttype: 'terms',\n\t\t\tdataType: 'text',\n\t\t\tmissing: 0,\n\t\t\ttotal: 0,\n\t\t\tother: 0,\n\t\t\tterms: [],\n\t\t}\n\t\tconst terms: Record<any, number> = {}\n\n\t\tif (facet.startsWith('variants.')) {\n\t\t\tproducts.forEach((p) => {\n\t\t\t\tconst variants = getVariants(p)\n\t\t\t\tvariants.forEach((v) => {\n\t\t\t\t\tresult.total++\n\n\t\t\t\t\tlet value = resolveVariantValue(v, facet)\n\t\t\t\t\tif (value === undefined) {\n\t\t\t\t\t\tresult.missing++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (typeof value === 'number') {\n\t\t\t\t\t\t\tvalue = Number(value).toFixed(1)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tterms[value] = value in terms ? terms[value] + 1 : 1\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t} else {\n\t\t\tproducts.forEach((p) => {\n\t\t\t\tconst value = nestedLookup(p, facet)\n\t\t\t\tresult.total++\n\t\t\t\tif (value === undefined) {\n\t\t\t\t\tresult.missing++\n\t\t\t\t} else {\n\t\t\t\t\tterms[value] = value in terms ? terms[value] + 1 : 1\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tfor (const term in terms) {\n\t\t\tresult.terms.push({\n\t\t\t\tterm: term as any,\n\t\t\t\tcount: terms[term],\n\t\t\t})\n\t\t}\n\t\treturn result\n\t}\n\n\tfilterFacet(\n\t\tsource: string,\n\t\tfilters: FilterExpression[] | undefined,\n\t\tproducts: ProductProjection[]\n\t): FilteredFacetResult {\n\t\tlet count = 0\n\t\tif (source.startsWith('variants.')) {\n\t\t\tfor (const p of products) {\n\t\t\t\tfor (const v of getVariants(p)) {\n\t\t\t\t\tconst val = resolveVariantValue(v, source)\n\t\t\t\t\tif (filters?.some((f) => f.match(val))) {\n\t\t\t\t\t\tcount++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new Error('not supported')\n\t\t}\n\n\t\treturn {\n\t\t\ttype: 'filter',\n\t\t\tcount: count,\n\t\t}\n\t}\n\n\trangeFacet(\n\t\tsource: string,\n\t\tranges: RangeExpression[] | undefined,\n\t\tproducts: ProductProjection[]\n\t): RangeFacetResult {\n\t\tconst counts =\n\t\t\tranges?.map((range) => {\n\t\t\t\tif (source.startsWith('variants.')) {\n\t\t\t\t\tconst values = []\n\t\t\t\t\tfor (const p of products) {\n\t\t\t\t\t\tfor (const v of getVariants(p)) {\n\t\t\t\t\t\t\tconst val = resolveVariantValue(v, source)\n\t\t\t\t\t\t\tif (val === undefined) {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (range.match(val)) {\n\t\t\t\t\t\t\t\tvalues.push(val)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst numValues = values.length\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: 'double',\n\t\t\t\t\t\tfrom: range.start || 0,\n\t\t\t\t\t\tfromStr: range.start !== null ? Number(range.start).toFixed(1) : '',\n\t\t\t\t\t\tto: range.stop || 0,\n\t\t\t\t\t\ttoStr: range.stop !== null ? Number(range.stop).toFixed(1) : '',\n\t\t\t\t\t\tcount: numValues,\n\t\t\t\t\t\t// totalCount: 0,\n\t\t\t\t\t\ttotal: values.reduce((a, b) => a + b, 0),\n\t\t\t\t\t\tmin: numValues > 0 ? Math.min(...values) : 0,\n\t\t\t\t\t\tmax: numValues > 0 ? Math.max(...values) : 0,\n\t\t\t\t\t\tmean: numValues > 0 ? mean(values) : 0,\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error('not supported')\n\t\t\t\t}\n\t\t\t}) || []\n\t\tconst data: RangeFacetResult = {\n\t\t\ttype: 'range',\n\t\t\t// @ts-ignore\n\t\t\tdataType: 'number',\n\t\t\tranges: counts,\n\t\t}\n\t\treturn data\n\t}\n}\n\nconst mean = (arr: number[]) => {\n\tlet total = 0\n\tfor (let i = 0; i < arr.length; i++) {\n\t\ttotal += arr[i]\n\t}\n\treturn total / arr.length\n}\n","import type {\n\tInvalidInputError,\n\tProductDraft,\n\tProductProjection,\n\tQueryParam,\n} from '@commercetools/platform-sdk'\nimport { ParsedQs } from 'qs'\nimport { QueryParamsAsArray } from '../helpers.js'\nimport { ProductProjectionSearch } from '../product-projection-search.js'\nimport { type AbstractStorage } from '../storage/index.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport { parseQueryExpression } from '../lib/predicateParser.js'\nimport { CommercetoolsError } from '../exceptions.js'\n\ntype ProductProjectionQueryParams = {\n\tstaged?: boolean\n\tpriceCurrency?: string\n\tpriceCountry?: string\n\tpriceCustomerGroup?: string\n\tpriceChannel?: string\n\tlocaleProjection?: string | string[]\n\tstoreProjection?: string\n\texpand?: string | string[]\n\tsort?: string | string[]\n\tlimit?: number\n\toffset?: number\n\twithTotal?: boolean\n\twhere?: string | string[]\n\t[key: string]: QueryParam\n}\n\nexport class ProductProjectionRepository extends AbstractResourceRepository<'product-projection'> {\n\tprotected _searchService: ProductProjectionSearch\n\n\tconstructor(storage: AbstractStorage) {\n\t\tsuper(storage)\n\t\tthis._searchService = new ProductProjectionSearch(storage)\n\t}\n\n\tgetTypeId() {\n\t\treturn 'product-projection' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: ProductDraft): ProductProjection {\n\t\tthrow new Error('No valid action')\n\t}\n\n\tquery(context: RepositoryContext, params: ProductProjectionQueryParams = {}) {\n\t\tlet resources = this._storage\n\t\t\t.all(context.projectKey, 'product')\n\t\t\t.map((r) => this._searchService.transform(r, params.staged ?? false))\n\t\t\t.filter((p) => {\n\t\t\t\tif (!params.staged ?? false) {\n\t\t\t\t\treturn p.published\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t})\n\n\t\t// Apply predicates\n\t\tif (params.where) {\n\t\t\tconst variableMap: Record<string, QueryParam> = {}\n\t\t\tfor (const [k, v] of Object.entries(params)) {\n\t\t\t\tif (k.startsWith('var.')) {\n\t\t\t\t\tvariableMap[k.substring(4)] = v\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst filterFunc = parseQueryExpression(params.where)\n\t\t\t\tresources = resources.filter((resource) =>\n\t\t\t\t\tfilterFunc(resource, variableMap)\n\t\t\t\t)\n\t\t\t} catch (err) {\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidInput',\n\t\t\t\t\t\tmessage: (err as any).message,\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Expand the resources\n\t\tif (params.expand !== undefined) {\n\t\t\tresources = resources.map((resource) =>\n\t\t\t\tthis._storage.expand(context.projectKey, resource, params.expand)\n\t\t\t)\n\t\t}\n\n\t\t// Create a slice for the pagination. If we were working with large datasets\n\t\t// then we should have done this before transforming. But that isn't the\n\t\t// goal of this library. So lets keep it simple.\n\t\tconst totalResults = resources.length\n\t\tconst offset = params.offset || 0\n\t\tconst limit = params.limit || 20\n\t\tconst results = resources.slice(offset, offset + limit)\n\n\t\treturn {\n\t\t\tcount: totalResults,\n\t\t\ttotal: results.length,\n\t\t\toffset: offset,\n\t\t\tlimit: limit,\n\t\t\tresults: results,\n\t\t}\n\t}\n\n\tsearch(context: RepositoryContext, query: ParsedQs) {\n\t\tconst results = this._searchService.search(context.projectKey, {\n\t\t\tfilter: QueryParamsAsArray(query.filter),\n\t\t\t'filter.query': QueryParamsAsArray(query['filter.query']),\n\t\t\tfacet: QueryParamsAsArray(query.facet),\n\t\t\toffset: query.offset ? Number(query.offset) : undefined,\n\t\t\tlimit: query.limit ? Number(query.limit) : undefined,\n\t\t\texpand: QueryParamsAsArray(query.expand),\n\t\t\tstaged: query.staged === 'true',\n\t\t})\n\n\t\treturn results\n\t}\n\n\tactions = {}\n}\n","import type {\n\tProductSelection,\n\tProductSelectionDraft,\n\tReview,\n\tReviewUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class ProductSelectionRepository extends AbstractResourceRepository<'product-selection'> {\n\tgetTypeId() {\n\t\treturn 'product-selection' as const\n\t}\n\n\tcreate(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ProductSelectionDraft\n\t): ProductSelection {\n\t\tconst resource: ProductSelection = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tproductCount: 0,\n\t\t\tname: draft.name,\n\t\t\ttype: 'individual',\n\t\t\tmode: 'Individual',\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tReviewUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Review>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {}\n}\n","import type {\n\tAttributeDefinition,\n\tAttributeDefinitionDraft,\n\tAttributeType,\n\tProductType,\n\tProductTypeAddAttributeDefinitionAction,\n\tProductTypeChangeAttributeOrderByNameAction,\n\tProductTypeChangeLabelAction,\n\tProductTypeChangeLocalizedEnumValueLabelAction,\n\tProductTypeDraft,\n\tProductTypeRemoveAttributeDefinitionAction,\n\tProductTypeRemoveEnumValuesAction,\n\tProductTypeUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class ProductTypeRepository extends AbstractResourceRepository<'product-type'> {\n\tgetTypeId() {\n\t\treturn 'product-type' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: ProductTypeDraft): ProductType {\n\t\tconst resource: ProductType = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t\tattributes: (draft.attributes ?? []).map((a) =>\n\t\t\t\tthis.attributeDefinitionFromAttributeDefinitionDraft(context, a)\n\t\t\t),\n\t\t}\n\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tattributeDefinitionFromAttributeDefinitionDraft = (\n\t\t_context: RepositoryContext,\n\t\tdraft: AttributeDefinitionDraft\n\t): AttributeDefinition => ({\n\t\t...draft,\n\t\tattributeConstraint: draft.attributeConstraint ?? 'None',\n\t\tinputHint: draft.inputHint ?? 'SingleLine',\n\t\tinputTip:\n\t\t\tdraft.inputTip && Object.keys(draft.inputTip).length > 0\n\t\t\t\t? draft.inputTip\n\t\t\t\t: undefined,\n\t\tisSearchable: draft.isSearchable ?? true,\n\t})\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tProductTypeUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<ProductType>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tchangeLocalizedEnumValueLabel: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductType>,\n\t\t\t{\n\t\t\t\tattributeName,\n\t\t\t\tnewValue,\n\t\t\t}: ProductTypeChangeLocalizedEnumValueLabelAction\n\t\t) => {\n\t\t\tconst updateAttributeType = (type: Writable<AttributeType>) => {\n\t\t\t\tswitch (type.name) {\n\t\t\t\t\tcase 'lenum':\n\t\t\t\t\t\ttype.values.forEach((v) => {\n\t\t\t\t\t\t\tif (v.key === newValue.key) {\n\t\t\t\t\t\t\t\tv.label = newValue.label\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase 'set':\n\t\t\t\t\t\tupdateAttributeType(type.elementType)\n\t\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresource.attributes?.forEach((value) => {\n\t\t\t\tif (value.name === attributeName) {\n\t\t\t\t\tupdateAttributeType(value.type)\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\tchangeLabel: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductType>,\n\t\t\t{ attributeName, label }: ProductTypeChangeLabelAction\n\t\t) => {\n\t\t\tresource.attributes?.forEach((value) => {\n\t\t\t\tif (value.name === attributeName) {\n\t\t\t\t\tvalue.label = label\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\taddAttributeDefinition: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductType>,\n\t\t\t{ attribute }: ProductTypeAddAttributeDefinitionAction\n\t\t) => {\n\t\t\tresource.attributes?.push(\n\t\t\t\tthis.attributeDefinitionFromAttributeDefinitionDraft(context, attribute)\n\t\t\t)\n\t\t},\n\t\tchangeAttributeOrderByName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductType>,\n\t\t\t{ attributeNames }: ProductTypeChangeAttributeOrderByNameAction\n\t\t) => {\n\t\t\tconst attrs = new Map(\n\t\t\t\tresource.attributes?.map((item) => [item.name, item])\n\t\t\t)\n\t\t\tconst result: AttributeDefinition[] = []\n\t\t\tlet current = resource.attributes\n\n\t\t\tattributeNames.forEach((attrName) => {\n\t\t\t\tconst attr = attrs.get(attrName)\n\t\t\t\tif (attr === undefined) {\n\t\t\t\t\tthrow new Error('New attr')\n\t\t\t\t}\n\t\t\t\tresult.push(attr)\n\n\t\t\t\t// Remove from current items\n\t\t\t\tcurrent = current?.filter((f) => f.name !== attrName)\n\t\t\t})\n\n\t\t\tresource.attributes = result\n\t\t\t// Add attrs which were not specified in the order as last items. Not\n\t\t\t// sure if this follows commercetools\n\t\t\tif (current) {\n\t\t\t\tresource.attributes.push(...current)\n\t\t\t}\n\t\t},\n\t\tremoveAttributeDefinition: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductType>,\n\t\t\t{ name }: ProductTypeRemoveAttributeDefinitionAction\n\t\t) => {\n\t\t\tresource.attributes = resource.attributes?.filter((f) => f.name !== name)\n\t\t},\n\t\tremoveEnumValues: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ProductType>,\n\t\t\t{ attributeName, keys }: ProductTypeRemoveEnumValuesAction\n\t\t) => {\n\t\t\tresource.attributes?.forEach((attr) => {\n\t\t\t\tif (attr.name == attributeName) {\n\t\t\t\t\tif (attr.type.name == 'enum') {\n\t\t\t\t\t\tattr.type.values = attr.type.values.filter(\n\t\t\t\t\t\t\t(v) => !keys.includes(v.key)\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\tif (attr.type.name == 'set') {\n\t\t\t\t\t\tif (attr.type.elementType.name == 'enum') {\n\t\t\t\t\t\t\tattr.type.elementType.values =\n\t\t\t\t\t\t\t\tattr.type.elementType.values.filter(\n\t\t\t\t\t\t\t\t\t(v) => !keys.includes(v.key)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t}\n}\n","import type {\n\tProject,\n\tProjectChangeCartsConfigurationAction,\n\tProjectChangeCountriesAction,\n\tProjectChangeCountryTaxRateFallbackEnabledAction,\n\tProjectChangeCurrenciesAction,\n\tProjectChangeLanguagesAction,\n\tProjectChangeMessagesConfigurationAction,\n\tProjectChangeNameAction,\n\tProjectChangeOrderSearchStatusAction,\n\tProjectChangeProductSearchIndexingEnabledAction,\n\tProjectSetExternalOAuthAction,\n\tProjectSetShippingRateInputTypeAction,\n\tProjectUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { maskSecretValue } from '../lib/masking.js'\nimport type { Writable } from '../types.js'\nimport { AbstractRepository, RepositoryContext } from './abstract.js'\n\nexport class ProjectRepository extends AbstractRepository<Project> {\n\tget(context: RepositoryContext): Project | null {\n\t\tconst resource = this._storage.getProject(context.projectKey)\n\t\treturn this.postProcessResource(resource)\n\t}\n\n\tpostProcessResource(resource: Project): Project {\n\t\tif (resource) {\n\t\t\treturn maskSecretValue(resource, 'externalOAuth.authorizationHeader')\n\t\t}\n\t\treturn resource\n\t}\n\n\tsaveNew(context: RepositoryContext, resource: Writable<Project>) {\n\t\tresource.version = 1\n\t\tthis._storage.saveProject(resource)\n\t}\n\n\tsaveUpdate(context: RepositoryContext, version: number, resource: Project) {\n\t\tthis._storage.saveProject(resource)\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tProjectUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Project>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tchangeName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ name }: ProjectChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tchangeCurrencies: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ currencies }: ProjectChangeCurrenciesAction\n\t\t) => {\n\t\t\tresource.currencies = currencies\n\t\t},\n\t\tchangeCountries: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ countries }: ProjectChangeCountriesAction\n\t\t) => {\n\t\t\tresource.countries = countries\n\t\t},\n\t\tchangeLanguages: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ languages }: ProjectChangeLanguagesAction\n\t\t) => {\n\t\t\tresource.languages = languages\n\t\t},\n\t\tchangeMessagesConfiguration: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ messagesConfiguration }: ProjectChangeMessagesConfigurationAction\n\t\t) => {\n\t\t\tresource.messages.enabled = messagesConfiguration.enabled\n\t\t\tresource.messages.deleteDaysAfterCreation =\n\t\t\t\tmessagesConfiguration.deleteDaysAfterCreation\n\t\t},\n\t\tchangeProductSearchIndexingEnabled: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ enabled }: ProjectChangeProductSearchIndexingEnabledAction\n\t\t) => {\n\t\t\tif (!resource.searchIndexing?.products) {\n\t\t\t\tthrow new Error('Invalid project state')\n\t\t\t}\n\t\t\tresource.searchIndexing.products.status = enabled\n\t\t\t\t? 'Activated'\n\t\t\t\t: 'Deactivated'\n\t\t\tresource.searchIndexing.products.lastModifiedAt = new Date().toISOString()\n\t\t},\n\t\tchangeOrderSearchStatus: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ status }: ProjectChangeOrderSearchStatusAction\n\t\t) => {\n\t\t\tif (!resource.searchIndexing?.orders) {\n\t\t\t\tthrow new Error('Invalid project state')\n\t\t\t}\n\t\t\tresource.searchIndexing.orders.status = status\n\t\t\tresource.searchIndexing.orders.lastModifiedAt = new Date().toISOString()\n\t\t},\n\t\tsetShippingRateInputType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ shippingRateInputType }: ProjectSetShippingRateInputTypeAction\n\t\t) => {\n\t\t\tresource.shippingRateInputType = shippingRateInputType\n\t\t},\n\t\tsetExternalOAuth: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ externalOAuth }: ProjectSetExternalOAuthAction\n\t\t) => {\n\t\t\tresource.externalOAuth = externalOAuth\n\t\t},\n\t\tchangeCountryTaxRateFallbackEnabled: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{\n\t\t\t\tcountryTaxRateFallbackEnabled,\n\t\t\t}: ProjectChangeCountryTaxRateFallbackEnabledAction\n\t\t) => {\n\t\t\tresource.carts.countryTaxRateFallbackEnabled =\n\t\t\t\tcountryTaxRateFallbackEnabled\n\t\t},\n\t\tchangeCartsConfiguration: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Project>,\n\t\t\t{ cartsConfiguration }: ProjectChangeCartsConfigurationAction\n\t\t) => {\n\t\t\tresource.carts = cartsConfiguration || {\n\t\t\t\tcountryTaxRateFallbackEnabled: false,\n\t\t\t\tdeleteDaysAfterLastModification: 90,\n\t\t\t}\n\t\t},\n\t}\n}\n","import type {\n\tQuote,\n\tQuoteDraft,\n\tQuoteUpdateAction,\n} from '@commercetools/platform-sdk'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class QuoteRepository extends AbstractResourceRepository<'quote'> {\n\tgetTypeId() {\n\t\treturn 'quote' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: QuoteDraft): Quote {\n\t\tthrow new Error('not implemented')\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tQuoteUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Quote>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {}\n}\n","import type {\n\tQuoteRequest,\n\tQuoteRequestDraft,\n\tQuoteRequestUpdateAction,\n} from '@commercetools/platform-sdk'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class QuoteRequestRepository extends AbstractResourceRepository<'quote-request'> {\n\tgetTypeId() {\n\t\treturn 'quote-request' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: QuoteRequestDraft): QuoteRequest {\n\t\tthrow new Error('not implemented')\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tQuoteRequestUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<QuoteRequest>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {}\n}\n","import type {\n\tReview,\n\tReviewDraft,\n\tReviewUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class ReviewRepository extends AbstractResourceRepository<'review'> {\n\tgetTypeId() {\n\t\treturn 'review' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: ReviewDraft): Review {\n\t\tconst resource: Review = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tincludedInStatistics: false,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tReviewUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Review>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {}\n}\n","import type {\n\tShippingMethod,\n\tShippingMethodAddShippingRateAction,\n\tShippingMethodAddZoneAction,\n\tShippingMethodChangeIsDefaultAction,\n\tShippingMethodChangeNameAction,\n\tShippingMethodDraft,\n\tShippingMethodRemoveZoneAction,\n\tShippingMethodSetCustomFieldAction,\n\tShippingMethodSetCustomTypeAction,\n\tShippingMethodSetDescriptionAction,\n\tShippingMethodSetKeyAction,\n\tShippingMethodSetLocalizedDescriptionAction,\n\tShippingMethodSetLocalizedNameAction,\n\tShippingMethodSetPredicateAction,\n\tShippingMethodUpdateAction,\n\tShippingRate,\n\tShippingRateDraft,\n\tZoneRate,\n\tZoneRateDraft,\n\tZoneReference,\n} from '@commercetools/platform-sdk'\nimport deepEqual from 'deep-equal'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n\tcreateCustomFields,\n\tcreateTypedMoney,\n\tgetReferenceFromResourceIdentifier,\n} from './helpers.js'\n\nexport class ShippingMethodRepository extends AbstractResourceRepository<'shipping-method'> {\n\tgetTypeId() {\n\t\treturn 'shipping-method' as const\n\t}\n\n\tcreate(\n\t\tcontext: RepositoryContext,\n\t\tdraft: ShippingMethodDraft\n\t): ShippingMethod {\n\t\tconst resource: ShippingMethod = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\t...draft,\n\t\t\ttaxCategory: getReferenceFromResourceIdentifier(\n\t\t\t\tdraft.taxCategory,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t\tzoneRates: draft.zoneRates?.map((z) =>\n\t\t\t\tthis._transformZoneRateDraft(context, z)\n\t\t\t),\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tprivate _transformZoneRateDraft = (\n\t\tcontext: RepositoryContext,\n\t\tdraft: ZoneRateDraft\n\t): ZoneRate => ({\n\t\t...draft,\n\t\tzone: getReferenceFromResourceIdentifier<ZoneReference>(\n\t\t\tdraft.zone,\n\t\t\tcontext.projectKey,\n\t\t\tthis._storage\n\t\t),\n\t\tshippingRates: draft.shippingRates?.map(this._transformShippingRate),\n\t})\n\n\tprivate _transformShippingRate = (rate: ShippingRateDraft): ShippingRate => ({\n\t\tprice: createTypedMoney(rate.price),\n\t\tfreeAbove: rate.freeAbove && createTypedMoney(rate.freeAbove),\n\t\ttiers: rate.tiers || [],\n\t})\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tShippingMethodUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\taddShippingRate: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ shippingRate, zone }: ShippingMethodAddShippingRateAction\n\t\t) => {\n\t\t\tconst rate = this._transformShippingRate(shippingRate)\n\n\t\t\tresource.zoneRates.forEach((zoneRate) => {\n\t\t\t\tif (zoneRate.zone.id === zone.id) {\n\t\t\t\t\tzoneRate.shippingRates.push(rate)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t})\n\t\t\tresource.zoneRates.push({\n\t\t\t\tzone: {\n\t\t\t\t\ttypeId: 'zone',\n\t\t\t\t\tid: zone.id!,\n\t\t\t\t},\n\t\t\t\tshippingRates: [rate],\n\t\t\t})\n\t\t},\n\t\tremoveShippingRate: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ shippingRate, zone }: ShippingMethodAddShippingRateAction\n\t\t) => {\n\t\t\tconst rate = this._transformShippingRate(shippingRate)\n\n\t\t\tresource.zoneRates.forEach((zoneRate) => {\n\t\t\t\tif (zoneRate.zone.id === zone.id) {\n\t\t\t\t\tzoneRate.shippingRates = zoneRate.shippingRates.filter(\n\t\t\t\t\t\t(otherRate) => !deepEqual(rate, otherRate)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\taddZone: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ zone }: ShippingMethodAddZoneAction\n\t\t) => {\n\t\t\tconst zoneReference = getReferenceFromResourceIdentifier<ZoneReference>(\n\t\t\t\tzone,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t)\n\n\t\t\tif (resource.zoneRates === undefined) {\n\t\t\t\tresource.zoneRates = []\n\t\t\t}\n\n\t\t\tresource.zoneRates.push({\n\t\t\t\tzone: zoneReference,\n\t\t\t\tshippingRates: [],\n\t\t\t})\n\t\t},\n\t\tremoveZone: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ zone }: ShippingMethodRemoveZoneAction\n\t\t) => {\n\t\t\tresource.zoneRates = resource.zoneRates.filter(\n\t\t\t\t(zoneRate) => zoneRate.zone.id !== zone.id\n\t\t\t)\n\t\t},\n\t\tsetKey: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ key }: ShippingMethodSetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t\tsetDescription: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ description }: ShippingMethodSetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tsetLocalizedDescription: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ localizedDescription }: ShippingMethodSetLocalizedDescriptionAction\n\t\t) => {\n\t\t\tresource.localizedDescription = localizedDescription\n\t\t},\n\t\tsetLocalizedName: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ localizedName }: ShippingMethodSetLocalizedNameAction\n\t\t) => {\n\t\t\tresource.localizedName = localizedName\n\t\t},\n\t\tsetPredicate: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ predicate }: ShippingMethodSetPredicateAction\n\t\t) => {\n\t\t\tresource.predicate = predicate\n\t\t},\n\t\tchangeIsDefault: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ isDefault }: ShippingMethodChangeIsDefaultAction\n\t\t) => {\n\t\t\tresource.isDefault = isDefault\n\t\t},\n\t\tchangeName: (\n\t\t\t_context: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ name }: ShippingMethodChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ type, fields }: ShippingMethodSetCustomTypeAction\n\t\t) => {\n\t\t\tif (type) {\n\t\t\t\tresource.custom = createCustomFields(\n\t\t\t\t\t{ type, fields },\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tresource.custom = undefined\n\t\t\t}\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<ShippingMethod>,\n\t\t\t{ name, value }: ShippingMethodSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (value === null) {\n\t\t\t\tdelete resource.custom.fields[name]\n\t\t\t} else {\n\t\t\t\tresource.custom.fields[name] = value\n\t\t\t}\n\t\t},\n\t}\n}\n","import type {\n\tCustomerReference,\n\tShoppingList,\n\tShoppingListDraft,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n\tgetStoreKeyReference,\n} from './helpers.js'\n\nexport class ShoppingListRepository extends AbstractResourceRepository<'shopping-list'> {\n\tgetTypeId() {\n\t\treturn 'shopping-list' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: ShoppingListDraft): ShoppingList {\n\t\t// const product =\n\n\t\tconst resource: ShoppingList = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\t...draft,\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t\ttextLineItems: [],\n\t\t\tlineItems:\n\t\t\t\tdraft.lineItems?.map((e) => ({\n\t\t\t\t\t...getBaseResourceProperties(),\n\t\t\t\t\t...e,\n\t\t\t\t\taddedAt: e.addedAt ?? '',\n\t\t\t\t\tproductId: e.productId ?? '',\n\t\t\t\t\tname: {},\n\t\t\t\t\tquantity: e.quantity ?? 1,\n\t\t\t\t\tproductType: { typeId: 'product-type', id: '' },\n\t\t\t\t\tcustom: createCustomFields(\n\t\t\t\t\t\te.custom,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage\n\t\t\t\t\t),\n\t\t\t\t})) ?? [],\n\t\t\tcustomer: draft.customer\n\t\t\t\t? getReferenceFromResourceIdentifier<CustomerReference>(\n\t\t\t\t\t\tdraft.customer,\n\t\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\t\tthis._storage\n\t\t\t\t )\n\t\t\t\t: undefined,\n\t\t\tstore: draft.store\n\t\t\t\t? getStoreKeyReference(draft.store, context.projectKey, this._storage)\n\t\t\t\t: undefined,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n}\n","import type {\n\tQuote,\n\tStagedQuote,\n\tStagedQuoteDraft,\n\tStagedQuoteUpdateAction,\n} from '@commercetools/platform-sdk'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class StagedQuoteRepository extends AbstractResourceRepository<'staged-quote'> {\n\tgetTypeId() {\n\t\treturn 'staged-quote' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: StagedQuoteDraft): StagedQuote {\n\t\tthrow new Error('not implemented')\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tStagedQuoteUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Quote>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {}\n}\n","import type {\n\tChannelReference,\n\tChannelResourceIdentifier,\n\tDiscountedPriceDraft,\n\tStandalonePrice,\n\tStandalonePriceChangeActiveAction,\n\tStandalonePriceChangeValueAction,\n\tStandalonePriceDraft,\n\tStandalonePriceSetDiscountedPriceAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport { createTypedMoney } from './helpers.js'\n\nexport class StandAlonePriceRepository extends AbstractResourceRepository<'standalone-price'> {\n\tgetTypeId() {\n\t\treturn 'standalone-price' as const\n\t}\n\n\tcreate(\n\t\tcontext: RepositoryContext,\n\t\tdraft: StandalonePriceDraft\n\t): StandalonePrice {\n\t\tconst resource: StandalonePrice = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tactive: draft.active ? draft.active : false,\n\t\t\tsku: draft.sku,\n\t\t\tvalue: createTypedMoney(draft.value),\n\t\t\tcountry: draft.country,\n\t\t\tdiscounted: draft.discounted\n\t\t\t\t? this.transformDiscountDraft(draft.discounted)\n\t\t\t\t: undefined,\n\t\t\tchannel: draft.channel?.id\n\t\t\t\t? this.transformChannelReferenceDraft(draft.channel)\n\t\t\t\t: undefined,\n\t\t\tvalidFrom: draft.validFrom,\n\t\t\tvalidUntil: draft.validUntil,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\ttransformChannelReferenceDraft(\n\t\tchannel: ChannelResourceIdentifier\n\t): ChannelReference {\n\t\treturn {\n\t\t\ttypeId: channel.typeId,\n\t\t\tid: channel.id as string,\n\t\t}\n\t}\n\n\ttransformDiscountDraft(discounted: DiscountedPriceDraft) {\n\t\treturn {\n\t\t\tvalue: createTypedMoney(discounted.value),\n\t\t\tdiscount: discounted.discount,\n\t\t}\n\t}\n\n\tactions = {\n\t\tsetActive: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<StandalonePrice>,\n\t\t\taction: StandalonePriceChangeActiveAction\n\t\t) => {\n\t\t\tresource.active = action.active\n\t\t},\n\t\tchangeValue: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<StandalonePrice>,\n\t\t\taction: StandalonePriceChangeValueAction\n\t\t) => {\n\t\t\tresource.value = createTypedMoney(action.value)\n\t\t},\n\t\tsetDiscountedPrice: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<StandalonePrice>,\n\t\t\taction: StandalonePriceSetDiscountedPriceAction\n\t\t) => {\n\t\t\tresource.discounted = action.discounted\n\t\t\t\t? this.transformDiscountDraft(action.discounted)\n\t\t\t\t: undefined\n\t\t},\n\t}\n}\n","import type {\n\tState,\n\tStateChangeInitialAction,\n\tStateChangeKeyAction,\n\tStateDraft,\n\tStateReference,\n\tStateSetDescriptionAction,\n\tStateSetNameAction,\n\tStateSetRolesAction,\n\tStateSetTransitionsAction,\n\tStateUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport { getReferenceFromResourceIdentifier } from './helpers.js'\n\nexport class StateRepository extends AbstractResourceRepository<'state'> {\n\tgetTypeId() {\n\t\treturn 'state' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: StateDraft): State {\n\t\tconst resource: State = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\t...draft,\n\t\t\tbuiltIn: false,\n\t\t\tinitial: draft.initial || false,\n\t\t\ttransitions: (draft.transitions || []).map((t) =>\n\t\t\t\tgetReferenceFromResourceIdentifier(t, context.projectKey, this._storage)\n\t\t\t),\n\t\t}\n\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tStateUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<State>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tchangeKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<State>,\n\t\t\t{ key }: StateChangeKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t\tchangeInitial: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<State>,\n\t\t\t{ initial }: StateChangeInitialAction\n\t\t) => {\n\t\t\tresource.initial = initial\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<State>,\n\t\t\t{ description }: StateSetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tsetName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<State>,\n\t\t\t{ name }: StateSetNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tsetRoles: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<State>,\n\t\t\t{ roles }: StateSetRolesAction\n\t\t) => {\n\t\t\tresource.roles = roles\n\t\t},\n\t\tsetTransitions: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<State>,\n\t\t\t{ transitions }: StateSetTransitionsAction\n\t\t) => {\n\t\t\tresource.transitions = transitions?.map(\n\t\t\t\t(resourceId): StateReference => ({\n\t\t\t\t\tid: resourceId.id || '',\n\t\t\t\t\ttypeId: 'state',\n\t\t\t\t})\n\t\t\t)\n\t\t},\n\t}\n}\n","import type {\n\tChannelReference,\n\tChannelResourceIdentifier,\n\tStore,\n\tStoreDraft,\n\tStoreSetCustomFieldAction,\n\tStoreSetCustomTypeAction,\n\tStoreSetDistributionChannelsAction,\n\tStoreSetLanguagesAction,\n\tStoreSetNameAction,\n\tStoreUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\nimport {\n\tcreateCustomFields,\n\tgetReferenceFromResourceIdentifier,\n} from './helpers.js'\n\nexport class StoreRepository extends AbstractResourceRepository<'store'> {\n\tgetTypeId() {\n\t\treturn 'store' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: StoreDraft): Store {\n\t\tconst resource: Store = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tlanguages: draft.languages ?? [],\n\t\t\tcountries: draft.countries ?? [],\n\t\t\tdistributionChannels: this.transformChannels(\n\t\t\t\tcontext,\n\t\t\t\tdraft.distributionChannels\n\t\t\t),\n\t\t\tsupplyChannels: this.transformChannels(context, draft.supplyChannels),\n\t\t\tproductSelections: [],\n\t\t\tcustom: createCustomFields(\n\t\t\t\tdraft.custom,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t),\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tprivate transformChannels(\n\t\tcontext: RepositoryContext,\n\t\tchannels?: ChannelResourceIdentifier[]\n\t) {\n\t\tif (!channels) return []\n\n\t\treturn channels.map((ref) =>\n\t\t\tgetReferenceFromResourceIdentifier<ChannelReference>(\n\t\t\t\tref,\n\t\t\t\tcontext.projectKey,\n\t\t\t\tthis._storage\n\t\t\t)\n\t\t)\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tStoreUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Store>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\tsetName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Store>,\n\t\t\t{ name }: StoreSetNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tsetDistributionChannels: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Store>,\n\t\t\t{ distributionChannels }: StoreSetDistributionChannelsAction\n\t\t) => {\n\t\t\tresource.distributionChannels = this.transformChannels(\n\t\t\t\tcontext,\n\t\t\t\tdistributionChannels\n\t\t\t)\n\t\t},\n\t\tsetLanguages: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Store>,\n\t\t\t{ languages }: StoreSetLanguagesAction\n\t\t) => {\n\t\t\tresource.languages = languages ?? []\n\t\t},\n\t\tsetCustomType: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Store>,\n\t\t\t{ type, fields }: StoreSetCustomTypeAction\n\t\t) => {\n\t\t\tif (type) {\n\t\t\t\tresource.custom = createCustomFields(\n\t\t\t\t\t{ type, fields },\n\t\t\t\t\tcontext.projectKey,\n\t\t\t\t\tthis._storage\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tresource.custom = undefined\n\t\t\t}\n\t\t},\n\t\tsetCustomField: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Store>,\n\t\t\t{ name, value }: StoreSetCustomFieldAction\n\t\t) => {\n\t\t\tif (!resource.custom) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (value === null) {\n\t\t\t\tdelete resource.custom.fields[name]\n\t\t\t} else {\n\t\t\t\tresource.custom.fields[name] = value\n\t\t\t}\n\t\t},\n\t}\n}\n","import type {\n\tInvalidInputError,\n\tSubscription,\n\tSubscriptionDraft,\n} from '@commercetools/platform-sdk'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class SubscriptionRepository extends AbstractResourceRepository<'subscription'> {\n\tgetTypeId() {\n\t\treturn 'subscription' as const\n\t}\n\tcreate(context: RepositoryContext, draft: SubscriptionDraft): Subscription {\n\t\t// TODO: We could actually test this here by using the aws sdk. For now\n\t\t// hardcode a failed check when account id is 0000000000\n\t\tif (draft.destination.type === 'SQS') {\n\t\t\tconst queueURL = new URL(draft.destination.queueUrl)\n\t\t\tconst accountId = queueURL.pathname.split('/')[1]\n\t\t\tif (accountId === '0000000000') {\n\t\t\t\tconst dest = draft.destination\n\t\t\t\tthrow new CommercetoolsError<InvalidInputError>(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidInput',\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t'A test message could not be delivered to this destination: ' +\n\t\t\t\t\t\t\t`SQS ${dest.queueUrl} in ${dest.region} for ${dest.accessKey}. ` +\n\t\t\t\t\t\t\t'Please make sure your destination is correctly configured.',\n\t\t\t\t\t},\n\t\t\t\t\t400\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst resource: Subscription = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tchanges: draft.changes || [],\n\t\t\tdestination: draft.destination,\n\t\t\tformat: draft.format || {\n\t\t\t\ttype: 'Platform',\n\t\t\t},\n\t\t\tkey: draft.key,\n\t\t\tmessages: draft.messages || [],\n\t\t\tstatus: 'Healthy',\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n}\n","import type {\n\tTaxCategory,\n\tTaxCategoryAddTaxRateAction,\n\tTaxCategoryChangeNameAction,\n\tTaxCategoryDraft,\n\tTaxCategoryRemoveTaxRateAction,\n\tTaxCategoryReplaceTaxRateAction,\n\tTaxCategorySetDescriptionAction,\n\tTaxCategorySetKeyAction,\n\tTaxCategoryUpdateAction,\n\tTaxRate,\n\tTaxRateDraft,\n} from '@commercetools/platform-sdk'\nimport { v4 as uuidv4 } from 'uuid'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class TaxCategoryRepository extends AbstractResourceRepository<'tax-category'> {\n\tgetTypeId() {\n\t\treturn 'tax-category' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: TaxCategoryDraft): TaxCategory {\n\t\tconst resource: TaxCategory = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\t...draft,\n\t\t\trates: draft.rates?.map(this.taxRateFromTaxRateDraft) || [],\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tprivate taxRateFromTaxRateDraft = (draft: TaxRateDraft): TaxRate => ({\n\t\t...draft,\n\t\tid: uuidv4(),\n\t\tamount: draft.amount || 0,\n\t})\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tTaxCategoryUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<TaxCategory>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\taddTaxRate: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<TaxCategory>,\n\t\t\t{ taxRate }: TaxCategoryAddTaxRateAction\n\t\t) => {\n\t\t\tif (resource.rates === undefined) {\n\t\t\t\tresource.rates = []\n\t\t\t}\n\t\t\tresource.rates.push(this.taxRateFromTaxRateDraft(taxRate))\n\t\t},\n\t\tremoveTaxRate: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<TaxCategory>,\n\t\t\t{ taxRateId }: TaxCategoryRemoveTaxRateAction\n\t\t) => {\n\t\t\tif (resource.rates === undefined) {\n\t\t\t\tresource.rates = []\n\t\t\t}\n\t\t\tresource.rates = resource.rates.filter(\n\t\t\t\t(taxRate) => taxRate.id !== taxRateId\n\t\t\t)\n\t\t},\n\t\treplaceTaxRate: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<TaxCategory>,\n\t\t\t{ taxRateId, taxRate }: TaxCategoryReplaceTaxRateAction\n\t\t) => {\n\t\t\tif (resource.rates === undefined) {\n\t\t\t\tresource.rates = []\n\t\t\t}\n\n\t\t\tconst taxRateObj = this.taxRateFromTaxRateDraft(taxRate)\n\t\t\tfor (let i = 0; i < resource.rates.length; i++) {\n\t\t\t\tconst rate = resource.rates[i]\n\t\t\t\tif (rate.id === taxRateId) {\n\t\t\t\t\tresource.rates[i] = taxRateObj\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<TaxCategory>,\n\t\t\t{ description }: TaxCategorySetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tsetKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<TaxCategory>,\n\t\t\t{ key }: TaxCategorySetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t\tchangeName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<TaxCategory>,\n\t\t\t{ name }: TaxCategoryChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t}\n}\n","import type {\n\tFieldDefinition,\n\tInvalidOperationError,\n\tType,\n\tTypeAddEnumValueAction,\n\tTypeAddFieldDefinitionAction,\n\tTypeChangeEnumValueLabelAction,\n\tTypeChangeFieldDefinitionOrderAction,\n\tTypeChangeNameAction,\n\tTypeDraft,\n\tTypeRemoveFieldDefinitionAction,\n\tTypeSetDescriptionAction,\n\tTypeUpdateAction,\n} from '@commercetools/platform-sdk'\nimport isEqual from 'lodash.isequal'\nimport { CommercetoolsError } from '../exceptions.js'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class TypeRepository extends AbstractResourceRepository<'type'> {\n\tgetTypeId() {\n\t\treturn 'type' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: TypeDraft): Type {\n\t\tconst resource: Type = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tname: draft.name,\n\t\t\tresourceTypeIds: draft.resourceTypeIds,\n\t\t\tfieldDefinitions: draft.fieldDefinitions || [],\n\t\t\tdescription: draft.description,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\tactions: Partial<\n\t\tRecord<\n\t\t\tTypeUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Type>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\taddFieldDefinition: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Type>,\n\t\t\t{ fieldDefinition }: TypeAddFieldDefinitionAction\n\t\t) => {\n\t\t\tresource.fieldDefinitions.push(fieldDefinition)\n\t\t},\n\t\tremoveFieldDefinition: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Type>,\n\t\t\t{ fieldName }: TypeRemoveFieldDefinitionAction\n\t\t) => {\n\t\t\tresource.fieldDefinitions = resource.fieldDefinitions.filter(\n\t\t\t\t(f) => f.name !== fieldName\n\t\t\t)\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Type>,\n\t\t\t{ description }: TypeSetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tchangeName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Type>,\n\t\t\t{ name }: TypeChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tchangeFieldDefinitionOrder: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Type>,\n\t\t\t{ fieldNames }: TypeChangeFieldDefinitionOrderAction\n\t\t) => {\n\t\t\tconst fields = new Map(\n\t\t\t\tresource.fieldDefinitions.map((item) => [item.name, item])\n\t\t\t)\n\t\t\tconst result: FieldDefinition[] = []\n\t\t\tlet current = resource.fieldDefinitions\n\n\t\t\tfieldNames.forEach((fieldName) => {\n\t\t\t\tconst field = fields.get(fieldName)\n\t\t\t\tif (field === undefined) {\n\t\t\t\t\tthrow new Error('New field')\n\t\t\t\t}\n\t\t\t\tresult.push(field)\n\n\t\t\t\t// Remove from current items\n\t\t\t\tcurrent = current.filter((f) => f.name !== fieldName)\n\t\t\t})\n\n\t\t\tif (\n\t\t\t\tisEqual(\n\t\t\t\t\tfieldNames,\n\t\t\t\t\tresource.fieldDefinitions.map((item) => item.name)\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new CommercetoolsError<InvalidOperationError>({\n\t\t\t\t\tcode: 'InvalidOperation',\n\t\t\t\t\tmessage: \"'fieldDefinitions' has no changes.\",\n\t\t\t\t\taction: {\n\t\t\t\t\t\taction: 'changeFieldDefinitionOrder',\n\t\t\t\t\t\tfieldNames: fieldNames,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tresource.fieldDefinitions = result\n\t\t\t// Add fields which were not specified in the order as last items. Not\n\t\t\t// sure if this follows commercetools\n\t\t\tresource.fieldDefinitions.push(...current)\n\t\t},\n\t\taddEnumValue: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Type>,\n\t\t\t{ fieldName, value }: TypeAddEnumValueAction\n\t\t) => {\n\t\t\tresource.fieldDefinitions.forEach((field) => {\n\t\t\t\tif (field.name === fieldName) {\n\t\t\t\t\t// TODO, should be done better i suppose\n\t\t\t\t\tif (field.type.name === 'Enum') {\n\t\t\t\t\t\tfield.type.values.push(value)\n\t\t\t\t\t} else if (\n\t\t\t\t\t\tfield.type.name === 'Set' &&\n\t\t\t\t\t\tfield.type.elementType.name === 'Enum'\n\t\t\t\t\t) {\n\t\t\t\t\t\tfield.type.elementType.values.push(value)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Error('Type is not a Enum (or Set of Enum)')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\tchangeEnumValueLabel: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Type>,\n\t\t\t{ fieldName, value }: TypeChangeEnumValueLabelAction\n\t\t) => {\n\t\t\tresource.fieldDefinitions.forEach((field) => {\n\t\t\t\tif (field.name === fieldName) {\n\t\t\t\t\t// TODO, should be done better i suppose\n\t\t\t\t\tif (field.type.name === 'Enum') {\n\t\t\t\t\t\tfield.type.values.forEach((v) => {\n\t\t\t\t\t\t\tif (v.key === value.key) {\n\t\t\t\t\t\t\t\tv.label = value.label\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t} else if (\n\t\t\t\t\t\tfield.type.name === 'Set' &&\n\t\t\t\t\t\tfield.type.elementType.name === 'Enum'\n\t\t\t\t\t) {\n\t\t\t\t\t\tfield.type.elementType.values.forEach((v) => {\n\t\t\t\t\t\t\tif (v.key === value.key) {\n\t\t\t\t\t\t\t\tv.label = value.label\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new Error('Type is not a Enum (or Set of Enum)')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t}\n}\n","import type {\n\tZone,\n\tZoneAddLocationAction,\n\tZoneChangeNameAction,\n\tZoneDraft,\n\tZoneRemoveLocationAction,\n\tZoneSetDescriptionAction,\n\tZoneSetKeyAction,\n\tZoneUpdateAction,\n} from '@commercetools/platform-sdk'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport type { Writable } from '../types.js'\nimport { AbstractResourceRepository, RepositoryContext } from './abstract.js'\n\nexport class ZoneRepository extends AbstractResourceRepository<'zone'> {\n\tgetTypeId() {\n\t\treturn 'zone' as const\n\t}\n\n\tcreate(context: RepositoryContext, draft: ZoneDraft): Zone {\n\t\tconst resource: Zone = {\n\t\t\t...getBaseResourceProperties(),\n\t\t\tkey: draft.key,\n\t\t\tlocations: draft.locations || [],\n\t\t\tname: draft.name,\n\t\t\tdescription: draft.description,\n\t\t}\n\t\tthis.saveNew(context, resource)\n\t\treturn resource\n\t}\n\n\tactions: Partial<\n\t\tRecord<\n\t\t\tZoneUpdateAction['action'],\n\t\t\t(\n\t\t\t\tcontext: RepositoryContext,\n\t\t\t\tresource: Writable<Zone>,\n\t\t\t\taction: any\n\t\t\t) => void\n\t\t>\n\t> = {\n\t\taddLocation: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Zone>,\n\t\t\t{ location }: ZoneAddLocationAction\n\t\t) => {\n\t\t\tresource.locations.push(location)\n\t\t},\n\t\tremoveLocation: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Zone>,\n\t\t\t{ location }: ZoneRemoveLocationAction\n\t\t) => {\n\t\t\tresource.locations = resource.locations.filter(\n\t\t\t\t(loc) =>\n\t\t\t\t\t!(loc.country === location.country && loc.state === location.state)\n\t\t\t)\n\t\t},\n\t\tchangeName: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Zone>,\n\t\t\t{ name }: ZoneChangeNameAction\n\t\t) => {\n\t\t\tresource.name = name\n\t\t},\n\t\tsetDescription: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Zone>,\n\t\t\t{ description }: ZoneSetDescriptionAction\n\t\t) => {\n\t\t\tresource.description = description\n\t\t},\n\t\tsetKey: (\n\t\t\tcontext: RepositoryContext,\n\t\t\tresource: Writable<Zone>,\n\t\t\t{ key }: ZoneSetKeyAction\n\t\t) => {\n\t\t\tresource.key = key\n\t\t},\n\t}\n}\n","import { AbstractStorage } from '../storage/index.js'\nimport { AssociateRoleRepository } from './associate-role.js'\nimport { AttributeGroupRepository } from './attribute-group.js'\nimport { BusinessUnitRepository } from './business-unit.js'\nimport { CartRepository } from './cart.js'\nimport { CartDiscountRepository } from './cart-discount.js'\nimport { CategoryRepository } from './category.js'\nimport { ChannelRepository } from './channel.js'\nimport { CustomObjectRepository } from './custom-object.js'\nimport { CustomerRepository } from './customer.js'\nimport { CustomerGroupRepository } from './customer-group.js'\nimport { DiscountCodeRepository } from './discount-code.js'\nimport { ExtensionRepository } from './extension.js'\nimport { InventoryEntryRepository } from './inventory-entry.js'\nimport { MyOrderRepository } from './my-order.js'\nimport { OrderRepository } from './order.js'\nimport { OrderEditRepository } from './order-edit.js'\nimport { PaymentRepository } from './payment.js'\nimport { ProductRepository } from './product.js'\nimport { ProductDiscountRepository } from './product-discount.js'\nimport { ProductProjectionRepository } from './product-projection.js'\nimport { ProductSelectionRepository } from './product-selection.js'\nimport { ProductTypeRepository } from './product-type.js'\nimport { ProjectRepository } from './project.js'\nimport { QuoteRepository } from './quote.js'\nimport { QuoteRequestRepository } from './quote-request.js'\nimport { ReviewRepository } from './review.js'\nimport { ShippingMethodRepository } from './shipping-method.js'\nimport { ShoppingListRepository } from './shopping-list.js'\nimport { StagedQuoteRepository } from './staged-quote.js'\nimport { StandAlonePriceRepository } from './standalone-price.js'\nimport { StateRepository } from './state.js'\nimport { StoreRepository } from './store.js'\nimport { SubscriptionRepository } from './subscription.js'\nimport { TaxCategoryRepository } from './tax-category.js'\nimport { TypeRepository } from './type.js'\nimport { ZoneRepository } from './zone.js'\n\nexport type RepositoryMap = ReturnType<typeof createRepositories>\n\nexport const createRepositories = (storage: AbstractStorage) => ({\n\t'associate-role': new AssociateRoleRepository(storage),\n\t'attribute-group': new AttributeGroupRepository(storage),\n\t'business-unit': new BusinessUnitRepository(storage),\n\tcategory: new CategoryRepository(storage),\n\tcart: new CartRepository(storage),\n\t'cart-discount': new CartDiscountRepository(storage),\n\tcustomer: new CustomerRepository(storage),\n\tchannel: new ChannelRepository(storage),\n\t'customer-group': new CustomerGroupRepository(storage),\n\t'discount-code': new DiscountCodeRepository(storage),\n\textension: new ExtensionRepository(storage),\n\t'inventory-entry': new InventoryEntryRepository(storage),\n\t'key-value-document': new CustomObjectRepository(storage),\n\torder: new OrderRepository(storage),\n\t'order-edit': new OrderEditRepository(storage),\n\tpayment: new PaymentRepository(storage),\n\t'my-cart': new CartRepository(storage),\n\t'my-order': new MyOrderRepository(storage),\n\t'my-customer': new CustomerRepository(storage),\n\t'my-payment': new PaymentRepository(storage),\n\tproduct: new ProductRepository(storage),\n\t'product-type': new ProductTypeRepository(storage),\n\t'product-discount': new ProductDiscountRepository(storage),\n\t'product-projection': new ProductProjectionRepository(storage),\n\t'product-selection': new ProductSelectionRepository(storage),\n\tproject: new ProjectRepository(storage),\n\treview: new ReviewRepository(storage),\n\tquote: new QuoteRepository(storage),\n\t'quote-request': new QuoteRequestRepository(storage),\n\t'shipping-method': new ShippingMethodRepository(storage),\n\t'shopping-list': new ShoppingListRepository(storage),\n\t'staged-quote': new StagedQuoteRepository(storage),\n\t'standalone-price': new StandAlonePriceRepository(storage),\n\tstate: new StateRepository(storage),\n\tstore: new StoreRepository(storage),\n\tsubscription: new SubscriptionRepository(storage),\n\t'tax-category': new TaxCategoryRepository(storage),\n\ttype: new TypeRepository(storage),\n\tzone: new ZoneRepository(storage),\n})\n","import type { Update } from '@commercetools/platform-sdk'\nimport { type Request, type Response, Router } from 'express'\nimport { ParsedQs } from 'qs'\nimport { AbstractResourceRepository } from '../repositories/abstract.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\n\nexport default abstract class AbstractService {\n\tprotected abstract getBasePath(): string\n\tpublic abstract repository: AbstractResourceRepository<any>\n\n\tcreateStatusCode = 201\n\n\tconstructor(parent: Router) {\n\t\tthis.registerRoutes(parent)\n\t}\n\n\textraRoutes(router: Router) {}\n\n\tregisterRoutes(parent: Router) {\n\t\tconst basePath = this.getBasePath()\n\t\tconst router = Router({ mergeParams: true })\n\n\t\t// Bind this first since the `/:id` routes are currently a bit to greedy\n\t\tthis.extraRoutes(router)\n\n\t\trouter.get('/', this.get.bind(this))\n\t\trouter.get('/key=:key', this.getWithKey.bind(this)) // same thing goes for the key routes\n\t\trouter.get('/:id', this.getWithId.bind(this))\n\n\t\trouter.delete('/key=:key', this.deleteWithKey.bind(this))\n\t\trouter.delete('/:id', this.deleteWithId.bind(this))\n\n\t\trouter.post('/', this.post.bind(this))\n\t\trouter.post('/key=:key', this.postWithKey.bind(this))\n\t\trouter.post('/:id', this.postWithId.bind(this))\n\n\t\tparent.use(`/${basePath}`, router)\n\t}\n\n\tget(request: Request, response: Response) {\n\t\tconst limit = this._parseParam(request.query.limit)\n\t\tconst offset = this._parseParam(request.query.offset)\n\n\t\tconst result = this.repository.query(getRepositoryContext(request), {\n\t\t\texpand: this._parseParam(request.query.expand),\n\t\t\twhere: this._parseParam(request.query.where),\n\t\t\tlimit: limit !== undefined ? Number(limit) : undefined,\n\t\t\toffset: offset !== undefined ? Number(offset) : undefined,\n\t\t})\n\t\treturn response.status(200).send(result)\n\t}\n\n\tgetWithId(request: Request, response: Response) {\n\t\tconst result = this._expandWithId(request, request.params['id'])\n\t\tif (!result) {\n\t\t\treturn response.status(404).send()\n\t\t}\n\t\treturn response.status(200).send(result)\n\t}\n\n\tgetWithKey(request: Request, response: Response) {\n\t\tconst result = this.repository.getByKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.params['key'],\n\t\t\t{ expand: this._parseParam(request.query.expand) }\n\t\t)\n\t\tif (!result) return response.status(404).send()\n\t\treturn response.status(200).send(result)\n\t}\n\n\tdeleteWithId(request: Request, response: Response) {\n\t\tconst result = this.repository.delete(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.params['id'],\n\t\t\t{\n\t\t\t\texpand: this._parseParam(request.query.expand),\n\t\t\t}\n\t\t)\n\t\tif (!result) {\n\t\t\treturn response.status(404).send('Not found')\n\t\t}\n\t\treturn response.status(200).send(result)\n\t}\n\n\tdeleteWithKey(request: Request, response: Response) {\n\t\tconst resource = this.repository.getByKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.params['key']\n\t\t)\n\t\tif (!resource) {\n\t\t\treturn response.status(404).send('Not found')\n\t\t}\n\n\t\tconst result = this.repository.delete(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresource.id,\n\t\t\t{\n\t\t\t\texpand: this._parseParam(request.query.expand),\n\t\t\t}\n\t\t)\n\t\tif (!result) {\n\t\t\treturn response.status(404).send('Not found')\n\t\t}\n\t\treturn response.status(200).send(result)\n\t}\n\n\tpost(request: Request, response: Response) {\n\t\tconst draft = request.body\n\t\tconst resource = this.repository.create(\n\t\t\tgetRepositoryContext(request),\n\t\t\tdraft\n\t\t)\n\t\tconst result = this._expandWithId(request, resource.id)\n\t\treturn response.status(this.createStatusCode).send(result)\n\t}\n\n\tpostWithId(request: Request, response: Response) {\n\t\tconst updateRequest: Update = request.body\n\t\tconst resource = this.repository.get(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.params['id']\n\t\t)\n\t\tif (!resource) {\n\t\t\treturn response.status(404).send('Not found')\n\t\t}\n\n\t\tconst updatedResource = this.repository.processUpdateActions(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresource,\n\t\t\tupdateRequest.version,\n\t\t\tupdateRequest.actions\n\t\t)\n\n\t\tconst result = this._expandWithId(request, updatedResource.id)\n\t\treturn response.status(200).send(result)\n\t}\n\n\tpostWithKey(request: Request, response: Response) {\n\t\tconst updateRequest: Update = request.body\n\t\tconst resource = this.repository.getByKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.params['key']\n\t\t)\n\t\tif (!resource) {\n\t\t\treturn response.status(404).send('Not found')\n\t\t}\n\t\tconst updatedResource = this.repository.processUpdateActions(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresource,\n\t\t\tupdateRequest.version,\n\t\t\tupdateRequest.actions\n\t\t)\n\n\t\tconst result = this._expandWithId(request, updatedResource.id)\n\t\treturn response.status(200).send(result)\n\t}\n\n\tprotected _expandWithId(request: Request, resourceId: string) {\n\t\tconst result = this.repository.get(\n\t\t\tgetRepositoryContext(request),\n\t\t\tresourceId,\n\t\t\t{\n\t\t\t\texpand: this._parseParam(request.query.expand),\n\t\t\t}\n\t\t)\n\t\treturn result\n\t}\n\n\t// No idea what i'm doing\n\tprotected _parseParam(\n\t\tvalue: string | ParsedQs | string[] | ParsedQs[] | undefined\n\t): string[] | undefined {\n\t\tif (Array.isArray(value)) {\n\t\t\t// @ts-ignore\n\t\t\treturn value\n\t\t} else if (value !== undefined) {\n\t\t\treturn [`${value}`]\n\t\t}\n\t\treturn undefined\n\t}\n}\n","import type { Cart, CartDraft, Order } from '@commercetools/platform-sdk'\nimport type { Request, Response, Router } from 'express'\nimport type { CartRepository } from '../repositories/cart.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport type { OrderRepository } from '../repositories/order.js'\nimport AbstractService from './abstract.js'\n\nexport class CartService extends AbstractService {\n\tpublic repository: CartRepository\n\tpublic orderRepository: OrderRepository\n\n\tconstructor(\n\t\tparent: Router,\n\t\tcartRepository: CartRepository,\n\t\torderRepository: OrderRepository\n\t) {\n\t\tsuper(parent)\n\t\tthis.repository = cartRepository\n\t\tthis.orderRepository = orderRepository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'carts'\n\t}\n\n\textraRoutes(parent: Router) {\n\t\tparent.post('/replicate', this.replicate.bind(this))\n\t}\n\n\treplicate(request: Request, response: Response) {\n\t\tconst context = getRepositoryContext(request)\n\n\t\t// @ts-ignore\n\t\tconst cartOrOrder: Cart | Order | null =\n\t\t\trequest.body.reference.typeId === 'order'\n\t\t\t\t? this.orderRepository.get(context, request.body.reference.id)\n\t\t\t\t: this.repository.get(context, request.body.reference.id)\n\n\t\tif (!cartOrOrder) {\n\t\t\treturn response.status(400).send()\n\t\t}\n\n\t\tconst cartDraft: CartDraft = {\n\t\t\t...cartOrOrder,\n\t\t\tcurrency: cartOrOrder.totalPrice.currencyCode,\n\t\t\tdiscountCodes: [],\n\t\t\tshipping: [], // TODO: cartOrOrder.shipping,\n\t\t\tlineItems: cartOrOrder.lineItems.map((lineItem) => ({\n\t\t\t\t...lineItem,\n\t\t\t\tvariantId: lineItem.variant.id,\n\t\t\t\tsku: lineItem.variant.sku,\n\t\t\t})),\n\t\t}\n\n\t\tconst newCart = this.repository.create(context, cartDraft)\n\n\t\treturn response.status(200).send(newCart)\n\t}\n}\n","import { Router } from 'express'\nimport { CartDiscountRepository } from '../repositories/cart-discount.js'\nimport AbstractService from './abstract.js'\n\nexport class CartDiscountService extends AbstractService {\n\tpublic repository: CartDiscountRepository\n\n\tconstructor(parent: Router, repository: CartDiscountRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'cart-discounts'\n\t}\n}\n","import { Router } from 'express'\nimport { CategoryRepository } from '../repositories/category.js'\nimport AbstractService from './abstract.js'\n\nexport class CategoryServices extends AbstractService {\n\tpublic repository: CategoryRepository\n\n\tconstructor(parent: Router, repository: CategoryRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'categories'\n\t}\n}\n","import { Router } from 'express'\nimport { ChannelRepository } from '../repositories/channel.js'\nimport AbstractService from './abstract.js'\n\nexport class ChannelService extends AbstractService {\n\tpublic repository: ChannelRepository\n\n\tconstructor(parent: Router, repository: ChannelRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'channels'\n\t}\n}\n","import type { CustomObjectDraft } from '@commercetools/platform-sdk'\nimport type { Request, Response, Router } from 'express'\nimport type { CustomObjectRepository } from '../repositories/custom-object.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport AbstractService from './abstract.js'\n\nexport class CustomObjectService extends AbstractService {\n\tpublic repository: CustomObjectRepository\n\n\tconstructor(parent: Router, repository: CustomObjectRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'custom-objects'\n\t}\n\n\textraRoutes(router: Router) {\n\t\trouter.get('/:container/:key', this.getWithContainerAndKey.bind(this))\n\t\trouter.post('/:container/:key', this.createWithContainerAndKey.bind(this))\n\t\trouter.delete('/:container/:key', this.deleteWithContainerAndKey.bind(this))\n\t}\n\n\tgetWithContainerAndKey(request: Request, response: Response) {\n\t\tconst result = this.repository.getWithContainerAndKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.params.container,\n\t\t\trequest.params.key\n\t\t)\n\n\t\tif (!result) {\n\t\t\treturn response.status(404).send('Not Found')\n\t\t}\n\t\treturn response.status(200).send(result)\n\t}\n\n\tcreateWithContainerAndKey(request: Request, response: Response) {\n\t\tconst draft: CustomObjectDraft = {\n\t\t\t...request.body,\n\t\t\tkey: request.params.key,\n\t\t\tcontainer: request.params.container,\n\t\t}\n\n\t\tconst result = this.repository.create(getRepositoryContext(request), draft)\n\t\treturn response.status(200).send(result)\n\t}\n\n\tdeleteWithContainerAndKey(request: Request, response: Response) {\n\t\tconst current = this.repository.getWithContainerAndKey(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.params.container,\n\t\t\trequest.params.key\n\t\t)\n\n\t\tif (!current) {\n\t\t\treturn response.status(404).send('Not Found')\n\t\t}\n\n\t\tconst result = this.repository.delete(\n\t\t\tgetRepositoryContext(request),\n\t\t\tcurrent.id\n\t\t)\n\n\t\treturn response.status(200).send(result)\n\t}\n}\n","import { Router } from 'express'\nimport { v4 as uuidv4 } from 'uuid'\nimport { getBaseResourceProperties } from '../helpers.js'\nimport { CustomerRepository } from '../repositories/customer.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport AbstractService from './abstract.js'\n\nexport class CustomerService extends AbstractService {\n\tpublic repository: CustomerRepository\n\n\tconstructor(parent: Router, repository: CustomerRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'customers'\n\t}\n\n\textraRoutes(parent: Router) {\n\t\tparent.post('/password-token', (request, response) => {\n\t\t\tconst customer = this.repository.query(getRepositoryContext(request), {\n\t\t\t\twhere: [`email=\"${request.body.email}\"`],\n\t\t\t})\n\t\t\t// @ts-ignore\n\t\t\tconst ttlMinutes: number = request.params.ttlMinutes\n\t\t\t\t? // @ts-ignore\n\t\t\t\t +request.params.ttlMinutes\n\t\t\t\t: 34560\n\t\t\tconst { version, ...rest } = getBaseResourceProperties()\n\n\t\t\treturn response.status(200).send({\n\t\t\t\t...rest,\n\t\t\t\tcustomerId: customer.results[0].id,\n\t\t\t\texpiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),\n\t\t\t\tvalue: uuidv4(),\n\t\t\t})\n\t\t})\n\t}\n}\n","import { Router } from 'express'\nimport { CustomerGroupRepository } from '../repositories/customer-group.js'\nimport AbstractService from './abstract.js'\n\nexport class CustomerGroupService extends AbstractService {\n\tpublic repository: CustomerGroupRepository\n\n\tconstructor(parent: Router, repository: CustomerGroupRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'customer-groups'\n\t}\n}\n","import { Router } from 'express'\nimport { DiscountCodeRepository } from '../repositories/discount-code.js'\nimport AbstractService from './abstract.js'\n\nexport class DiscountCodeService extends AbstractService {\n\tpublic repository: DiscountCodeRepository\n\n\tconstructor(parent: Router, repository: DiscountCodeRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'discount-codes'\n\t}\n}\n","import { Router } from 'express'\nimport { ExtensionRepository } from '../repositories/extension.js'\nimport AbstractService from './abstract.js'\n\nexport class ExtensionServices extends AbstractService {\n\tpublic repository: ExtensionRepository\n\n\tconstructor(parent: Router, repository: ExtensionRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'extensions'\n\t}\n}\n","import { Router } from 'express'\nimport { InventoryEntryRepository } from '../repositories/inventory-entry.js'\nimport AbstractService from './abstract.js'\n\nexport class InventoryEntryService extends AbstractService {\n\tpublic repository: InventoryEntryRepository\n\n\tconstructor(parent: Router, repository: InventoryEntryRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'inventory'\n\t}\n}\n","import { Request, Response, Router } from 'express'\nimport { CartRepository } from '../repositories/cart.js'\nimport AbstractService from './abstract.js'\n\nexport class MyCartService extends AbstractService {\n\tpublic repository: CartRepository\n\n\tconstructor(parent: Router, repository: CartRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'me'\n\t}\n\n\tregisterRoutes(parent: Router) {\n\t\t// Overwrite this function to be able to handle /me/active-cart path.\n\t\tconst basePath = this.getBasePath()\n\t\tconst router = Router({ mergeParams: true })\n\n\t\tthis.extraRoutes(router)\n\n\t\trouter.get('/active-cart', this.activeCart.bind(this))\n\t\trouter.get('/carts/', this.get.bind(this))\n\t\trouter.get('/carts/:id', this.getWithId.bind(this))\n\n\t\trouter.delete('/carts/:id', this.deleteWithId.bind(this))\n\n\t\trouter.post('/carts/', this.post.bind(this))\n\t\trouter.post('/carts/:id', this.postWithId.bind(this))\n\n\t\tparent.use(`/${basePath}`, router)\n\t}\n\n\tactiveCart(request: Request, response: Response) {\n\t\tconst resource = this.repository.getActiveCart(request.params.projectKey)\n\t\tif (!resource) {\n\t\t\treturn response.status(404).send('Not found')\n\t\t}\n\t\treturn response.status(200).send(resource)\n\t}\n}\n","import { Request, Response, Router } from 'express'\nimport { CustomerRepository } from '../repositories/customer.js'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport AbstractService from './abstract.js'\n\nexport class MyCustomerService extends AbstractService {\n\tpublic repository: CustomerRepository\n\n\tconstructor(parent: Router, repository: CustomerRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'me'\n\t}\n\n\tregisterRoutes(parent: Router) {\n\t\t// Overwrite this function to be able to handle /me path.\n\t\tconst basePath = this.getBasePath()\n\t\tconst router = Router({ mergeParams: true })\n\n\t\tthis.extraRoutes(router)\n\n\t\trouter.get('', this.getMe.bind(this))\n\n\t\trouter.post('/signup', this.signUp.bind(this))\n\n\t\trouter.post('/login', this.signIn.bind(this))\n\n\t\tparent.use(`/${basePath}`, router)\n\t}\n\n\tgetMe(request: Request, response: Response) {\n\t\tconst resource = this.repository.getMe(getRepositoryContext(request))\n\t\tif (!resource) {\n\t\t\treturn response.status(404).send('Not found')\n\t\t}\n\t\treturn response.status(200).send(resource)\n\t}\n\n\tsignUp(request: Request, response: Response) {\n\t\tconst draft = request.body\n\t\tconst resource = this.repository.create(\n\t\t\tgetRepositoryContext(request),\n\t\t\tdraft\n\t\t)\n\t\tconst result = this._expandWithId(request, resource.id)\n\t\treturn response.status(this.createStatusCode).send({ customer: result })\n\t}\n\n\tsignIn(request: Request, response: Response) {\n\t\tconst { email, password } = request.body\n\t\tconst encodedPassword = Buffer.from(password).toString('base64')\n\n\t\tconst result = this.repository.query(getRepositoryContext(request), {\n\t\t\twhere: [`email = \"${email}\"`, `password = \"${encodedPassword}\"`],\n\t\t})\n\n\t\tif (result.count === 0) {\n\t\t\treturn response.status(400).send({\n\t\t\t\tmessage: 'Account with the given credentials not found.',\n\t\t\t\terrors: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'InvalidCredentials',\n\t\t\t\t\t\tmessage: 'Account with the given credentials not found.',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\n\t\treturn response.status(200).send({ customer: result.results[0] })\n\t}\n}\n","import { Router } from 'express'\nimport { MyOrderRepository } from '../repositories/my-order.js'\nimport AbstractService from './abstract.js'\n\nexport class MyOrderService extends AbstractService {\n\tpublic repository: MyOrderRepository\n\n\tconstructor(parent: Router, repository: MyOrderRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'me'\n\t}\n\n\tregisterRoutes(parent: Router) {\n\t\t// Overwrite this function to be able to handle /me/active-cart path.\n\t\tconst basePath = this.getBasePath()\n\t\tconst router = Router({ mergeParams: true })\n\n\t\tthis.extraRoutes(router)\n\n\t\trouter.get('/orders/', this.get.bind(this))\n\t\trouter.get('/orders/:id', this.getWithId.bind(this))\n\n\t\trouter.delete('/orders/:id', this.deleteWithId.bind(this))\n\n\t\trouter.post('/orders/', this.post.bind(this))\n\t\trouter.post('/orders/:id', this.postWithId.bind(this))\n\n\t\tparent.use(`/${basePath}`, router)\n\t}\n}\n","import { Router } from 'express'\nimport { PaymentRepository } from '../repositories/payment.js'\nimport AbstractService from './abstract.js'\n\nexport class MyPaymentService extends AbstractService {\n\tpublic repository: PaymentRepository\n\n\tconstructor(parent: Router, repository: PaymentRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'me/payments'\n\t}\n}\n","import { Request, Response, Router } from 'express'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport { OrderRepository } from '../repositories/order.js'\nimport AbstractService from './abstract.js'\n\nexport class OrderService extends AbstractService {\n\tpublic repository: OrderRepository\n\n\tconstructor(parent: Router, repository: OrderRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'orders'\n\t}\n\n\textraRoutes(router: Router) {\n\t\trouter.post('/import', this.import.bind(this))\n\t\trouter.get('/order-number=:orderNumber', this.getWithOrderNumber.bind(this))\n\t}\n\n\timport(request: Request, response: Response) {\n\t\tconst importDraft = request.body\n\t\tconst resource = this.repository.import(\n\t\t\tgetRepositoryContext(request),\n\t\t\timportDraft\n\t\t)\n\t\treturn response.status(200).send(resource)\n\t}\n\n\tgetWithOrderNumber(request: Request, response: Response) {\n\t\tconst resource = this.repository.getWithOrderNumber(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.params.orderNumber,\n\t\t\trequest.query\n\t\t)\n\t\tif (resource) {\n\t\t\treturn response.status(200).send(resource)\n\t\t}\n\t\treturn response.status(404).send('Not found')\n\t}\n}\n","import { Router } from 'express'\nimport { PaymentRepository } from '../repositories/payment.js'\nimport AbstractService from './abstract.js'\n\nexport class PaymentService extends AbstractService {\n\tpublic repository: PaymentRepository\n\n\tconstructor(parent: Router, repository: PaymentRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'payments'\n\t}\n}\n","import { Router } from 'express'\nimport { ProductRepository } from '../repositories/product.js'\nimport AbstractService from './abstract.js'\n\nexport class ProductService extends AbstractService {\n\tpublic repository: ProductRepository\n\n\tconstructor(parent: Router, repository: ProductRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'products'\n\t}\n}\n","import { Router } from 'express'\nimport { ProductDiscountRepository } from '../repositories/product-discount.js'\nimport AbstractService from './abstract.js'\n\nexport class ProductDiscountService extends AbstractService {\n\tpublic repository: ProductDiscountRepository\n\n\tconstructor(parent: Router, repository: ProductDiscountRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'product-discounts'\n\t}\n}\n","import { Request, Response, Router } from 'express'\nimport { getRepositoryContext } from '../repositories/helpers.js'\nimport { ProductProjectionRepository } from './../repositories/product-projection.js'\nimport AbstractService from './abstract.js'\n\nexport class ProductProjectionService extends AbstractService {\n\tpublic repository: ProductProjectionRepository\n\n\tconstructor(parent: Router, repository: ProductProjectionRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'product-projections'\n\t}\n\n\textraRoutes(router: Router) {\n\t\trouter.get('/search', this.search.bind(this))\n\t}\n\n\tget(request: Request, response: Response) {\n\t\tconst limit = this._parseParam(request.query.limit)\n\t\tconst offset = this._parseParam(request.query.offset)\n\n\t\tconst result = this.repository.query(getRepositoryContext(request), {\n\t\t\t...request.query,\n\t\t\texpand: this._parseParam(request.query.expand),\n\t\t\twhere: this._parseParam(request.query.where),\n\t\t\tlimit: limit !== undefined ? Number(limit) : undefined,\n\t\t\toffset: offset !== undefined ? Number(offset) : undefined,\n\t\t})\n\t\treturn response.status(200).send(result)\n\t}\n\n\tsearch(request: Request, response: Response) {\n\t\tconst resource = this.repository.search(\n\t\t\tgetRepositoryContext(request),\n\t\t\trequest.query\n\t\t)\n\t\treturn response.status(200).send(resource)\n\t}\n}\n","import { Router } from 'express'\nimport { ProductTypeRepository } from '../repositories/product-type.js'\nimport AbstractService from './abstract.js'\n\nexport class ProductTypeService extends AbstractService {\n\tpublic repository: ProductTypeRepository\n\n\tconstructor(parent: Router, repository: ProductTypeRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'product-types'\n\t}\n}\n","import { Router } from 'express'\nimport { ShippingMethodRepository } from '../repositories/shipping-method.js'\nimport AbstractService from './abstract.js'\n\nexport class ShippingMethodService extends AbstractService {\n\tpublic repository: ShippingMethodRepository\n\n\tconstructor(parent: Router, repository: ShippingMethodRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t\tthis.registerRoutes(parent)\n\t}\n\n\tgetBasePath() {\n\t\treturn 'shipping-methods'\n\t}\n\n\textraRoutes(parent: Router) {\n\t\tparent.get('/matching-cart', this.get.bind(this))\n\t}\n}\n","import { Router } from 'express'\nimport { ShoppingListRepository } from './../repositories/shopping-list.js'\nimport AbstractService from './abstract.js'\n\nexport class ShoppingListService extends AbstractService {\n\tpublic repository: ShoppingListRepository\n\n\tconstructor(parent: Router, repository: ShoppingListRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'shopping-lists'\n\t}\n}\n","import { Router } from 'express'\nimport { StandAlonePriceRepository } from '../repositories/standalone-price.js'\nimport AbstractService from './abstract.js'\n\nexport class StandAlonePriceService extends AbstractService {\n\tpublic repository: StandAlonePriceRepository\n\n\tconstructor(parent: Router, repository: StandAlonePriceRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'standalone-prices'\n\t}\n}\n","import { Router } from 'express'\nimport { StateRepository } from '../repositories/state.js'\nimport AbstractService from './abstract.js'\n\nexport class StateService extends AbstractService {\n\tpublic repository: StateRepository\n\n\tconstructor(parent: Router, repository: StateRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'states'\n\t}\n}\n","import { Router } from 'express'\nimport { StoreRepository } from '../repositories/store.js'\nimport AbstractService from './abstract.js'\n\nexport class StoreService extends AbstractService {\n\tpublic repository: StoreRepository\n\n\tconstructor(parent: Router, repository: StoreRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'stores'\n\t}\n}\n","import { Router } from 'express'\nimport { SubscriptionRepository } from '../repositories/subscription.js'\nimport AbstractService from './abstract.js'\n\nexport class SubscriptionService extends AbstractService {\n\tpublic repository: SubscriptionRepository\n\n\tconstructor(parent: Router, repository: SubscriptionRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'subscriptions'\n\t}\n}\n","import { Router } from 'express'\nimport { TaxCategoryRepository } from '../repositories/tax-category.js'\nimport AbstractService from './abstract.js'\n\nexport class TaxCategoryService extends AbstractService {\n\tpublic repository: TaxCategoryRepository\n\n\tconstructor(parent: Router, repository: TaxCategoryRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'tax-categories'\n\t}\n}\n","import { Router } from 'express'\nimport { TypeRepository } from '../repositories/type.js'\nimport AbstractService from './abstract.js'\n\nexport class TypeService extends AbstractService {\n\tpublic repository: TypeRepository\n\n\tconstructor(parent: Router, repository: TypeRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'types'\n\t}\n}\n","import { Router } from 'express'\nimport { ZoneRepository } from '../repositories/zone.js'\nimport AbstractService from './abstract.js'\n\nexport class ZoneService extends AbstractService {\n\tpublic repository: ZoneRepository\n\n\tconstructor(parent: Router, repository: ZoneRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'zones'\n\t}\n}\n","import { Router } from 'express'\nimport AbstractService from './abstract.js'\nimport { AttributeGroupRepository } from '../repositories/attribute-group.js'\n\nexport class AttributeGroupService extends AbstractService {\n\tpublic repository: AttributeGroupRepository\n\n\tconstructor(parent: Router, repository: AttributeGroupRepository) {\n\t\tsuper(parent)\n\t\tthis.repository = repository\n\t}\n\n\tgetBasePath() {\n\t\treturn 'attribute-groups'\n\t}\n}\n","import { CartService } from './cart.js'\nimport { CartDiscountService } from './cart-discount.js'\nimport { CategoryServices } from './category.js'\nimport { ChannelService } from './channel.js'\nimport { CustomObjectService } from './custom-object.js'\nimport { CustomerService } from './customer.js'\nimport { CustomerGroupService } from './customer-group.js'\nimport { DiscountCodeService } from './discount-code.js'\nimport { ExtensionServices } from './extension.js'\nimport { InventoryEntryService } from './inventory-entry.js'\nimport { MyCartService } from './my-cart.js'\nimport { MyCustomerService } from './my-customer.js'\nimport { MyOrderService } from './my-order.js'\nimport { MyPaymentService } from './my-payment.js'\nimport { OrderService } from './order.js'\nimport { PaymentService } from './payment.js'\nimport { ProductService } from './product.js'\nimport { ProductDiscountService } from './product-discount.js'\nimport { ProductProjectionService } from './product-projection.js'\nimport { ProductTypeService } from './product-type.js'\nimport { ShippingMethodService } from './shipping-method.js'\nimport { ShoppingListService } from './shopping-list.js'\nimport { StandAlonePriceService } from './standalone-price.js'\nimport { StateService } from './state.js'\nimport { StoreService } from './store.js'\nimport { SubscriptionService } from './subscription.js'\nimport { TaxCategoryService } from './tax-category.js'\nimport { TypeService } from './type.js'\nimport { ZoneService } from './zone.js'\nimport { AttributeGroupService } from './attribute-group.js'\n\nexport const createServices = (router: any, repos: any) => ({\n\tcategory: new CategoryServices(router, repos['category']),\n\tcart: new CartService(router, repos['cart'], repos['order']),\n\t'cart-discount': new CartDiscountService(router, repos['cart-discount']),\n\tcustomer: new CustomerService(router, repos['customer']),\n\tchannel: new ChannelService(router, repos['channel']),\n\t'customer-group': new CustomerGroupService(router, repos['customer-group']),\n\t'discount-code': new DiscountCodeService(router, repos['discount-code']),\n\textension: new ExtensionServices(router, repos['extension']),\n\t'inventory-entry': new InventoryEntryService(\n\t\trouter,\n\t\trepos['inventory-entry']\n\t),\n\t'key-value-document': new CustomObjectService(\n\t\trouter,\n\t\trepos['key-value-document']\n\t),\n\torder: new OrderService(router, repos['order']),\n\tpayment: new PaymentService(router, repos['payment']),\n\t'standalone-price': new StandAlonePriceService(\n\t\trouter,\n\t\trepos['standalone-price']\n\t),\n\t'my-cart': new MyCartService(router, repos['my-cart']),\n\t'my-order': new MyOrderService(router, repos['my-order']),\n\t'my-customer': new MyCustomerService(router, repos['my-customer']),\n\t'my-payment': new MyPaymentService(router, repos['my-payment']),\n\t'shipping-method': new ShippingMethodService(\n\t\trouter,\n\t\trepos['shipping-method']\n\t),\n\t'product-type': new ProductTypeService(router, repos['product-type']),\n\tproduct: new ProductService(router, repos['product']),\n\t'product-discount': new ProductDiscountService(\n\t\trouter,\n\t\trepos['product-discount']\n\t),\n\t'product-projection': new ProductProjectionService(\n\t\trouter,\n\t\trepos['product-projection']\n\t),\n\t'shopping-list': new ShoppingListService(router, repos['shopping-list']),\n\tstate: new StateService(router, repos['state']),\n\tstore: new StoreService(router, repos['store']),\n\tsubscription: new SubscriptionService(router, repos['subscription']),\n\t'tax-category': new TaxCategoryService(router, repos['tax-category']),\n\t'attribute-group': new AttributeGroupService(\n\t\trouter,\n\t\trepos['attribute-group']\n\t),\n\ttype: new TypeService(router, repos['type']),\n\tzone: new ZoneService(router, repos['zone']),\n})\n"],"mappings":";AAAA,OAAO,UAAU;AACjB,OAAOA,cAAkD;AACzD,OAAO,eAAe;AACtB,OAAO,YAAY;;;ACmBZ,IAAe,kBAAf,MAA+B;AAuDtC;;;ACxCA,OAAO,YAAY;;;ACjCZ,IAAM,qBAAN,cAAsD,MAAM;AAAA,EAClE;AAAA,EACA;AAAA,EAEA,YAAY,MAAS,aAAa,KAAK;AACtC,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;A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AM,KAAK;AAEjB,SAAK,YAAY,OAAO,KAAK,KAAK,QAAQ,QAAQ,EAChD,QAAQ,EACR,KAAK,cAAc,EACnB,MAAM,eAAgB,KAAK,MAAM;AACjC,YAAM,WAAW,MAAM,UAAU,GAAG,EAClC,KAAK,MAAM,MAAM,IAAI,EACrB,IAAI,YAAY,KAAK,IAAI,OAAO,CAAC,EACjC,KAAK;AACP,aAAO,CAAC,SAAS,QAAQ,SAAS,IAAI;AAAA,IACvC,CAAC;AAAA,EACH;AACD;","names":["express","e","uuidv4","uuidv4","uuidv4","uuidv4","uuidv4","uuidv4","assert","assert","assert","assert","uuidv4","uuidv4","uuidv4","deepEqual","variant","uuidv4","generateMatchFunc","getLexer","deepEqual","deepEqual","uuidv4","uuidv4","uuidv4","uuidv4","Router","Router","Router","Router","Router","Router","express"]}