@labdigital/commercetools-mock 0.5.22 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commercetools-mock.cjs.development.js +149 -13
- package/dist/commercetools-mock.cjs.development.js.map +1 -1
- package/dist/commercetools-mock.cjs.production.min.js +1 -1
- package/dist/commercetools-mock.cjs.production.min.js.map +1 -1
- package/dist/commercetools-mock.esm.js +149 -13
- package/dist/commercetools-mock.esm.js.map +1 -1
- package/dist/projectAPI.d.ts +2 -1
- package/dist/repositories/cart.d.ts +3 -1
- package/package.json +5 -2
- package/src/projectAPI.ts +4 -2
- package/src/repositories/cart.ts +166 -6
- package/src/repositories/customer.ts +3 -1
- package/src/services/cart.test.ts +48 -8
- package/src/services/cart.ts +15 -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=e(require("nock")),s=require("express"),r=e(s),n=e(require("supertest")),i=e(require("morgan")),a=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,i=null==(s=e.pos)?void 0:s.start.column;throw new y(`Invalid input '${r}', expected input parameter or primitive value (line ${n}, column ${i})`)}},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),i=g(r,s);return Array.isArray(n)?!!n.some(e=>e===i):n===i}}).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),i=g(r,s);if("string"!=typeof n)throw new y(`The field '${e.value}' does not support this expression.`);return n.toLowerCase()===i.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 i=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 i=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(i),Math.sqrt(1-i))*6371*1e3})({longitude:r[0],latitude:r[1]},{longitude:g(n[0],s),latitude:g(n[1],s)})<=i}}).led("CONTAINS",20,({left:e})=>{const r=t.next();let n=s.parse();return Array.isArray(n)||(n=[n]),(t,s)=>{const i=f(t,e);if(!Array.isArray(i))throw new y(`The field '${e.value}' does not support this expression.`);const a=n.map(e=>g(e,s));return"ALL"===r.type?a.every(e=>i.includes(e)):a.some(e=>i.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 i=this.get(e,t,s.id,r);return a(i,`resource of type ${t} with id ${s.id} not created`),i}get(e,t,s,r={}){var n;const i=null==(n=this.forProjectKey(e)[t])?void 0:n.get(s);return i?this.expand(e,i,r.expand):null}getByKey(e,t,s,r={}){const n=this.forProjectKey(e)[t];if(!n)throw new Error("No type");const i=Array.from(n.values()).find(e=>e.key===s);return i?this.expand(e,i,r.expand):null}delete(e,t,s,r={}){const n=this.get(e,t,s);var i;return n?(null==(i=this.forProjectKey(e)[t])||i.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 i=n.length,a=s.offset||0,o=s.limit||20;return n=n.slice(a,a+o),void 0!==s.expand&&(n=n.map(t=>this.expand(e,t,s.expand))),{count:i,total:n.length,offset:a,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 b{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 i=e.query.grant_type||e.body.grant_type;if(!i)return s(new w({code:"invalid_request",message:"Missing required parameter: grant_type."},400));if("client_credentials"===i){var a;const s=this.store.getClientToken(n.name,n.pass,null==(a=e.query.scope)?void 0:a.toString());return t.status(200).send(s)}return s(new w({code:"unsupported_grant_type",message:"Invalid parameter: grant_type: Invalid grant type: "+i},400))}}const x=()=>({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,{...x(),...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._parseParam(e.query.limit),r=this._parseParam(e.query.offset),n=this.repository.query(e.params.projectKey,{expand:this._parseParam(e.query.expand),where:this._parseParam(e.query.where),limit:void 0!==s?Number(s):void 0,offset:void 0!==r?Number(r):void 0});return t.status(200).send(n)}getWithId(e,t){const s=this._expandWithId(e,e.params.id);return s?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),i=this._expandWithId(e,n.id);return t.status(200).send(i)}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 R=(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 T{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 T{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,offset:t.offset,limit:t.limit})}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)R(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:K(e.value)}),K=e=>({type:"centPrecision",fractionDigits:2,...e}),C=(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={...x(),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(K)};case"fixed":return{type:"fixed",money:e.money.map(K)};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:i=1})=>{let a,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(a=[o.masterData.current.masterVariant,...o.masterData.current.variants].find(e=>n?e.sku===n:!!r&&e.id===r),!a)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=a)?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=a)?void 0:s.id)&&(e.quantity+=i,e.totalPrice.centAmount=$(e)),e});else{var c;if(null==(c=a.prices)||!c.length)throw new w({code:"General",message:`A product with ID '${s}' doesn't have any prices.`});const e=a.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:a,price:e,totalPrice:{...e.value,centAmount:e.value.centAmount*i},quantity:i,discountedPricePerQuantity:[],lineItemMode:"Standard",priceMode:"Platform",state:[]})}t.totalPrice.centAmount=B(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=$(e)),e)),t.totalPrice.centAmount=B(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={...x(),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 $=e=>e.price.value.centAmount*e.quantity,B=e=>e.lineItems.reduce((e,t)=>e+t.totalPrice.centAmount,0);class O 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},transitionState:(e,t,{state:s})=>{const r=this._storage.getByResourceIdentifier(e,s);if(!r)throw new Error(`No state found with key=${s.key} or id=${s.key}`);t.state={typeId:"state",id:r.id}},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){a(t.cart,"draft.cart is missing");const s=this._storage.getByResourceIdentifier(e,t.cart);if(!s)throw new Error("Cannot find cart");const r={...x(),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;a(this,"OrderRepository not valid");const n={...x(),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:C(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{...x(),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:K(t.price.value),variant:{id:r.id,sku:r.sku,price:E(t.price)}}}customLineItemFromImportDraft(e,t){return{...x(),custom:S(t.custom,e,this._storage),discountedPricePerQuantity:[],money:K(t.money),name:t.name,quantity:t.quantity,slug:t.slug,state:[],totalPrice:K(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 F extends D{constructor(e,t){super(e),this.repository=new q(t),this.orderRepository=new O(t)}getBasePath(){return"carts"}extraRoutes(e){e.post("/replicate",(e,t)=>{const s="order"===e.body.reference.typeId?this.orderRepository.get(e.params.projectKey,e.body.reference.id):this.repository.get(e.params.projectKey,e.body.reference.id);if(!s)return t.status(400).send();const r=this.repository.create(e.params.projectKey,{...s,currency:s.totalPrice.currencyCode,discountCodes:[]});return t.status(200).send(r)})}}class z extends P{constructor(){super(...arguments),this.actions={changeAssetName:(e,t,{assetId:s,assetKey:r,name:n})=>{var i;null==(i=t.assets)||i.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 i;null==(i=t.assets)||i.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 i;null==(i=t.assets)||i.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={...x(),key:t.key,name:t.name,slug:t.slug,orderHint:t.orderHint||"",externalId:t.externalId||"",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 W extends D{constructor(e,t){super(e),this.repository=new z(t)}getBasePath(){return"categories"}}class L extends P{getTypeId(){return"channel"}create(e,t){const s={...x(),key:t.key,roles:t.roles||[]};return this.save(e,s),s}}class V extends D{constructor(e,t){super(e),this.repository=new L(t)}getBasePath(){return"channels"}}class U 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={...x(),key:t.key,name:t.groupName};return this.save(e,s),s}}class H extends D{constructor(e,t){super(e),this.repository=new U(t)}getBasePath(){return"customer-groups"}}class G extends P{constructor(){super(...arguments),this.actions={changeEmail:(e,t,{email:s})=>{t.email=s}}}getTypeId(){return"customer"}create(e,t){const s={...x(),email:t.email,password:Buffer.from(t.password).toString("base64"),isEmailVerified:t.isEmailVerified||!1,addresses:[]};return this.save(e,s),s}getMe(e){const t=this._storage.query(e,this.getTypeId(),{});if(t.count>0)return t.results[0]}}class Q extends D{constructor(e,t){super(e),this.repository=new G(t)}getBasePath(){return"customers"}extraRoutes(e){e.post("/password-token",(e,t)=>{const s=this.repository.query(e.params.projectKey,{where:[`email="${e.body.email}"`]}),r=e.params.ttlMinutes?+e.params.ttlMinutes:34560,{...n}=x();return t.status(200).send({...n,customerId:s.results[0].id,expiresAt:new Date(Date.now()+60*r).toISOString(),value:l.v4()})})}}class Z extends P{getTypeId(){return"key-value-document"}create(e,t){const s=this.getWithContainerAndKey(e,t.container,t.key),r=x();if(s){if(r.id=s.id,t.version||(t.version=s.version),R(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 J extends D{constructor(e,t){super(e),this.repository=new Z(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 Y 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){const s={...x(),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 X extends D{constructor(e,t){super(e),this.repository=new Y(t)}getBasePath(){return"discount-codes"}}class ee 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={...x(),key:t.key,timeoutInMs:t.timeoutInMs,destination:t.destination,triggers:t.triggers};return this.save(e,s),s}}class te extends D{constructor(e,t){super(e),this.repository=new ee(t)}getBasePath(){return"extensions"}}class se 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={...x(),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 re extends D{constructor(e,t){super(e),this.repository=new se(t)}getBasePath(){return"inventory"}}class ne 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 ie extends P{constructor(){super(...arguments),this.transactionFromTransactionDraft=(e,t)=>({...e,id:l.v4(),amount:K(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)]},changeTransactionState:(e,t,{transactionId:s,state:r})=>{const n=t.transactions.findIndex(e=>e.id===s),i={...t.transactions[n],state:r};t.transactions[n]=i},transitionState:(e,t,{state:s})=>{const r=this._storage.getByResourceIdentifier(e,s);if(!r)throw new Error(`State ${s} not found`);t.paymentStatus.state={typeId:"state",id:r.id,obj:r}}}}getTypeId(){return"payment"}create(e,t){const s={...x(),amountPlanned:K(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 ie(t)}getBasePath(){return"me/payments"}}class oe extends D{constructor(e,t){super(e),this.repository=new O(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 ie(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={...x(),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){var s;const r=null!=(s=t["filter.query"])?s:t.filter,n=r?(e=>"object"==typeof e?e.map(ue).join(" and "):ue(e))(r):void 0;return this._storage.query(e,this.getTypeId(),{where:n,offset:t.offset?Number(t.offset):void 0,limit:t.limit?Number(t.limit):void 0})}}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:i,staged:a})=>{const o=void 0!==a&&a,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=i:u.attributes.push({name:n,value:i}),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},i={...x(),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,i),i}}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 i=e=>{switch(e.name){case"lenum":return void e.values.forEach(e=>{e.key===r.key&&(e.label=r.label)});case"set":return void i(e.elementType)}};null==(n=t.attributes)||n.forEach(e=>{e.name===s&&i(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={...x(),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 T{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})=>{t.carts=s||{countryTaxRateFallbackEnabled:!1,deleteDaysAfterLastModification:90}}}}get(e){return((e,t)=>{const s="externalOAuth.authorizationHeader".split("."),r=JSON.parse(JSON.stringify(e));let n=r;const i=s.pop();for(let t=0;t<s.length;t++)if(n=n[s[t]],void 0===n)return e;return n&&i&&n[i]&&(n[i]="****"),r})(this._storage.getProject(e))}save(e,t){const s=this.get(e);if(s)R(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 be 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:K(e.price),freeAbove:e.freeAbove&&K(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={...x(),...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 xe extends D{constructor(e,t){super(e),this.repository=new be(t),this.registerRoutes(e)}getBasePath(){return"shipping-methods"}extraRoutes(e){e.get("/matching-cart",this.get.bind(this))}}class _e extends P{getTypeId(){return"shopping-list"}create(e,t){var s,r;const n={...x(),...t,custom:S(t.custom,e,this._storage),textLineItems:[],lineItems:null==(s=t.lineItems)?void 0:s.map(t=>{var s,r,n;return{...x(),...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={...x(),...t,builtIn:!1,initial:t.initial||!1,transitions:(t.transitions||[]).map(t=>N(t,e,this._storage))};return this.save(e,s),s}}class Re extends D{constructor(e,t){super(e),this.repository=new De(t)}getBasePath(){return"states"}}class Te 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={...x(),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)):[]}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 store key")}}class Pe extends D{constructor(e,t){super(e),this.repository=new Te(t)}getBasePath(){return"stores"}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 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={...x(),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 Ke 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={...x(),...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 Ce extends D{constructor(e,t){super(e),this.repository=new Ke(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 i=t.fieldDefinitions;s.forEach(e=>{const t=r.get(e);if(void 0===t)throw new Error("New field");n.push(t),i=i.filter(t=>t.name!==e)}),t.fieldDefinitions=n,t.fieldDefinitions.push(...i)},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={...x(),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={...x(),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"}}class $e extends D{constructor(e,t){super(e),this.repository=new G(t)}getBasePath(){return"me"}registerRoutes(e){const t=this.getBasePath(),r=s.Router({mergeParams:!0});this.extraRoutes(r),r.get("",this.getMe.bind(this)),r.post("/signup",this.signUp.bind(this)),r.post("/login",this.signIn.bind(this)),e.use("/"+t,r)}getMe(e,t){const s=this.repository.getMe(e.params.projectKey);return s?t.status(200).send(s):t.status(404).send("Not found")}signUp(e,t){const s=this.repository.create(e.params.projectKey,e.body),r=this._expandWithId(e,s.id);return t.status(this.createStatusCode).send({customer:r})}signIn(e,t){const{email:s,password:r}=e.body,n=Buffer.from(r).toString("base64"),i=this.repository.query(e.params.projectKey,{where:[`email = "${s}"`,`password = "${n}"`]});return 0===i.count?t.status(400).send({message:"Account with the given credentials not found.",errors:[{code:"InvalidCredentials",message:"Account with the given credentials not found."}]}):t.status(200).send({customer:i.results[0]})}}class Be extends D{constructor(e,t){super(e),this.repository=new O(t)}getBasePath(){return"me"}registerRoutes(e){const t=this.getBasePath(),r=s.Router({mergeParams:!0});this.extraRoutes(r),r.get("/orders/",this.get.bind(this)),r.get("/orders/:id",this.getWithId.bind(this)),r.delete("/orders/:id",this.deletewithId.bind(this)),r.post("/orders/",this.post.bind(this)),r.post("/orders/:id",this.postWithId.bind(this)),e.use("/"+t,r)}}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 b({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(i("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 W(s,this._storage),cart:new F(s,this._storage),"cart-discount":new j(s,this._storage),customer:new Q(s,this._storage),channel:new V(s,this._storage),"customer-group":new H(s,this._storage),"discount-code":new X(s,this._storage),extension:new te(s,this._storage),"inventory-entry":new re(s,this._storage),"key-value-document":new J(s,this._storage),order:new oe(s,this._storage),payment:new ce(s,this._storage),"my-cart":new ne(s,this._storage),"my-order":new Be(s,this._storage),"my-customer":new $e(s,this._storage),"my-payment":new ae(s,this._storage),"shipping-method":new xe(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 Re(s,this._storage),store:new Pe(s,this._storage),subscription:new Ee(s,this._storage),"tax-category":new Ce(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=x;
|
|
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")),i=e(require("morgan")),a=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,i=null==(s=e.pos)?void 0:s.start.column;throw new y(`Invalid input '${r}', expected input parameter or primitive value (line ${n}, column ${i})`)}},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),i=g(r,s);return Array.isArray(n)?!!n.some(e=>e===i):n===i}}).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),i=g(r,s);if("string"!=typeof n)throw new y(`The field '${e.value}' does not support this expression.`);return n.toLowerCase()===i.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 i=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 i=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(i),Math.sqrt(1-i))*6371*1e3})({longitude:r[0],latitude:r[1]},{longitude:g(n[0],s),latitude:g(n[1],s)})<=i}}).led("CONTAINS",20,({left:e})=>{const r=t.next();let n=s.parse();return Array.isArray(n)||(n=[n]),(t,s)=>{const i=f(t,e);if(!Array.isArray(i))throw new y(`The field '${e.value}' does not support this expression.`);const a=n.map(e=>g(e,s));return"ALL"===r.type?a.every(e=>i.includes(e)):a.some(e=>i.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 i=this.get(e,t,s.id,r);return a(i,`resource of type ${t} with id ${s.id} not created`),i}get(e,t,s,r={}){var n;const i=null==(n=this.forProjectKey(e)[t])?void 0:n.get(s);return i?this.expand(e,i,r.expand):null}getByKey(e,t,s,r={}){const n=this.forProjectKey(e)[t];if(!n)throw new Error("No type");const i=Array.from(n.values()).find(e=>e.key===s);return i?this.expand(e,i,r.expand):null}delete(e,t,s,r={}){const n=this.get(e,t,s);var i;return n?(null==(i=this.forProjectKey(e)[t])||i.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 i=n.length,a=s.offset||0,o=s.limit||20;return n=n.slice(a,a+o),void 0!==s.expand&&(n=n.map(t=>this.expand(e,t,s.expand))),{count:i,total:n.length,offset:a,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 b{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 i=e.query.grant_type||e.body.grant_type;if(!i)return s(new w({code:"invalid_request",message:"Missing required parameter: grant_type."},400));if("client_credentials"===i){var a;const s=this.store.getClientToken(n.name,n.pass,null==(a=e.query.scope)?void 0:a.toString());return t.status(200).send(s)}return s(new w({code:"unsupported_grant_type",message:"Invalid parameter: grant_type: Invalid grant type: "+i},400))}}const x=()=>({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,{...x(),...t})}get(e,t,s){return this._storage.get(this.projectKey,e,t,s)}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._parseParam(e.query.limit),r=this._parseParam(e.query.offset),n=this.repository.query(e.params.projectKey,{expand:this._parseParam(e.query.expand),where:this._parseParam(e.query.where),limit:void 0!==s?Number(s):void 0,offset:void 0!==r?Number(r):void 0});return t.status(200).send(n)}getWithId(e,t){const s=this._expandWithId(e,e.params.id);return s?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),i=this._expandWithId(e,n.id);return t.status(200).send(i)}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 R=(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 T{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 T{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,offset:t.offset,limit:t.limit})}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)R(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:K(e.value)}),K=e=>({type:"centPrecision",fractionDigits:2,...e}),C=(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}},M=(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 N 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={...x(),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(K)};case"fixed":return{type:"fixed",money:e.money.map(K)};case"giftLineItem":case"relative":return{...e}}return e}}class j extends D{constructor(e,t){super(e),this.repository=new N(t)}getBasePath(){return"cart-discounts"}}class $ extends P{constructor(){super(...arguments),this.actions={addLineItem:(e,t,{productId:s,variantId:r,sku:n,quantity:i=1})=>{let a,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(a=[o.masterData.current.masterVariant,...o.masterData.current.variants].find(e=>n?e.sku===n:!!r&&e.id===r),!a)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=a)?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=a)?void 0:s.id)&&(e.quantity+=i,e.totalPrice.centAmount=B(e)),e});else{var c;if(null==(c=a.prices)||!c.length)throw new w({code:"General",message:`A product with ID '${s}' doesn't have any prices.`});const e=t.totalPrice.currencyCode,r=q({prices:a.prices,currency:e,country:t.country});if(!r)throw new Error(`No valid price found for ${s} for country ${t.country} and currency ${e}`);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:a,price:r,totalPrice:{...r.value,centAmount:r.value.centAmount*i},quantity:i,discountedPricePerQuantity:[],lineItemMode:"Standard",priceMode:"Platform",state:[]})}t.totalPrice.centAmount=O(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=B(e)),e)),t.totalPrice.centAmount=O(t)},setBillingAddress:(e,t,{address:s})=>{t.billingAddress=s},setShippingMethod:(e,t,{shippingMethod:s})=>{const r=this._storage.getByResourceIdentifier(e,s);if(!r)throw new Error(`Type ${s} not found`);t.shippingInfo={shippingMethod:{typeId:"shipping-method",id:r.id}}},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}},this.draftLineItemtoLineItem=(e,t,s,r)=>{const{productId:n,quantity:i,variantId:a,sku:o}=t;let c,u=null;if(n&&a)u=this._storage.get(e,"product",n,{});else if(o){const t=this._storage.query(e,"product",{where:[`masterData(current(masterVariant(sku="${o}"))) or masterData(current(variants(sku="${o}")))`]});1===t.count&&(u=t.results[0])}if(!u)throw new w({code:"General",message:o?`A product containing a variant with SKU '${o}' not found.`:`A product with ID '${n}' not found.`});if(c=[u.masterData.current.masterVariant,...u.masterData.current.variants].find(e=>o?e.sku===o:!!a&&e.id===a),!c)throw new Error(o?`A variant with SKU '${o}' for product '${u.id}' not found.`:`A variant with ID '${a}' for product '${u.id}' not found.`);const d=null!=i?i:1,p=q({prices:c.prices,currency:s,country:r});if(!p)throw new Error(`No valid price found for ${n} for country ${r} and currency ${s}`);return{id:l.v4(),productId:u.id,productKey:u.key,name:u.masterData.current.name,productSlug:u.masterData.current.slug,productType:u.productType,variant:c,price:p,totalPrice:{...p.value,centAmount:p.value.centAmount*d},quantity:d,discountedPricePerQuantity:[],lineItemMode:"Standard",priceMode:"Platform",state:[]}}}getTypeId(){return"cart"}create(e,t){var s,r,n,i,a,o;const c=null!=(s=null==(r=t.lineItems)?void 0:r.map(s=>this.draftLineItemtoLineItem(e,s,t.currency,t.country)))?s:[],u={...x(),cartState:"Active",lineItems:c,customLineItems:[],totalPrice:{type:"centPrecision",centAmount:0,currencyCode:t.currency,fractionDigits:0},taxMode:null!=(n=t.taxMode)?n:"Platform",taxRoundingMode:null!=(i=t.taxRoundingMode)?i:"HalfEven",taxCalculationMode:null!=(a=t.taxCalculationMode)?a:"LineItemLevel",refusedGifts:[],locale:t.locale,country:t.country,origin:null!=(o=t.origin)?o:"Customer",custom:S(t.custom,e,this._storage)};return u.totalPrice.centAmount=O(u),this.save(e,u),u}getActiveCart(e){const t=this._storage.query(e,this.getTypeId(),{where:['cartState="Active"']});if(t.count>0)return t.results[0]}}const q=({prices:e,currency:t,country:s})=>{if(e)return e.find(e=>(!e.country||e.country===s)&&e.value.currencyCode===t)},B=e=>e.price.value.centAmount*e.quantity,O=e=>e.lineItems.reduce((e,t)=>e+t.totalPrice.centAmount,0);class F 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},transitionState:(e,t,{state:s})=>{const r=this._storage.getByResourceIdentifier(e,s);if(!r)throw new Error(`No state found with key=${s.key} or id=${s.key}`);t.state={typeId:"state",id:r.id}},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){a(t.cart,"draft.cart is missing");const s=this._storage.getByResourceIdentifier(e,t.cart);if(!s)throw new Error("Cannot find cart");const r={...x(),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;a(this,"OrderRepository not valid");const n={...x(),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:C(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{...x(),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:K(t.price.value),variant:{id:r.id,sku:r.sku,price:E(t.price)}}}customLineItemFromImportDraft(e,t){return{...x(),custom:S(t.custom,e,this._storage),discountedPricePerQuantity:[],money:K(t.money),name:t.name,quantity:t.quantity,slug:t.slug,state:[],totalPrice:K(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 z extends D{constructor(e,t){super(e),this.repository=new $(t),this.orderRepository=new F(t)}getBasePath(){return"carts"}extraRoutes(e){e.post("/replicate",(e,t)=>{const s="order"===e.body.reference.typeId?this.orderRepository.get(e.params.projectKey,e.body.reference.id):this.repository.get(e.params.projectKey,e.body.reference.id);if(!s)return t.status(400).send();const r={...s,currency:s.totalPrice.currencyCode,discountCodes:[],lineItems:s.lineItems.map(e=>({...e,variantId:e.variant.id,sku:e.variant.sku}))},n=this.repository.create(e.params.projectKey,r);return t.status(200).send(n)})}}class W extends P{constructor(){super(...arguments),this.actions={changeAssetName:(e,t,{assetId:s,assetKey:r,name:n})=>{var i;null==(i=t.assets)||i.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 i;null==(i=t.assets)||i.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 i;null==(i=t.assets)||i.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={...x(),key:t.key,name:t.name,slug:t.slug,orderHint:t.orderHint||"",externalId:t.externalId||"",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 L extends D{constructor(e,t){super(e),this.repository=new W(t)}getBasePath(){return"categories"}}class V extends P{getTypeId(){return"channel"}create(e,t){const s={...x(),key:t.key,roles:t.roles||[]};return this.save(e,s),s}}class U extends D{constructor(e,t){super(e),this.repository=new V(t)}getBasePath(){return"channels"}}class H 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={...x(),key:t.key,name:t.groupName};return this.save(e,s),s}}class G extends D{constructor(e,t){super(e),this.repository=new H(t)}getBasePath(){return"customer-groups"}}class Q extends P{constructor(){super(...arguments),this.actions={changeEmail:(e,t,{email:s})=>{t.email=s}}}getTypeId(){return"customer"}create(e,t){const s={...x(),email:t.email,password:t.password?Buffer.from(t.password).toString("base64"):void 0,isEmailVerified:t.isEmailVerified||!1,addresses:[]};return this.save(e,s),s}getMe(e){const t=this._storage.query(e,this.getTypeId(),{});if(t.count>0)return t.results[0]}}class Z extends D{constructor(e,t){super(e),this.repository=new Q(t)}getBasePath(){return"customers"}extraRoutes(e){e.post("/password-token",(e,t)=>{const s=this.repository.query(e.params.projectKey,{where:[`email="${e.body.email}"`]}),r=e.params.ttlMinutes?+e.params.ttlMinutes:34560,{...n}=x();return t.status(200).send({...n,customerId:s.results[0].id,expiresAt:new Date(Date.now()+60*r).toISOString(),value:l.v4()})})}}class J extends P{getTypeId(){return"key-value-document"}create(e,t){const s=this.getWithContainerAndKey(e,t.container,t.key),r=x();if(s){if(r.id=s.id,t.version||(t.version=s.version),R(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 Y extends D{constructor(e,t){super(e),this.repository=new J(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 X 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){const s={...x(),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 ee extends D{constructor(e,t){super(e),this.repository=new X(t)}getBasePath(){return"discount-codes"}}class te 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={...x(),key:t.key,timeoutInMs:t.timeoutInMs,destination:t.destination,triggers:t.triggers};return this.save(e,s),s}}class se extends D{constructor(e,t){super(e),this.repository=new te(t)}getBasePath(){return"extensions"}}class re 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={...x(),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 ne extends D{constructor(e,t){super(e),this.repository=new re(t)}getBasePath(){return"inventory"}}class ie extends D{constructor(e,t){super(e),this.repository=new $(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 ae extends P{constructor(){super(...arguments),this.transactionFromTransactionDraft=(e,t)=>({...e,id:l.v4(),amount:K(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)]},changeTransactionState:(e,t,{transactionId:s,state:r})=>{const n=t.transactions.findIndex(e=>e.id===s),i={...t.transactions[n],state:r};t.transactions[n]=i},transitionState:(e,t,{state:s})=>{const r=this._storage.getByResourceIdentifier(e,s);if(!r)throw new Error(`State ${s} not found`);t.paymentStatus.state={typeId:"state",id:r.id,obj:r}}}}getTypeId(){return"payment"}create(e,t){const s={...x(),amountPlanned:K(t.amountPlanned),paymentMethodInfo:t.paymentMethodInfo,paymentStatus:t.paymentStatus?{...t.paymentStatus,state:t.paymentStatus.state?M(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 oe extends D{constructor(e,t){super(e),this.repository=new ae(t)}getBasePath(){return"me/payments"}}class ce extends D{constructor(e,t){super(e),this.repository=new F(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 ue extends D{constructor(e,t){super(e),this.repository=new ae(t)}getBasePath(){return"payments"}}const de=e=>{let t=e.replace(/:/g,"=");do{t=t.replace(/(.*)\.(.*)=(.*)$/g,"$1($2=$3)")}while(t.includes("."));return t};class pe 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={...x(),name:t.name,slug:t.slug,categories:[],productType:{...t.productType,id:t.productType.id},masterVariant:le(0,t.masterVariant),variants:null!=(s=null==(r=t.variants)?void 0:r.map((e,t)=>le(t+1,e)))?s:[],searchKeywords:t.searchKeywords};return this.save(e,n),n}search(e,t){var s;const r=null!=(s=t["filter.query"])?s:t.filter,n=r?(e=>"object"==typeof e?e.map(de).join(" and "):de(e))(r):void 0;return this._storage.query(e,this.getTypeId(),{where:n,offset:t.offset?Number(t.offset):void 0,limit:t.limit?Number(t.limit):void 0})}}const le=(e,t)=>({id:e,sku:null==t?void 0:t.sku,attributes:null==t?void 0:t.attributes});class he extends D{constructor(e,t){super(e),this.repository=new pe(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 ye 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:i,staged:a})=>{const o=void 0!==a&&a,c=me(t,o),{variant:u,isMasterVariant:d,variantIndex:p}=ge(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=i:u.attributes.push({name:n,value:i}),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&&fe(0,t.masterVariant),variants:t.variants&&t.variants.map((e,t)=>fe(t+1,e)),searchKeywords:t.searchKeywords},i={...x(),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,i),i}}const me=(e,t)=>!t&&e.masterData.current?e.masterData.current:e.masterData.staged,ge=(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}},fe=(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 ve extends D{constructor(e,t){super(e),this.repository=new ye(t)}getBasePath(){return"products"}}class we 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 i=e=>{switch(e.name){case"lenum":return void e.values.forEach(e=>{e.key===r.key&&(e.label=r.label)});case"set":return void i(e.elementType)}};null==(n=t.attributes)||n.forEach(e=>{e.name===s&&i(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={...x(),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 Ie extends D{constructor(e,t){super(e),this.repository=new we(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 ke extends T{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})=>{t.carts=s||{countryTaxRateFallbackEnabled:!1,deleteDaysAfterLastModification:90}}}}get(e){return((e,t)=>{const s="externalOAuth.authorizationHeader".split("."),r=JSON.parse(JSON.stringify(e));let n=r;const i=s.pop();for(let t=0;t<s.length;t++)if(n=n[s[t]],void 0===n)return e;return n&&i&&n[i]&&(n[i]="****"),r})(this._storage.getProject(e))}save(e,t){const s=this.get(e);if(s)R(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 be{constructor(e,t){this.repository=new ke(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:M(t.zone,e,this._storage),shippingRates:null==(s=t.shippingRates)?void 0:s.map(this._transformShippingRate)}},this._transformShippingRate=e=>({price:K(e.price),freeAbove:e.freeAbove&&K(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=M(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={...x(),...t,taxCategory:M(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 _e extends D{constructor(e,t){super(e),this.repository=new xe(t),this.registerRoutes(e)}getBasePath(){return"shipping-methods"}extraRoutes(e){e.get("/matching-cart",this.get.bind(this))}}class Ae extends P{getTypeId(){return"shopping-list"}create(e,t){var s,r;const n={...x(),...t,custom:S(t.custom,e,this._storage),textLineItems:[],lineItems:null==(s=t.lineItems)?void 0:s.map(t=>{var s,r,n;return{...x(),...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?M(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 De extends D{constructor(e,t){super(e),this.repository=new Ae(t)}getBasePath(){return"shopping-lists"}}class Re 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={...x(),...t,builtIn:!1,initial:t.initial||!1,transitions:(t.transitions||[]).map(t=>M(t,e,this._storage))};return this.save(e,s),s}}class Te extends D{constructor(e,t){super(e),this.repository=new Re(t)}getBasePath(){return"states"}}class Pe 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={...x(),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=>M(t,e,this._storage)):[]}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 store key")}}class Se extends D{constructor(e,t){super(e),this.repository=new Pe(t)}getBasePath(){return"stores"}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 Ee 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={...x(),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 Ke extends D{constructor(e,t){super(e),this.repository=new Ee(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={...x(),...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 Me 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 i=t.fieldDefinitions;s.forEach(e=>{const t=r.get(e);if(void 0===t)throw new Error("New field");n.push(t),i=i.filter(t=>t.name!==e)}),t.fieldDefinitions=n,t.fieldDefinitions.push(...i)},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={...x(),key:t.key,name:t.name,resourceTypeIds:t.resourceTypeIds,fieldDefinitions:t.fieldDefinitions||[],description:t.description};return this.save(e,s),s}}class je extends D{constructor(e,t){super(e),this.repository=new Ne(t)}getBasePath(){return"types"}}class $e 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={...x(),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 $e(t)}getBasePath(){return"zones"}}class Be 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("",this.getMe.bind(this)),r.post("/signup",this.signUp.bind(this)),r.post("/login",this.signIn.bind(this)),e.use("/"+t,r)}getMe(e,t){const s=this.repository.getMe(e.params.projectKey);return s?t.status(200).send(s):t.status(404).send("Not found")}signUp(e,t){const s=this.repository.create(e.params.projectKey,e.body),r=this._expandWithId(e,s.id);return t.status(this.createStatusCode).send({customer:r})}signIn(e,t){const{email:s,password:r}=e.body,n=Buffer.from(r).toString("base64"),i=this.repository.query(e.params.projectKey,{where:[`email = "${s}"`,`password = "${n}"`]});return 0===i.count?t.status(400).send({message:"Account with the given credentials not found.",errors:[{code:"InvalidCredentials",message:"Account with the given credentials not found."}]}):t.status(200).send({customer:i.results[0]})}}class Oe extends D{constructor(e,t){super(e),this.repository=new F(t)}getBasePath(){return"me"}registerRoutes(e){const t=this.getBasePath(),r=s.Router({mergeParams:!0});this.extraRoutes(r),r.get("/orders/",this.get.bind(this)),r.get("/orders/:id",this.getWithId.bind(this)),r.delete("/orders/:id",this.deletewithId.bind(this)),r.post("/orders/",this.post.bind(this)),r.post("/orders/:id",this.postWithId.bind(this)),e.use("/"+t,r)}}const Fe={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={...Fe,...e},this._services={},this._projectService=void 0,this._storage=new I,this._oauth2=new b({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(i("tiny")),t.use("/oauth",this._oauth2.createRouter()),this.options.enableAuthentication?t.use("/:projectKey",this._oauth2.createMiddleware(),s):t.use("/:projectKey",s),this._projectService=new be(s,this._storage),this._services={category:new L(s,this._storage),cart:new z(s,this._storage),"cart-discount":new j(s,this._storage),customer:new Z(s,this._storage),channel:new U(s,this._storage),"customer-group":new G(s,this._storage),"discount-code":new ee(s,this._storage),extension:new se(s,this._storage),"inventory-entry":new ne(s,this._storage),"key-value-document":new Y(s,this._storage),order:new ce(s,this._storage),payment:new ue(s,this._storage),"my-cart":new ie(s,this._storage),"my-order":new Oe(s,this._storage),"my-customer":new Be(s,this._storage),"my-payment":new oe(s,this._storage),"shipping-method":new _e(s,this._storage),"product-type":new Ie(s,this._storage),product:new ve(s,this._storage),"product-projection":new he(s,this._storage),"shopping-list":new De(s,this._storage),state:new Te(s,this._storage),store:new Se(s,this._storage),subscription:new Ke(s,this._storage),"tax-category":new Me(s,this._storage),type:new je(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=x;
|
|
2
2
|
//# sourceMappingURL=commercetools-mock.cjs.production.min.js.map
|