@labdigital/commercetools-mock 0.5.11 → 0.5.14

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 (115) hide show
  1. package/README.md +30 -12
  2. package/dist/commercetools-mock.cjs.development.js +3190 -1574
  3. package/dist/commercetools-mock.cjs.development.js.map +1 -1
  4. package/dist/commercetools-mock.cjs.production.min.js +1 -1
  5. package/dist/commercetools-mock.cjs.production.min.js.map +1 -1
  6. package/dist/commercetools-mock.esm.js +3190 -1574
  7. package/dist/commercetools-mock.esm.js.map +1 -1
  8. package/dist/ctMock.d.ts +1 -0
  9. package/dist/lib/filterParser.d.ts +1 -0
  10. package/dist/repositories/abstract.d.ts +11 -7
  11. package/dist/repositories/cart-discount.d.ts +9 -0
  12. package/dist/repositories/cart.d.ts +16 -3
  13. package/dist/repositories/category.d.ts +18 -0
  14. package/dist/repositories/channel.d.ts +6 -0
  15. package/dist/repositories/custom-object.d.ts +2 -2
  16. package/dist/repositories/customer-group.d.ts +11 -0
  17. package/dist/repositories/customer.d.ts +2 -2
  18. package/dist/repositories/discount-code.d.ts +8 -0
  19. package/dist/repositories/errors.d.ts +2 -2
  20. package/dist/repositories/extension.d.ts +8 -0
  21. package/dist/repositories/inventory-entry.d.ts +2 -2
  22. package/dist/repositories/order.d.ts +2 -2
  23. package/dist/repositories/payment.d.ts +4 -3
  24. package/dist/repositories/product-projection.d.ts +10 -0
  25. package/dist/repositories/product-type.d.ts +5 -4
  26. package/dist/repositories/product.d.ts +2 -2
  27. package/dist/repositories/project.d.ts +8 -0
  28. package/dist/repositories/shipping-method.d.ts +7 -5
  29. package/dist/repositories/shopping-list.d.ts +6 -0
  30. package/dist/repositories/state.d.ts +5 -4
  31. package/dist/repositories/store.d.ts +6 -3
  32. package/dist/repositories/subscription.d.ts +6 -0
  33. package/dist/repositories/tax-category.d.ts +6 -5
  34. package/dist/repositories/type.d.ts +5 -3
  35. package/dist/repositories/zone.d.ts +8 -0
  36. package/dist/services/abstract.d.ts +4 -3
  37. package/dist/services/cart-discount.d.ts +9 -0
  38. package/dist/services/category.d.ts +9 -0
  39. package/dist/services/channel.d.ts +9 -0
  40. package/dist/services/custom-object.d.ts +2 -0
  41. package/dist/services/customer-group.d.ts +9 -0
  42. package/dist/services/discount-code.d.ts +9 -0
  43. package/dist/services/extension.d.ts +9 -0
  44. package/dist/services/my-cart.d.ts +11 -0
  45. package/dist/services/product-projection.d.ts +11 -0
  46. package/dist/services/project.d.ts +11 -0
  47. package/dist/services/shopping-list.d.ts +9 -0
  48. package/dist/services/subscription.d.ts +9 -0
  49. package/dist/services/zone.d.ts +9 -0
  50. package/dist/storage.d.ts +27 -16
  51. package/dist/types.d.ts +9 -4
  52. package/package.json +20 -20
  53. package/src/ctMock.ts +49 -15
  54. package/src/lib/filterParser.test.ts +15 -0
  55. package/src/lib/filterParser.ts +17 -0
  56. package/src/oauth/server.ts +3 -1
  57. package/src/repositories/abstract.ts +49 -34
  58. package/src/repositories/cart-discount.ts +140 -0
  59. package/src/repositories/cart.ts +247 -3
  60. package/src/repositories/category.ts +140 -0
  61. package/src/repositories/channel.ts +23 -0
  62. package/src/repositories/custom-object.ts +5 -2
  63. package/src/repositories/customer-group.ts +42 -0
  64. package/src/repositories/customer.ts +2 -2
  65. package/src/repositories/discount-code.ts +143 -0
  66. package/src/repositories/errors.ts +7 -2
  67. package/src/repositories/extension.ts +65 -0
  68. package/src/repositories/inventory-entry.ts +2 -2
  69. package/src/repositories/order.ts +2 -2
  70. package/src/repositories/payment.ts +10 -6
  71. package/src/repositories/product-projection.ts +74 -0
  72. package/src/repositories/product-type.ts +57 -4
  73. package/src/repositories/product.ts +4 -2
  74. package/src/repositories/project.ts +150 -0
  75. package/src/repositories/shipping-method.ts +149 -13
  76. package/src/repositories/shopping-list.ts +50 -0
  77. package/src/repositories/state.ts +48 -4
  78. package/src/repositories/store.ts +69 -4
  79. package/src/repositories/subscription.ts +50 -0
  80. package/src/repositories/tax-category.ts +80 -6
  81. package/src/repositories/type.ts +133 -3
  82. package/src/repositories/zone.ts +77 -0
  83. package/src/server.ts +6 -1
  84. package/src/services/abstract.ts +26 -18
  85. package/src/services/cart-discount.ts +17 -0
  86. package/src/services/cart.test.ts +314 -3
  87. package/src/services/category.test.ts +37 -0
  88. package/src/services/category.ts +17 -0
  89. package/src/services/channel.ts +17 -0
  90. package/src/services/custom-object.test.ts +53 -3
  91. package/src/services/custom-object.ts +30 -0
  92. package/src/services/customer-group.ts +17 -0
  93. package/src/services/discount-code.ts +17 -0
  94. package/src/services/extension.ts +17 -0
  95. package/src/services/inventory-entry.test.ts +3 -3
  96. package/src/services/my-cart.test.ts +93 -0
  97. package/src/services/my-cart.ts +44 -0
  98. package/src/services/my-payment.test.ts +2 -2
  99. package/src/services/my-payment.ts +1 -1
  100. package/src/services/order.test.ts +4 -4
  101. package/src/services/payment.test.ts +2 -2
  102. package/src/services/product-projection.test.ts +105 -0
  103. package/src/services/product-projection.ts +29 -0
  104. package/src/services/product-type.test.ts +2 -2
  105. package/src/services/product.test.ts +6 -2
  106. package/src/services/project.ts +42 -0
  107. package/src/services/shipping-method.test.ts +3 -3
  108. package/src/services/shopping-list.ts +17 -0
  109. package/src/services/state.test.ts +2 -2
  110. package/src/services/store.test.ts +60 -0
  111. package/src/services/subscription.ts +17 -0
  112. package/src/services/tax-category.test.ts +3 -3
  113. package/src/services/zone.ts +17 -0
  114. package/src/storage.ts +127 -31
  115. package/src/types.ts +9 -3
@@ -1,2 +1,2 @@
1
- "use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("uuid"),r=e(require("deep-equal")),s=require("express"),n=e(s),o=e(require("nock")),i=e(require("supertest")),a=e(require("morgan")),u=e(require("assert")),c=e(require("perplex")),d=require("pratt"),p=e(require("basic-auth")),h=require("crypto");const l=()=>({id:t.v4(),createdAt:(new Date).toISOString(),lastModifiedAt:(new Date).toISOString(),version:0});class y extends Error{constructor(e,t=400){super(e.message),this.info=e,this.statusCode=t||500}}const m=(e,t)=>{if(e.version!==t)throw new y({message:`Object ${e.id} has a different version than expected. Expected: ${t} - Actual: ${e.version}.`,currentVersion:e.version,code:"ConcurrentModification"},409)};class g{constructor(e){this.actions={},this._storage=e,this._storage.assertStorage(this.getTypeId())}query(e,t={}){return this._storage.query(e,this.getTypeId(),{expand:t.expand,where:t.where})}get(e,t,r={}){return this._storage.get(e,this.getTypeId(),t,r)}delete(e,t,r={}){return this._storage.delete(e,this.getTypeId(),t,r)}save(e,t){const r=this.getTypeId(),s=this.get(e,t.id);if(s)m(s,t.version);else if(0!==t.version)throw new y({code:"InvalidOperation",message:"version on create must be 0"},400);t.version+=1,this._storage.add(e,r,t)}processUpdateActions(e,t,s){const n=JSON.parse(JSON.stringify(t));return s.forEach(t=>{const r=this.actions[t.action];r?r(e,n,t):console.error("No mock implemented for update action "+t.action)}),r(n,t)||this.save(e,n),n}}class f extends g{constructor(){super(...arguments),this.attributeDefinitionFromAttributeDefinitionDraft=(e,t)=>{var r,s,n;return{...t,attributeConstraint:null!=(r=t.attributeConstraint)?r:"None",inputHint:null!=(s=t.inputHint)?s:"SingleLine",isSearchable:null==(n=t.isSearchable)||n}},this.actions={}}getTypeId(){return"product-type"}create(e,t){var r;const s={...l(),...t,attributes:(null!=(r=t.attributes)?r:[]).map(t=>this.attributeDefinitionFromAttributeDefinitionDraft(e,t))};return this.save(e,s),s}getWithKey(e,t){const r=this._storage.query(e,this.getTypeId(),{where:[`key="${t}"`]});if(1===r.count)return r.results[0];if(r.count>1)throw new Error("Duplicate product type key")}}class v{constructor(e){this.registerRoutes(e)}extraRoutes(e){}registerRoutes(e){const t=this.getBasePath(),r=s.Router({mergeParams:!0});this.extraRoutes(r),r.get("/",this.get.bind(this)),r.get("/:id",this.getWithId.bind(this)),r.get("/key=:key",this.getWithKey.bind(this)),r.delete("/:id",this.deletewithId.bind(this)),r.delete("/key=:key",this.deletewithKey.bind(this)),r.post("/",this.post.bind(this)),r.post("/:id",this.postWithId.bind(this)),r.post("/key=:key",this.postWithKey.bind(this)),e.use("/"+t,r)}get(e,t){const r=this.repository.query(e.params.projectKey,{expand:this._parseParam(e.query.expand),where:this._parseParam(e.query.where)});return t.status(200).send(r)}getWithId(e,t){return this._expandWithId(e,t,e.params.id)}getWithKey(e,t){return t.status(500).send("Not implemented")}deletewithId(e,t){const r=this.repository.delete(e.params.projectKey,e.params.id,{expand:this._parseParam(e.query.expand)});return r?t.status(200).send(r):t.status(404).send("Not found")}deletewithKey(e,t){return t.status(500).send("Not implemented")}post(e,t){const r=this.repository.create(e.params.projectKey,e.body);return this._expandWithId(e,t,r.id)}postWithId(e,t){const r=e.body,s=this.repository.get(e.params.projectKey,e.params.id);if(!s)return t.status(404).send("Not found");if(s.version!==r.version)return t.status(409).send("Concurrent modification");const n=this.repository.processUpdateActions(e.params.projectKey,s,r.actions);return this._expandWithId(e,t,n.id)}postWithKey(e,t){return t.status(500).send("Not implemented")}_expandWithId(e,t,r){const s=this.repository.get(e.params.projectKey,r,{expand:this._parseParam(e.query.expand)});return s?t.status(200).send(s):t.status(404).send("Not found")}_parseParam(e){return Array.isArray(e)?e:void 0!==e?[""+e]:void 0}}class w extends v{constructor(e,t){super(e),this.repository=new f(t)}getBasePath(){return"product-types"}extraRoutes(e){e.get("/key=:key",this.getWithKey.bind(this))}getWithKey(e,t){const r=this.repository.getWithKey(e.params.projectKey,e.params.key);return r?t.status(200).send(r):t.status(404).send("Not found")}}const k=(e,t,r)=>{if(!e)return;if(!e.type)return;if(!e.type.typeId)return;if(!e.fields)return;const s=r.getByResourceIdentifier(t,e.type);if(!s)throw new Error(`No type '${e.type.typeId}' with id=${e.type.id} or key=${e.type.key}`);return{type:{typeId:e.type.typeId,id:s.id},fields:e.fields}},I=e=>({id:t.v4(),value:_(e.value)}),_=e=>({type:"centPrecision",fractionDigits:2,...e}),b=(e,t,r)=>{if(!e)return;const s=r.getByResourceIdentifier(t,e);if(!s)throw new Error("No such store");return{typeId:"store",key:s.key}},x=(e,t,r)=>{const s=r.getByResourceIdentifier(t,e);if(!s)throw new Error(`resource type ${e.typeId} with id ${e.id} and key ${e.key} not found`);return{typeId:e.typeId,id:null==s?void 0:s.id}};class A extends g{constructor(){super(...arguments),this.zoneRateFromZoneRateDraft=(e,t)=>({...t,zone:x(t.zone,e,this._storage),shippingRates:t.shippingRates.map(e=>({...e,price:_(e.price),freeAbove:e.freeAbove&&_(e.freeAbove),tiers:e.tiers||[]}))}),this.actions={}}getTypeId(){return"shipping-method"}create(e,t){const r={...l(),...t,taxCategory:x(t.taxCategory,e,this._storage),zoneRates:t.zoneRates.map(t=>this.zoneRateFromZoneRateDraft(e,t)),custom:k(t.custom,e,this._storage)};return this.save(e,r),r}}class T extends v{constructor(e,t){super(e),this.repository=new A(t)}getBasePath(){return"shipping-methods"}}class S extends g{constructor(){super(...arguments),this.actions={}}getTypeId(){return"state"}create(e,t){const r={...l(),...t,builtIn:!1,initial:t.initial||!1,transitions:(t.transitions||[]).map(t=>x(t,e,this._storage))};return this.save(e,r),r}}class D extends v{constructor(e,t){super(e),this.repository=new S(t)}getBasePath(){return"states"}}class N extends g{constructor(){super(...arguments),this.taxRateFromTaxRateDraft=e=>({...e,id:t.v4(),amount:e.amount||0}),this.actions={}}getTypeId(){return"tax-category"}create(e,t){const r={...l(),...t,rates:t.rates.map(this.taxRateFromTaxRateDraft)};return this.save(e,r),r}getWithKey(e,t){const r=this._storage.query(e,this.getTypeId(),{where:[`key="${t}"`]});if(1===r.count)return r.results[0];if(r.count>1)throw new Error("Duplicate tax categorie key")}}class R extends v{constructor(e,t){super(e),this.repository=new N(t)}getBasePath(){return"tax-categories"}extraRoutes(e){e.get("/key=:key",this.getWithKey.bind(this))}getWithKey(e,t){const r=this.repository.getWithKey(e.params.projectKey,e.params.key);return r?t.status(200).send(r):t.status(404).send("Not found")}}class P extends g{constructor(){super(...arguments),this.transactionFromTransactionDraft=e=>({...e,id:t.v4(),amount:_(e.amount)}),this.actions={setCustomField:(e,t,{name:r,value:s})=>{if(!t.custom)throw new Error("Resource has no custom field");t.custom.fields[r]=s},setCustomType:(e,t,{type:r,fields:s})=>{if(r){const n=this._storage.getByResourceIdentifier(e,r);if(!n)throw new Error(`Type ${r} not found`);t.custom={type:{typeId:"type",id:n.id},fields:s||[]}}else t.custom=void 0},addTransaction:(e,t,{transaction:r})=>{t.transactions=[...t.transactions,this.transactionFromTransactionDraft(r)]}}}getTypeId(){return"payment"}create(e,t){const r={...l(),amountPlanned:_(t.amountPlanned),paymentMethodInfo:t.paymentMethodInfo,paymentStatus:t.paymentStatus?{...t.paymentStatus,state:t.paymentStatus.state?x(t.paymentStatus.state,e,this._storage):void 0}:{},transactions:(t.transactions||[]).map(this.transactionFromTransactionDraft),interfaceInteractions:(t.interfaceInteractions||[]).map(t=>k(t,e,this._storage)),custom:k(t.custom,e,this._storage)};return this.save(e,r),r}}class E extends v{constructor(e,t){super(e),this.repository=new P(t)}getBasePath(){return"payments"}}class C{constructor(e){this.message=e}}const M=e=>{if(!e.type)throw new C("Internal error");if("identifier"===e.type){var t,r;const s=e.value.charAt(0),n=null==(t=e.pos)?void 0:t.start.line,o=null==(r=e.pos)?void 0:r.start.column;throw new C(`Invalid input '${s}', expected input parameter or primitive value (line ${n}, column ${o})`)}},K=(e,t)=>{if("var"===e.type){if(!(e.value in t))throw new C("Missing parameter value for "+e.value);return t[e.value]}return e.value},q=(e,t)=>{if("identifier"!==t.type)throw new C("Internal error");if(!(t.value in e)){if(Array.isArray(e))return Object.values(e).filter(e=>t.value in e).map(e=>e[t.value]);throw new C(`The field '${t.value}' does not exist.`)}return e[t.value]},O=e=>{const t=new c(e).token("AND",/and(?![-_a-z0-9]+)/i).token("OR",/or(?![-_a-z0-9]+)/i).token("NOT",/not(?![-_a-z0-9]+)/i).token("WITHIN",/within(?![-_a-z0-9]+)/i).token("IN",/in(?![-_a-z0-9]+)/i).token("MATCHES_IGNORE_CASE",/matches\s+ignore\s+case(?![-_a-z0-9]+)/i).token("CONTAINS",/contains(?![-_a-z0-9]+)/i).token("ALL",/all(?![-_a-z0-9]+)/i).token("ANY",/any(?![-_a-z0-9]+)/i).token("EMPTY",/empty(?![-_a-z0-9]+)/i).token("IS",/is(?![-_a-z0-9]+)/i).token("DEFINED",/defined(?![-_a-z0-9]+)/i).token("FLOAT",/\d+\.\d+/).token("INT",/\d+/).token("VARIABLE",/:([-_A-Za-z0-9]+)/).token("IDENTIFIER",/[-_A-Za-z0-9]+/).token("STRING",/"((?:\\.|[^"\\])*)"/).token("STRING",/'((?:\\.|[^'\\])*)'/).token("COMMA",",").token("(","(").token(")",")").token(">=",">=").token("<=","<=").token(">",">").token("<","<").token("!=","!=").token("=","=").token('"','"').token("WS",/\s+/,!0),r=new d.Parser(t).builder().nud("IDENTIFIER",100,e=>({type:"identifier",value:e.token.match,pos:e.token.strpos()})).nud("VARIABLE",100,e=>({type:"var",value:e.token.groups[1],pos:e.token.strpos()})).nud("STRING",100,e=>({type:"string",value:e.token.groups[1],pos:e.token.strpos()})).nud("INT",1,e=>({type:"int",value:parseInt(e.token.match,10),pos:e.token.strpos()})).nud("FLOAT",1,e=>({type:"float",value:parseFloat(e.token.match),pos:e.token.strpos()})).nud("NOT",100,({bp:e})=>{const t=r.parse({terminals:[e-1]});return e=>!t(e)}).nud("EMPTY",10,({})=>"empty").nud("DEFINED",10,({})=>"defined").led("AND",5,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return t=>e(t)&&s(t)}).led("OR",5,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return(t,r)=>e(t,r)||s(t,r)}).led("COMMA",1,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return Array.isArray(s)?[e,...s]:[e,s]}).nud("(",100,e=>r.parse({terminals:[")"]})).led("(",100,({left:e})=>{const s=r.parse();return t.expect(")"),(t,r)=>{const n=q(t,e);return!!n&&s(n)}}).bp(")",0).led("=",20,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return M(s),(t,r)=>{const n=q(t,e),o=K(s,r);return Array.isArray(n)?!!n.some(e=>e===o):n===o}}).led("!=",20,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return M(s),(t,r)=>q(t,e)!==K(s,r)}).led(">",20,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return M(s),(t,r)=>q(t,e)>K(s,r)}).led(">=",20,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return M(s),(t,r)=>q(t,e)>=K(s,r)}).led("<",20,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return M(s),(t,r)=>q(t,e)<K(s,r)}).led("<=",20,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return M(s),(t,r)=>q(t,e)<=K(s,r)}).led("IS",20,({left:e,bp:s})=>{let n=!1;switch("NOT"===t.peek().type&&(n=!0,t.next()),r.parse({terminals:[s-1]})){case"empty":return n?(t,r)=>0!==q(t,e).length:(t,r)=>0===q(t,e).length;case"defined":return n?(t,r)=>void 0===q(t,e):(t,r)=>void 0!==q(t,e);default:throw new Error("Unexpected")}}).led("IN",20,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return(t,r)=>{let n=s;return Array.isArray(n)||(n=[s]),n.map(e=>K(e,r)).includes(q(t,e))}}).led("MATCHES_IGNORE_CASE",20,({left:e,bp:t})=>{const s=r.parse({terminals:[t-1]});return M(s),(t,r)=>{const n=q(t,e),o=K(s,r);if("string"!=typeof n)throw new C(`The field '${e.value}' does not support this expression.`);return n.toLowerCase()===o.toLowerCase()}}).led("WITHIN",20,({left:e})=>{const s=t.next();if("circle"!==s.match)throw new C(`Invalid input '${s.match}', expected circle`);t.expect("(");const n=r.parse({terminals:[")"]});return(t,r)=>{const s=q(t,e);if(!s)return!1;const o=K(n[2],r);return((e,t)=>{const r=e=>e*(Math.PI/180),s=r(t.latitude-e.latitude),n=r(t.longitude-e.longitude);var o=Math.sin(s/2)*Math.sin(s/2)+Math.cos(r(e.latitude))*Math.cos(r(t.latitude))*Math.sin(n/2)*Math.sin(n/2);return 2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o))*6371*1e3})({longitude:s[0],latitude:s[1]},{longitude:K(n[0],r),latitude:K(n[1],r)})<=o}}).led("CONTAINS",20,({left:e})=>{const s=t.next();let n=r.parse();return Array.isArray(n)||(n=[n]),(t,r)=>{const o=q(t,e);if(!Array.isArray(o))throw new C(`The field '${e.value}' does not support this expression.`);const i=n.map(e=>K(e,r));return"ALL"===s.type?i.every(e=>o.includes(e)):i.some(e=>o.includes(e))}}).build(),s=r.parse();if("function"!=typeof s){const t=e.split("\n");throw new C(`Unexpected end of input, expected SphereIdentifierChar, comparison operator, not, in, contains, is, within or matches (line ${t.length}, column ${t[t.length-1].length})`)}return s};class j extends class{}{constructor(){super(...arguments),this.resources={},this.expand=(e,t,r)=>{if(!r)return t;const s=JSON.parse(JSON.stringify(t));return Array.isArray(r)?r.forEach(t=>{this._resolveResource(e,s,t)}):this._resolveResource(e,s,r),s},this._resolveResource=(e,t,r)=>{const s=(e=>{const t={element:e,index:void 0,rest:void 0},r=e.indexOf(".");r>0&&(t.element=e.substring(0,r),t.rest=e.substring(r+1));const s=t.element.match(/\[([^\]+])]/);return s&&(t.index="*"===s[1]?"*":parseInt(s[1],10),t.element=t.element.substring(0,s.index)),t})(r);if(s.index)if("*"===s.index){const r=t[s.element];if(void 0===r||!Array.isArray(r))return;r.forEach(t=>{this._resolveReference(e,t,s.rest)})}else{const r=t[s.element][s.index];if(void 0===r)return;this._resolveReference(e,r,s.rest)}else{const r=t[s.element];if(void 0===r)return;this._resolveReference(e,r,s.rest)}}}forProjectKey(e){let t=this.resources[e];return t||(t=this.resources[e]={cart:new Map,customer:new Map,"inventory-entry":new Map,"key-value-document":new Map,order:new Map,payment:new Map,"product-type":new Map,product:new Map,"shipping-method":new Map,state:new Map,store:new Map,"tax-category":new Map,type:new Map}),t}clear(){for(const[,e]of Object.entries(this.resources))for(const[,t]of Object.entries(e))null==t||t.clear()}assertStorage(e){}all(e,t){const r=this.forProjectKey(e)[t];return r?Array.from(r.values()):[]}add(e,t,r,s={}){var n;null==(n=this.forProjectKey(e)[t])||n.set(r.id,r);const o=this.get(e,t,r.id,s);return u(o,`resource of type ${t} with id ${r.id} not created`),o}get(e,t,r,s={}){var n;const o=null==(n=this.forProjectKey(e)[t])?void 0:n.get(r);return o?this.expand(e,o,s.expand):null}delete(e,t,r,s={}){const n=this.get(e,t,r);var o;return n?(null==(o=this.forProjectKey(e)[t])||o.delete(r),this.expand(e,n,s.expand)):n}query(e,t,r){const s=this.forProjectKey(e)[t];if(!s)throw new Error("No type");let n=Array.from(s.values());if(r.where)try{const e=(e=>{if(Array.isArray(e)){const t=e.map(e=>O(e));return(e,r)=>t.every(t=>t(e,r))}return O(e)})(r.where);n=n.filter(t=>e(t,{}))}catch(e){throw new y({code:"InvalidInput",message:e.message},400)}const o=n.length,i=r.offset||0,a=r.limit||20;return n=n.slice(i,i+a),void 0!==r.expand&&(n=n.map(t=>this.expand(e,t,r.expand))),{count:o,total:n.length,offset:i,limit:a,results:n}}getByResourceIdentifier(e,t){if(t.id)return this.get(e,t.typeId,t.id)||void console.error(`No resource found with typeId=${t.typeId}, id=${t.id}`);if(t.key){const r=this.forProjectKey(e)[t.typeId];if(!r)throw new Error("No storage found for resource type: "+t.typeId);{const e=Array.from(r.values()).find(e=>e.key===t.key);if(e)return e}}}_resolveReference(e,t,r){void 0!==t&&(void 0===t.typeId||void 0===t.id&&void 0===t.key?r&&this._resolveResource(e,t,r):(t.obj=this.getByResourceIdentifier(e,{typeId:t.typeId,id:t.id,key:t.key}),r&&this._resolveResource(e,t.obj,r)))}}class $ extends g{getTypeId(){return"type"}create(e,t){const r={...l(),key:t.key,name:t.name,resourceTypeIds:t.resourceTypeIds,fieldDefinitions:t.fieldDefinitions||[],description:t.description};return this.save(e,r),r}}class B extends v{constructor(e,t){super(e),this.repository=new $(t)}getBasePath(){return"types"}}class W extends g{getTypeId(){return"key-value-document"}create(e,t){const r=this.getWithContainerAndKey(e,t.container,t.key),s=l();if(r){if(t.version||(t.version=r.version),m(r,t.version),t.value===r.value)return r;s.version=r.version}else t.version&&(s.version=t.version);const n={...s,container:t.container,key:t.key,value:t.value};return this.save(e,n),n}getWithContainerAndKey(e,t,r){return this._storage.all(e,this.getTypeId()).find(e=>e.container===t&&e.key===r)}}class z extends v{constructor(e,t){super(e),this.repository=new W(t)}getBasePath(){return"custom-objects"}extraRoutes(e){e.get("/:container/:key",this.getWithContainerAndKey.bind(this))}getWithContainerAndKey(e,t){const r=this.repository.getWithContainerAndKey(e.params.projectKey,e.params.container,e.params.key);return r?t.status(200).send(r):t.status(404).send("Not Found")}}class F extends g{getTypeId(){return"customer"}create(e,t){const r={...l(),email:t.email,password:t.password,isEmailVerified:t.isEmailVerified||!1,addresses:[]};return this.save(e,r),r}}class L extends v{constructor(e,t){super(e),this.repository=new F(t)}getBasePath(){return"customers"}}class H extends g{getTypeId(){return"cart"}create(e,t){const r={...l(),cartState:"Active",lineItems:[],customLineItems:[],totalPrice:{type:"centPrecision",centAmount:0,currencyCode:t.currency,fractionDigits:0},taxMode:"Platform",taxRoundingMode:"HalfEven",taxCalculationMode:"LineItemLevel",refusedGifts:[],origin:"Customer",custom:k(t.custom,e,this._storage)};return this.save(e,r),r}}class V extends v{constructor(e,t){super(e),this.repository=new H(t)}getBasePath(){return"carts"}}class G extends g{constructor(){super(...arguments),this.actions={changeQuantity:(e,t,{quantity:r})=>{t.quantityOnStock=r,t.availableQuantity=r},setExpectedDelivery:(e,t,{expectedDelivery:r})=>{t.expectedDelivery=new Date(r).toISOString()},setCustomField:(e,t,{name:r,value:s})=>{if(!t.custom)throw new Error("Resource has no custom field");t.custom.fields[r]=s},setCustomType:(e,t,{type:r,fields:s})=>{if(r){const n=this._storage.getByResourceIdentifier(e,r);if(!n)throw new Error(`Type ${r} not found`);t.custom={type:{typeId:"type",id:n.id},fields:s||[]}}else t.custom=void 0},setRestockableInDays:(e,t,{restockableInDays:r})=>{t.restockableInDays=r}}}getTypeId(){return"inventory-entry"}create(e,t){var r,s;const n={...l(),sku:t.sku,quantityOnStock:t.quantityOnStock,availableQuantity:t.quantityOnStock,expectedDelivery:t.expectedDelivery,restockableInDays:t.restockableInDays,supplyChannel:{...t.supplyChannel,typeId:"channel",id:null!=(r=null==(s=t.supplyChannel)?void 0:s.id)?r:""},custom:k(t.custom,e,this._storage)};return this.save(e,n),n}}class Q extends v{constructor(e,t){super(e),this.repository=new G(t)}getBasePath(){return"inventory"}}class U extends g{constructor(){super(...arguments),this.actions={addPayment:(e,t,{payment:r})=>{if(!this._storage.getByResourceIdentifier(e,r))throw new Error(`Payment ${r.id} not found`);t.paymentInfo||(t.paymentInfo={payments:[]}),t.paymentInfo.payments.push({typeId:"payment",id:r.id})},changeOrderState:(e,t,{orderState:r})=>{t.orderState=r},changePaymentState:(e,t,{paymentState:r})=>{t.paymentState=r},setBillingAddress:(e,t,{address:r})=>{t.billingAddress=r},setCustomerEmail:(e,t,{email:r})=>{t.customerEmail=r},setCustomField:(e,t,{name:r,value:s})=>{if(!t.custom)throw new Error("Resource has no custom field");t.custom.fields[r]=s},setCustomType:(e,t,{type:r,fields:s})=>{if(r){const n=this._storage.getByResourceIdentifier(e,r);if(!n)throw new Error(`Type ${r} not found`);t.custom={type:{typeId:"type",id:n.id},fields:s||[]}}else t.custom=void 0},setLocale:(e,t,{locale:r})=>{t.locale=r},setOrderNumber:(e,t,{orderNumber:r})=>{t.orderNumber=r},setShippingAddress:(e,t,{address:r})=>{t.shippingAddress=r},setStore:(e,t,{store:r})=>{if(!r)return;const s=this._storage.getByResourceIdentifier(e,r);if(!s)throw new Error("No store found with key="+r.key);t.store={typeId:"store",key:s.key}}}}getTypeId(){return"order"}create(e,t){u(t.cart,"draft.cart is missing");const r=this._storage.getByResourceIdentifier(e,t.cart);if(!r)throw new Error("Cannot find cart");const s={...l(),orderNumber:t.orderNumber,orderState:"Open",lineItems:[],customLineItems:[],totalPrice:r.totalPrice,refusedGifts:[],origin:"Customer",syncInfo:[],lastMessageSequenceNumber:0};return this.save(e,s),s}import(e,t){var r,s;u(this,"OrderRepository not valid");const n={...l(),billingAddress:t.billingAddress,shippingAddress:t.shippingAddress,custom:k(t.custom,e,this._storage),customerEmail:t.customerEmail,lastMessageSequenceNumber:0,orderNumber:t.orderNumber,orderState:t.orderState||"Open",origin:t.origin||"Customer",paymentState:t.paymentState,refusedGifts:[],store:b(t.store,e,this._storage),syncInfo:[],lineItems:(null==(r=t.lineItems)?void 0:r.map(t=>this.lineItemFromImportDraft.bind(this)(e,t)))||[],customLineItems:(null==(s=t.customLineItems)?void 0:s.map(t=>this.customLineItemFromImportDraft.bind(this)(e,t)))||[],totalPrice:{type:"centPrecision",...t.totalPrice,fractionDigits:2}};return this.save(e,n),n}lineItemFromImportDraft(e,t){let r,s;if(!t.variant.sku)throw new Error("No product found");s={id:0,sku:t.variant.sku};var n=this._storage.query(e,"product",{where:[`masterData(current(masterVariant(sku="${t.variant.sku}"))) or masterData(current(variants(sku="${t.variant.sku}")))`]});if(1!==n.count)throw new y({code:"General",message:`A product containing a variant with SKU '${t.variant.sku}' not found.`});if(r=n.results[0],s=r.masterData.current.masterVariant.sku===t.variant.sku?r.masterData.current.masterVariant:r.masterData.current.variants.find(e=>e.sku===t.variant.sku),!s)throw new Error("Internal state error");return{...l(),custom:k(t.custom,e,this._storage),discountedPricePerQuantity:[],lineItemMode:"Standard",name:t.name,price:I(t.price),priceMode:"Platform",productId:r.id,productType:r.productType,quantity:t.quantity,state:t.state||[],taxRate:t.taxRate,totalPrice:_(t.price.value),variant:{id:s.id,sku:s.sku,price:I(t.price)}}}customLineItemFromImportDraft(e,t){return{...l(),custom:k(t.custom,e,this._storage),discountedPricePerQuantity:[],money:_(t.money),name:t.name,quantity:t.quantity,slug:t.slug,state:[],totalPrice:_(t.money)}}getWithOrderNumber(e,t,r={}){const s=this._storage.query(e,this.getTypeId(),{...r,where:[`orderNumber="${t}"`]});if(1===s.count)return s.results[0];if(s.count>1)throw new Error("Duplicate order numbers")}}class J extends v{constructor(e,t){super(e),this.repository=new U(t)}getBasePath(){return"orders"}extraRoutes(e){e.post("/import",this.import.bind(this)),e.get("/order-number=:orderNumber",this.getWithOrderNumber.bind(this))}import(e,t){const r=this.repository.import(e.params.projectKey,e.body);return t.status(200).send(r)}getWithOrderNumber(e,t){const r=this.repository.getWithOrderNumber(e.params.projectKey,e.params.orderNumber,e.query);return r?t.status(200).send(r):t.status(404).send("Not found")}}class Y extends g{getTypeId(){return"store"}create(e,t){const r={...l(),key:t.key,distributionChannels:[]};return this.save(e,r),r}}class Z extends v{constructor(e,t){super(e),this.repository=new Y(t)}getBasePath(){return"stores"}}class X{constructor(e=!0){this.tokens=[],this.validate=!0,this.validate=e}getClientToken(e,t,r){const s={access_token:h.randomBytes(16).toString("base64"),token_type:"Bearer",expires_in:172800,scope:r||"todo"};return this.tokens.push(s),s}validateToken(e){return!this.validate||!!this.tokens.find(t=>t.access_token===e)}}class ee{constructor(e){this.store=new X(e.validate)}createRouter(){const e=n.Router();return e.post("/token",this.tokenHandler.bind(this)),e}createMiddleware(){return async(e,t,r)=>{const s=(e=>{const t=e.header("Authorization"),r=null==t?void 0:t.match(/^Bearer\s(?<token>[^\s]+)$/);var s;if(r)return null==(s=r.groups)?void 0:s.token})(e);s||r(new y({code:"access_denied",message:"This endpoint requires an access token. You can get one from the authorization server."},401)),s&&this.store.validateToken(s)||r(new y({code:"invalid_token",message:"invalid_token"},401)),r()}}async tokenHandler(e,t,r){const s=e.header("Authorization");if(!s)return r(new y({code:"invalid_client",message:"Please provide valid client credentials using HTTP Basic Authentication."},401));const n=p.parse(s);if(!n)return r(new y({code:"invalid_client",message:"Please provide valid client credentials using HTTP Basic Authentication."},400));const o=e.query.grant_type;if(!o)return r(new y({code:"invalid_request",message:"Missing required parameter: grant_type."},400));if("client_credentials"===o){var i;const r=this.store.getClientToken(n.name,n.pass,null==(i=e.query.scope)?void 0:i.toString());return t.status(200).send(r)}return r(new y({code:"unsupported_grant_type",message:"Invalid parameter: grant_type: Invalid grant type: "+o},400))}}class te{constructor(e,t,r){this.projectKey=e,this._storage=r,this._services=t}add(e,t){"custom-object"===e&&(e="key-value-document");const r=e;if(!this._services[r])throw new Error(`Service for ${e} not implemented yet`);this._storage.add(this.projectKey,r,{...l(),...t})}get(e,t){return this._storage.get(this.projectKey,e,t,{})}getRepository(e){const t=this._services[e];if(void 0!==t)return t.repository;throw new Error("No such repository")}}const re=e=>{const t=["accept","host","authorization"],r={};return Object.entries(e).forEach(([e,s])=>{t.includes(e.toLowerCase())&&(r[e]=s)}),r};class se extends g{constructor(){super(...arguments),this.actions={publish:(e,t,{})=>{t.masterData.staged&&(t.masterData.current=t.masterData.staged,t.masterData.staged=void 0),t.masterData.hasStagedChanges=!1,t.masterData.published=!0},setAttribute:(e,t,{variantId:r,sku:s,name:n,value:o,staged:i})=>{const a=void 0!==i&&i,u=ne(t,a),{variant:c,isMasterVariant:d,variantIndex:p}=oe(u,r,s);if(!c)throw new Error(`Variant with id ${r} or sku ${s} not found on product ${t.id}`);c.attributes||(c.attributes=[]);const h=c.attributes.find(e=>e.name===n);h?h.value=o:c.attributes.push({name:n,value:o}),a?(t.masterData.staged=u,d?t.masterData.staged.masterVariant=c:t.masterData.staged.variants[p]=c,t.masterData.hasStagedChanges=!0):(t.masterData.current=u,d?t.masterData.current.masterVariant=c:t.masterData.current.variants[p]=c)}}}getTypeId(){return"product"}create(e,t){var r,s;const n={name:t.name,slug:t.slug,categories:[],masterVariant:t.masterVariant&&ie(0,t.masterVariant),variants:t.variants&&t.variants.map((e,t)=>ie(t+1,e)),searchKeywords:t.searchKeywords},o={...l(),masterData:{current:t.publish?n:void 0,staged:t.publish?void 0:n,hasStagedChanges:null==(r=t.publish)||r,published:null!=(s=t.publish)&&s}};return this.save(e,o),o}}const ne=(e,t)=>!t&&e.masterData.current?e.masterData.current:e.masterData.staged,oe=(e,t,r)=>{const s=[e.masterVariant,...e.variants].find(e=>t?e.id===t:!!r&&e.sku===r),n=s===e.masterVariant;return{variant:s,isMasterVariant:n,variantIndex:!n&&s?e.variants.indexOf(s):-1}},ie=(e,t)=>({id:e,sku:null==t?void 0:t.sku,attributes:null==t?void 0:t.attributes});class ae extends v{constructor(e,t){super(e),this.repository=new se(t)}getBasePath(){return"products"}}class ue extends v{constructor(e,t){super(e),this.repository=new P(t)}getBasePath(){return"me/payments"}}const ce={enableAuthentication:!1,validateCredentials:!1,defaultProjectKey:void 0,apiHost:/^https:\/\/api\..*?\.commercetools.com:443$/,authHost:/^https:\/\/auth\..*?\.commercetools.com:443$/,silent:!1};exports.CommercetoolsMock=class{constructor(e={}){this._nockScopes={auth:void 0,api:void 0},this.options={...ce,...e},this._services={},this._storage=new j,this._oauth2=new ee({enabled:this.options.enableAuthentication,validate:this.options.validateCredentials}),this.app=this.createApp({silent:this.options.silent})}start(){this.mockAuthHost(),this.mockApiHost()}stop(){var e,t;null==(e=this._nockScopes.auth)||e.persist(!1),this._nockScopes.auth=void 0,null==(t=this._nockScopes.api)||t.persist(!1),this._nockScopes.api=void 0}clear(){this._storage.clear()}project(e){if(!e&&!this.options.defaultProjectKey)throw new Error("No projectKey passed and no default set");return new te(e||this.options.defaultProjectKey,this._services,this._storage)}runServer(e=3e3,t){this.createApp(t).listen(e,()=>{console.log("Mock server listening at http://localhost:"+e)})}createApp(e){const t=n(),r=n.Router({mergeParams:!0});return r.use(n.json()),null!=e&&e.silent||t.use(a("tiny")),t.use("/oauth",this._oauth2.createRouter()),this.options.enableAuthentication?t.use("/:projectKey",this._oauth2.createMiddleware(),r):t.use("/:projectKey",r),this._services={cart:new V(r,this._storage),customer:new L(r,this._storage),"inventory-entry":new Q(r,this._storage),"key-value-document":new z(r,this._storage),order:new J(r,this._storage),payment:new E(r,this._storage),"my-payment":new ue(r,this._storage),"shipping-method":new T(r,this._storage),"product-type":new w(r,this._storage),product:new ae(r,this._storage),state:new D(r,this._storage),store:new Z(r,this._storage),"tax-category":new R(r,this._storage),type:new B(r,this._storage)},t.use((e,t,r,s)=>e instanceof y?r.status(e.statusCode).send({statusCode:e.statusCode,message:e.message,errors:[e.info]}):r.status(500).send({error:e.message})),t}mockApiHost(){const e=this.app;this._nockScopes.api=o(this.options.apiHost).persist().get(/.*/).reply((async function(t){const r=await i(e).get(t).set(re(this.req.headers));return[r.status,r.body]})).post(/.*/).reply((async function(t,r){const s=await i(e).post(t).set(re(this.req.headers)).send(r);return[s.status,s.body]})).delete(/.*/).reply((async function(t,r){const s=await i(e).delete(t).set(re(this.req.headers)).send(r);return[s.status,s.body]}))}mockAuthHost(){const e=this.app;this._nockScopes.auth=o(this.options.authHost).persist().post(/^\/oauth\/.*/).reply((async function(t,r){const s=await i(e).post(t+"?"+r).set(re(this.req.headers)).send();return[s.status,s.body]}))}},exports.getBaseResourceProperties=l;
1
+ "use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("nock")),s=require("express"),r=e(s),n=e(require("supertest")),a=e(require("morgan")),i=e(require("assert")),o=e(require("perplex")),c=require("pratt"),u=e(require("basic-auth")),d=e(require("body-parser")),p=require("crypto"),l=require("uuid"),h=e(require("deep-equal"));class y{constructor(e){this.message=e}}const m=e=>{if(!e.type)throw new y("Internal error");if("identifier"===e.type){var t,s;const r=e.value.charAt(0),n=null==(t=e.pos)?void 0:t.start.line,a=null==(s=e.pos)?void 0:s.start.column;throw new y(`Invalid input '${r}', expected input parameter or primitive value (line ${n}, column ${a})`)}},g=(e,t)=>{if("var"===e.type){if(!(e.value in t))throw new y("Missing parameter value for "+e.value);return t[e.value]}return e.value},f=(e,t)=>{if("identifier"!==t.type)throw new y("Internal error");if(!(t.value in e)){if(Array.isArray(e))return Object.values(e).filter(e=>t.value in e).map(e=>e[t.value]);throw new y(`The field '${t.value}' does not exist.`)}return e[t.value]},v=e=>{const t=new o(e).token("AND",/and(?![-_a-z0-9]+)/i).token("OR",/or(?![-_a-z0-9]+)/i).token("NOT",/not(?![-_a-z0-9]+)/i).token("WITHIN",/within(?![-_a-z0-9]+)/i).token("IN",/in(?![-_a-z0-9]+)/i).token("MATCHES_IGNORE_CASE",/matches\s+ignore\s+case(?![-_a-z0-9]+)/i).token("CONTAINS",/contains(?![-_a-z0-9]+)/i).token("ALL",/all(?![-_a-z0-9]+)/i).token("ANY",/any(?![-_a-z0-9]+)/i).token("EMPTY",/empty(?![-_a-z0-9]+)/i).token("IS",/is(?![-_a-z0-9]+)/i).token("DEFINED",/defined(?![-_a-z0-9]+)/i).token("FLOAT",/\d+\.\d+/).token("INT",/\d+/).token("VARIABLE",/:([-_A-Za-z0-9]+)/).token("IDENTIFIER",/[-_A-Za-z0-9]+/).token("STRING",/"((?:\\.|[^"\\])*)"/).token("STRING",/'((?:\\.|[^'\\])*)'/).token("COMMA",",").token("(","(").token(")",")").token(">=",">=").token("<=","<=").token(">",">").token("<","<").token("!=","!=").token("=","=").token('"','"').token("WS",/\s+/,!0),s=new c.Parser(t).builder().nud("IDENTIFIER",100,e=>({type:"identifier",value:e.token.match,pos:e.token.strpos()})).nud("VARIABLE",100,e=>({type:"var",value:e.token.groups[1],pos:e.token.strpos()})).nud("STRING",100,e=>({type:"string",value:e.token.groups[1],pos:e.token.strpos()})).nud("INT",1,e=>({type:"int",value:parseInt(e.token.match,10),pos:e.token.strpos()})).nud("FLOAT",1,e=>({type:"float",value:parseFloat(e.token.match),pos:e.token.strpos()})).nud("NOT",100,({bp:e})=>{const t=s.parse({terminals:[e-1]});return e=>!t(e)}).nud("EMPTY",10,({})=>"empty").nud("DEFINED",10,({})=>"defined").led("AND",5,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return t=>e(t)&&r(t)}).led("OR",5,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return(t,s)=>e(t,s)||r(t,s)}).led("COMMA",1,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return Array.isArray(r)?[e,...r]:[e,r]}).nud("(",100,e=>s.parse({terminals:[")"]})).led("(",100,({left:e})=>{const r=s.parse();return t.expect(")"),(t,s)=>{const n=f(t,e);return!!n&&r(n)}}).bp(")",0).led("=",20,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return m(r),(t,s)=>{const n=f(t,e),a=g(r,s);return Array.isArray(n)?!!n.some(e=>e===a):n===a}}).led("!=",20,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return m(r),(t,s)=>f(t,e)!==g(r,s)}).led(">",20,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return m(r),(t,s)=>f(t,e)>g(r,s)}).led(">=",20,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return m(r),(t,s)=>f(t,e)>=g(r,s)}).led("<",20,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return m(r),(t,s)=>f(t,e)<g(r,s)}).led("<=",20,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return m(r),(t,s)=>f(t,e)<=g(r,s)}).led("IS",20,({left:e,bp:r})=>{let n=!1;switch("NOT"===t.peek().type&&(n=!0,t.next()),s.parse({terminals:[r-1]})){case"empty":return n?(t,s)=>0!==f(t,e).length:(t,s)=>0===f(t,e).length;case"defined":return n?(t,s)=>void 0===f(t,e):(t,s)=>void 0!==f(t,e);default:throw new Error("Unexpected")}}).led("IN",20,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return(t,s)=>{let n=r;return Array.isArray(n)||(n=[r]),n.map(e=>g(e,s)).includes(f(t,e))}}).led("MATCHES_IGNORE_CASE",20,({left:e,bp:t})=>{const r=s.parse({terminals:[t-1]});return m(r),(t,s)=>{const n=f(t,e),a=g(r,s);if("string"!=typeof n)throw new y(`The field '${e.value}' does not support this expression.`);return n.toLowerCase()===a.toLowerCase()}}).led("WITHIN",20,({left:e})=>{const r=t.next();if("circle"!==r.match)throw new y(`Invalid input '${r.match}', expected circle`);t.expect("(");const n=s.parse({terminals:[")"]});return(t,s)=>{const r=f(t,e);if(!r)return!1;const a=g(n[2],s);return((e,t)=>{const s=e=>e*(Math.PI/180),r=s(t.latitude-e.latitude),n=s(t.longitude-e.longitude);var a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(s(e.latitude))*Math.cos(s(t.latitude))*Math.sin(n/2)*Math.sin(n/2);return 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))*6371*1e3})({longitude:r[0],latitude:r[1]},{longitude:g(n[0],s),latitude:g(n[1],s)})<=a}}).led("CONTAINS",20,({left:e})=>{const r=t.next();let n=s.parse();return Array.isArray(n)||(n=[n]),(t,s)=>{const a=f(t,e);if(!Array.isArray(a))throw new y(`The field '${e.value}' does not support this expression.`);const i=n.map(e=>g(e,s));return"ALL"===r.type?i.every(e=>a.includes(e)):i.some(e=>a.includes(e))}}).build(),r=s.parse();if("function"!=typeof r){const t=e.split("\n");throw new y(`Unexpected end of input, expected SphereIdentifierChar, comparison operator, not, in, contains, is, within or matches (line ${t.length}, column ${t[t.length-1].length})`)}return r};class w extends Error{constructor(e,t=400){super(e.message),this.info=e,this.statusCode=t||500}}class I extends class{}{constructor(){super(...arguments),this.resources={},this.projects={},this.addProject=e=>(this.projects[e]||(this.projects[e]={key:e,name:"",countries:[],currencies:[],languages:[],createdAt:"2018-10-04T11:32:12.603Z",trialUntil:"2018-12",carts:{countryTaxRateFallbackEnabled:!1,deleteDaysAfterLastModification:90},messages:{enabled:!1,deleteDaysAfterCreation:15},shippingRateInputType:void 0,externalOAuth:void 0,searchIndexing:{products:{status:"Deactivated"},orders:{status:"Deactivated"}},version:1}),this.projects[e]),this.saveProject=e=>(this.projects[e.key]=e,e),this.getProject=e=>this.addProject(e),this.expand=(e,t,s)=>{if(!s)return t;const r=JSON.parse(JSON.stringify(t));return Array.isArray(s)?s.forEach(t=>{this._resolveResource(e,r,t)}):this._resolveResource(e,r,s),r},this._resolveResource=(e,t,s)=>{const r=(e=>{const t={element:e,index:void 0,rest:void 0},s=e.indexOf(".");s>0&&(t.element=e.substring(0,s),t.rest=e.substring(s+1));const r=t.element.match(/\[([^\]+])]/);return r&&(t.index="*"===r[1]?"*":parseInt(r[1],10),t.element=t.element.substring(0,r.index)),t})(s);if(r.index)if("*"===r.index){const s=t[r.element];if(void 0===s||!Array.isArray(s))return;s.forEach(t=>{this._resolveReference(e,t,r.rest)})}else{const s=t[r.element][r.index];if(void 0===s)return;this._resolveReference(e,s,r.rest)}else{const s=t[r.element];if(void 0===s)return;this._resolveReference(e,s,r.rest)}}}forProjectKey(e){this.addProject(e);let t=this.resources[e];return t||(t=this.resources[e]={cart:new Map,"cart-discount":new Map,category:new Map,channel:new Map,customer:new Map,"customer-group":new Map,"discount-code":new Map,extension:new Map,"inventory-entry":new Map,"key-value-document":new Map,order:new Map,payment:new Map,"product-type":new Map,product:new Map,"product-selection":new Map,"product-projection":new Map,"shipping-method":new Map,state:new Map,store:new Map,"shopping-list":new Map,subscription:new Map,"tax-category":new Map,type:new Map,zone:new Map}),t}clear(){for(const[,e]of Object.entries(this.resources))for(const[,t]of Object.entries(e))null==t||t.clear()}assertStorage(e){}all(e,t){const s=this.forProjectKey(e)[t];return s?Array.from(s.values()):[]}add(e,t,s,r={}){var n;null==(n=this.forProjectKey(e)[t])||n.set(s.id,s);const a=this.get(e,t,s.id,r);return i(a,`resource of type ${t} with id ${s.id} not created`),a}get(e,t,s,r={}){var n;const a=null==(n=this.forProjectKey(e)[t])?void 0:n.get(s);return a?this.expand(e,a,r.expand):null}getByKey(e,t,s,r={}){const n=this.forProjectKey(e)[t];if(!n)throw new Error("No type");const a=Array.from(n.values()).find(e=>e.key===s);return r.expand?this.expand(e,a,r.expand):a}delete(e,t,s,r={}){const n=this.get(e,t,s);var a;return n?(null==(a=this.forProjectKey(e)[t])||a.delete(s),this.expand(e,n,r.expand)):n}query(e,t,s){const r=this.forProjectKey(e)[t];if(!r)throw new Error("No type");let n=Array.from(r.values());if(s.where)try{const e=(e=>{if(Array.isArray(e)){const t=e.map(e=>v(e));return(e,s)=>t.every(t=>t(e,s))}return v(e)})(s.where);n=n.filter(t=>e(t,{}))}catch(e){throw new w({code:"InvalidInput",message:e.message},400)}const a=n.length,i=s.offset||0,o=s.limit||20;return n=n.slice(i,i+o),void 0!==s.expand&&(n=n.map(t=>this.expand(e,t,s.expand))),{count:a,total:n.length,offset:i,limit:o,results:n}}getByResourceIdentifier(e,t){if(t.id)return this.get(e,t.typeId,t.id)||void console.error(`No resource found with typeId=${t.typeId}, id=${t.id}`);if(t.key){const s=this.forProjectKey(e)[t.typeId];if(!s)throw new Error("No storage found for resource type: "+t.typeId);{const e=Array.from(s.values()).find(e=>e.key===t.key);if(e)return e}}}_resolveReference(e,t,s){void 0!==t&&(void 0===t.typeId||void 0===t.id&&void 0===t.key?s&&this._resolveResource(e,t,s):(t.obj=this.getByResourceIdentifier(e,{typeId:t.typeId,id:t.id,key:t.key}),s&&this._resolveResource(e,t.obj,s)))}}class k{constructor(e=!0){this.tokens=[],this.validate=!0,this.validate=e}getClientToken(e,t,s){const r={access_token:p.randomBytes(16).toString("base64"),token_type:"Bearer",expires_in:172800,scope:s||"todo"};return this.tokens.push(r),r}validateToken(e){return!this.validate||!!this.tokens.find(t=>t.access_token===e)}}class x{constructor(e){this.store=new k(e.validate)}createRouter(){const e=r.Router();return e.use(d.urlencoded({extended:!0})),e.post("/token",this.tokenHandler.bind(this)),e}createMiddleware(){return async(e,t,s)=>{const r=(e=>{const t=e.header("Authorization"),s=null==t?void 0:t.match(/^Bearer\s(?<token>[^\s]+)$/);var r;if(s)return null==(r=s.groups)?void 0:r.token})(e);r||s(new w({code:"access_denied",message:"This endpoint requires an access token. You can get one from the authorization server."},401)),r&&this.store.validateToken(r)||s(new w({code:"invalid_token",message:"invalid_token"},401)),s()}}async tokenHandler(e,t,s){const r=e.header("Authorization");if(!r)return s(new w({code:"invalid_client",message:"Please provide valid client credentials using HTTP Basic Authentication."},401));const n=u.parse(r);if(!n)return s(new w({code:"invalid_client",message:"Please provide valid client credentials using HTTP Basic Authentication."},400));const a=e.query.grant_type||e.body.grant_type;if(!a)return s(new w({code:"invalid_request",message:"Missing required parameter: grant_type."},400));if("client_credentials"===a){var i;const s=this.store.getClientToken(n.name,n.pass,null==(i=e.query.scope)?void 0:i.toString());return t.status(200).send(s)}return s(new w({code:"unsupported_grant_type",message:"Invalid parameter: grant_type: Invalid grant type: "+a},400))}}const b=()=>({id:l.v4(),createdAt:(new Date).toISOString(),lastModifiedAt:(new Date).toISOString(),version:0});class _{constructor(e,t,s){this.projectKey=e,this._storage=s,this._services=t}add(e,t){"custom-object"===e&&(e="key-value-document");const s=e;if(!this._services[s])throw new Error(`Service for ${e} not implemented yet`);this._storage.add(this.projectKey,s,{...b(),...t})}get(e,t){return this._storage.get(this.projectKey,e,t,{})}getRepository(e){const t=this._services[e];if(void 0!==t)return t.repository;throw new Error("No such repository")}}const A=e=>{const t=["accept","host","authorization"],s={};return Object.entries(e).forEach(([e,r])=>{t.includes(e.toLowerCase())&&(s[e]=r)}),s};class D{constructor(e){this.createStatusCode=201,this.registerRoutes(e)}extraRoutes(e){}registerRoutes(e){const t=this.getBasePath(),r=s.Router({mergeParams:!0});this.extraRoutes(r),r.get("/",this.get.bind(this)),r.get("/key=:key",this.getWithKey.bind(this)),r.get("/:id",this.getWithId.bind(this)),r.delete("/key=:key",this.deletewithKey.bind(this)),r.delete("/:id",this.deletewithId.bind(this)),r.post("/",this.post.bind(this)),r.post("/key=:key",this.postWithKey.bind(this)),r.post("/:id",this.postWithId.bind(this)),e.use("/"+t,r)}get(e,t){const s=this.repository.query(e.params.projectKey,{expand:this._parseParam(e.query.expand),where:this._parseParam(e.query.where)});return t.status(200).send(s)}getWithId(e,t){const s=this._expandWithId(e,e.params.id);return s?(console.log(JSON.stringify(s,null,4)),t.status(200).send(s)):t.status(404).send()}getWithKey(e,t){const s=this.repository.getByKey(e.params.projectKey,e.params.key,{expand:this._parseParam(e.query.expand)});return s?t.status(200).send(s):t.status(404).send()}deletewithId(e,t){const s=this.repository.delete(e.params.projectKey,e.params.id,{expand:this._parseParam(e.query.expand)});return s?t.status(200).send(s):t.status(404).send("Not found")}deletewithKey(e,t){return t.status(500).send("Not implemented")}post(e,t){const s=this.repository.create(e.params.projectKey,e.body),r=this._expandWithId(e,s.id);return t.status(this.createStatusCode).send(r)}postWithId(e,t){const s=e.body,r=this.repository.get(e.params.projectKey,e.params.id);if(!r)return t.status(404).send("Not found");if(r.version!==s.version)return t.status(409).send("Concurrent modification");const n=this.repository.processUpdateActions(e.params.projectKey,r,s.actions),a=this._expandWithId(e,n.id);return t.status(200).send(a)}postWithKey(e,t){return t.status(500).send("Not implemented")}_expandWithId(e,t){return this.repository.get(e.params.projectKey,t,{expand:this._parseParam(e.query.expand)})}_parseParam(e){return Array.isArray(e)?e:void 0!==e?[""+e]:void 0}}const T=(e,t)=>{if(e.version!==t)throw new w({message:`Object ${e.id?e.id:e.key} has a different version than expected. Expected: ${t} - Actual: ${e.version}.`,currentVersion:e.version,code:"ConcurrentModification"},409)};class R{constructor(e){this.actions={},this._storage=e}processUpdateActions(e,t,s){const r=JSON.parse(JSON.stringify(t));return s.forEach(t=>{const s=this.actions[t.action];s?s(e,r,t):console.error("No mock implemented for update action "+t.action)}),h(r,t)||this.save(e,r),r}}class P extends R{constructor(e){super(e),this._storage.assertStorage(this.getTypeId())}query(e,t={}){return this._storage.query(e,this.getTypeId(),{expand:t.expand,where:t.where})}get(e,t,s={}){return this._storage.get(e,this.getTypeId(),t,s)}getByKey(e,t,s={}){return this._storage.getByKey(e,this.getTypeId(),t,s)}delete(e,t,s={}){return this._storage.delete(e,this.getTypeId(),t,s)}save(e,t){const s=this.get(e,t.id);if(s)T(s,t.version);else if(0!==t.version)throw new w({code:"InvalidOperation",message:"version on create must be 0"},400);t.version+=1,this._storage.add(e,this.getTypeId(),t)}}const S=(e,t,s)=>{if(!e)return;if(!e.type)return;if(!e.type.typeId)return;if(!e.fields)return;const r=s.getByResourceIdentifier(t,e.type);if(!r)throw new Error(`No type '${e.type.typeId}' with id=${e.type.id} or key=${e.type.key}`);return{type:{typeId:e.type.typeId,id:r.id},fields:e.fields}},E=e=>({id:l.v4(),value:C(e.value)}),C=e=>({type:"centPrecision",fractionDigits:2,...e}),K=(e,t,s)=>{if(!e)return;const r=s.getByResourceIdentifier(t,e);if(!r)throw new Error("No such store");return{typeId:"store",key:r.key}},N=(e,t,s)=>{const r=s.getByResourceIdentifier(t,e);if(!r)throw new Error(`resource type ${e.typeId} with id ${e.id} and key ${e.key} not found`);return{typeId:e.typeId,id:null==r?void 0:r.id}};class M extends P{constructor(){super(...arguments),this.actions={setKey:(e,t,{key:s})=>{t.key=s},setDescription:(e,t,{description:s})=>{t.description=s},setValidFrom:(e,t,{validFrom:s})=>{t.validFrom=s},setValidUntil:(e,t,{validUntil:s})=>{t.validUntil=s},setValidFromAndUntil:(e,t,{validFrom:s,validUntil:r})=>{t.validFrom=s,t.validUntil=r},changeSortOrder:(e,t,{sortOrder:s})=>{t.sortOrder=s},changeIsActive:(e,t,{isActive:s})=>{t.isActive=s}}}getTypeId(){return"cart-discount"}create(e,t){const s={...b(),key:t.key,description:t.description,cartPredicate:t.cartPredicate,isActive:t.isActive||!1,name:t.name,references:[],target:t.target,requiresDiscountCode:t.requiresDiscountCode||!1,sortOrder:t.sortOrder,stackingMode:t.stackingMode||"Stacking",validFrom:t.validFrom,validUntil:t.validUntil,value:this.transformValueDraft(t.value)};return this.save(e,s),s}transformValueDraft(e){switch(e.type){case"absolute":return{type:"absolute",money:e.money.map(C)};case"fixed":return{type:"fixed",money:e.money.map(C)};case"giftLineItem":case"relative":return{...e}}return e}}class j extends D{constructor(e,t){super(e),this.repository=new M(t)}getBasePath(){return"cart-discounts"}}class q extends P{constructor(){super(...arguments),this.actions={addLineItem:(e,t,{productId:s,variantId:r,sku:n,quantity:a=1})=>{let i,o=null;if(s&&r)o=this._storage.get(e,"product",s,{});else if(n){const t=this._storage.query(e,"product",{where:[`masterData(current(masterVariant(sku="${n}"))) or masterData(current(variants(sku="${n}")))`]});1===t.count&&(o=t.results[0])}if(!o)throw new w({code:"General",message:n?`A product containing a variant with SKU '${n}' not found.`:`A product with ID '${s}' not found.`});if(i=[o.masterData.current.masterVariant,...o.masterData.current.variants].find(e=>n?e.sku===n:!!r&&e.id===r),!i)throw new w({code:"General",message:n?`A variant with SKU '${n}' for product '${o.id}' not found.`:`A variant with ID '${r}' for product '${o.id}' not found.`});if(t.lineItems.some(e=>{var t,s;return e.productId===(null==(t=o)?void 0:t.id)&&e.variant.id===(null==(s=i)?void 0:s.id)}))t.lineItems.map(e=>{var t,s;return e.productId===(null==(t=o)?void 0:t.id)&&e.variant.id===(null==(s=i)?void 0:s.id)&&(e.quantity+=a,e.totalPrice.centAmount=O(e)),e});else{var c;if(null==(c=i.prices)||!c.length)throw new w({code:"General",message:`A product with ID '${s}' doesn't have any prices.`});const e=i.prices[0];t.lineItems.push({id:l.v4(),productId:o.id,productKey:o.key,name:o.masterData.current.name,productSlug:o.masterData.current.slug,productType:o.productType,variant:i,price:e,totalPrice:{...e.value,centAmount:e.value.centAmount*a},quantity:a,discountedPricePerQuantity:[],lineItemMode:"Standard",priceMode:"Platform",state:[]})}t.totalPrice.centAmount=$(t)},removeLineItem:(e,t,{lineItemId:s,quantity:r})=>{const n=t.lineItems.find(e=>e.id===s);if(!n)throw new w({code:"General",message:`A line item with ID '${s}' not found.`});!r||r>=n.quantity?t.lineItems=t.lineItems.filter(e=>e.id!==s):t.lineItems.map(e=>(e.id===s&&r&&(e.quantity-=r,e.totalPrice.centAmount=O(e)),e)),t.totalPrice.centAmount=$(t)},setBillingAddress:(e,t,{address:s})=>{t.billingAddress=s},setCountry:(e,t,{country:s})=>{t.country=s},setCustomerEmail:(e,t,{email:s})=>{t.customerEmail=s},setCustomField:(e,t,{name:s,value:r})=>{if(!t.custom)throw new Error("Resource has no custom field");t.custom.fields[s]=r},setCustomType:(e,t,{type:s,fields:r})=>{if(s){const n=this._storage.getByResourceIdentifier(e,s);if(!n)throw new Error(`Type ${s} not found`);t.custom={type:{typeId:"type",id:n.id},fields:r||[]}}else t.custom=void 0},setLocale:(e,t,{locale:s})=>{t.locale=s},setShippingAddress:(e,t,{address:s})=>{t.shippingAddress=s}}}getTypeId(){return"cart"}create(e,t){const s={...b(),cartState:"Active",lineItems:[],customLineItems:[],totalPrice:{type:"centPrecision",centAmount:0,currencyCode:t.currency,fractionDigits:0},taxMode:"Platform",taxRoundingMode:"HalfEven",taxCalculationMode:"LineItemLevel",refusedGifts:[],origin:"Customer",custom:S(t.custom,e,this._storage)};return this.save(e,s),s}getActiveCart(e){const t=this._storage.query(e,this.getTypeId(),{where:['cartState="Active"']});if(t.count>0)return t.results[0]}}const O=e=>e.price.value.centAmount*e.quantity,$=e=>e.lineItems.reduce((e,t)=>e+t.totalPrice.centAmount,0);class B extends D{constructor(e,t){super(e),this.repository=new q(t)}getBasePath(){return"carts"}}class F extends P{constructor(){super(...arguments),this.actions={changeAssetName:(e,t,{assetId:s,assetKey:r,name:n})=>{var a;null==(a=t.assets)||a.forEach(e=>{s&&s==e.id&&(e.name=n),r&&r==e.key&&(e.name=n)})},changeSlug:(e,t,{slug:s})=>{t.slug=s},setKey:(e,t,{key:s})=>{t.key=s},setAssetDescription:(e,t,{assetId:s,assetKey:r,description:n})=>{var a;null==(a=t.assets)||a.forEach(e=>{s&&s==e.id&&(e.description=n),r&&r==e.key&&(e.description=n)})},setAssetSources:(e,t,{assetId:s,assetKey:r,sources:n})=>{var a;null==(a=t.assets)||a.forEach(e=>{s&&s==e.id&&(e.sources=n),r&&r==e.key&&(e.sources=n)})},setDescription:(e,t,{description:s})=>{t.description=s},setMetaDescription:(e,t,{metaDescription:s})=>{t.metaDescription=s},setMetaKeywords:(e,t,{metaKeywords:s})=>{t.metaKeywords=s},setMetaTitle:(e,t,{metaTitle:s})=>{t.metaTitle=s}}}getTypeId(){return"category"}create(e,t){var s;const r={...b(),key:t.key,name:t.name,slug:t.slug,orderHint:t.orderHint||"",parent:t.parent?{typeId:"category",id:t.parent.id}:void 0,ancestors:[],assets:(null==(s=t.assets)?void 0:s.map(s=>({id:l.v4(),name:s.name,description:s.description,sources:s.sources,tags:s.tags,key:s.key,custom:S(t.custom,e,this._storage)})))||[]};return this.save(e,r),r}}class z extends D{constructor(e,t){super(e),this.repository=new F(t)}getBasePath(){return"categories"}}class W extends P{getTypeId(){return"channel"}create(e,t){const s={...b(),key:t.key,roles:t.roles||[]};return this.save(e,s),s}}class L extends D{constructor(e,t){super(e),this.repository=new W(t)}getBasePath(){return"channels"}}class V extends P{constructor(){super(...arguments),this.actions={setKey:(e,t,{key:s})=>{t.key=s},changeName:(e,t,{name:s})=>{t.name=s}}}getTypeId(){return"customer"}create(e,t){const s={...b(),key:t.key,name:t.groupName};return this.save(e,s),s}}class U extends D{constructor(e,t){super(e),this.repository=new V(t)}getBasePath(){return"customer-groups"}}class H extends P{getTypeId(){return"customer"}create(e,t){const s={...b(),email:t.email,password:t.password,isEmailVerified:t.isEmailVerified||!1,addresses:[]};return this.save(e,s),s}}class G extends D{constructor(e,t){super(e),this.repository=new H(t)}getBasePath(){return"customers"}}class Q extends P{getTypeId(){return"key-value-document"}create(e,t){const s=this.getWithContainerAndKey(e,t.container,t.key),r=b();if(s){if(r.id=s.id,t.version||(t.version=s.version),T(s,t.version),t.value===s.value)return s;r.version=s.version}else t.version&&(r.version=t.version);const n={...r,container:t.container,key:t.key,value:t.value};return this.save(e,n),n}getWithContainerAndKey(e,t,s){return this._storage.all(e,this.getTypeId()).find(e=>e.container===t&&e.key===s)}}class Z extends D{constructor(e,t){super(e),this.repository=new Q(t)}getBasePath(){return"custom-objects"}extraRoutes(e){e.get("/:container/:key",this.getWithContainerAndKey.bind(this)),e.post("/:container/:key",this.createWithContainerAndKey.bind(this)),e.delete("/:container/:key",this.deleteWithContainerAndKey.bind(this))}getWithContainerAndKey(e,t){const s=this.repository.getWithContainerAndKey(e.params.projectKey,e.params.container,e.params.key);return s?t.status(200).send(s):t.status(404).send("Not Found")}createWithContainerAndKey(e,t){const s={...e.body,key:e.params.key,container:e.params.container},r=this.repository.create(e.params.projectKey,s);return t.status(200).send(r)}deleteWithContainerAndKey(e,t){const s=this.repository.getWithContainerAndKey(e.params.projectKey,e.params.container,e.params.key);if(!s)return t.status(404).send("Not Found");const r=this.repository.delete(e.params.projectKey,s.id);return t.status(200).send(r)}}class J extends P{constructor(){super(...arguments),this.actions={changeIsActive:(e,t,{isActive:s})=>{t.isActive=s},changeCartDiscounts:(e,t,{cartDiscounts:s})=>{t.cartDiscounts=s.map(e=>({typeId:"cart-discount",id:e.id}))},setDescription:(e,t,{description:s})=>{t.description=s},setCartPredicate:(e,t,{cartPredicate:s})=>{t.cartPredicate=s},setName:(e,t,{name:s})=>{t.name=s},setMaxApplications:(e,t,{maxApplications:s})=>{t.maxApplications=s},setMaxApplicationsPerCustomer:(e,t,{maxApplicationsPerCustomer:s})=>{t.maxApplicationsPerCustomer=s},setValidFrom:(e,t,{validFrom:s})=>{t.validFrom=s},setValidUntil:(e,t,{validUntil:s})=>{t.validUntil=s},setValidFromAndUntil:(e,t,{validFrom:s,validUntil:r})=>{t.validFrom=s,t.validUntil=r}}}getTypeId(){return"cart-discount"}create(e,t){console.log(t);const s={...b(),applicationVersion:1,cartDiscounts:t.cartDiscounts.map(e=>({typeId:"cart-discount",id:e.id})),cartPredicate:t.cartPredicate,code:t.code,description:t.description,groups:t.groups||[],isActive:t.isActive||!0,name:t.name,references:[],validFrom:t.validFrom,validUntil:t.validUntil,maxApplications:t.maxApplications,maxApplicationsPerCustomer:t.maxApplicationsPerCustomer};return this.save(e,s),s}}class Y extends D{constructor(e,t){super(e),this.repository=new J(t)}getBasePath(){return"discount-codes"}}class X extends P{constructor(){super(...arguments),this.actions={setKey:(e,t,{key:s})=>{t.key=s},setTimeoutInMs:(e,t,{timeoutInMs:s})=>{t.timeoutInMs=s},changeTriggers:(e,t,{triggers:s})=>{t.triggers=s},changeDestination:(e,t,{destination:s})=>{t.destination=s}}}getTypeId(){return"extension"}create(e,t){const s={...b(),key:t.key,timeoutInMs:t.timeoutInMs,destination:t.destination,triggers:t.triggers};return this.save(e,s),s}}class ee extends D{constructor(e,t){super(e),this.repository=new X(t)}getBasePath(){return"extensions"}}class te extends P{constructor(){super(...arguments),this.actions={changeQuantity:(e,t,{quantity:s})=>{t.quantityOnStock=s,t.availableQuantity=s},setExpectedDelivery:(e,t,{expectedDelivery:s})=>{t.expectedDelivery=new Date(s).toISOString()},setCustomField:(e,t,{name:s,value:r})=>{if(!t.custom)throw new Error("Resource has no custom field");t.custom.fields[s]=r},setCustomType:(e,t,{type:s,fields:r})=>{if(s){const n=this._storage.getByResourceIdentifier(e,s);if(!n)throw new Error(`Type ${s} not found`);t.custom={type:{typeId:"type",id:n.id},fields:r||[]}}else t.custom=void 0},setRestockableInDays:(e,t,{restockableInDays:s})=>{t.restockableInDays=s}}}getTypeId(){return"inventory-entry"}create(e,t){var s,r;const n={...b(),sku:t.sku,quantityOnStock:t.quantityOnStock,availableQuantity:t.quantityOnStock,expectedDelivery:t.expectedDelivery,restockableInDays:t.restockableInDays,supplyChannel:{...t.supplyChannel,typeId:"channel",id:null!=(s=null==(r=t.supplyChannel)?void 0:r.id)?s:""},custom:S(t.custom,e,this._storage)};return this.save(e,n),n}}class se extends D{constructor(e,t){super(e),this.repository=new te(t)}getBasePath(){return"inventory"}}class re extends D{constructor(e,t){super(e),this.repository=new q(t)}getBasePath(){return"me"}registerRoutes(e){const t=this.getBasePath(),r=s.Router({mergeParams:!0});this.extraRoutes(r),r.get("/active-cart",this.activeCart.bind(this)),r.get("/carts/",this.get.bind(this)),r.get("/carts/:id",this.getWithId.bind(this)),r.delete("/carts/:id",this.deletewithId.bind(this)),r.post("/carts/",this.post.bind(this)),r.post("/carts/:id",this.postWithId.bind(this)),e.use("/"+t,r)}activeCart(e,t){const s=this.repository.getActiveCart(e.params.projectKey);return s?t.status(200).send(s):t.status(404).send("Not found")}}class ne extends P{constructor(){super(...arguments),this.transactionFromTransactionDraft=(e,t)=>({...e,id:l.v4(),amount:C(e.amount),custom:S(e.custom,t,this._storage)}),this.actions={setCustomField:(e,t,{name:s,value:r})=>{if(!t.custom)throw new Error("Resource has no custom field");t.custom.fields[s]=r},setCustomType:(e,t,{type:s,fields:r})=>{if(s){const n=this._storage.getByResourceIdentifier(e,s);if(!n)throw new Error(`Type ${s} not found`);t.custom={type:{typeId:"type",id:n.id},fields:r||[]}}else t.custom=void 0},addTransaction:(e,t,{transaction:s})=>{t.transactions=[...t.transactions,this.transactionFromTransactionDraft(s,e)]}}}getTypeId(){return"payment"}create(e,t){const s={...b(),amountPlanned:C(t.amountPlanned),paymentMethodInfo:t.paymentMethodInfo,paymentStatus:t.paymentStatus?{...t.paymentStatus,state:t.paymentStatus.state?N(t.paymentStatus.state,e,this._storage):void 0}:{},transactions:(t.transactions||[]).map(t=>this.transactionFromTransactionDraft(t,e)),interfaceInteractions:(t.interfaceInteractions||[]).map(t=>S(t,e,this._storage)),custom:S(t.custom,e,this._storage)};return this.save(e,s),s}}class ae extends D{constructor(e,t){super(e),this.repository=new ne(t)}getBasePath(){return"me/payments"}}class ie extends P{constructor(){super(...arguments),this.actions={addPayment:(e,t,{payment:s})=>{if(!this._storage.getByResourceIdentifier(e,s))throw new Error(`Payment ${s.id} not found`);t.paymentInfo||(t.paymentInfo={payments:[]}),t.paymentInfo.payments.push({typeId:"payment",id:s.id})},changeOrderState:(e,t,{orderState:s})=>{t.orderState=s},changePaymentState:(e,t,{paymentState:s})=>{t.paymentState=s},setBillingAddress:(e,t,{address:s})=>{t.billingAddress=s},setCustomerEmail:(e,t,{email:s})=>{t.customerEmail=s},setCustomField:(e,t,{name:s,value:r})=>{if(!t.custom)throw new Error("Resource has no custom field");t.custom.fields[s]=r},setCustomType:(e,t,{type:s,fields:r})=>{if(s){const n=this._storage.getByResourceIdentifier(e,s);if(!n)throw new Error(`Type ${s} not found`);t.custom={type:{typeId:"type",id:n.id},fields:r||[]}}else t.custom=void 0},setLocale:(e,t,{locale:s})=>{t.locale=s},setOrderNumber:(e,t,{orderNumber:s})=>{t.orderNumber=s},setShippingAddress:(e,t,{address:s})=>{t.shippingAddress=s},setStore:(e,t,{store:s})=>{if(!s)return;const r=this._storage.getByResourceIdentifier(e,s);if(!r)throw new Error("No store found with key="+s.key);t.store={typeId:"store",key:r.key}}}}getTypeId(){return"order"}create(e,t){i(t.cart,"draft.cart is missing");const s=this._storage.getByResourceIdentifier(e,t.cart);if(!s)throw new Error("Cannot find cart");const r={...b(),orderNumber:t.orderNumber,orderState:"Open",lineItems:[],customLineItems:[],totalPrice:s.totalPrice,refusedGifts:[],origin:"Customer",syncInfo:[],lastMessageSequenceNumber:0};return this.save(e,r),r}import(e,t){var s,r;i(this,"OrderRepository not valid");const n={...b(),billingAddress:t.billingAddress,shippingAddress:t.shippingAddress,custom:S(t.custom,e,this._storage),customerEmail:t.customerEmail,lastMessageSequenceNumber:0,orderNumber:t.orderNumber,orderState:t.orderState||"Open",origin:t.origin||"Customer",paymentState:t.paymentState,refusedGifts:[],store:K(t.store,e,this._storage),syncInfo:[],lineItems:(null==(s=t.lineItems)?void 0:s.map(t=>this.lineItemFromImportDraft.bind(this)(e,t)))||[],customLineItems:(null==(r=t.customLineItems)?void 0:r.map(t=>this.customLineItemFromImportDraft.bind(this)(e,t)))||[],totalPrice:{type:"centPrecision",...t.totalPrice,fractionDigits:2}};return this.save(e,n),n}lineItemFromImportDraft(e,t){let s,r;if(!t.variant.sku)throw new Error("No product found");r={id:0,sku:t.variant.sku};var n=this._storage.query(e,"product",{where:[`masterData(current(masterVariant(sku="${t.variant.sku}"))) or masterData(current(variants(sku="${t.variant.sku}")))`]});if(1!==n.count)throw new w({code:"General",message:`A product containing a variant with SKU '${t.variant.sku}' not found.`});if(s=n.results[0],r=s.masterData.current.masterVariant.sku===t.variant.sku?s.masterData.current.masterVariant:s.masterData.current.variants.find(e=>e.sku===t.variant.sku),!r)throw new Error("Internal state error");return{...b(),custom:S(t.custom,e,this._storage),discountedPricePerQuantity:[],lineItemMode:"Standard",name:t.name,price:E(t.price),priceMode:"Platform",productId:s.id,productType:s.productType,quantity:t.quantity,state:t.state||[],taxRate:t.taxRate,totalPrice:C(t.price.value),variant:{id:r.id,sku:r.sku,price:E(t.price)}}}customLineItemFromImportDraft(e,t){return{...b(),custom:S(t.custom,e,this._storage),discountedPricePerQuantity:[],money:C(t.money),name:t.name,quantity:t.quantity,slug:t.slug,state:[],totalPrice:C(t.money)}}getWithOrderNumber(e,t,s={}){const r=this._storage.query(e,this.getTypeId(),{...s,where:[`orderNumber="${t}"`]});if(1===r.count)return r.results[0];if(r.count>1)throw new Error("Duplicate order numbers")}}class oe extends D{constructor(e,t){super(e),this.repository=new ie(t)}getBasePath(){return"orders"}extraRoutes(e){e.post("/import",this.import.bind(this)),e.get("/order-number=:orderNumber",this.getWithOrderNumber.bind(this))}import(e,t){const s=this.repository.import(e.params.projectKey,e.body);return t.status(200).send(s)}getWithOrderNumber(e,t){const s=this.repository.getWithOrderNumber(e.params.projectKey,e.params.orderNumber,e.query);return s?t.status(200).send(s):t.status(404).send("Not found")}}class ce extends D{constructor(e,t){super(e),this.repository=new ne(t)}getBasePath(){return"payments"}}const ue=e=>{let t=e.replace(/:/g,"=");do{t=t.replace(/(.*)\.(.*)=(.*)$/g,"$1($2=$3)")}while(t.includes("."));return t};class de extends P{constructor(){super(...arguments),this.actions={}}getTypeId(){return"product-projection"}create(e,t){var s,r;if(!t.masterVariant)throw new Error("must provider mastervariant for product projection with key "+t.key);if(!t.productType.id)throw new Error("must provider product type id for product projection with key "+t.key);const n={...b(),name:t.name,slug:t.slug,categories:[],productType:{...t.productType,id:t.productType.id},masterVariant:pe(0,t.masterVariant),variants:null!=(s=null==(r=t.variants)?void 0:r.map((e,t)=>pe(t+1,e)))?s:[],searchKeywords:t.searchKeywords};return this.save(e,n),n}search(e,t){const s="object"==typeof(r=t.filter)?r.map(ue).join(" and "):ue(r);var r;return this._storage.query(e,this.getTypeId(),{where:s})}}const pe=(e,t)=>({id:e,sku:null==t?void 0:t.sku,attributes:null==t?void 0:t.attributes});class le extends D{constructor(e,t){super(e),this.repository=new de(t)}getBasePath(){return"product-projections"}extraRoutes(e){e.get("/search",this.search.bind(this))}search(e,t){const s=this.repository.search(e.params.projectKey,e.query);return t.status(200).send(s)}}class he extends P{constructor(){super(...arguments),this.actions={publish:(e,t,{})=>{t.masterData.staged&&(t.masterData.current=t.masterData.staged,t.masterData.staged=void 0),t.masterData.hasStagedChanges=!1,t.masterData.published=!0},setAttribute:(e,t,{variantId:s,sku:r,name:n,value:a,staged:i})=>{const o=void 0!==i&&i,c=ye(t,o),{variant:u,isMasterVariant:d,variantIndex:p}=me(c,s,r);if(!u)throw new Error(`Variant with id ${s} or sku ${r} not found on product ${t.id}`);u.attributes||(u.attributes=[]);const l=u.attributes.find(e=>e.name===n);l?l.value=a:u.attributes.push({name:n,value:a}),o?(t.masterData.staged=c,d?t.masterData.staged.masterVariant=u:t.masterData.staged.variants[p]=u,t.masterData.hasStagedChanges=!0):(t.masterData.current=c,d?t.masterData.current.masterVariant=u:t.masterData.current.variants[p]=u)}}}getTypeId(){return"product"}create(e,t){var s,r;const n={name:t.name,slug:t.slug,categories:[],masterVariant:t.masterVariant&&ge(0,t.masterVariant),variants:t.variants&&t.variants.map((e,t)=>ge(t+1,e)),searchKeywords:t.searchKeywords},a={...b(),masterData:{current:t.publish?n:void 0,staged:t.publish?void 0:n,hasStagedChanges:null==(s=t.publish)||s,published:null!=(r=t.publish)&&r}};return this.save(e,a),a}}const ye=(e,t)=>!t&&e.masterData.current?e.masterData.current:e.masterData.staged,me=(e,t,s)=>{const r=[e.masterVariant,...e.variants].find(e=>t?e.id===t:!!s&&e.sku===s),n=r===e.masterVariant;return{variant:r,isMasterVariant:n,variantIndex:!n&&r?e.variants.indexOf(r):-1}},ge=(e,t)=>({id:e,sku:null==t?void 0:t.sku,attributes:null==t?void 0:t.attributes,prices:null==t?void 0:t.prices});class fe extends D{constructor(e,t){super(e),this.repository=new he(t)}getBasePath(){return"products"}}class ve extends P{constructor(){super(...arguments),this.attributeDefinitionFromAttributeDefinitionDraft=(e,t)=>{var s,r,n;return{...t,attributeConstraint:null!=(s=t.attributeConstraint)?s:"None",inputHint:null!=(r=t.inputHint)?r:"SingleLine",isSearchable:null==(n=t.isSearchable)||n}},this.actions={changeLocalizedEnumValueLabel:(e,t,{attributeName:s,newValue:r})=>{var n;const a=e=>{switch(e.name){case"lenum":return void e.values.forEach(e=>{e.key==r.key&&(e.label=r.label)});case"set":return void a(e.elementType)}};null==(n=t.attributes)||n.forEach(e=>{e.name==s&&a(e.type)})},changeLabel:(e,t,{attributeName:s,label:r})=>{var n;null==(n=t.attributes)||n.forEach(e=>{e.name==s&&(e.label=r)})}}}getTypeId(){return"product-type"}create(e,t){var s;const r={...b(),key:t.key,name:t.name,description:t.description,attributes:(null!=(s=t.attributes)?s:[]).map(t=>this.attributeDefinitionFromAttributeDefinitionDraft(e,t))};return this.save(e,r),r}getWithKey(e,t){const s=this._storage.query(e,this.getTypeId(),{where:[`key="${t}"`]});if(1===s.count)return s.results[0];if(s.count>1)throw new Error("Duplicate product type key")}}class we extends D{constructor(e,t){super(e),this.repository=new ve(t)}getBasePath(){return"product-types"}extraRoutes(e){e.get("/key=:key",this.getWithKey.bind(this))}getWithKey(e,t){const s=this.repository.getWithKey(e.params.projectKey,e.params.key);return s?t.status(200).send(s):t.status(404).send("Not found")}}class Ie extends R{constructor(){super(...arguments),this.actions={changeName:(e,t,{name:s})=>{t.name=s},changeCurrencies:(e,t,{currencies:s})=>{t.currencies=s},changeCountries:(e,t,{countries:s})=>{t.countries=s},changeLanguages:(e,t,{languages:s})=>{t.languages=s},changeMessagesEnabled:(e,t,{messagesEnabled:s})=>{t.messages.enabled=s},changeProductSearchIndexingEnabled:(e,t,{enabled:s})=>{var r;if(null==(r=t.searchIndexing)||!r.products)throw new Error("Invalid project state");t.searchIndexing.products.status=s?"Activated":"Deactivated",t.searchIndexing.products.lastModifiedAt=(new Date).toISOString()},changeOrderSearchStatus:(e,t,{status:s})=>{var r;if(null==(r=t.searchIndexing)||!r.orders)throw new Error("Invalid project state");t.searchIndexing.orders.status=s,t.searchIndexing.orders.lastModifiedAt=(new Date).toISOString()},setShippingRateInputType:(e,t,{shippingRateInputType:s})=>{t.shippingRateInputType=s},setExternalOAuth:(e,t,{externalOAuth:s})=>{t.externalOAuth=s},changeCountryTaxRateFallbackEnabled:(e,t,{countryTaxRateFallbackEnabled:s})=>{t.carts.countryTaxRateFallbackEnabled=s},changeCartsConfiguration:(e,t,{cartsConfiguration:s})=>{console.log(s),t.carts=s||{countryTaxRateFallbackEnabled:!1,deleteDaysAfterLastModification:90}}}}get(e){return this._storage.getProject(e),this._storage.getProject(e)}save(e,t){const s=this.get(e);if(s)T(s,t.version);else if(0!==t.version)throw new w({code:"InvalidOperation",message:"version on create must be 0"},400);t.version+=1,this._storage.saveProject(t)}}class ke{constructor(e,t){this.repository=new Ie(t),this.registerRoutes(e)}registerRoutes(e){e.get("",this.get.bind(this)),e.post("",this.post.bind(this))}get(e,t){const s=this.repository.get(e.params.projectKey);return t.status(200).send(s)}post(e,t){const s=e.body,r=this.repository.get(e.params.projectKey);return r?(this.repository.processUpdateActions(e.params.projectKey,r,s.actions),t.status(200).send({})):t.status(404).send({})}}class xe extends P{constructor(){super(...arguments),this._transformZoneRateDraft=(e,t)=>{var s;return{...t,zone:N(t.zone,e,this._storage),shippingRates:null==(s=t.shippingRates)?void 0:s.map(this._transformShippingRate)}},this._transformShippingRate=e=>({price:C(e.price),freeAbove:e.freeAbove&&C(e.freeAbove),tiers:e.tiers||[]}),this.actions={addShippingRate:(e,t,{shippingRate:s,zone:r})=>{const n=this._transformShippingRate(s);t.zoneRates.forEach(e=>{e.zone.id!=r.id||e.shippingRates.push(n)}),t.zoneRates.push({zone:{typeId:"zone",id:r.id},shippingRates:[n]})},removeShippingRate:(e,t,{shippingRate:s,zone:r})=>{const n=this._transformShippingRate(s);t.zoneRates.forEach(e=>{e.zone.id==r.id&&(e.shippingRates=e.shippingRates.filter(e=>!h(n,e)))})},addZone:(e,t,{zone:s})=>{const r=N(s,e,this._storage);void 0===t.zoneRates&&(t.zoneRates=[]),t.zoneRates.push({zone:r,shippingRates:[]})},removeZone:(e,t,{zone:s})=>{t.zoneRates=t.zoneRates.filter(e=>e.zone.id!==s.id)},setKey:(e,t,{key:s})=>{t.key=s},setDescription:(e,t,{description:s})=>{t.description=s},setLocalizedDescription:(e,t,{localizedDescription:s})=>{t.localizedDescription=s},setPredicate:(e,t,{predicate:s})=>{t.predicate=s},changeIsDefault:(e,t,{isDefault:s})=>{t.isDefault=s},changeName:(e,t,{name:s})=>{t.name=s}}}getTypeId(){return"shipping-method"}create(e,t){var s;const r={...b(),...t,taxCategory:N(t.taxCategory,e,this._storage),zoneRates:null==(s=t.zoneRates)?void 0:s.map(t=>this._transformZoneRateDraft(e,t)),custom:S(t.custom,e,this._storage)};return this.save(e,r),r}}class be extends D{constructor(e,t){super(e),this.repository=new xe(t)}getBasePath(){return"shipping-methods"}}class _e extends P{getTypeId(){return"shopping-list"}create(e,t){var s,r;const n={...b(),...t,custom:S(t.custom,e,this._storage),textLineItems:[],lineItems:null==(s=t.lineItems)?void 0:s.map(t=>{var s,r,n;return{...b(),...t,addedAt:null!=(s=t.addedAt)?s:"",productId:null!=(r=t.productId)?r:"",name:{},quantity:null!=(n=t.quantity)?n:1,productType:{typeId:"product-type",id:""},custom:S(t.custom,e,this._storage)}}),customer:t.customer?N(t.customer,e,this._storage):void 0,store:null!=(r=t.store)&&r.key?{typeId:"store",key:t.store.key}:void 0};return this.save(e,n),n}}class Ae extends D{constructor(e,t){super(e),this.repository=new _e(t)}getBasePath(){return"shopping-lists"}}class De extends P{constructor(){super(...arguments),this.actions={changeKey:(e,t,{key:s})=>{t.key=s},setDescription:(e,t,{description:s})=>{t.description=s},setName:(e,t,{name:s})=>{t.name=s},setRoles:(e,t,{roles:s})=>{t.roles=s}}}getTypeId(){return"state"}create(e,t){const s={...b(),...t,builtIn:!1,initial:t.initial||!1,transitions:(t.transitions||[]).map(t=>N(t,e,this._storage))};return this.save(e,s),s}}class Te extends D{constructor(e,t){super(e),this.repository=new De(t)}getBasePath(){return"states"}}class Re extends P{constructor(){super(...arguments),this.actions={setName:(e,t,{name:s})=>{t.name=s},setDistributionChannels:(e,t,{distributionChannels:s})=>{t.distributionChannels=this.transformChannels(e,s)},setLanguages:(e,t,{languages:s})=>{t.languages=s}}}getTypeId(){return"store"}create(e,t){const s={...b(),key:t.key,name:t.name,languages:t.languages,distributionChannels:this.transformChannels(e,t.distributionChannels),supplyChannels:this.transformChannels(e,t.supplyChannels)};return this.save(e,s),s}transformChannels(e,t){return t?t.map(t=>N(t,e,this._storage)):[]}}class Pe extends D{constructor(e,t){super(e),this.repository=new Re(t)}getBasePath(){return"stores"}}class Se extends P{getTypeId(){return"subscription"}create(e,t){if("SQS"==t.destination.type&&"0000000000"==new URL(t.destination.queueUrl).pathname.split("/")[1]){const e=t.destination;throw new w({code:"InvalidInput",message:`A test message could not be delivered to this destination: SQS ${e.queueUrl} in ${e.region} for ${e.accessKey}. Please make sure your destination is correctly configured.`},400)}const s={...b(),changes:t.changes||[],destination:t.destination,format:t.format||{type:"Platform"},key:t.key,messages:t.messages||[],status:"Healthy"};return this.save(e,s),s}}class Ee extends D{constructor(e,t){super(e),this.repository=new Se(t)}getBasePath(){return"subscriptions"}}class Ce extends P{constructor(){super(...arguments),this.taxRateFromTaxRateDraft=e=>({...e,id:l.v4(),amount:e.amount||0}),this.actions={addTaxRate:(e,t,{taxRate:s})=>{void 0===t.rates&&(t.rates=[]),t.rates.push(this.taxRateFromTaxRateDraft(s))},removeTaxRate:(e,t,{taxRateId:s})=>{void 0===t.rates&&(t.rates=[]),t.rates=t.rates.filter(e=>e.id!==s)},replaceTaxRate:(e,t,{taxRateId:s,taxRate:r})=>{void 0===t.rates&&(t.rates=[]);const n=this.taxRateFromTaxRateDraft(r);for(let e=0;e<t.rates.length;e++)t.rates[e].id==s&&(t.rates[e]=n)},setDescription:(e,t,{description:s})=>{t.description=s},setKey:(e,t,{key:s})=>{t.key=s},changeName:(e,t,{name:s})=>{t.name=s}}}getTypeId(){return"tax-category"}create(e,t){var s;const r={...b(),...t,rates:(null==(s=t.rates)?void 0:s.map(this.taxRateFromTaxRateDraft))||[]};return this.save(e,r),r}getWithKey(e,t){const s=this._storage.query(e,this.getTypeId(),{where:[`key="${t}"`]});if(1===s.count)return s.results[0];if(s.count>1)throw new Error("Duplicate tax category key")}}class Ke extends D{constructor(e,t){super(e),this.repository=new Ce(t)}getBasePath(){return"tax-categories"}extraRoutes(e){e.get("/key=:key",this.getWithKey.bind(this))}getWithKey(e,t){const s=this.repository.getWithKey(e.params.projectKey,e.params.key);return s?t.status(200).send(s):t.status(404).send("Not found")}}class Ne extends P{constructor(){super(...arguments),this.actions={addFieldDefinition:(e,t,{fieldDefinition:s})=>{t.fieldDefinitions.push(s)},removeFieldDefinition:(e,t,{fieldName:s})=>{t.fieldDefinitions=t.fieldDefinitions.filter(e=>e.name!==s)},setDescription:(e,t,{description:s})=>{t.description=s},changeName:(e,t,{name:s})=>{t.name=s},changeFieldDefinitionOrder:(e,t,{fieldNames:s})=>{const r=new Map(t.fieldDefinitions.map(e=>[e.name,e])),n=[];let a=t.fieldDefinitions;s.forEach(e=>{const t=r.get(e);if(void 0===t)throw new Error("New field");n.push(t),a=a.filter(t=>t.name!==e)}),t.fieldDefinitions=n,t.fieldDefinitions.push(...a)},addEnumValue:(e,t,{fieldName:s,value:r})=>{t.fieldDefinitions.forEach(e=>{if(e.name==s)if("Enum"==e.type.name)e.type.values.push(r);else{if("Set"!=e.type.name||"Enum"!=e.type.elementType.name)throw new Error("Type is not a Enum (or Set of Enum)");e.type.elementType.values.push(r)}})},changeEnumValueLabel:(e,t,{fieldName:s,value:r})=>{t.fieldDefinitions.forEach(e=>{if(e.name==s)if("Enum"==e.type.name)e.type.values.forEach(e=>{e.key==r.key&&(e.label=r.label)});else{if("Set"!=e.type.name||"Enum"!=e.type.elementType.name)throw new Error("Type is not a Enum (or Set of Enum)");e.type.elementType.values.forEach(e=>{e.key==r.key&&(e.label=r.label)})}})}}}getTypeId(){return"type"}create(e,t){const s={...b(),key:t.key,name:t.name,resourceTypeIds:t.resourceTypeIds,fieldDefinitions:t.fieldDefinitions||[],description:t.description};return this.save(e,s),s}}class Me extends D{constructor(e,t){super(e),this.repository=new Ne(t)}getBasePath(){return"types"}}class je extends P{constructor(){super(...arguments),this.actions={addLocation:(e,t,{location:s})=>{t.locations.push(s)},removeLocation:(e,t,{location:s})=>{t.locations=t.locations.filter(e=>!(e.country==s.country&&e.state==s.state))},changeName:(e,t,{name:s})=>{t.name=s},setDescription:(e,t,{description:s})=>{t.description=s},setKey:(e,t,{key:s})=>{t.key=s}}}getTypeId(){return"zone"}create(e,t){const s={...b(),key:t.key,locations:t.locations||[],name:t.name,description:t.description};return this.save(e,s),s}}class qe extends D{constructor(e,t){super(e),this.repository=new je(t)}getBasePath(){return"zones"}}const Oe={enableAuthentication:!1,validateCredentials:!1,defaultProjectKey:void 0,apiHost:/^https:\/\/api\..*?\.commercetools.com:443$/,authHost:/^https:\/\/auth\..*?\.commercetools.com:443$/,silent:!1};exports.CommercetoolsMock=class{constructor(e={}){this._nockScopes={auth:void 0,api:void 0},this.options={...Oe,...e},this._services={},this._projectService=void 0,this._storage=new I,this._oauth2=new x({enabled:this.options.enableAuthentication,validate:this.options.validateCredentials}),this.app=this.createApp({silent:this.options.silent})}start(){this.mockAuthHost(),this.mockApiHost()}stop(){var e,t;null==(e=this._nockScopes.auth)||e.persist(!1),this._nockScopes.auth=void 0,null==(t=this._nockScopes.api)||t.persist(!1),this._nockScopes.api=void 0}clear(){this._storage.clear()}project(e){if(!e&&!this.options.defaultProjectKey)throw new Error("No projectKey passed and no default set");return new _(e||this.options.defaultProjectKey,this._services,this._storage)}runServer(e=3e3,t){this.createApp(t).listen(e,()=>{console.log("Mock server listening at http://localhost:"+e)}).keepAliveTimeout=6e4}createApp(e){const t=r(),s=r.Router({mergeParams:!0});return s.use(r.json()),null!=e&&e.silent||t.use(a("tiny")),t.use("/oauth",this._oauth2.createRouter()),this.options.enableAuthentication?t.use("/:projectKey",this._oauth2.createMiddleware(),s):t.use("/:projectKey",s),this._projectService=new ke(s,this._storage),this._services={category:new z(s,this._storage),cart:new B(s,this._storage),"cart-discount":new j(s,this._storage),customer:new G(s,this._storage),channel:new L(s,this._storage),"customer-group":new U(s,this._storage),"discount-code":new Y(s,this._storage),extension:new ee(s,this._storage),"inventory-entry":new se(s,this._storage),"key-value-document":new Z(s,this._storage),order:new oe(s,this._storage),payment:new ce(s,this._storage),"my-cart":new re(s,this._storage),"my-payment":new ae(s,this._storage),"shipping-method":new be(s,this._storage),"product-type":new we(s,this._storage),product:new fe(s,this._storage),"product-projection":new le(s,this._storage),"shopping-list":new Ae(s,this._storage),state:new Te(s,this._storage),store:new Pe(s,this._storage),subscription:new Ee(s,this._storage),"tax-category":new Ke(s,this._storage),type:new Me(s,this._storage),zone:new qe(s,this._storage)},t.use((e,t,s,r)=>e instanceof w?s.status(e.statusCode).send({statusCode:e.statusCode,message:e.message,errors:[e.info]}):(console.error(e),s.status(500).send({error:e.message}))),t}mockApiHost(){const e=this.app;this._nockScopes.api=t(this.options.apiHost).persist().get(/.*/).reply((async function(t){const s=await n(e).get(t).set(A(this.req.headers));return[s.status,s.body]})).post(/.*/).reply((async function(t,s){const r=await n(e).post(t).set(A(this.req.headers)).send(s);return[r.status,r.body]})).delete(/.*/).reply((async function(t,s){const r=await n(e).delete(t).set(A(this.req.headers)).send(s);return[r.status,r.body]}))}mockAuthHost(){const e=this.app;this._nockScopes.auth=t(this.options.authHost).persist().post(/^\/oauth\/.*/).reply((async function(t,s){const r=await n(e).post(t+"?"+s).set(A(this.req.headers)).send();return[r.status,r.body]}))}},exports.getBaseResourceProperties=b;
2
2
  //# sourceMappingURL=commercetools-mock.cjs.production.min.js.map