@faststore/api 4.6.0-dev.0 → 4.6.0-dev.2
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/cjs/index.js +51 -45
- package/dist/cjs/index.js.map +1 -1
- package/dist/es/index.mjs +1345 -1237
- package/dist/es/index.mjs.map +1 -1
- package/dist/src/__generated__/schema.d.ts +6 -0
- package/dist/src/__generated__/schema.d.ts.map +1 -1
- package/dist/src/platforms/vtex/clients/commerce/index.d.ts +8 -1
- package/dist/src/platforms/vtex/clients/commerce/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/clients/index.d.ts +2 -1
- package/dist/src/platforms/vtex/clients/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/index.d.ts +1 -0
- package/dist/src/platforms/vtex/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/getOrderEntryOperation.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/index.d.ts +1 -0
- package/dist/src/platforms/vtex/resolvers/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/mutation.d.ts +1 -0
- package/dist/src/platforms/vtex/resolvers/mutation.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/query.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/validateCart.d.ts +1 -0
- package/dist/src/platforms/vtex/resolvers/validateCart.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/validateSession.d.ts.map +1 -1
- package/dist/src/platforms/vtex/utils/cartSalesChannel.d.ts +11 -0
- package/dist/src/platforms/vtex/utils/cartSalesChannel.d.ts.map +1 -0
- package/dist/src/platforms/vtex/utils/sessionChannel.d.ts +10 -0
- package/dist/src/platforms/vtex/utils/sessionChannel.d.ts.map +1 -0
- package/dist/src/platforms/vtex/utils/validateSessionHelpers.d.ts +88 -0
- package/dist/src/platforms/vtex/utils/validateSessionHelpers.d.ts.map +1 -0
- package/package.json +3 -3
- package/src/__generated__/schema.ts +6 -0
- package/src/platforms/vtex/clients/commerce/index.ts +17 -2
- package/src/platforms/vtex/resolvers/validateCart.ts +86 -8
- package/src/platforms/vtex/resolvers/validateSession.ts +63 -140
- package/src/platforms/vtex/typeDefs/order.graphql +6 -0
- package/src/platforms/vtex/utils/cartSalesChannel.ts +31 -0
- package/src/platforms/vtex/utils/sessionChannel.ts +32 -0
- package/src/platforms/vtex/utils/validateSessionHelpers.ts +202 -0
package/dist/cjs/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
%o`,e),
|
|
3
|
-
%o`,t,e),e}class W extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class E extends W{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Q extends W{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class x extends W{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class L extends W{constructor(n){super({status:404,type:"NotFoundError"},n)}}const Qn=e=>e?.name==="FastStoreError",Zn=e=>e?.extensions?.type==="BadRequestError",et=e=>e?.extensions?.type==="UnauthorizedError",hn=e=>e?.extensions?.type==="ForbiddenError",q=e=>e?.extensions?.type==="NotFoundError",nt=`${ke.name}@${ke.version}`,I=async(e,n,t)=>{const r=await qn(e,{...n,headers:{...n?.headers??{},"User-Agent":nt}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new E(i);case 401:throw new Q(i);case 403:throw new x(i);case 404:throw new L(i);default:throw new W({status:r.status,type:"UnknownError"},i)}throw new Error(i)},tt=({account:e,environment:n})=>{const t=`https://${e}.${n}.com.br`;return{getLocalizedProduct:(r,i)=>I(`${t}/api/catalog-dataplane/product/${r}`,{method:"GET",headers:{"Accept-Language":i,"Content-Type":"application/json"}})}},fn=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const o=i.trim();if(o){const a=o.indexOf("=");if(a>0){const s=o.substring(0,a),c=o.substring(a+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},rt=/^([^=]+)=([^;]*)/,it=(e,n)=>{const t=n.match(rt);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},ot=(e,n)=>{n.getSetCookie().forEach(t=>it(e,t))},at=e=>n=>ot(e,n),me=e=>{if(!e.headers?.cookie)return null;const n=fn(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:o}])=>st(r,i,o),n)},Sn=e=>function(t){const r=me(e);return r?{...t,cookie:r}:t},V=(e,n)=>{const t=fn(e);return te.parse(t)[`VtexIdclientAutCookie_${n}`]||""},st=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function Z(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const ct="storefront/faststore.recommendation-shelf@v4",X={method:"POST",headers:{"content-type":"application/json"}},lt=e=>e.split("/").map(encodeURIComponent).join("/"),ge=e=>e?{headers:{"Accept-Language":e}}:void 0,dt=/^\d{4}-\d{2}-\d{2}$/,ut=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function pt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a}){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`listUserQuotes: invalid page "${e}" — must be a positive integer`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`listUserQuotes: invalid perPage "${n}" — must be a positive integer`);for(const[s,c]of[["createdAtFrom",r],["createdAtTo",i],["expiresAtFrom",o],["expiresAtTo",a]])if(c&&!dt.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!ut.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function gt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(l=>c.append("status",l)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),o&&c.append("expiresAtFrom",o),a&&c.append("expiresAtTo",a),s?.trim()&&c.append("label",s.trim()),c}const mt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const o=`https://${e}.${n}.com.br`,a=at(i),s=Sn(i),c=jn(),l=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",g=r&&r.map(d=>d+".").find(d=>l.includes(d))||"",u=l.replace(g,""),h=`${o}/api/recommend-bff/v2`,f=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${ct}`}),v=(d={})=>{const p=V(me(i)??"",e);return s({...d,"X-FORWARDED-HOST":u,...p?{[`VtexIdclientAutCookie_${e}`]:p}:{}})};return{catalog:{salesChannel:d=>I(`${o}/api/catalog_system/pub/saleschannel/${d}`,void 0,{storeCookies:a}),brand:{list:()=>I(`${o}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:a})},category:{tree:(d=3)=>I(`${o}/api/catalog_system/pub/category/tree/${d}`,void 0,{storeCookies:a})},portal:{pagetype:d=>I(`${o}/api/catalog_system/pub/portal/pagetype/${d}`,void 0,{storeCookies:a})},byLinkId:{category:async(d,p)=>{try{return await I(`${o}/api/catalog_system/pub/category/by-linkid/${lt(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}},brand:async(d,p)=>{try{return await I(`${o}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}},collection:async(d,p)=>{try{return await I(`${o}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}}},products:{crossselling:({type:d,productId:p,groupByProduct:m=!0})=>{const y=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return I(`${o}/api/catalog_system/pub/products/crossselling/${d}/${p}?${y}`,void 0,{storeCookies:a})}}},checkout:{simulation:(d,{salesChannel:p}=i.storage.channel)=>{const m=new URLSearchParams({sc:p}),y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...X,headers:y,body:JSON.stringify(d)},{storeCookies:a})},shippingData:({id:d,index:p,deliveryMode:m,selectedAddresses:y},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,C={logisticsInfo:Array.from({length:p},(S,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:y,clearAddressIfPostalCodeNotFound:t},P=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/shippingData`,{...X,headers:P,body:JSON.stringify(C)},{storeCookies:a})},marketingData:({id:d,marketingData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/marketingData`,{headers:m,body:JSON.stringify(p),method:"POST"},{storeCookies:a})},clientPreferencesData:({id:d,clientPreferencesData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(p),method:"POST"},{storeCookies:a})},orderForm:({id:d,refreshOutdatedData:p=!0,channel:m=i.storage.channel})=>{const{salesChannel:y}=m,O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),w=new URLSearchParams({sc:y});d&&w.set("refreshOutdatedData",p.toString());const C=`${o}/api/checkout/pub/orderForm${d?`/${d}`:""}?${w.toString()}`;return I(C,{...X,headers:O,...d?{}:{body:"{}"}},{storeCookies:a})},clearOrderFormMessages:({id:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/messages/clear`,{...X,headers:p,body:"{}"})},updateOrderFormItems:({id:d,orderItems:p,allowOutdatedData:m="paymentData",salesChannel:y=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:y}),C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/items?${w}`,{headers:C,body:JSON.stringify({orderItems:p,noSplitItem:!O}),method:"PATCH"},{storeCookies:a})},setCustomData:({id:d,appId:p,key:m,value:y})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/customData/${p}/${m}`,{headers:O,body:JSON.stringify({value:y}),method:"PUT"})},region:async({postalCode:d,geoCoordinates:p,country:m,salesChannel:y})=>{const O=new URLSearchParams({country:m,sc:y??""});d?O.append("postalCode",d):O.append("geoCoordinates",`${p?.longitude};${p?.latitude}`);const w=`${o}/api/checkout/pub/regions/?${O.toString()}`,C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(w,{headers:C},{storeCookies:a})},address:async({postalCode:d,country:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/postal-code/${p}/${d}`,{headers:m},{storeCookies:a})},cancelOrder:({orderId:d,customerEmail:p,reason:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orders/${d}/user-cancel-request`,{method:"POST",headers:y,body:JSON.stringify({customerEmail:p,reason:m})},{})},pickupPoints:({geoCoordinates:d})=>{if(!d)throw new Error("Missing required parameter for listing pickup points.");const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:p,body:JSON.stringify({coordinate:d})},{storeCookies:a})}},session:d=>{const p=new URLSearchParams(d);p.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,shopper.availableContracts,shopper.activeContractId,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol,authentication.customerId,authentication.storeUserId,authentication.storeUserEmail,authentication.unitId,authentication.unitName,checkout.regionId,public.postalCode");const m=s({"content-type":"application/json"}),y=te.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${o}/api/sessions?${p.toString()}`,{method:y?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:a})},subscribeToNewsletter:d=>I(`${o}/api/dataentities/NL/documents/`,{...X,body:JSON.stringify({...d,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:a}),profile:{addresses:async d=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/profile-system/pvt/profiles/${d}/addresses`,{headers:p},{storeCookies:a})}},oms:{userOrder:({orderId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/oms/user/orders/${d}`,{method:"GET",headers:p},{storeCookies:a})},listUserOrders:({page:d,status:p,dateInitial:m,dateFinal:y,text:O,clientEmail:w,perPage:C,pendingMyApproval:P})=>{const S=new URLSearchParams;if(m){const A=new Date(m).setHours(0,0,0,0);m=new Date(A).toISOString()}if(y){const A=new Date(y).setHours(23,59,59,999);y=new Date(A).toISOString()}O&&S.append("text",O),p&&p.length>0&&S.append("status",p.filter(Boolean).join(",")),m&&y?S.append("creation_date",`creationDate:[${m} TO ${y}]`):m?S.append("creation_date",`creationDate:[${m} TO *]`):y&&S.append("creation_date",`creationDate:[* TO ${y}]`),w&&S.append("clientEmail",w),d&&S.append("page",d.toString()),C&&S.append("per_page",C.toString()),P&&S.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/oms/user/orders?${S.toString()}`,{method:"GET",headers:D},{storeCookies:a})},getCommercialAuthorizationsByOrderId:({orderId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/${e}/commercial-authorizations/order/${d}`,{method:"GET",headers:p},{storeCookies:a})},processOrderAuthorization:async({orderAuthorizationId:d,dimensionId:p,ruleId:m,approved:y})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),P={params:{ruleId:m,dimensionId:p,score:y?100:0}};return I(`${o}/${e}/commercial-authorizations/${d}/callback`,{method:"POST",headers:O,body:JSON.stringify(P)},{storeCookies:a})}},units:{getUnitByUserId:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}/unit`,{method:"GET",headers:p},{})},getOrgUnitById:({orgUnitId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}`,{method:"GET",headers:p},{})},getScopesByOrgUnit:({orgUnitId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}/scopes`,{method:"GET",headers:p},{})}},licenseManager:{getUserById:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/users/${d}`,{method:"GET",headers:p},{})},getUserByEmail:({email:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/pvt/users/${d}`,{method:"GET",headers:p},{})},getUserRoles:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/storefront/users/${d}/roles`,{method:"GET",headers:p},{})}},masterData:{getContractById:({contractId:d})=>{if(!d)throw new E("Missing contractId to fetch CL fields.");const p=v({Accept:"application/json","content-type":"application/json"});return I(`${o}/api/dataentities/CL/documents/${d}?_fields=_all`,{method:"GET",headers:p},{})},getShopperById:({userId:d})=>{if(!d)throw new E("Missing userId to fetch shopper name.");const p=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),m=d.replace(/-/g,"");return I(`${o}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${d})&_fields=_all&_schema=v1`,{method:"GET",headers:p},{})}},quotes:{listUserQuotes:d=>{pt(d);const p=gt(d),m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/quoting/quotes?${p.toString()}`,{method:"GET",headers:m},{storeCookies:a})}},vtexid:{validate:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u}),p=V(me(i)??"",e);return I(`${o}/api/vtexid/credential/validate`,{headers:d,body:JSON.stringify({token:p}),method:"POST"},{storeCookies:a})}},orderEntry:{uploadFile:({fileBuffer:d,fileName:p,mimeType:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),O=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
|
|
4
|
-
`,P=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",S=p.replaceAll(/[\r\n"]/g,"_"),D=[`--${O}`,`Content-Disposition: form-data; name="file"; filename="${S}"`,`Content-Type: ${P}`,"",""].join(w),A=`${w}--${O}--${w}`,T=Buffer.from(D),b=Buffer.from(A),k=new Uint8Array(T.byteLength+d.byteLength+b.byteLength);let U=0;return k.set(T,U),U+=T.byteLength,k.set(d,U),U+=d.byteLength,k.set(b,U),I(`${o}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...y,"content-type":`multipart/form-data; boundary=${O}`},body:k.buffer},{})},startOperation:({objectKey:d,orderFormId:p,sessionToken:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),O=JSON.stringify({objectKey:d,orderFormId:p,operation:"CreateCart",...m?{sessionToken:m}:{}});return I(`${o}/api/order-entry/operation?an=${e}`,{method:"POST",headers:y,body:O},{})},getOperation:({operationId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/order-entry/operation/${d}?an=${e}`,{method:"GET",headers:p},{})},createOrderForm:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:d,body:"{}"},{})},getOrderFormItems:({orderFormId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}`,{method:"GET",headers:p},{})}},recommendation:{recommendations:({campaignVrn:d,userId:p,products:m=[],salesChannel:y,locale:O})=>{const w=new URLSearchParams({an:e,campaignVrn:d});return p&&w.append("userId",p),m.length>0&&w.append("products",m.join(",")),y&&w.append("salesChannel",y),O&&w.append("locale",O),I(`${h}/recommendations?${w.toString()}`,{headers:f},{storeCookies:a})},startRecommendationSession:()=>{const d=new URLSearchParams({an:e});return I(`${h}/users/start-session?${d.toString()}`,{method:"POST",headers:f},{storeCookies:a})}}}},ee=e=>e.discoveryConfig?.localization??{},ne=e=>ee(e).enabled===!0,ht=e=>Object.keys(ee(e).locales??{}),ft=e=>ee(e).defaultLocale,ie=e=>ne(e)&&e.storage.locale||void 0,he="fuzzy",fe="operator",Se="pickupPoint",_e="shipping",Re="delivery-options",St="in-stock",yt="trade-policy",It="region-id",vt=new Set([yt,It,he,fe,Se]),Ot=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),Fe=e=>encodeURI(decodeURI(e)),Ct=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),bt=/^pickup-in-point-(.+)$/;function yn(e){if(!e)return{};try{const t=te.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function wt(e){const n={},t=[];for(const r of e.split(";")){const i=r.indexOf("=");if(i<0)continue;const o=r.slice(0,i),a=r.slice(i+1);!o||!a||(Ot.has(o)?n[o]=a:t.push({key:o,value:a}))}return{shipping:n,extraFacets:t}}function Dt(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=wt(n);return{segmentParams:{sc:e.channel,regionId:e.regionId,country:e.countryCode??t.country,locale:e.cultureInfo,"zip-code":t["zip-code"],coordinates:t.coordinates,pickupPoint:t.pickupPoint,deliveryZonesHash:t.deliveryZonesHash,pickupPointHash:t.pickupPointsHash,utmSource:e.utm_source??void 0,utmCampaign:e.utm_campaign??void 0,utmiCampaign:e.utmi_campaign??void 0,campaigns:typeof e.campaigns=="string"?e.campaigns:void 0,priceTables:e.priceTables??void 0},extraFacets:r}}function In(e,n){const t=[["sc",n.sc],["regionId",n.regionId],["country",n.country],["locale",n.locale],["zip-code",n["zip-code"]],["coordinates",n.coordinates],["pickupPoint",n.pickupPoint],["deliveryZonesHash",n.deliveryZonesHash],["pickupPointHash",n.pickupPointHash],["utmSource",n.utmSource],["utmCampaign",n.utmCampaign],["utmiCampaign",n.utmiCampaign],["campaigns",n.campaigns],["priceTables",n.priceTables]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function vn(e){return bt.exec(e)?.[1]}function At(e){const n=e.find(r=>r.key==="shipping"),t=n?vn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function Pt(e,n){const t=At(n);return t===void 0?e:{...e,pickupPoint:t}}function Et(e){return e.map(n=>n.key!=="shipping"||vn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function Tt(e,n){let t=[...e];const r=t.some(i=>i.key==="shipping");for(const i of n)(!r||i.key!=="shipping")&&t.push(i);return t.some(i=>i.key==="shipping"&&i.value==="ignore")&&(t=t.filter(i=>i.key!=="shipping")),Et(t)}function kt(e){return e.reduce((n,t)=>{let{key:r,value:i}=t;return r==="priceRange"&&(r="price",i=i.replace(" TO ",":")),r==="ft"?n:`${n}${Fe(r)}/${Ct(Fe(i)).replaceAll(/ |%20/g,"-")}/`},"")}const Ut=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),_t=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function Rt(e,n){const{segmentParams:t,extraFacets:r}=Dt(e??{}),i=n?.salesChannel??t.sc,o=n?.regionId??t.regionId,a=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...o?{regionId:o}:{},locale:a},extraFacets:r}}function Ft(e,n){const t=e.filter(({key:c})=>!vt.has(c)),r=e.find(({key:c,value:l})=>c===_e&&l!=="all-delivery-methods")??null,i=e.find(({key:c,value:l})=>c===Re&&l!=="all-delivery-options")??null,o=[...t],a=o.some(({key:c})=>c===_e),s=o.some(({key:c})=>c===Re);return r!==null&&!a&&o.push(r),i!==null&&!s&&o.push(i),Tt(o,n)}function Nt(e,n){const t=e.find(({key:o})=>o===he)??null,r=e.find(({key:o})=>o===fe)??null,i=e.find(({key:o})=>o===Se)??null;t&&Ut(t)&&n.append(he,t.value),r&&_t(r)&&n.append(fe,r.value),i&&n.append(Se,i.value)}function Ne(e,n,t,r){const{query:i="",page:o,count:a,sort:s,selectedFacets:c=[],showInvisibleItems:l,sponsoredCount:g,hideUnavailableItems:u,allowRedirect:h=!1}=e,f=new URLSearchParams;if(r.includePagination&&o!==void 0&&a!==void 0){const p=o*a,m=a===0?p:p+a-1;f.append("from",p.toString()),f.append("to",m.toString())}i&&f.append("query",i),r.includeSort&&s&&f.append("sort",s);const v=Pt(t.segmentParams,c);if(In(f,v??t.segmentParams),Nt(c,f),l&&f.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const p=c.find(({key:y})=>y===St),m=p?p.value:u?.toString()??n.hideUnavailableItems.toString();f.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&f.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&f.append("showSponsored",n.showSponsored.toString()),g!==void 0&&f.append("sponsoredCount",g.toString()),h!==void 0&&f.append("allowRedirect",h.toString());const d=kt(Ft(c,t.extraFacets));return{params:f,path:d}}function Lt(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:o}=e,a=new URLSearchParams({field:t??"",value:r??""});return In(a,n),i&&a.append("hideUnavailableItems","true"),o&&a.append("show-invisible-items","true"),a}function Y(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function J(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,o=Rt(t,r);switch(n){case"product-search":case"facets":{const{params:a,path:s}=Ne(i,r,o,{includePagination:!0,includeSort:!0});return Y(s,a)}case"catalog-count":{const{params:a,path:s}=Ne(i,r,o,{includePagination:!1,includeSort:!1});return Y(s,a)}case"products":{const a=Lt(i,o.segmentParams);return Y("",a)}case"search-suggestions":{const a=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??o.segmentParams.locale??""});return Y("",a)}case"top-searches":{const a=new URLSearchParams({locale:r?.locale??o.segmentParams.locale??""});return Y("",a)}default:{const a=n;throw new Error(`Unknown intelligent-search endpoint: ${a}`)}}}const Bt=10;function $t(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function Mt(e){const t=yn(e.headers?.cookie).cultureInfo||"";return ne(e)?e.storage.locale||t:t||e.storage.locale||""}const zt=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:o},a)=>{const s=`https://${e}.${n}.com.br`,c=Sn(a),l=yn(a.headers?.cookie),g=()=>({salesChannel:a.storage.channel.salesChannel,regionId:$t(a),locale:Mt(a),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),u=new Headers(a.headers).get("x-forwarded-host")??a.headers?.host??"",h=o&&o.map(S=>S+".").find(S=>u.includes(S))||"",f=u.replace(h,""),v=c({"content-type":"application/json","X-FORWARDED-HOST":f}),d=({type:S,...D})=>{const A=S==="facets"?"facets":"product-search",T=J({endpoint:A,segment:l,defaults:g(),args:D});return I(`${s}/api/intelligent-search/v1/${A}/${T.path}?${T.params.toString()}`,{headers:v})},p=S=>d({...S,type:"product_search"}),m=({field:S,value:D,hideUnavailableItems:A,showInvisibleItems:T})=>{const b=J({endpoint:"products",segment:l,defaults:g(),args:{field:S,value:D,hideUnavailableItems:A,showInvisibleItems:T}});return I(`${s}/api/intelligent-search/v1/products?${b.params.toString()}`,{headers:v})};return{facets:S=>d({...S,type:"facets"}),products:p,fetchProduct:m,productsByIdentifier:async({field:S,values:D,showInvisibleItems:A,hideUnavailableItems:T})=>{const b=Ae(Bt);return(await Promise.all(D.map(U=>b(async()=>{try{return await m({field:S,value:U,hideUnavailableItems:T,showInvisibleItems:A})}catch{return null}})))).filter(U=>U!==null)},suggestedTerms:S=>{const D=J({endpoint:"search-suggestions",segment:l,defaults:g(),args:{query:S.query}});return I(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:v})},topSearches:()=>{const S=J({endpoint:"top-searches",segment:l,defaults:g()});return I(`${s}/api/intelligent-search/v1/top-searches?${S.params.toString()}`,{headers:v})},productCount:S=>{const D=J({endpoint:"catalog-count",segment:l,defaults:g(),args:S});return I(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:v})}}},qt=(e,n)=>{const t=zt(e,n),r=mt(e,n),i=tt(e);return{search:t,commerce:r,catalog:i}},Vt=20,xt=e=>e.entityType==="category",ye=e=>e.entityType==="brand",Le=e=>e.entityType==="collection",jt=(e,n)=>{const t=Ae(Vt),r=async i=>Promise.all(i.map(o=>t(async()=>{const a=o.slug.toLowerCase(),s=o.locale,c=await n.commerce.catalog.byLinkId.category(a,s);if(c)return{...c,entityType:"category",slug:a};const l=await n.commerce.catalog.byLinkId.brand(a,s);if(l)return{...l,entityType:"brand"};const g=await n.commerce.catalog.byLinkId.collection(a,s);if(g)return{...g,entityType:"collection"};throw new L(`No catalog entity found for slug: ${o.slug}. Cascade exhausted (category → brand → collection).`)})));return new ue(r,{batch:!1,cacheKeyFn:({slug:i,locale:o})=>`${i.toLowerCase()}::${o??""}`})},Wt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new ue(t)},Gt=1,Ht=(e,n)=>{const t=Ae(Gt),r=async o=>{const a=o.reduce((u,{items:h})=>[...u,h],[]),s=[...a.flat()],c=await n.commerce.checkout.simulation({country:o[0].country,postalCode:o[0].postalCode,items:s}),l=c.items.reduce((u,h)=>{const f=h.requestIndex;return typeof f=="number"&&f<u.length&&(u[f]=h),u},Array(s.length).fill(null)),g=a.reduce((u,h)=>[...u,h.length+u[u.length-1]],[0]);return a.map((u,h)=>({...c,items:l.slice(g[h],g[h+1]).filter(f=>!!f)}))},i=async o=>t(r,o);return new ue(i,{maxBatchSize:50})},Xt=(e,n)=>Vn(e,n);function Yt(e){return{...e,description:e.description?Xt(e.description):e.description}}const N=(e,n)=>({...e,isVariantOf:Yt(n)}),Jt=({flags:e},n)=>{const t=async r=>{const i=r.map(g=>g.split("-")[0]),o=r.some(g=>g.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:o,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((g,u)=>{for(const h of u.items)g[h.itemId]=N(h,u);return g},{}),c=i.map(g=>s[g]),l=i.filter(g=>!s[g]);if(l.length>0)throw new L(`Search API did not found the following skus: ${l.join(",")}`);return c};return new ue(t,{maxBatchSize:99})},Kt=(e,n)=>{const{clients:t}=n,r=Jt(e,t),i=Ht(e,t),o=jt(e,t),a=Wt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:o,salesChannelLoader:a}},$=e=>e.AvailableQuantity>0,j=e=>e.spotPrice??0,Qt=e=>e.Price??0,Be=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",On=(e,n)=>$(e)&&!$(n)?-1:!$(e)&&$(n)?1:j(e)-j(n),Zt=e=>e==="available",M=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},er=(e,n={includeTaxes:!1})=>{const t=e.filter($),r=t[t.length-1],i=r?j(r):0;return n.includeTaxes?M(i,r?.Tax,r?.product?.unitMultiplier):i},$e=(e,n={includeTaxes:!1})=>{const[t]=e.filter($),r=t?j(t):0;return n.includeTaxes?M(r,t?.Tax,t?.product?.unitMultiplier):r},nr={highPrice:e=>er(e),lowPrice:e=>$e(e),lowPriceWithTaxes:e=>$e(e,{includeTaxes:!0}),offerCount:e=>e.length,priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:e=>e},tr={ratingValue:()=>5,reviewCount:()=>0},Me="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",rr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",ir=e=>{let n=e.slice(0);for(let t=0;t<Me.length;t++)n=n.replace(new RegExp(Me.charAt(t),"g"),rr.charAt(t));return n},or=e=>e.replace(/[·/_,:]/,"-");function se(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return or(ir(t)).toLowerCase()}const K=e=>xt(e)?e.slug:ye(e)?e.linkId:e.linkId??se(e.name),Cn={id:({id:e})=>e.toString(),slug:e=>K(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>ye(e)?"Brand":Le(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=K(e);if(ye(e))return{selectedFacets:[{key:"brand",value:r}]};if(Le(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=ee(t),o=r.split("/").filter(Boolean),a=o.map((l,g)=>o.slice(0,g+1).join("/")),{loaders:{collectionLoader:s}}=t;return{selectedFacets:(await Promise.all(a.map(l=>s.load({slug:l,locale:ie(t)})))).map((l,g)=>({key:`category-${g+1}`,value:i&&l.availableLinkIds?.[i]||l.linkId}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,o=K(e).split("/").filter(Boolean),a=o.map((c,l)=>o.slice(0,l+1).join("/")),s=await Promise.all(a.map(c=>r.load({slug:c,locale:ie(t)})));return{itemListElement:s.map((c,l)=>({item:`/${K(c)}`,name:c.name,position:l+1})),numberOfItems:s.length}},otherLocales:async(e,n,t)=>{const r=ee(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const o=t.storage.locale,a=K(e),s=a.split("/").filter(Boolean);if(s.length===0)return null;const{loaders:{collectionLoader:c}}=t,l=s.map((u,h)=>s.slice(0,h+1).join("/"));let g;try{g=await Promise.all(l.map(u=>c.load({slug:u,locale:ie(t)})))}catch(u){return console.warn("[otherLocales] failed to load collection entities:",u),null}return i.map(u=>{if(u===o)return{locale:u,slug:a};const h=[];for(const f of g){const v=f.availableLinkIds?.[u];if(!v)return null;h.push(v)}return h.length>0?{locale:u,slug:h.join("/")}:null}).filter(u=>u!==null)}},bn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},ze=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},qe=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},ar=e=>typeof bn[e]=="string",sr=e=>{const n=e?.filter(t=>ar(t.key));if(Array.isArray(n)&&n.length>1)throw new E(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},cr=e=>e?.find(n=>n.key==="slug")?.value??null,lr=e=>e?.find(n=>n.key==="id")?.value??null,Ve=e=>e?.find(n=>n.key==="locale")?.value??null,xe=e=>e?.find(n=>n.key==="channel")?.value??null,Ie=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},dr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},ur={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},pr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=qe(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Ie(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??a,absolute:a}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=qe(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Ie(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??a,absolute:a}}},gr={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},mr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new E("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function wn(e){if(!e||e.status!=="pending")return null;for(const n of e.dimensionStatus){if(n.status!=="pending")continue;const t=n.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:e.id,dimensionId:n.id}}return null}function hr(e){if(!e||e.status!=="pending")return!1;const n=e.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return n.length===0?!1:n.every(t=>!t.isUserNextAuthorizer)}const fr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=wn(r);return{isPendingForOtherAuthorizer:!i&&hr(r),ruleForAuthorization:i}},Sr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new E("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},yr=async(e,n,t)=>{if(!(await t.clients.commerce.recommendation.startRecommendationSession())?.recommendationsUserId)throw new Error("Failed to start recommendation session: no session data returned");return!0},Ir=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),vr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:o}=n;if(!r||!i||!o)throw new E("Missing required fields: fileContent, fileName, mimeType");const a=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(a.length*3/4)>s)throw new E("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a))throw new E("Invalid Base64 fileContent");const g=Buffer.from(a,"base64");return await t.orderEntry.uploadFile({fileBuffer:g,fileName:i,mimeType:o})};class ce{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}const ve=(e,n)=>{e.storage.channel=ce.parse(n)},Oe=(e,n)=>{e.storage.locale=n},Dn=e=>xn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function An(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function Or(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function Pn(e){return Dn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const Cr=e=>{const n=e.postalCode,t=e.geoCoordinates,r={addressType:e.addressType||null,postalCode:n||null,city:null,state:null,country:e.country||null,street:null,number:null,neighborhood:null,complement:null,reference:null,geoCoordinates:[]};if(t){const i=typeof t=="object"&&"latitude"in t?t.latitude:null,o=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&o!==null?[o,i]:[]}return[r]},br=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,o=e?.shippingData?.availableAddresses??[],a=e?.shippingData?.selectedAddresses??[];if(!t&&a.length>0)return[a[0]];if(t&&o.length>0)for(const s of o){if(r&&i&&(s.postalCode===r||s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude))return[s];if(r&&!i&&s.postalCode===r)return[s];if(i&&!r&&s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude)return[s]}return null},En=(e,n)=>{if(!wr(n))return{updateShipping:!1,addressChanged:!1};if(!Er(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(Dr(t,n.postalCode)||Ar(t,n.geoCoordinates)||Pr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Tr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},wr=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,Dr=(e,n)=>typeof n=="string"&&e?.postalCode!==n,Ar=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Pr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Er=e=>e.items.length!==0,Tr=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:o}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:a,selectedSla:s,slas:c})=>{const l=t&&a!==t,g=r&&s!==r;return c?.some(u=>l&&u.deliveryChannel===t||g&&u.id===r?!0:i&&o&&u.deliveryChannel===t&&u.id===r&&(!u?.deliveryWindow||u?.deliveryWindow?.startDateUtc!==i||u?.deliveryWindow?.endDateUtc!==o)&&u.availableDeliveryWindows?.some(h=>h?.startDateUtc===i&&h?.endDateUtc===o))})},Tn=e=>e.valueReference===re.attachment,Ce=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Tn).map(Pn).join("-")].filter(Boolean).join("::"),le=(e,n)=>({listPrice:e.listPrice/100,price:e.sellingPrice/100,quantity:e.quantity,seller:{identifier:e.seller},itemOffered:{sku:e.id,image:[],name:e.name,additionalProperty:e.attachments.map(An)},index:n}),kr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Tn)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),je=e=>e.reduce((n,t)=>{const r=Ce(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),Ur=(e,n)=>{const t=({priceToken:s,...c},l)=>({...c,itemOffered:{sku:c.itemOffered.sku},index:l}),r=n.items.map(le).map(t),i=e.acceptedOffer.map(t),o=e.orderNumber===n.orderFormId,a=Pe(r,i);return o&&a};function kn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Un(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const We=e=>{const n=e.items.reduce((t,r,i)=>{const o=Un(e.items,r.id)||kn(e.items,r.id)?`${Ce(le(r))}::${i}`:Ce(le(r));return t[o]||(t[o]=[]),t[o].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((a,s)=>a+s.quantity,0),o=t.reduce((a,s)=>a+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:o/i}})}},Ge=async(e,n,t)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async r=>({...r,product:await n.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:e.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),_n=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return Dn(JSON.stringify({sessionId:n?.id??"",items:t}))},He=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:_n(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const on=require("@graphql-tools/merge"),an=require("@graphql-tools/schema"),z=require("@graphql-tools/utils"),se=require("graphql"),B=require("@faststore/diagnostics"),Gn=require("isomorphic-unfetch"),ne=require("cookie"),Pe=require("p-limit"),pe=require("dataloader"),Hn=require("sanitize-html"),Ae=require("fast-deep-equal"),Xn=require("node:crypto");var sn=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(sn||{}),cn=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(cn||{}),ln=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(ln||{}),dn=(e=>(e.DiscountDesc="discount_desc",e.NameAsc="name_asc",e.NameDesc="name_desc",e.OrdersDesc="orders_desc",e.PriceAsc="price_asc",e.PriceDesc="price_desc",e.ReleaseDesc="release_desc",e.ScoreDesc="score_desc",e))(dn||{}),un=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(un||{}),pn=(e=>(e.Input="Input",e.Output="Output",e))(pn||{});const Yn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new x("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Jn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new K("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new K("Authentication required"):r===403?new x("You are not allowed to access this resource"):new K("Authentication required")}},Kn="auth",gn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{if(z.getDirective(e,n,Kn)?.[0]){const r=n.resolve;n.resolve=async(i,o,a,s)=>(await Jn(a),r?.(i,o,a,s))}return n}})},Qn="cacheControl",Zn=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},Ue=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,et=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,mn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{const t=z.getDirective(e,n,Qn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:o}=t,a=n.resolve;n.resolve=(s,c,d,u)=>(d.cacheControl={sMaxAge:Ue(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:Ue(d.cacheControl?.staleWhileRevalidate,i),scope:et(d.cacheControl?.scope,o)},a?.(s,c,d,u))}return n}})},hn=e=>(n,t)=>{const r=on.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:o})=>o?.(i)??i,an.makeExecutableSchema({typeDefs:r,resolvers:n}))},fn="@faststore/api",Sn="4.6.0-dev.1",ke={name:fn,version:Sn},nt=B.logger("@faststore/api"),tt=(e,n="Unknown Graphql Resolver")=>(t,r,i,o)=>{if(!i?.OTEL_ENABLED)return e(t,r,i,o);const a=B.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:B.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":Sn,"@faststore_package_name":fn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV,"@faststore_resolver_parent_type":o?.parentType?.name,"@faststore_resolver_field_name":o?.fieldName}}),s=B.OTELAPI.trace.setSpan(B.OTELAPI.context.active(),a);try{const c=B.OTELAPI.context.with(s,()=>e(t,r,i,o));return c instanceof Promise?c.then(d=>(a.end(),d),d=>_e(d,a,n)):(a.end(),c)}catch(c){return _e(c,a,n)}};function _e(e,n,t){throw n.setStatus({code:B.OTELAPI.SpanStatusCode.ERROR}),n.recordException(e),n.end(),console.error(`Error at resolver: ${t}:
|
|
2
|
+
%o`,e),nt("error",`Error at resolver: %s
|
|
3
|
+
%o`,t,e),e}class W extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class T extends W{constructor(n){super({status:400,type:"BadRequestError"},n)}}class K extends W{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class x extends W{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class N extends W{constructor(n){super({status:404,type:"NotFoundError"},n)}}const rt=e=>e?.name==="FastStoreError",it=e=>e?.extensions?.type==="BadRequestError",ot=e=>e?.extensions?.type==="UnauthorizedError",yn=e=>e?.extensions?.type==="ForbiddenError",q=e=>e?.extensions?.type==="NotFoundError",at=`${ke.name}@${ke.version}`,y=async(e,n,t)=>{const r=await Gn(e,{...n,headers:{...n?.headers??{},"User-Agent":at}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new T(i);case 401:throw new K(i);case 403:throw new x(i);case 404:throw new N(i);default:throw new W({status:r.status,type:"UnknownError"},i)}throw new Error(i)},st=({account:e,environment:n})=>{const t=`https://${e}.${n}.com.br`;return{getLocalizedProduct:(r,i)=>y(`${t}/api/catalog-dataplane/product/${r}`,{method:"GET",headers:{"Accept-Language":i,"Content-Type":"application/json"}})}},In=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const o=i.trim();if(o){const a=o.indexOf("=");if(a>0){const s=o.substring(0,a),c=o.substring(a+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},ct=/^([^=]+)=([^;]*)/,lt=(e,n)=>{const t=n.match(ct);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},dt=(e,n)=>{n.getSetCookie().forEach(t=>lt(e,t))},ut=e=>n=>dt(e,n),me=e=>{if(!e.headers?.cookie)return null;const n=In(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:o}])=>pt(r,i,o),n)},vn=e=>function(t){const r=me(e);return r?{...t,cookie:r}:t},V=(e,n)=>{const t=In(e);return ne.parse(t)[`VtexIdclientAutCookie_${n}`]||""},pt=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function Q(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const gt="storefront/faststore.recommendation-shelf@v4",H={method:"POST",headers:{"content-type":"application/json"}},mt=e=>e.split("/").map(encodeURIComponent).join("/"),ge=e=>e?{headers:{"Accept-Language":e}}:void 0,ht=/^\d{4}-\d{2}-\d{2}$/,ft=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function St({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a}){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`listUserQuotes: invalid page "${e}" — must be a positive integer`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`listUserQuotes: invalid perPage "${n}" — must be a positive integer`);for(const[s,c]of[["createdAtFrom",r],["createdAtTo",i],["expiresAtFrom",o],["expiresAtTo",a]])if(c&&!ht.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!ft.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function yt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(d=>c.append("status",d)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),o&&c.append("expiresAtFrom",o),a&&c.append("expiresAtTo",a),s?.trim()&&c.append("label",s.trim()),c}const It=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const o=`https://${e}.${n}.com.br`,a=ut(i),s=vn(i),c=Yn(),d=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",u=r&&r.map(l=>l+".").find(l=>d.includes(l))||"",p=d.replace(u,""),f=`${o}/api/recommend-bff/v2`,h=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${gt}`}),v=(l={})=>{const g=V(me(i)??"",e);return s({...l,"X-FORWARDED-HOST":p,...g?{[`VtexIdclientAutCookie_${e}`]:g}:{}})};return{catalog:{salesChannel:l=>y(`${o}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:a}),brand:{list:()=>y(`${o}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:a})},category:{tree:(l=3)=>y(`${o}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:a})},portal:{pagetype:l=>y(`${o}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:a})},byLinkId:{category:async(l,g)=>{try{return await y(`${o}/api/catalog_system/pub/category/by-linkid/${mt(l)}`,ge(g))}catch(m){if(q(m))return null;throw m}},brand:async(l,g)=>{try{return await y(`${o}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(l)}`,ge(g))}catch(m){if(q(m))return null;throw m}},collection:async(l,g)=>{try{return await y(`${o}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(l)}`,ge(g))}catch(m){if(q(m))return null;throw m}}},products:{crossselling:({type:l,productId:g,groupByProduct:m=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return y(`${o}/api/catalog_system/pub/products/crossselling/${l}/${g}?${S}`,void 0,{storeCookies:a})}}},checkout:{simulation:(l,{salesChannel:g}=i.storage.channel)=>{const m=new URLSearchParams({sc:g}),S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...H,headers:S,body:JSON.stringify(l)},{storeCookies:a})},shippingData:({id:l,index:g,deliveryMode:m,selectedAddresses:S},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,b={logisticsInfo:Array.from({length:g},(I,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},U=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...H,headers:U,body:JSON.stringify(b)},{storeCookies:a})},marketingData:({id:l,marketingData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:a})},clientPreferencesData:({id:l,clientPreferencesData:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(g),method:"POST"},{storeCookies:a})},orderForm:({id:l,refreshOutdatedData:g=!0,channel:m=i.storage.channel,preserveSalesChannel:S=!1})=>{const{salesChannel:O}=m,w=s({"content-type":"application/json","X-FORWARDED-HOST":p}),b=new URLSearchParams;(!S||!l)&&b.set("sc",O),l&&b.set("refreshOutdatedData",g.toString());const U=l?`/${l}`:"",I=`${o}/api/checkout/pub/orderForm${U}?${b}`;return y(I,{...H,headers:w,...l?{}:{body:"{}"}},{storeCookies:a})},clearOrderFormMessages:({id:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/messages/clear`,{...H,headers:g,body:"{}"})},updateOrderFormItems:({id:l,orderItems:g,allowOutdatedData:m="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:S}),b=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/items?${w}`,{headers:b,body:JSON.stringify({orderItems:g,noSplitItem:!O}),method:"PATCH"},{storeCookies:a})},setCustomData:({id:l,appId:g,key:m,value:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}/customData/${g}/${m}`,{headers:O,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:g,country:m,salesChannel:S})=>{const O=new URLSearchParams({country:m,sc:S??""});l?O.append("postalCode",l):O.append("geoCoordinates",`${g?.longitude};${g?.latitude}`);const w=`${o}/api/checkout/pub/regions/?${O.toString()}`,b=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(w,{headers:b},{storeCookies:a})},address:async({postalCode:l,country:g})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/postal-code/${g}/${l}`,{headers:m},{storeCookies:a})},cancelOrder:({orderId:l,customerEmail:g,reason:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:g,reason:m})},{})},pickupPoints:({geoCoordinates:l})=>{if(!l)throw new Error("Missing required parameter for listing pickup points.");const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:g,body:JSON.stringify({coordinate:l})},{storeCookies:a})}},session:l=>{const g=new URLSearchParams(l);g.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,shopper.availableContracts,shopper.activeContractId,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol,authentication.customerId,authentication.storeUserId,authentication.storeUserEmail,authentication.unitId,authentication.unitName,checkout.regionId,public.postalCode");const m=s({"content-type":"application/json"}),S=ne.parse(i?.headers?.cookie??"")?.vtex_session;return y(`${o}/api/sessions?${g.toString()}`,{method:S?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:a})},subscribeToNewsletter:l=>y(`${o}/api/dataentities/NL/documents/`,{...H,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:a}),profile:{addresses:async l=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:g},{storeCookies:a})}},oms:{userOrder:({orderId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/oms/user/orders/${l}`,{method:"GET",headers:g},{storeCookies:a})},listUserOrders:({page:l,status:g,dateInitial:m,dateFinal:S,text:O,clientEmail:w,perPage:b,pendingMyApproval:U})=>{const I=new URLSearchParams;if(m){const P=new Date(m).setHours(0,0,0,0);m=new Date(P).toISOString()}if(S){const P=new Date(S).setHours(23,59,59,999);S=new Date(P).toISOString()}O&&I.append("text",O),g&&g.length>0&&I.append("status",g.filter(Boolean).join(",")),m&&S?I.append("creation_date",`creationDate:[${m} TO ${S}]`):m?I.append("creation_date",`creationDate:[${m} TO *]`):S&&I.append("creation_date",`creationDate:[* TO ${S}]`),w&&I.append("clientEmail",w),l&&I.append("page",l.toString()),b&&I.append("per_page",b.toString()),U&&I.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/oms/user/orders?${I.toString()}`,{method:"GET",headers:D},{storeCookies:a})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/${e}/commercial-authorizations/order/${l}`,{method:"GET",headers:g},{storeCookies:a})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:g,ruleId:m,approved:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":p}),U={params:{ruleId:m,dimensionId:g,score:S?100:0}};return y(`${o}/${e}/commercial-authorizations/${l}/callback`,{method:"POST",headers:O,body:JSON.stringify(U)},{storeCookies:a})}},units:{getUnitByUserId:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/units/v1/${l}/unit`,{method:"GET",headers:g},{})},getOrgUnitById:({orgUnitId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/units/v1/${l}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/units/v1/${l}/scopes`,{method:"GET",headers:g},{})}},licenseManager:{getUserById:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/license-manager/users/${l}`,{method:"GET",headers:g},{})},getUserByEmail:({email:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:g},{})},getUserRoles:({userId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:g},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new T("Missing contractId to fetch CL fields.");const g=v({Accept:"application/json","content-type":"application/json"});return y(`${o}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:g},{})},getShopperById:({userId:l})=>{if(!l)throw new T("Missing userId to fetch shopper name.");const g=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":p}),m=l.replace(/-/g,"");return y(`${o}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},quotes:{listUserQuotes:l=>{St(l);const g=yt(l),m=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/quoting/quotes?${g.toString()}`,{method:"GET",headers:m},{storeCookies:a})}},vtexid:{validate:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p}),g=V(me(i)??"",e);return y(`${o}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:g}),method:"POST"},{storeCookies:a})}},orderEntry:{uploadFile:({fileBuffer:l,fileName:g,mimeType:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),O=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
|
|
4
|
+
`,U=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",I=g.replaceAll(/[\r\n"]/g,"_"),D=[`--${O}`,`Content-Disposition: form-data; name="file"; filename="${I}"`,`Content-Type: ${U}`,"",""].join(w),P=`${w}--${O}--${w}`,E=Buffer.from(D),A=Buffer.from(P),R=new Uint8Array(E.byteLength+l.byteLength+A.byteLength);let C=0;return R.set(E,C),C+=E.byteLength,R.set(l,C),C+=l.byteLength,R.set(A,C),y(`${o}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...S,"content-type":`multipart/form-data; boundary=${O}`},body:R.buffer},{})},startOperation:({objectKey:l,orderFormId:g,sessionToken:m})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":p}),O=JSON.stringify({objectKey:l,orderFormId:g,operation:"CreateCart",...m?{sessionToken:m}:{}});return y(`${o}/api/order-entry/operation?an=${e}`,{method:"POST",headers:S,body:O},{})},getOperation:({operationId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/order-entry/operation/${l}?an=${e}`,{method:"GET",headers:g},{})},createOrderForm:()=>{const l=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:l,body:"{}"},{})},getOrderFormItems:({orderFormId:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":p});return y(`${o}/api/checkout/pub/orderForm/${l}`,{method:"GET",headers:g},{})}},recommendation:{recommendations:({campaignVrn:l,userId:g,products:m=[],salesChannel:S,locale:O})=>{const w=new URLSearchParams({an:e,campaignVrn:l});return g&&w.append("userId",g),m.length>0&&w.append("products",m.join(",")),S&&w.append("salesChannel",S),O&&w.append("locale",O),y(`${f}/recommendations?${w.toString()}`,{headers:h},{storeCookies:a})},startRecommendationSession:()=>{const l=new URLSearchParams({an:e});return y(`${f}/users/start-session?${l.toString()}`,{method:"POST",headers:h},{storeCookies:a})}}}},Z=e=>e.discoveryConfig?.localization??{},ee=e=>Z(e).enabled===!0,vt=e=>Object.keys(Z(e).locales??{}),Ot=e=>Z(e).defaultLocale,oe=e=>ee(e)&&e.storage.locale||void 0,he="fuzzy",fe="operator",Se="pickupPoint",Re="shipping",Fe="delivery-options",Ct="in-stock",bt="trade-policy",wt="region-id",Dt=new Set([bt,wt,he,fe,Se]),Pt=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),Ne=e=>encodeURI(decodeURI(e)),At=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),Et=/^pickup-in-point-(.+)$/;function On(e){if(!e)return{};try{const t=ne.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function Tt(e){const n={},t=[];for(const r of e.split(";")){const i=r.indexOf("=");if(i<0)continue;const o=r.slice(0,i),a=r.slice(i+1);!o||!a||(Pt.has(o)?n[o]=a:t.push({key:o,value:a}))}return{shipping:n,extraFacets:t}}function Ut(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=Tt(n);return{segmentParams:{sc:e.channel,regionId:e.regionId,country:e.countryCode??t.country,locale:e.cultureInfo,"zip-code":t["zip-code"],coordinates:t.coordinates,pickupPoint:t.pickupPoint,deliveryZonesHash:t.deliveryZonesHash,pickupPointHash:t.pickupPointsHash,utmSource:e.utm_source??void 0,utmCampaign:e.utm_campaign??void 0,utmiCampaign:e.utmi_campaign??void 0,campaigns:typeof e.campaigns=="string"?e.campaigns:void 0,priceTables:e.priceTables??void 0},extraFacets:r}}function Cn(e,n){const t=[["sc",n.sc],["regionId",n.regionId],["country",n.country],["locale",n.locale],["zip-code",n["zip-code"]],["coordinates",n.coordinates],["pickupPoint",n.pickupPoint],["deliveryZonesHash",n.deliveryZonesHash],["pickupPointHash",n.pickupPointHash],["utmSource",n.utmSource],["utmCampaign",n.utmCampaign],["utmiCampaign",n.utmiCampaign],["campaigns",n.campaigns],["priceTables",n.priceTables]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function bn(e){return Et.exec(e)?.[1]}function kt(e){const n=e.find(r=>r.key==="shipping"),t=n?bn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function _t(e,n){const t=kt(n);return t===void 0?e:{...e,pickupPoint:t}}function Rt(e){return e.map(n=>n.key!=="shipping"||bn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function Ft(e,n){let t=[...e];const r=t.some(i=>i.key==="shipping");for(const i of n)(!r||i.key!=="shipping")&&t.push(i);return t.some(i=>i.key==="shipping"&&i.value==="ignore")&&(t=t.filter(i=>i.key!=="shipping")),Rt(t)}function Nt(e){return e.reduce((n,t)=>{let{key:r,value:i}=t;return r==="priceRange"&&(r="price",i=i.replace(" TO ",":")),r==="ft"?n:`${n}${Ne(r)}/${At(Ne(i)).replaceAll(/ |%20/g,"-")}/`},"")}const Lt=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),Bt=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function $t(e,n){const{segmentParams:t,extraFacets:r}=Ut(e??{}),i=n?.salesChannel??t.sc,o=n?.regionId??t.regionId,a=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...o?{regionId:o}:{},locale:a},extraFacets:r}}function Mt(e,n){const t=e.filter(({key:c})=>!Dt.has(c)),r=e.find(({key:c,value:d})=>c===Re&&d!=="all-delivery-methods")??null,i=e.find(({key:c,value:d})=>c===Fe&&d!=="all-delivery-options")??null,o=[...t],a=o.some(({key:c})=>c===Re),s=o.some(({key:c})=>c===Fe);return r!==null&&!a&&o.push(r),i!==null&&!s&&o.push(i),Ft(o,n)}function zt(e,n){const t=e.find(({key:o})=>o===he)??null,r=e.find(({key:o})=>o===fe)??null,i=e.find(({key:o})=>o===Se)??null;t&&Lt(t)&&n.append(he,t.value),r&&Bt(r)&&n.append(fe,r.value),i&&n.append(Se,i.value)}function Le(e,n,t,r){const{query:i="",page:o,count:a,sort:s,selectedFacets:c=[],showInvisibleItems:d,sponsoredCount:u,hideUnavailableItems:p,allowRedirect:f=!1}=e,h=new URLSearchParams;if(r.includePagination&&o!==void 0&&a!==void 0){const g=o*a,m=a===0?g:g+a-1;h.append("from",g.toString()),h.append("to",m.toString())}i&&h.append("query",i),r.includeSort&&s&&h.append("sort",s);const v=_t(t.segmentParams,c);if(Cn(h,v??t.segmentParams),zt(c,h),d&&h.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const g=c.find(({key:S})=>S===Ct),m=g?g.value:p?.toString()??n.hideUnavailableItems.toString();h.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&h.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&h.append("showSponsored",n.showSponsored.toString()),u!==void 0&&h.append("sponsoredCount",u.toString()),f!==void 0&&h.append("allowRedirect",f.toString());const l=Nt(Mt(c,t.extraFacets));return{params:h,path:l}}function qt(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:o}=e,a=new URLSearchParams({field:t??"",value:r??""});return Cn(a,n),i&&a.append("hideUnavailableItems","true"),o&&a.append("show-invisible-items","true"),a}function X(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function Y(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,o=$t(t,r);switch(n){case"product-search":case"facets":{const{params:a,path:s}=Le(i,r,o,{includePagination:!0,includeSort:!0});return X(s,a)}case"catalog-count":{const{params:a,path:s}=Le(i,r,o,{includePagination:!1,includeSort:!1});return X(s,a)}case"products":{const a=qt(i,o.segmentParams);return X("",a)}case"search-suggestions":{const a=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??o.segmentParams.locale??""});return X("",a)}case"top-searches":{const a=new URLSearchParams({locale:r?.locale??o.segmentParams.locale??""});return X("",a)}default:{const a=n;throw new Error(`Unknown intelligent-search endpoint: ${a}`)}}}const Vt=10;function xt(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function jt(e){const t=On(e.headers?.cookie).cultureInfo||"";return ee(e)?e.storage.locale||t:t||e.storage.locale||""}const Wt=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:o},a)=>{const s=`https://${e}.${n}.com.br`,c=vn(a),d=On(a.headers?.cookie),u=()=>({salesChannel:a.storage.channel.salesChannel,regionId:xt(a),locale:jt(a),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),p=new Headers(a.headers).get("x-forwarded-host")??a.headers?.host??"",f=o&&o.map(I=>I+".").find(I=>p.includes(I))||"",h=p.replace(f,""),v=c({"content-type":"application/json","X-FORWARDED-HOST":h}),l=({type:I,...D})=>{const P=I==="facets"?"facets":"product-search",E=Y({endpoint:P,segment:d,defaults:u(),args:D});return y(`${s}/api/intelligent-search/v1/${P}/${E.path}?${E.params.toString()}`,{headers:v})},g=I=>l({...I,type:"product_search"}),m=({field:I,value:D,hideUnavailableItems:P,showInvisibleItems:E})=>{const A=Y({endpoint:"products",segment:d,defaults:u(),args:{field:I,value:D,hideUnavailableItems:P,showInvisibleItems:E}});return y(`${s}/api/intelligent-search/v1/products?${A.params.toString()}`,{headers:v})};return{facets:I=>l({...I,type:"facets"}),products:g,fetchProduct:m,productsByIdentifier:async({field:I,values:D,showInvisibleItems:P,hideUnavailableItems:E})=>{const A=Pe(Vt);return(await Promise.all(D.map(C=>A(async()=>{try{return await m({field:I,value:C,hideUnavailableItems:E,showInvisibleItems:P})}catch{return null}})))).filter(C=>C!==null)},suggestedTerms:I=>{const D=Y({endpoint:"search-suggestions",segment:d,defaults:u(),args:{query:I.query}});return y(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:v})},topSearches:()=>{const I=Y({endpoint:"top-searches",segment:d,defaults:u()});return y(`${s}/api/intelligent-search/v1/top-searches?${I.params.toString()}`,{headers:v})},productCount:I=>{const D=Y({endpoint:"catalog-count",segment:d,defaults:u(),args:I});return y(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:v})}}},Gt=(e,n)=>{const t=Wt(e,n),r=It(e,n),i=st(e);return{search:t,commerce:r,catalog:i}},Ht=20,Xt=e=>e.entityType==="category",ye=e=>e.entityType==="brand",Be=e=>e.entityType==="collection",Yt=(e,n)=>{const t=Pe(Ht),r=async i=>Promise.all(i.map(o=>t(async()=>{const a=o.slug.toLowerCase(),s=o.locale,c=await n.commerce.catalog.byLinkId.category(a,s);if(c)return{...c,entityType:"category",slug:a};const d=await n.commerce.catalog.byLinkId.brand(a,s);if(d)return{...d,entityType:"brand"};const u=await n.commerce.catalog.byLinkId.collection(a,s);if(u)return{...u,entityType:"collection"};throw new N(`No catalog entity found for slug: ${o.slug}. Cascade exhausted (category → brand → collection).`)})));return new pe(r,{batch:!1,cacheKeyFn:({slug:i,locale:o})=>`${i.toLowerCase()}::${o??""}`})},Jt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new pe(t)},Kt=1,Qt=(e,n)=>{const t=Pe(Kt),r=async o=>{const a=o.reduce((p,{items:f})=>[...p,f],[]),s=[...a.flat()],c=await n.commerce.checkout.simulation({country:o[0].country,postalCode:o[0].postalCode,items:s}),d=c.items.reduce((p,f)=>{const h=f.requestIndex;return typeof h=="number"&&h<p.length&&(p[h]=f),p},Array(s.length).fill(null)),u=a.reduce((p,f)=>[...p,f.length+p[p.length-1]],[0]);return a.map((p,f)=>({...c,items:d.slice(u[f],u[f+1]).filter(h=>!!h)}))},i=async o=>t(r,o);return new pe(i,{maxBatchSize:50})},Zt=(e,n)=>Hn(e,n);function er(e){return{...e,description:e.description?Zt(e.description):e.description}}const F=(e,n)=>({...e,isVariantOf:er(n)}),nr=({flags:e},n)=>{const t=async r=>{const i=r.map(u=>u.split("-")[0]),o=r.some(u=>u.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:o,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((u,p)=>{for(const f of p.items)u[f.itemId]=F(f,p);return u},{}),c=i.map(u=>s[u]),d=i.filter(u=>!s[u]);if(d.length>0)throw new N(`Search API did not found the following skus: ${d.join(",")}`);return c};return new pe(t,{maxBatchSize:99})},tr=(e,n)=>{const{clients:t}=n,r=nr(e,t),i=Qt(e,t),o=Yt(e,t),a=Jt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:o,salesChannelLoader:a}},$=e=>e.AvailableQuantity>0,j=e=>e.spotPrice??0,rr=e=>e.Price??0,$e=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",wn=(e,n)=>$(e)&&!$(n)?-1:!$(e)&&$(n)?1:j(e)-j(n),ir=e=>e==="available",M=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},or=(e,n={includeTaxes:!1})=>{const t=e.filter($),r=t[t.length-1],i=r?j(r):0;return n.includeTaxes?M(i,r?.Tax,r?.product?.unitMultiplier):i},Me=(e,n={includeTaxes:!1})=>{const[t]=e.filter($),r=t?j(t):0;return n.includeTaxes?M(r,t?.Tax,t?.product?.unitMultiplier):r},ar={highPrice:e=>or(e),lowPrice:e=>Me(e),lowPriceWithTaxes:e=>Me(e,{includeTaxes:!0}),offerCount:e=>e.length,priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:e=>e},sr={ratingValue:()=>5,reviewCount:()=>0},ze="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",cr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",lr=e=>{let n=e.slice(0);for(let t=0;t<ze.length;t++)n=n.replace(new RegExp(ze.charAt(t),"g"),cr.charAt(t));return n},dr=e=>e.replace(/[·/_,:]/,"-");function ce(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return dr(lr(t)).toLowerCase()}const J=e=>Xt(e)?e.slug:ye(e)?e.linkId:e.linkId??ce(e.name),Dn={id:({id:e})=>e.toString(),slug:e=>J(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>ye(e)?"Brand":Be(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=J(e);if(ye(e))return{selectedFacets:[{key:"brand",value:r}]};if(Be(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=Z(t),o=r.split("/").filter(Boolean),a=o.map((d,u)=>o.slice(0,u+1).join("/")),{loaders:{collectionLoader:s}}=t;return{selectedFacets:(await Promise.all(a.map(d=>s.load({slug:d,locale:oe(t)})))).map((d,u)=>({key:`category-${u+1}`,value:i&&d.availableLinkIds?.[i]||d.linkId}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,o=J(e).split("/").filter(Boolean),a=o.map((c,d)=>o.slice(0,d+1).join("/")),s=await Promise.all(a.map(c=>r.load({slug:c,locale:oe(t)})));return{itemListElement:s.map((c,d)=>({item:`/${J(c)}`,name:c.name,position:d+1})),numberOfItems:s.length}},otherLocales:async(e,n,t)=>{const r=Z(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const o=t.storage.locale,a=J(e),s=a.split("/").filter(Boolean);if(s.length===0)return null;const{loaders:{collectionLoader:c}}=t,d=s.map((p,f)=>s.slice(0,f+1).join("/"));let u;try{u=await Promise.all(d.map(p=>c.load({slug:p,locale:oe(t)})))}catch(p){return console.warn("[otherLocales] failed to load collection entities:",p),null}return i.map(p=>{if(p===o)return{locale:p,slug:a};const f=[];for(const h of u){const v=h.availableLinkIds?.[p];if(!v)return null;f.push(v)}return f.length>0?{locale:p,slug:f.join("/")}:null}).filter(p=>p!==null)}},Pn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},qe=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},Ve=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},ur=e=>typeof Pn[e]=="string",pr=e=>{const n=e?.filter(t=>ur(t.key));if(Array.isArray(n)&&n.length>1)throw new T(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},gr=e=>e?.find(n=>n.key==="slug")?.value??null,mr=e=>e?.find(n=>n.key==="id")?.value??null,xe=e=>e?.find(n=>n.key==="locale")?.value??null,je=e=>e?.find(n=>n.key==="channel")?.value??null,Ie=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},hr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},fr={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},Sr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Ie(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??a,absolute:a}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Ie(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??a,absolute:a}}},yr={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},Ir=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new T("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function An(e){if(!e||e.status!=="pending")return null;for(const n of e.dimensionStatus){if(n.status!=="pending")continue;const t=n.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:e.id,dimensionId:n.id}}return null}function vr(e){if(!e||e.status!=="pending")return!1;const n=e.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return n.length===0?!1:n.every(t=>!t.isUserNextAuthorizer)}const Or=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=An(r);return{isPendingForOtherAuthorizer:!i&&vr(r),ruleForAuthorization:i}},Cr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new T("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},br=async(e,n,t)=>{if(!(await t.clients.commerce.recommendation.startRecommendationSession())?.recommendationsUserId)throw new Error("Failed to start recommendation session: no session data returned");return!0},wr=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),Dr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:o}=n;if(!r||!i||!o)throw new T("Missing required fields: fileContent, fileName, mimeType");const a=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(a.length*3/4)>s)throw new T("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a))throw new T("Invalid Base64 fileContent");const u=Buffer.from(a,"base64");return await t.orderEntry.uploadFile({fileBuffer:u,fileName:i,mimeType:o})};class te{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}function Pr(e,n){return n==null||n===""||String(n)===String(e.salesChannel??"")?null:te.stringify({...e,salesChannel:String(n),hasOnlyDefaultSalesChannel:!1})}const le=(e,n)=>{e.storage.channel=te.parse(n)},ve=(e,n)=>{e.storage.locale=n},En=e=>Xn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function Tn(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function Ar(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function Un(e){return En(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const Er=e=>{const n=e.postalCode,t=e.geoCoordinates,r={addressType:e.addressType||null,postalCode:n||null,city:null,state:null,country:e.country||null,street:null,number:null,neighborhood:null,complement:null,reference:null,geoCoordinates:[]};if(t){const i=typeof t=="object"&&"latitude"in t?t.latitude:null,o=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&o!==null?[o,i]:[]}return[r]},Tr=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,o=e?.shippingData?.availableAddresses??[],a=e?.shippingData?.selectedAddresses??[];if(!t&&a.length>0)return[a[0]];if(t&&o.length>0)for(const s of o){if(r&&i&&(s.postalCode===r||s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude))return[s];if(r&&!i&&s.postalCode===r)return[s];if(i&&!r&&s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude)return[s]}return null},kn=(e,n)=>{if(!Ur(n))return{updateShipping:!1,addressChanged:!1};if(!Fr(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(kr(t,n.postalCode)||_r(t,n.geoCoordinates)||Rr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Nr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},Ur=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,kr=(e,n)=>typeof n=="string"&&e?.postalCode!==n,_r=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Rr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Fr=e=>e.items.length!==0,Nr=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:o}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:a,selectedSla:s,slas:c})=>{const d=t&&a!==t,u=r&&s!==r;return c?.some(p=>d&&p.deliveryChannel===t||u&&p.id===r?!0:i&&o&&p.deliveryChannel===t&&p.id===r&&(!p?.deliveryWindow||p?.deliveryWindow?.startDateUtc!==i||p?.deliveryWindow?.endDateUtc!==o)&&p.availableDeliveryWindows?.some(f=>f?.startDateUtc===i&&f?.endDateUtc===o))})},_n=e=>e.valueReference===re.attachment,Oe=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(_n).map(Un).join("-")].filter(Boolean).join("::"),de=(e,n)=>({listPrice:e.listPrice/100,price:e.sellingPrice/100,quantity:e.quantity,seller:{identifier:e.seller},itemOffered:{sku:e.id,image:[],name:e.name,additionalProperty:e.attachments.map(Tn)},index:n}),Lr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(_n)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),We=e=>e.reduce((n,t)=>{const r=Oe(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),Br=(e,n)=>{const t=({priceToken:s,...c},d)=>({...c,itemOffered:{sku:c.itemOffered.sku},index:d}),r=n.items.map(de).map(t),i=e.acceptedOffer.map(t),o=e.orderNumber===n.orderFormId,a=Ae(r,i);return o&&a};function Rn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Fn(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const Ge=e=>{const n=e.items.reduce((t,r,i)=>{const o=Fn(e.items,r.id)||Rn(e.items,r.id)?`${Oe(de(r))}::${i}`:Oe(de(r));return t[o]||(t[o]=[]),t[o].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((a,s)=>a+s.quantity,0),o=t.reduce((a,s)=>a+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:o/i}})}},Ce=async(e,n,t,r)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async i=>({...i,product:await n.load(`${i.id}-invisibleItems`)})),shouldSplitItem:t,...r?{salesChannel:r}:{}},messages:e.messages.map(({text:i,status:o})=>({text:i,status:o.toUpperCase()}))}),Nn=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return En(JSON.stringify({sessionId:n?.id??"",items:t}))},He=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:Nn(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
|
|
5
5
|
Make sure to add the following custom app to the orderForm:
|
|
6
6
|
{"fields":["cartEtag"],"id":"faststore","major":1}.
|
|
7
|
-
More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}}
|
|
8
|
-
`),r}}
|
|
9
|
-
`)}let U;a.seller&&(s||g)&&(U=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:g,country:c,salesChannel:f}))?.[0]?.sellers.find(pe=>a.seller===pe.id));const G={...n,currency:{code:D?.currencyCode?.value??n.currency.code,symbol:D?.currencySymbol?.value??n.currency.symbol},country:D?.countryCode?.value??c,channel:ce.stringify({salesChannel:D?.channel?.value??a.salesChannel,regionId:T?.regionId?.value??a.regionId,seller:U?.id,hasOnlyDefaultSalesChannel:!D?.channel?.value}),b2b:y?{isRepresentative:y??!1,customerId:A?.customerId?.value??O??"",unitName:A?.unitName?.value??"",unitId:A?.unitId?.value??w??"",firstName:typeof S?.firstName?.value=="string"?S.firstName.value:"",lastName:typeof S?.lastName?.value=="string"?S.lastName.value:"",userName:`${typeof S?.firstName?.value=="string"?S.firstName.value:""} ${typeof S?.lastName?.value=="string"?S.lastName.value:""}`.trim(),userEmail:A?.storeUserEmail.value??"",savedPostalCode:b?.postalCode?.value??"",contractName:Rn(k,P),organizationManager:S?.organizationManager?.value??!1}:null,marketingData:d,person:P?.id?{id:P.id?.value??"",email:P.email?.value??"",givenName:P.firstName?.value??"",familyName:P.lastName?.value??""}:null,geoCoordinates:g?.latitude&&g?.longitude&&g||null,city:l};return Pe(n,G)?null:G},xr={validateCart:Nr,validateSession:Vr,subscribeToNewsletter:Ir,cancelOrder:mr,processOrderAuthorization:fr,uploadFileToOrderEntry:vr,startOrderEntryOperation:Sr,startRecommendationSession:yr};var be;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(be||(be={}));const jr=e=>typeof e=="string"?Fn(e):null;function Fn(e){try{return JSON.parse(e)}catch{return e}}const Wr=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,Gr=new ae.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:jr,serialize:Wr,parseLiteral(e){return e.kind===be.STRING?Fn(e.value):null}}),R=e=>"Price"in e&&"seller"in e&&"product"in e,F=e=>"skuName"in e,Hr={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>R(e)?e.PriceValidUntil??"":F(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>R(e)?Be($(e)):F(e)?Be(Zt(e.availability)):null,seller:(e,n,t)=>R(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:F(e)?{identifier:e.seller}:null,price:e=>R(e)?j(e):F(e)?e.sellingPrice/100:null,priceWithTaxes:e=>R(e)?M(j(e),e?.Tax,e.product.unitMultiplier):F(e)?M(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>R(e)?Qt(e):F(e)?e.sellingPrice/100:null,listPrice:e=>R(e)?e.ListPrice??0:F(e)?e.listPrice/100:null,listPriceWithTaxes:e=>R(e)?M(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):F(e)?M(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>R(e)?e.product:F(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>R(e)?e.AvailableQuantity??0:F(e)?e.quantity:null,isGift:e=>F(e)?e.isGift??!1:null,priceToken:e=>R(e)?e.PriceToken??null:null},Xr=({linkText:e})=>`/${e}/p`,Yr=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),Jr={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},oe=(e,n)=>`${e}-${n}`,Je=(e,n)=>`/${oe(e,n)}/p`,Kr=e=>Array.isArray(e)&&e.length>0?e:null;function we(e){return e.replace(/^\/+|\/+$/g,"")}async function De(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,o=i.get(r);if(o)return o;const a=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch{return null}})();return i.set(r,a),a}const Qr=(e,n)=>{const t=e.findIndex(r=>we(r).split("/").at(-1)===n);return t<0?0:t},Zr={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>oe(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:Xr(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:o,categoryId:a,categoriesIds:s,productId:c},itemId:l}=e,g=Qr(s,a),u=r[g],h=we(u).split("/"),f=t.storage.locale;if(ne(t)&&f){const v=await De(t,c,f);if(v){const d=new Set(we(s[g]).split("/").filter(Boolean)),p=v.categories.filter(y=>d.has(y.id.toString())).sort((y,O)=>y.fullPath.split("/").length-O.fullPath.split("/").length);if(p.length===h.length)return{itemListElement:[...p.map((y,O)=>({name:y.name,item:`/${y.fullPathUriName}/`,position:O+1})),{name:i,item:Je(v.linkId,l),position:h.length+1}],numberOfItems:h.length}}}return{itemListElement:[...h.map((v,d)=>{const p=`/${h.slice(0,d+1).map(se).join("/")}/`;return{name:v,item:p,position:d+1}}),{name:i,item:Je(o,l),position:h.length+1}],numberOfItems:h.length}},image:({images:e},n)=>{const t=(Kr(e)??[Jr]).map(({imageUrl:s,imageText:c,imageLabel:l})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:l}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const o=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let a=o?t.filter(({keywords:s})=>s===r):t;return a=a.length===0?t:a,a.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>Yr({offer:n.commertialOffer,seller:n,product:e})).sort(On),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:a,values:s})=>s.map(c=>({name:a,value:c,valueReference:re.specification}))),i=n.map(An),o=t.map(Or);return[...r,...i,...o]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!ne(t))return null;const r=ht(t);if(r.length===0)return null;const i=e.isVariantOf.productId,o=e.itemId,a=t.storage.locale,s=ft(t),c=await De(t,i,a);if(!c?.availableLinkIds)return null;const{availableLinkIds:l}=c,{linkText:g}=e.isVariantOf;return r.map(u=>{if(u===s)return{locale:u,slug:oe(g,o)};const h=l[u];return h?{locale:u,slug:oe(h,o)}:null}).filter(u=>u!==null)}},ei=new Set(["allSpecifications"]),ni={hasVariant:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!ei.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},ti={propertyID:e=>e.propertyID||Pn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},de=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Ie(n,({offer:r},{offer:i})=>On(r,i));return t?t.sku:e[0]},Nn=e=>e!==""&&!Number.isNaN(Number(e)),ri=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,ii=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:o}}=i,{salesChannel:a}=i.storage.channel,s=n?.trim();if(!s||!ri.test(s))throw new E(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new E("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(f=>!f?.trim())))throw new E("Invalid products: must be an array of non-empty strings");const l=await o.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:a??void 0,locale:i.storage.locale}),{campaign:g,correlationId:u}=l;return{products:(l.products??[]).map(f=>{const v=de(f.items);return v?N(v,f):null}).filter(f=>!!f),correlationId:u,campaign:g}},Ke={price_desc:"price:desc",price_asc:"price:asc",orders_desc:"orders:desc",name_desc:"name:desc",name_asc:"name:asc",release_desc:"release:desc",discount_desc:"discount:desc",score_desc:""},oi=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new E("Missing operationId");return t.orderEntry.getOperation({operationId:n})},ai=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new E("Missing orderFormId");const{items:r}=await t.orderEntry.getOrderFormItems({orderFormId:n});return(r??[]).map(i=>({id:i.id,name:i.name,price:i.price,listPrice:i.listPrice,quantity:i.quantity,imageUrl:i.imageUrl??null,availability:i.availability,seller:i.seller,unitMultiplier:i.unitMultiplier??1}))};async function si(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await De(e,t,r))?.linkId===i}const Ln="Invalid SkuId",Bn="Slug was set but the fetched sku does not satisfy the slug condition.",ci=e=>q(e)||e instanceof Error&&(e.message===Ln||e.message.startsWith(Bn));async function li(e,n,t,r){const{linkText:i,productId:o}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||ne(e)&&r&&Nn(t.split("-").pop()??"")&&await si(e,t,o,r)))throw new Error(`${Bn} slug: ${t}, linkText: ${i}`)}async function di(e,n){if(n==null)throw new E("Missing slug or id");const{clients:{commerce:t,search:r}}=e,i=await t.catalog.portal.pagetype(`${n}/p`);if(i.pageType!=="Product"||!i.id)throw new L(`No product found for slug ${n}`);const o=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!o)throw new L(`No product found for id ${i.id}`);return N(de(o.items),o)}const ui={product:async(e,{locator:n},t)=>{const r=xe(n),i=Ve(n),o=lr(n),a=cr(n);r&&ve(t,r),i&&Oe(t,i);const{loaders:{skuLoader:s}}=t;try{const c=o??a?.split("-").pop()??"";if(!Nn(c))throw new Error(Ln);const l=await s.load(c);return await li(t,l,a,i),l}catch(c){if(!ci(c))throw c;return di(t,a)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:ie(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:o,sponsoredCount:a},s)=>{const c=xe(o),l=Ve(o),g=sr(o);c&&ve(s,c),l&&Oe(s,l);const u=t?Number(t):0,h={page:Math.ceil(u/n)||0,count:n,query:i??void 0,sort:Ke[r??"score_desc"]??Ke.score_desc,selectedFacets:o?.flatMap(ze)??[],sponsoredCount:a??void 0};if(g){const d=(await s.clients.commerce.catalog.products.crossselling({type:bn[g.key],productId:g.value})).map(m=>m.productId).slice(0,n),p=s.clients.search.productsByIdentifier({field:"id",values:d}).then(m=>({products:m,recordsFiltered:m.length,pagination:{count:m.length,current:{index:0,proxyURL:""},before:[],after:[],perPage:n,next:{index:0,proxyURL:""},previous:{index:0,proxyURL:""},first:{index:0,proxyURL:""},last:{index:0,proxyURL:""}},sampling:!1,options:{sorts:[],counts:[]},translated:!1,locale:"",query:"",operator:"and",fuzzy:"0",searchId:""}));return{searchArgs:h,productSearchPromise:p}}const f=s.clients.search.products(h);return{searchArgs:h,productSearchPromise:f}},allProducts:async(e,{first:n,after:t},r)=>{const{clients:{search:i}}=r,o=t?Number(t):0,a=await i.products({page:Math.ceil(o/n),count:n}),s=a.products.flatMap(c=>c.items.map(l=>N(l,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:a.pagination.after.length>0,hasPreviousPage:a.pagination.before.length>0,startCursor:"0",endCursor:a.recordsFiltered.toString(),totalCount:a.recordsFiltered},edges:s.map((c,l)=>({node:c,cursor:(o+l).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(o=>o.items.map(a=>N(a,o))).filter(o=>n.includes(o.itemId)&&o.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,o=t?Number(t):0,[a,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],l=(f,v)=>{c.push({id:f.id,name:f.name,fatherCategoryId:v,linkId:se(f.name),title:f.Title,description:null,metaTagDescription:f.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(f.url).pathname.slice(1).toLowerCase()});for(const d of f.children)l(d,f.id)};for(const f of s)l(f,null);const h=[...a.filter(f=>f.isActive).map(f=>({id:f.id,name:f.name,linkId:se(f.name),title:f.title,description:null,metaTagDescription:f.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(f=>!!Cn.slug(f,null,r,null));return{pageInfo:{hasNextPage:h.length-o>n,hasPreviousPage:o>0,startCursor:"0",endCursor:(Math.min(n,h.length-o)-1).toString(),totalCount:h.length},edges:h.slice(o,o+n).map((f,v)=>({node:f,cursor:(o+v).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:o},clients:{commerce:a}}=i,[s,c]=await Promise.all([o.load({country:n,items:t,postalCode:r}),a.checkout.address({postalCode:r,country:n})]);return{...s,address:c}},redirect:async(e,{term:n,selectedFacets:t},r)=>{if(!n&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:n??void 0,selectedFacets:t?.flatMap(ze)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},o)=>{const{clients:{commerce:a}}=o,c=(await a.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:l,sellers:g}=c;return{id:l,sellers:g}},profile:async(e,{id:n},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(n);function o(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:o(i)}},productCount:async(e,{term:n},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:n??void 0})},userOrder:async(e,{orderId:n},t)=>{try{if(!n)throw new E("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new L(`No order found for id ${n}`);let o=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});o=wn(c)}catch{}const s=(await r.masterData.getShopperById({userId:i.purchaseAgentData?.purchaseAgents?.[0]?.userId??""})??[])[0]??{};return{orderId:i.orderId,creationDate:i.creationDate,totals:i.totals,items:i.items,shippingData:i.shippingData,paymentData:i.paymentData,customData:i.customData,status:i.status,statusDescription:i.statusDescription,allowCancellation:i.allowCancellation,storePreferencesData:i.storePreferencesData,clientProfileData:i.clientProfileData,canProcessOrderAuthorization:(i.status==="waiting-for-confirmation"||i.status==="waiting-for-authorization")&&!!o,ruleForAuthorization:o,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let o={};try{const s=JSON.parse(i);o=s.error||s}catch{o={message:i}}const a=o?.message||i;throw q(r)?new L(`No order found for id ${n}. ${a}.`):hn(r)?new x(`You are forbidden to interact with order with id ${n}. ${a}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(o=>({orderId:o.orderId,creationDate:o.creationDate,clientName:o.clientName,items:o.items,totalValue:o.totalValue,status:o.status,statusDescription:o.statusDescription,ShippingEstimatedDate:o.ShippingEstimatedDate,customFields:o.customFields,currencyCode:o.currencyCode})),paging:i.paging}},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),o=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],a=new Map;return await Promise.all(o.map(async c=>{try{const[l]=await r.masterData.getShopperById({userId:c});if(l){const g=[l.firstName,l.lastName].filter(Boolean).join(" ");g&&a.set(c,g)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?a.get(c.createdBy)??c.createdBy:null})),paging:{total:i.totalItems,currentPage:i.pageNumber,perPage:i.pageSize}}},validateUser:async(e,n,t)=>({isValid:!0}),isOrganizationMember:async(e,n,t)=>{const{clients:{commerce:r}}=t;return!!(await r.session("").catch(()=>null))?.namespaces.authentication?.unitId?.value},userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,s=Z(V(i?.cookie??"",r))?.userId??"",[c,l,g]=await Promise.all([o.session("").catch(()=>null),s?o.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?o.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),u=l?.[0],h=c?.namespaces.authentication??null,f=`${(u?.firstName??"").trim()} ${(u?.lastName??"").trim()}`.trim();return{username:h?.storeUserEmail?.value??"",name:f,email:h?.storeUserEmail?.value??"",phone:u?.phone??"",role:g?.Roles?.map(v=>v.Name)??[],orgUnit:h?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,a=Z(V(i?.cookie??"",r));if(!a?.userId)return null;if(a?.isRepresentative){const c=await o.session("").catch(()=>null);if(!c)return null;const l=c.namespaces.profile??null,g=c.namespaces.shopper??null,u=c.namespaces.authentication??null,h=Ye(c)||a?.customerId?.trim()||"";let f=null;if(h)try{f=await o.masterData.getContractById({contractId:h})}catch(p){console.error(`Error while getting contract data for contract ID (${h}).`,p)}const v=`${(g?.firstName?.value??"").trim()} ${(g?.lastName?.value??"").trim()}`.trim();return{name:Rn(f,l)||v||"",email:l?.email?.value||u?.storeUserEmail?.value||"",id:l?.id?.value||u?.customerId?.value||a?.customerId?.trim()||""}}const s=await o.licenseManager.getUserById({userId:a?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},availableContracts:async(e,{orgUnitId:n},t)=>{if(!n)throw new E("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:o}}=t,a=await o.session("").catch(()=>null),s=V(i?.cookie??"",r);let c=null;try{c=s?Z(s):null}catch{c=null}const l=a?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!l||l!==n)throw new x("You are not allowed to list contracts for this organization unit");const g=$r(a?.namespaces.shopper),u=Ye(a)||c?.customerId?.trim()||"";return zr(g,u)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:oi,orderFormItems:ai,recommendations:ii},pi={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},gi=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,mi={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(u=>({value:u.term,count:u.count})),products:[]};const{productSearchPromise:o}=e,[a,s]=await Promise.all([r.suggestedTerms(i),o]),c=s.products.map(g=>{const u=de(g.items);return u&&N(u,g)}).filter(g=>!!g),{searches:l}=a;return{terms:l.map(g=>({value:g.term,count:g.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=de(r.items);return i&&N(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),o=!e.query,a=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(l=>!o||!gi(l,a,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},hi={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},fi=["bd","d","h","m"],Si=e=>fi.includes(e),yi={bd:{0:"Today",1:"In 1 business day",other:"Up to # business days"},d:{0:"Today",1:"In 1 day",other:"Up to # days"},h:{0:"Now",1:"In 1 hour",other:"Up to # hours"},m:{0:"Now",1:"In 1 minute",other:"Up to # minutes"}},$n=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=Si(t);if(!r||!i)return"";const o=Number(n)<2?Number(n):"other";return yi[t][o].replace("#",n)??""},Ii={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?$n(e.shippingEstimate):""},Qe="skuvariation";function Ze(e,n){const t=`${Qe}${n}`.toLowerCase(),r=e.find(o=>o.imageLabel===t);if(r)return r;const i=e.find(o=>o.imageLabel===Qe);return i||e[0]}function vi(e,n,t){const r={};return e.forEach(i=>{const o=i.variations;if(o.length===0)return;const a=`${n}-${o.find(c=>c.name===n)?.values[0]??""}`,s=o.reduce((c,l)=>l.name===n?c:c+`-${l.name}-${l.values[0]}`,a);r[s]=`${t}-${i.itemId}`}),r}function en(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function Oi(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Ci(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function bi(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,o)=>Ci(i.value,o.value));return n}function wi(e,n,t){const r={},i=new Set;return e.forEach(o=>{if(o.variations.length===0)return;const a=o.variations.find(c=>c.name===n);if(!(a?.values[0]===t)){const c=`${n}-${a?.values[0]}`;if(!a||i.has(c))return;i.add(c);const l=Ze(o.images,n),g={src:l.imageUrl,alt:l.imageLabel??"",label:`${n}: ${a.values[0]}`,value:a.values[0]};r[a.name]?r[a.name].push(g):r[a.name]=[g];return}o.variations.forEach(c=>{const l=`${c.name}-${c.values[0]}`;if(i.has(l))return;i.add(l);const g=Ze(o.images,c.name),u={src:g.imageUrl,alt:g.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(u):r[c.name]=[u]})}),bi(r)}const Di={activeVariations:e=>en(e.variations),allVariantsByName:e=>Oi(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>vi(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=en(e.variations)[t];return wi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf))},Ai={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Pi={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],o=r.reduce((l,g)=>{const u=g?.selectedSla||"",h=g?.selectedDeliveryChannel||g?.deliveryChannel||"",f=g?.deliveryCompany||"",v=g?.deliveryWindow,d=g?.pickupStoreInfo,p=g?.shippingEstimate||"",m=g?.shippingEstimate?$n(g?.shippingEstimate):"",y=g?.shippingEstimateDate||"",O=g?.addressId||"",w=g?.itemIndex??0,C=t?.[w],P=C?.seller||"",S=`${u}|${h}|${f}|${P}|${p}|${y}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(U=>U?.addressId===O),A=`${Ai[h]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:T,taxPriceTags:b}=Ei(C?.priceTags??[]),k=(C?.sellingPrice??0)*(C?.quantity??0)+(C?.tax??0)+(T??0);return l[S]||(l[S]={selectedSla:u,deliveryChannel:h,deliveryCompany:f,deliveryWindow:v,shippingEstimate:p,shippingEstimateDate:y,seller:P,friendlyShippingEstimate:m,friendlyDeliveryOptionName:A,address:D,pickupStoreInfo:d,quantityOfDifferentItems:0,total:0,items:[]}),l[S]&&(l[S].items?.push({id:C?.id||"",uniqueId:C?.uniqueId||"",name:C?.name||"",quantity:C?.quantity||0,price:C?.price||0,sellingPrice:C?.sellingPrice||0,imageUrl:C?.imageUrl||"",taxPriceTags:b??[],taxPriceTagsTotal:T??0,tax:C?.tax||0,total:k}),l[S].quantityOfDifferentItems=(l[S].quantityOfDifferentItems??0)+1,l[S].total=(l[S].total??0)+k),l},{}),a=Object.values(o),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||a?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:a,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",o=r?.linkedEntity?.id||"",a=`${i}|${o||""}`;return t[a]||(t[a]={type:i,id:o,fields:[]}),t[a].fields.push(...r?.fields||[]),t},{}))||[]}};function Ei(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,o)=>i+(o.rawValue?o.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const Ti={StoreCollection:Cn,StoreAggregateOffer:nr,StoreProduct:Zr,StoreSeo:hi,StoreFacet:dr,StoreFacetBoolean:ur,StoreFacetRange:pr,StoreFacetValueBoolean:gr,StoreOffer:Hr,StoreAggregateRating:tr,StoreReview:pi,StoreProductGroup:ni,StoreSearchResult:mi,StorePropertyValue:ti,SkuVariants:Di,ShippingSLA:Ii,UserOrderResult:Pi,ObjectOrString:Gr,Query:ui,Mutation:xr},ki=()=>Ti,Ui=`"""
|
|
7
|
+
More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},$r=(e,n)=>{const r=e.customData?.customApps.find(o=>o.id==="faststore")?.fields?.cartEtag;return r==null?!0:Nn(e,n)!==r},Mr=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),Xe=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=kn(e,n);if(r){const o=Tr(e,n,i),s=o||Er(n);return!!n.deliveryMode?.deliveryWindow&&await t.checkout.shippingData({id:e.orderFormId,index:e.items.length,deliveryMode:n.deliveryMode,selectedAddresses:s},!1),t.checkout.shippingData({id:e.orderFormId,index:e.items.length,deliveryMode:n.deliveryMode,selectedAddresses:s},!0)}return e},zr=(e,n)=>{if(!e)return"";const r=ne.parse(e)[n];return r?r.split("=")[1]:""},Ye=(e,n)=>{const t=Pr(e.storage.channel,n.salesChannel);return t?(le(e,t),n.salesChannel?String(n.salesChannel):null):null},Je=(e,n,t,r)=>r?Ce(e,n,t,r):null,qr=async(e,{cart:{order:n},session:t},r)=>{const i=zr(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:o},loaders:{skuLoader:a}}=r,s=t?.channel,c=t?.locale;s&&le(r,s),c&&ve(r,c);const d=i||void 0,u=await o.checkout.orderForm({id:d,channel:r.storage.channel,preserveSalesChannel:!!d}),p=u.orderFormId;u.messages.length!==0&&await Mr(p,r);const f=ne.parse(r?.headers?.cookie??"")?.vtex_session,h=Q(f),{acceptedOffer:v,shouldSplitItem:l}=n;if($r(u,h)){const C=Ye(r,u),L=await He(u,o,h).then(Ge);if(p)return Ce(L,a,l,C)}const m=Ye(r,u),S=We(v),O=We(u.items.map(de)),w=Array.from(O.entries()),b=Array.from(S.entries()),{itemsToAdd:U,itemsToUpdate:I}=b.reduce((C,[L,Ee])=>{const Te=O.get(L);if(!Te)return Ee.forEach(G=>C.itemsToAdd.push(G)),C;const[ie,...xn]=Te;if(Fn(u.items,ie.itemOffered.sku)||Rn(u.items,ie.itemOffered.sku))return C.itemsToUpdate.push(ie),C;const jn=Ee.reduce((G,Wn)=>G+Wn.quantity,0);return C.itemsToUpdate.push({...ie,quantity:jn}),xn.forEach(G=>C.itemsToUpdate.push({...G,quantity:0})),C},{itemsToAdd:[],itemsToUpdate:[]}),D=w.filter(([C])=>!S.has(C)).flatMap(([,C])=>C.map(L=>({...L,quantity:0}))),P=[...U,...I,...D].map(Lr),{updateShipping:E}=t?kn(u,t):{updateShipping:!1};if(P.length===0&&!E)return Je(u,a,l,m);let A;P.length>0?A=await o.checkout.updateOrderFormItems({id:u.orderFormId,orderItems:P,shouldSplitItem:l}).then(C=>Xe(C,t,r)):A=await Xe(u,t,r),A=await Promise.resolve(A).then(C=>{if(t?.marketingData){const L={...C.marketingData,...t.marketingData};return o.checkout.marketingData({id:u.orderFormId,marketingData:L})}return C}).then(C=>c&&C.clientPreferencesData?.locale!==c?o.checkout.clientPreferencesData({id:C.orderFormId,clientPreferencesData:{...C.clientPreferencesData,locale:c}}):C).then(C=>He(C,o,h)).then(Ge);const R=Ae(u.messages,A.messages);return Br(n,A)&&R?Je(A,a,l,m):Ce(A,a,l,m)};function Vr(e,n,t,r){const i=e.hasOnlyDefaultSalesChannel===!1,o=n??void 0,a=t??e.regionId;return te.stringify({salesChannel:i?e.salesChannel||o:o??e.salesChannel,regionId:a??void 0,seller:r,hasOnlyDefaultSalesChannel:i?!1:!o})}const xr=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},jr=e=>{if(!e||typeof e!="object")return!1;const n=e;return typeof n.customerId=="string"&&n.customerId.trim()!==""&&typeof n.contractName=="string"&&typeof n.isActive=="boolean"&&typeof n.isCurrent=="boolean"},Wr=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(jr):[]},Gr=e=>e?.customerId?!!((e.contractName??"").trim()&&e.isActive):!1,Ke=e=>e?.namespaces?.shopper?.activeContractId?.value?.trim()??e?.namespaces?.authentication?.customerId?.value?.trim()??e?.namespaces?.profile?.id?.value?.trim()??"",Hr=(e,n="")=>{const t=n.trim();return e.filter(Gr).map(r=>({id:r.customerId,corporateName:r.contractName.trim(),isActive:t?r.customerId===t:r.isCurrent}))},Ln=(e,n)=>{const t=xr(e);return t||(n?.firstName?.value??"").trim()};async function Xr(e,n,t){try{const r=await e.commerce.checkout.address({postalCode:t,country:n}),i=r.geoCoordinates?{latitude:r.geoCoordinates[1],longitude:r.geoCoordinates[0]}:null;return{city:r.city,geoCoordinates:i}}catch(r){throw console.error(`Error while getting geo coordinates for the current postal code (${t}) and country (${n}).
|
|
8
|
+
`),r}}function Yr(e,n,t,r,i,o){const a=new URLSearchParams(e);return a.has("facets")&&a.delete("facets"),a.set("sc",a.get("sc")??n.salesChannel),t&&a.set("postalCode",t),r&&a.set("country",r),i&&a.set("geoCoordinates",`${i.longitude},${i.latitude}`),a.set("locale",o),a}function Jr(e,n){return{utmCampaign:e.get("utm_campaign")??n?.utmCampaign??"",utmMedium:e.get("utm_medium")??n?.utmMedium??"",utmSource:e.get("utm_source")??n?.utmSource??"",utmiCampaign:e.get("utmi_cp")??n?.utmiCampaign??"",utmiPage:e.get("utmi_p")??n?.utmiPage??"",utmiPart:e.get("utmi_pc")??n?.utmiPart??""}}async function Kr(e,n,t){const r=Q(V(n??"",t));let i=!1;if(r)try{i=(await e.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(o){console.warn("JWT validation failed:",o),i=!1}return{isRepresentative:i?!!r?.isRepresentative:!1,customerId:i?r?.customerId:void 0,unitId:i?r?.unitId:void 0}}async function Qr(e,n,t,r,i,o){return!n.seller||!(t||r)?void 0:(await e.commerce.checkout.region({postalCode:t,geoCoordinates:r,country:i,salesChannel:o}))?.[0]?.sellers.find(c=>n.seller===c.id)?.id}function Qe(e){return typeof e?.value=="string"?e.value:""}function Zr(e){if(!e.isRepresentative)return null;const n=Qe(e.shopper?.firstName),t=Qe(e.shopper?.lastName);return{isRepresentative:!0,customerId:e.authentication?.customerId?.value??e.customerId??"",unitName:e.authentication?.unitName?.value??"",unitId:e.authentication?.unitId?.value??e.unitId??"",firstName:n,lastName:t,userName:`${n} ${t}`.trim(),userEmail:e.authentication?.storeUserEmail?.value??"",savedPostalCode:e.publicData?.postalCode?.value??"",contractName:Ln(e.contract,e.profile),organizationManager:e.shopper?.organizationManager?.value??!1}}function ei(e){return e?.id?{id:e.id?.value??"",email:e.email?.value??"",givenName:e.firstName?.value??"",familyName:e.lastName?.value??""}:null}const ni=async(e,{session:n,search:t},{clients:r,headers:i,account:o})=>{const a=te.parse(n.channel??""),s=String(n.postalCode??""),c=n.country??"";let d=n.city??null,u=n.geoCoordinates??null;if((!d||!u)&&s!==""&&c!==""){const A=await Xr(r,c,s);d=A.city,u=A.geoCoordinates}const f=Yr(t,a,s,c,u,n.locale),h=Jr(f,n.marketingData),{isRepresentative:v,customerId:l,unitId:g}=await Kr(r,i?.cookie,o),m=await r.commerce.session(f.toString()).catch(()=>null),S=m?.namespaces.profile??null,O=m?.namespaces.shopper??null,w=m?.namespaces.store??null,b=m?.namespaces.authentication??null,U=m?.namespaces.checkout??null,I=m?.namespaces.public??null;let D=null;if(v&&S?.id?.value)try{D=await r.commerce.masterData.getContractById({contractId:S.id.value})}catch{console.error(`Error while getting contract data for profile ID (${S.id.value}).
|
|
9
|
+
`)}const P=await Qr(r,a,s,u,c,f.get("sc")??a.salesChannel),E={...n,currency:{code:w?.currencyCode?.value??n.currency.code,symbol:w?.currencySymbol?.value??n.currency.symbol},country:w?.countryCode?.value??c,channel:Vr(a,w?.channel?.value,U?.regionId?.value,P),b2b:Zr({isRepresentative:v,authentication:b,shopper:O,publicData:I,profile:S,contract:D,customerId:l,unitId:g}),marketingData:h,person:ei(S),geoCoordinates:u?.latitude&&u?.longitude&&u||null,city:d};return Ae(n,E)?null:E},ti={validateCart:qr,validateSession:ni,subscribeToNewsletter:wr,cancelOrder:Ir,processOrderAuthorization:Or,uploadFileToOrderEntry:Dr,startOrderEntryOperation:Cr,startRecommendationSession:br};var be;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(be||(be={}));const ri=e=>typeof e=="string"?Bn(e):null;function Bn(e){try{return JSON.parse(e)}catch{return e}}const ii=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,oi=new se.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:ri,serialize:ii,parseLiteral(e){return e.kind===be.STRING?Bn(e.value):null}}),k=e=>"Price"in e&&"seller"in e&&"product"in e,_=e=>"skuName"in e,ai={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>k(e)?e.PriceValidUntil??"":_(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>k(e)?$e($(e)):_(e)?$e(ir(e.availability)):null,seller:(e,n,t)=>k(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:_(e)?{identifier:e.seller}:null,price:e=>k(e)?j(e):_(e)?e.sellingPrice/100:null,priceWithTaxes:e=>k(e)?M(j(e),e?.Tax,e.product.unitMultiplier):_(e)?M(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>k(e)?rr(e):_(e)?e.sellingPrice/100:null,listPrice:e=>k(e)?e.ListPrice??0:_(e)?e.listPrice/100:null,listPriceWithTaxes:e=>k(e)?M(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):_(e)?M(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>k(e)?e.product:_(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>k(e)?e.AvailableQuantity??0:_(e)?e.quantity:null,isGift:e=>_(e)?e.isGift??!1:null,priceToken:e=>k(e)?e.PriceToken??null:null},si=({linkText:e})=>`/${e}/p`,ci=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),li={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},ae=(e,n)=>`${e}-${n}`,Ze=(e,n)=>`/${ae(e,n)}/p`,di=e=>Array.isArray(e)&&e.length>0?e:null;function we(e){return e.replace(/^\/+|\/+$/g,"")}async function De(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,o=i.get(r);if(o)return o;const a=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch{return null}})();return i.set(r,a),a}const ui=(e,n)=>{const t=e.findIndex(r=>we(r).split("/").at(-1)===n);return t<0?0:t},pi={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>ae(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:si(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:o,categoryId:a,categoriesIds:s,productId:c},itemId:d}=e,u=ui(s,a),p=r[u],f=we(p).split("/"),h=t.storage.locale;if(ee(t)&&h){const v=await De(t,c,h);if(v){const l=new Set(we(s[u]).split("/").filter(Boolean)),g=v.categories.filter(S=>l.has(S.id.toString())).sort((S,O)=>S.fullPath.split("/").length-O.fullPath.split("/").length);if(g.length===f.length)return{itemListElement:[...g.map((S,O)=>({name:S.name,item:`/${S.fullPathUriName}/`,position:O+1})),{name:i,item:Ze(v.linkId,d),position:f.length+1}],numberOfItems:f.length}}}return{itemListElement:[...f.map((v,l)=>{const g=`/${f.slice(0,l+1).map(ce).join("/")}/`;return{name:v,item:g,position:l+1}}),{name:i,item:Ze(o,d),position:f.length+1}],numberOfItems:f.length}},image:({images:e},n)=>{const t=(di(e)??[li]).map(({imageUrl:s,imageText:c,imageLabel:d})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:d}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const o=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let a=o?t.filter(({keywords:s})=>s===r):t;return a=a.length===0?t:a,a.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>ci({offer:n.commertialOffer,seller:n,product:e})).sort(wn),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:a,values:s})=>s.map(c=>({name:a,value:c,valueReference:re.specification}))),i=n.map(Tn),o=t.map(Ar);return[...r,...i,...o]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!ee(t))return null;const r=vt(t);if(r.length===0)return null;const i=e.isVariantOf.productId,o=e.itemId,a=t.storage.locale,s=Ot(t),c=await De(t,i,a);if(!c?.availableLinkIds)return null;const{availableLinkIds:d}=c,{linkText:u}=e.isVariantOf;return r.map(p=>{if(p===s)return{locale:p,slug:ae(u,o)};const f=d[p];return f?{locale:p,slug:ae(f,o)}:null}).filter(p=>p!==null)}},gi=new Set(["allSpecifications"]),mi={hasVariant:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!gi.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},hi={propertyID:e=>e.propertyID||Un(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},ue=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Ie(n,({offer:r},{offer:i})=>wn(r,i));return t?t.sku:e[0]},$n=e=>e!==""&&!Number.isNaN(Number(e)),fi=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,Si=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:o}}=i,{salesChannel:a}=i.storage.channel,s=n?.trim();if(!s||!fi.test(s))throw new T(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new T("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(h=>!h?.trim())))throw new T("Invalid products: must be an array of non-empty strings");const d=await o.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:a??void 0,locale:i.storage.locale}),{campaign:u,correlationId:p}=d;return{products:(d.products??[]).map(h=>{const v=ue(h.items);return v?F(v,h):null}).filter(h=>!!h),correlationId:p,campaign:u}},en={price_desc:"price:desc",price_asc:"price:asc",orders_desc:"orders:desc",name_desc:"name:desc",name_asc:"name:asc",release_desc:"release:desc",discount_desc:"discount:desc",score_desc:""},yi=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing operationId");return t.orderEntry.getOperation({operationId:n})},Ii=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing orderFormId");const{items:r}=await t.orderEntry.getOrderFormItems({orderFormId:n});return(r??[]).map(i=>({id:i.id,name:i.name,price:i.price,listPrice:i.listPrice,quantity:i.quantity,imageUrl:i.imageUrl??null,availability:i.availability,seller:i.seller,unitMultiplier:i.unitMultiplier??1}))};async function vi(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await De(e,t,r))?.linkId===i}const Mn="Invalid SkuId",zn="Slug was set but the fetched sku does not satisfy the slug condition.",Oi=e=>q(e)||e instanceof Error&&(e.message===Mn||e.message.startsWith(zn));async function Ci(e,n,t,r){const{linkText:i,productId:o}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||ee(e)&&r&&$n(t.split("-").pop()??"")&&await vi(e,t,o,r)))throw new Error(`${zn} slug: ${t}, linkText: ${i}`)}async function bi(e,n){if(n==null)throw new T("Missing slug or id");const{clients:{commerce:t,search:r}}=e,i=await t.catalog.portal.pagetype(`${n}/p`);if(i.pageType!=="Product"||!i.id)throw new N(`No product found for slug ${n}`);const o=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!o)throw new N(`No product found for id ${i.id}`);return F(ue(o.items),o)}const wi={product:async(e,{locator:n},t)=>{const r=je(n),i=xe(n),o=mr(n),a=gr(n);r&&le(t,r),i&&ve(t,i);const{loaders:{skuLoader:s}}=t;try{const c=o??a?.split("-").pop()??"";if(!$n(c))throw new Error(Mn);const d=await s.load(c);return await Ci(t,d,a,i),d}catch(c){if(!Oi(c))throw c;return bi(t,a)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:oe(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:o,sponsoredCount:a},s)=>{const c=je(o),d=xe(o),u=pr(o);c&&le(s,c),d&&ve(s,d);const p=t?Number(t):0,f={page:Math.ceil(p/n)||0,count:n,query:i??void 0,sort:en[r??"score_desc"]??en.score_desc,selectedFacets:o?.flatMap(qe)??[],sponsoredCount:a??void 0};if(u){const l=(await s.clients.commerce.catalog.products.crossselling({type:Pn[u.key],productId:u.value})).map(m=>m.productId).slice(0,n),g=s.clients.search.productsByIdentifier({field:"id",values:l}).then(m=>({products:m,recordsFiltered:m.length,pagination:{count:m.length,current:{index:0,proxyURL:""},before:[],after:[],perPage:n,next:{index:0,proxyURL:""},previous:{index:0,proxyURL:""},first:{index:0,proxyURL:""},last:{index:0,proxyURL:""}},sampling:!1,options:{sorts:[],counts:[]},translated:!1,locale:"",query:"",operator:"and",fuzzy:"0",searchId:""}));return{searchArgs:f,productSearchPromise:g}}const h=s.clients.search.products(f);return{searchArgs:f,productSearchPromise:h}},allProducts:async(e,{first:n,after:t},r)=>{const{clients:{search:i}}=r,o=t?Number(t):0,a=await i.products({page:Math.ceil(o/n),count:n}),s=a.products.flatMap(c=>c.items.map(d=>F(d,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:a.pagination.after.length>0,hasPreviousPage:a.pagination.before.length>0,startCursor:"0",endCursor:a.recordsFiltered.toString(),totalCount:a.recordsFiltered},edges:s.map((c,d)=>({node:c,cursor:(o+d).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(o=>o.items.map(a=>F(a,o))).filter(o=>n.includes(o.itemId)&&o.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,o=t?Number(t):0,[a,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],d=(h,v)=>{c.push({id:h.id,name:h.name,fatherCategoryId:v,linkId:ce(h.name),title:h.Title,description:null,metaTagDescription:h.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(h.url).pathname.slice(1).toLowerCase()});for(const l of h.children)d(l,h.id)};for(const h of s)d(h,null);const f=[...a.filter(h=>h.isActive).map(h=>({id:h.id,name:h.name,linkId:ce(h.name),title:h.title,description:null,metaTagDescription:h.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(h=>!!Dn.slug(h,null,r,null));return{pageInfo:{hasNextPage:f.length-o>n,hasPreviousPage:o>0,startCursor:"0",endCursor:(Math.min(n,f.length-o)-1).toString(),totalCount:f.length},edges:f.slice(o,o+n).map((h,v)=>({node:h,cursor:(o+v).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:o},clients:{commerce:a}}=i,[s,c]=await Promise.all([o.load({country:n,items:t,postalCode:r}),a.checkout.address({postalCode:r,country:n})]);return{...s,address:c}},redirect:async(e,{term:n,selectedFacets:t},r)=>{if(!n&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:n??void 0,selectedFacets:t?.flatMap(qe)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},o)=>{const{clients:{commerce:a}}=o,c=(await a.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:d,sellers:u}=c;return{id:d,sellers:u}},profile:async(e,{id:n},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(n);function o(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:o(i)}},productCount:async(e,{term:n},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:n??void 0})},userOrder:async(e,{orderId:n},t)=>{try{if(!n)throw new T("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new N(`No order found for id ${n}`);let o=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});o=An(c)}catch{}const s=(await r.masterData.getShopperById({userId:i.purchaseAgentData?.purchaseAgents?.[0]?.userId??""})??[])[0]??{};return{orderId:i.orderId,creationDate:i.creationDate,totals:i.totals,items:i.items,shippingData:i.shippingData,paymentData:i.paymentData,customData:i.customData,status:i.status,statusDescription:i.statusDescription,allowCancellation:i.allowCancellation,storePreferencesData:i.storePreferencesData,clientProfileData:i.clientProfileData,canProcessOrderAuthorization:(i.status==="waiting-for-confirmation"||i.status==="waiting-for-authorization")&&!!o,ruleForAuthorization:o,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let o={};try{const s=JSON.parse(i);o=s.error||s}catch{o={message:i}}const a=o?.message||i;throw q(r)?new N(`No order found for id ${n}. ${a}.`):yn(r)?new x(`You are forbidden to interact with order with id ${n}. ${a}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(o=>({orderId:o.orderId,creationDate:o.creationDate,clientName:o.clientName,items:o.items,totalValue:o.totalValue,status:o.status,statusDescription:o.statusDescription,ShippingEstimatedDate:o.ShippingEstimatedDate,customFields:o.customFields,currencyCode:o.currencyCode})),paging:i.paging}},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),o=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],a=new Map;return await Promise.all(o.map(async c=>{try{const[d]=await r.masterData.getShopperById({userId:c});if(d){const u=[d.firstName,d.lastName].filter(Boolean).join(" ");u&&a.set(c,u)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?a.get(c.createdBy)??c.createdBy:null})),paging:{total:i.totalItems,currentPage:i.pageNumber,perPage:i.pageSize}}},validateUser:async(e,n,t)=>({isValid:!0}),isOrganizationMember:async(e,n,t)=>{const{clients:{commerce:r}}=t;return!!(await r.session("").catch(()=>null))?.namespaces.authentication?.unitId?.value},userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,s=Q(V(i?.cookie??"",r))?.userId??"",[c,d,u]=await Promise.all([o.session("").catch(()=>null),s?o.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?o.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),p=d?.[0],f=c?.namespaces.authentication??null,h=`${(p?.firstName??"").trim()} ${(p?.lastName??"").trim()}`.trim();return{username:f?.storeUserEmail?.value??"",name:h,email:f?.storeUserEmail?.value??"",phone:p?.phone??"",role:u?.Roles?.map(v=>v.Name)??[],orgUnit:f?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,a=Q(V(i?.cookie??"",r));if(!a?.userId)return null;if(a?.isRepresentative){const c=await o.session("").catch(()=>null);if(!c)return null;const d=c.namespaces.profile??null,u=c.namespaces.shopper??null,p=c.namespaces.authentication??null,f=Ke(c)||a?.customerId?.trim()||"";let h=null;if(f)try{h=await o.masterData.getContractById({contractId:f})}catch(g){console.error(`Error while getting contract data for contract ID (${f}).`,g)}const v=`${(u?.firstName?.value??"").trim()} ${(u?.lastName?.value??"").trim()}`.trim();return{name:Ln(h,d)||v||"",email:d?.email?.value||p?.storeUserEmail?.value||"",id:d?.id?.value||p?.customerId?.value||a?.customerId?.trim()||""}}const s=await o.licenseManager.getUserById({userId:a?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},availableContracts:async(e,{orgUnitId:n},t)=>{if(!n)throw new T("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:o}}=t,a=await o.session("").catch(()=>null),s=V(i?.cookie??"",r);let c=null;try{c=s?Q(s):null}catch{c=null}const d=a?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!d||d!==n)throw new x("You are not allowed to list contracts for this organization unit");const u=Wr(a?.namespaces.shopper),p=Ke(a)||c?.customerId?.trim()||"";return Hr(u,p)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:yi,orderFormItems:Ii,recommendations:Si},Di={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},Pi=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,Ai={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(p=>({value:p.term,count:p.count})),products:[]};const{productSearchPromise:o}=e,[a,s]=await Promise.all([r.suggestedTerms(i),o]),c=s.products.map(u=>{const p=ue(u.items);return p&&F(p,u)}).filter(u=>!!u),{searches:d}=a;return{terms:d.map(u=>({value:u.term,count:u.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=ue(r.items);return i&&F(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),o=!e.query,a=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(d=>!o||!Pi(d,a,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},Ei={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},Ti=["bd","d","h","m"],Ui=e=>Ti.includes(e),ki={bd:{0:"Today",1:"In 1 business day",other:"Up to # business days"},d:{0:"Today",1:"In 1 day",other:"Up to # days"},h:{0:"Now",1:"In 1 hour",other:"Up to # hours"},m:{0:"Now",1:"In 1 minute",other:"Up to # minutes"}},qn=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=Ui(t);if(!r||!i)return"";const o=Number(n)<2?Number(n):"other";return ki[t][o].replace("#",n)??""},_i={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?qn(e.shippingEstimate):""},nn="skuvariation";function tn(e,n){const t=`${nn}${n}`.toLowerCase(),r=e.find(o=>o.imageLabel===t);if(r)return r;const i=e.find(o=>o.imageLabel===nn);return i||e[0]}function Ri(e,n,t){const r={};return e.forEach(i=>{const o=i.variations;if(o.length===0)return;const a=`${n}-${o.find(c=>c.name===n)?.values[0]??""}`,s=o.reduce((c,d)=>d.name===n?c:c+`-${d.name}-${d.values[0]}`,a);r[s]=`${t}-${i.itemId}`}),r}function rn(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function Fi(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Ni(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Li(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,o)=>Ni(i.value,o.value));return n}function Bi(e,n,t){const r={},i=new Set;return e.forEach(o=>{if(o.variations.length===0)return;const a=o.variations.find(c=>c.name===n);if(!(a?.values[0]===t)){const c=`${n}-${a?.values[0]}`;if(!a||i.has(c))return;i.add(c);const d=tn(o.images,n),u={src:d.imageUrl,alt:d.imageLabel??"",label:`${n}: ${a.values[0]}`,value:a.values[0]};r[a.name]?r[a.name].push(u):r[a.name]=[u];return}o.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const u=tn(o.images,c.name),p={src:u.imageUrl,alt:u.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(p):r[c.name]=[p]})}),Li(r)}const $i={activeVariations:e=>rn(e.variations),allVariantsByName:e=>Fi(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>Ri(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=rn(e.variations)[t];return Bi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>F(n,e.isVariantOf))},Mi={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},zi={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],o=r.reduce((d,u)=>{const p=u?.selectedSla||"",f=u?.selectedDeliveryChannel||u?.deliveryChannel||"",h=u?.deliveryCompany||"",v=u?.deliveryWindow,l=u?.pickupStoreInfo,g=u?.shippingEstimate||"",m=u?.shippingEstimate?qn(u?.shippingEstimate):"",S=u?.shippingEstimateDate||"",O=u?.addressId||"",w=u?.itemIndex??0,b=t?.[w],U=b?.seller||"",I=`${p}|${f}|${h}|${U}|${g}|${S}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(C=>C?.addressId===O),P=`${Mi[f]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:E,taxPriceTags:A}=qi(b?.priceTags??[]),R=(b?.sellingPrice??0)*(b?.quantity??0)+(b?.tax??0)+(E??0);return d[I]||(d[I]={selectedSla:p,deliveryChannel:f,deliveryCompany:h,deliveryWindow:v,shippingEstimate:g,shippingEstimateDate:S,seller:U,friendlyShippingEstimate:m,friendlyDeliveryOptionName:P,address:D,pickupStoreInfo:l,quantityOfDifferentItems:0,total:0,items:[]}),d[I]&&(d[I].items?.push({id:b?.id||"",uniqueId:b?.uniqueId||"",name:b?.name||"",quantity:b?.quantity||0,price:b?.price||0,sellingPrice:b?.sellingPrice||0,imageUrl:b?.imageUrl||"",taxPriceTags:A??[],taxPriceTagsTotal:E??0,tax:b?.tax||0,total:R}),d[I].quantityOfDifferentItems=(d[I].quantityOfDifferentItems??0)+1,d[I].total=(d[I].total??0)+R),d},{}),a=Object.values(o),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||a?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:a,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",o=r?.linkedEntity?.id||"",a=`${i}|${o||""}`;return t[a]||(t[a]={type:i,id:o,fields:[]}),t[a].fields.push(...r?.fields||[]),t},{}))||[]}};function qi(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,o)=>i+(o.rawValue?o.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const Vi={StoreCollection:Dn,StoreAggregateOffer:ar,StoreProduct:pi,StoreSeo:Ei,StoreFacet:hr,StoreFacetBoolean:fr,StoreFacetRange:Sr,StoreFacetValueBoolean:yr,StoreOffer:ai,StoreAggregateRating:sr,StoreReview:Di,StoreProductGroup:mi,StoreSearchResult:Ai,StorePropertyValue:hi,SkuVariants:$i,ShippingSLA:_i,UserOrderResult:zi,ObjectOrString:oi,Query:wi,Mutation:ti},xi=()=>Vi,ji=`"""
|
|
10
10
|
Address information.
|
|
11
11
|
"""
|
|
12
12
|
type Address {
|
|
@@ -51,7 +51,7 @@ type Address {
|
|
|
51
51
|
"""
|
|
52
52
|
geoCoordinates: [Float]
|
|
53
53
|
}
|
|
54
|
-
`,
|
|
54
|
+
`,Wi=`"""
|
|
55
55
|
Advertisement information about a specific product in a campaign
|
|
56
56
|
"""
|
|
57
57
|
type Advertisement {
|
|
@@ -76,7 +76,7 @@ type Advertisement {
|
|
|
76
76
|
"""
|
|
77
77
|
adResponseId: String!
|
|
78
78
|
}
|
|
79
|
-
`,
|
|
79
|
+
`,Gi=`"""
|
|
80
80
|
Aggregate offer information, for a given SKU that is available to be fulfilled by multiple sellers.
|
|
81
81
|
"""
|
|
82
82
|
type StoreAggregateOffer {
|
|
@@ -105,7 +105,7 @@ type StoreAggregateOffer {
|
|
|
105
105
|
"""
|
|
106
106
|
offers: [StoreOffer!]!
|
|
107
107
|
}
|
|
108
|
-
`,
|
|
108
|
+
`,Hi=`"""
|
|
109
109
|
Average rating, based on multiple ratings or reviews.
|
|
110
110
|
"""
|
|
111
111
|
type StoreAggregateRating {
|
|
@@ -118,7 +118,7 @@ type StoreAggregateRating {
|
|
|
118
118
|
"""
|
|
119
119
|
reviewCount: Int!
|
|
120
120
|
}
|
|
121
|
-
`,
|
|
121
|
+
`,Xi=`"""
|
|
122
122
|
information about the author of a product review or rating.
|
|
123
123
|
"""
|
|
124
124
|
type StoreAuthor {
|
|
@@ -127,7 +127,7 @@ type StoreAuthor {
|
|
|
127
127
|
"""
|
|
128
128
|
name: String!
|
|
129
129
|
}
|
|
130
|
-
`,
|
|
130
|
+
`,Yi=`"""
|
|
131
131
|
Brand of a given product.
|
|
132
132
|
"""
|
|
133
133
|
type StoreBrand {
|
|
@@ -136,7 +136,7 @@ type StoreBrand {
|
|
|
136
136
|
"""
|
|
137
137
|
name: String!
|
|
138
138
|
}
|
|
139
|
-
`,
|
|
139
|
+
`,Ji=`"""
|
|
140
140
|
Item of a list.
|
|
141
141
|
"""
|
|
142
142
|
type StoreListItem {
|
|
@@ -167,7 +167,7 @@ type StoreBreadcrumbList {
|
|
|
167
167
|
"""
|
|
168
168
|
numberOfItems: Int!
|
|
169
169
|
}
|
|
170
|
-
|
|
170
|
+
`,Ki=`"""
|
|
171
171
|
Shopping cart message.
|
|
172
172
|
"""
|
|
173
173
|
type StoreCartMessage {
|
|
@@ -204,7 +204,7 @@ input IStoreCart {
|
|
|
204
204
|
"""
|
|
205
205
|
order: IStoreOrder!
|
|
206
206
|
}
|
|
207
|
-
`,
|
|
207
|
+
`,Qi=`"""
|
|
208
208
|
Product collection type. Possible values are \`Department\`, \`Category\`, \`Brand\` or \`Collection\`.
|
|
209
209
|
|
|
210
210
|
\`SubCategory\` and \`Cluster\` are still declared for backward compatibility but are
|
|
@@ -319,7 +319,7 @@ type StoreCollectionLocale {
|
|
|
319
319
|
"""
|
|
320
320
|
slug: String!
|
|
321
321
|
}
|
|
322
|
-
`,
|
|
322
|
+
`,Zi=`"""
|
|
323
323
|
Delivery Promise badge.
|
|
324
324
|
"""
|
|
325
325
|
type DeliveryPromiseBadge {
|
|
@@ -328,7 +328,7 @@ type DeliveryPromiseBadge {
|
|
|
328
328
|
"""
|
|
329
329
|
typeName: String
|
|
330
330
|
}
|
|
331
|
-
`,
|
|
331
|
+
`,eo=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
|
|
332
332
|
|
|
333
333
|
"""
|
|
334
334
|
Search facet range information.
|
|
@@ -405,7 +405,7 @@ type StoreFacetValueBoolean {
|
|
|
405
405
|
"""
|
|
406
406
|
quantity: Int
|
|
407
407
|
}
|
|
408
|
-
`,
|
|
408
|
+
`,no=`"""
|
|
409
409
|
Image.
|
|
410
410
|
"""
|
|
411
411
|
type StoreImage {
|
|
@@ -432,7 +432,7 @@ input IStoreImage {
|
|
|
432
432
|
"""
|
|
433
433
|
alternateName: String!
|
|
434
434
|
}
|
|
435
|
-
`,
|
|
435
|
+
`,to=`type Mutation {
|
|
436
436
|
"""
|
|
437
437
|
Checks for changes between the cart presented in the UI and the cart stored in the ecommerce platform. If changes are detected, it returns the cart stored on the platform. Otherwise, it returns \`null\`.
|
|
438
438
|
"""
|
|
@@ -474,7 +474,7 @@ input IStoreImage {
|
|
|
474
474
|
"""
|
|
475
475
|
startRecommendationSession: Boolean!
|
|
476
476
|
}
|
|
477
|
-
`,
|
|
477
|
+
`,ro=`"""
|
|
478
478
|
Newsletter information.
|
|
479
479
|
"""
|
|
480
480
|
type PersonNewsletter {
|
|
@@ -497,8 +497,8 @@ input IPersonNewsletter {
|
|
|
497
497
|
"""
|
|
498
498
|
email: String!
|
|
499
499
|
}
|
|
500
|
-
`,
|
|
501
|
-
`,
|
|
500
|
+
`,io=`scalar ObjectOrString
|
|
501
|
+
`,oo=`"""
|
|
502
502
|
Offer information.
|
|
503
503
|
"""
|
|
504
504
|
type StoreOffer {
|
|
@@ -591,7 +591,7 @@ input IStoreOffer {
|
|
|
591
591
|
"""
|
|
592
592
|
priceToken: String
|
|
593
593
|
}
|
|
594
|
-
`,
|
|
594
|
+
`,ao=`"""
|
|
595
595
|
Information of a specific order.
|
|
596
596
|
"""
|
|
597
597
|
type StoreOrder {
|
|
@@ -607,6 +607,12 @@ type StoreOrder {
|
|
|
607
607
|
Indicates whether or not items with attachments should be split.
|
|
608
608
|
"""
|
|
609
609
|
shouldSplitItem: Boolean
|
|
610
|
+
"""
|
|
611
|
+
Sales channel of the underlying orderForm when FastStore adopted it because
|
|
612
|
+
the browser session was stale (e.g. after Quick Order). Clients should align
|
|
613
|
+
\`session.channel\` to this value. Null when no SC adoption happened.
|
|
614
|
+
"""
|
|
615
|
+
salesChannel: String
|
|
610
616
|
}
|
|
611
617
|
|
|
612
618
|
"""
|
|
@@ -626,7 +632,7 @@ input IStoreOrder {
|
|
|
626
632
|
"""
|
|
627
633
|
shouldSplitItem: Boolean
|
|
628
634
|
}
|
|
629
|
-
`,
|
|
635
|
+
`,so=`"""
|
|
630
636
|
Commercial Authorization response.
|
|
631
637
|
"""
|
|
632
638
|
type CommercialAuthorizationResponse {
|
|
@@ -1025,7 +1031,7 @@ type ProcessOrderAuthorizationRule {
|
|
|
1025
1031
|
"""
|
|
1026
1032
|
rule: CommercialAuthorizationRule!
|
|
1027
1033
|
}
|
|
1028
|
-
`,
|
|
1034
|
+
`,co=`"""
|
|
1029
1035
|
Input for uploading a file to the Order Entry Service.
|
|
1030
1036
|
The file is transmitted as a Base64-encoded string so it can travel
|
|
1031
1037
|
through the standard GraphQL JSON pipeline without multipart support.
|
|
@@ -1086,7 +1092,7 @@ type StoreOrderFormCartItem {
|
|
|
1086
1092
|
seller: String!
|
|
1087
1093
|
unitMultiplier: Float
|
|
1088
1094
|
}
|
|
1089
|
-
`,
|
|
1095
|
+
`,lo=`"""
|
|
1090
1096
|
Organization.
|
|
1091
1097
|
"""
|
|
1092
1098
|
type StoreOrganization {
|
|
@@ -1123,7 +1129,7 @@ type StoreContract {
|
|
|
1123
1129
|
"""
|
|
1124
1130
|
isActive: Boolean!
|
|
1125
1131
|
}
|
|
1126
|
-
`,
|
|
1132
|
+
`,uo=`"""
|
|
1127
1133
|
Whenever you make a query that allows for pagination, such as \`allProducts\` or \`allCollections\`, you can check \`StorePageInfo\` to learn more about the complete set of items and use it to paginate your queries.
|
|
1128
1134
|
"""
|
|
1129
1135
|
type StorePageInfo {
|
|
@@ -1148,7 +1154,7 @@ type StorePageInfo {
|
|
|
1148
1154
|
"""
|
|
1149
1155
|
totalCount: Int!
|
|
1150
1156
|
}
|
|
1151
|
-
`,
|
|
1157
|
+
`,po=`"""
|
|
1152
1158
|
Input type for setting a new password.
|
|
1153
1159
|
"""
|
|
1154
1160
|
input ISetPassword {
|
|
@@ -1191,7 +1197,7 @@ type SetPasswordResponse {
|
|
|
1191
1197
|
"""
|
|
1192
1198
|
message: String
|
|
1193
1199
|
}
|
|
1194
|
-
`,
|
|
1200
|
+
`,go=`"""
|
|
1195
1201
|
Client profile data.
|
|
1196
1202
|
"""
|
|
1197
1203
|
type StorePerson {
|
|
@@ -1234,7 +1240,7 @@ input IStorePerson {
|
|
|
1234
1240
|
"""
|
|
1235
1241
|
familyName: String!
|
|
1236
1242
|
}
|
|
1237
|
-
`,
|
|
1243
|
+
`,mo=`type PickupPointAddress {
|
|
1238
1244
|
"""
|
|
1239
1245
|
Address city.
|
|
1240
1246
|
"""
|
|
@@ -1313,7 +1319,7 @@ type PickupPoints {
|
|
|
1313
1319
|
"""
|
|
1314
1320
|
pickupPointsHash: String
|
|
1315
1321
|
}
|
|
1316
|
-
`,
|
|
1322
|
+
`,ho=`"""
|
|
1317
1323
|
Product information. Products are variants within product groups, equivalent to VTEX [SKUs](https://help.vtex.com/en/tutorial/what-is-an-sku--1K75s4RXAQyOuGUYKMM68u#). For example, you may have a **Shirt** product group with associated products such as **Blue shirt size L**, **Green shirt size XL** and so on.
|
|
1318
1324
|
"""
|
|
1319
1325
|
type StoreProduct {
|
|
@@ -1481,7 +1487,7 @@ input IStoreProduct {
|
|
|
1481
1487
|
"""
|
|
1482
1488
|
additionalProperty: [IStorePropertyValue!]
|
|
1483
1489
|
}
|
|
1484
|
-
`,
|
|
1490
|
+
`,fo=`"""
|
|
1485
1491
|
Product group information. Product groups are catalog entities that may contain variants. They are equivalent to VTEX [Products](https://help.vtex.com/en/tutorial/what-is-a-product--2zrB2gFCHyQokCKKE8kuAw#), whereas each variant is equivalent to a VTEX [SKU](https://help.vtex.com/en/tutorial/what-is-an-sku--1K75s4RXAQyOuGUYKMM68u#). For example, you may have a **Shirt** product group with associated products such as **Blue shirt size L**, **Green shirt size XL** and so on.
|
|
1486
1492
|
"""
|
|
1487
1493
|
type StoreProductGroup {
|
|
@@ -1508,7 +1514,7 @@ type StoreProductGroup {
|
|
|
1508
1514
|
"""
|
|
1509
1515
|
skuVariants: SkuVariants
|
|
1510
1516
|
}
|
|
1511
|
-
`,
|
|
1517
|
+
`,So=`type Profile {
|
|
1512
1518
|
"""
|
|
1513
1519
|
Collection of user's address
|
|
1514
1520
|
"""
|
|
@@ -1569,7 +1575,7 @@ type ProfileAddress {
|
|
|
1569
1575
|
"""
|
|
1570
1576
|
geoCoordinate: [Float]
|
|
1571
1577
|
}
|
|
1572
|
-
`,
|
|
1578
|
+
`,yo=`"""
|
|
1573
1579
|
Properties that can be associated with products and products groups.
|
|
1574
1580
|
"""
|
|
1575
1581
|
type StorePropertyValue {
|
|
@@ -1609,7 +1615,7 @@ input IStorePropertyValue {
|
|
|
1609
1615
|
"""
|
|
1610
1616
|
valueReference: ObjectOrString!
|
|
1611
1617
|
}
|
|
1612
|
-
`,
|
|
1618
|
+
`,Io=`"""
|
|
1613
1619
|
Each product edge contains a \`node\`, with product information, and a \`cursor\`, that can be used as a reference for pagination.
|
|
1614
1620
|
"""
|
|
1615
1621
|
type StoreProductEdge {
|
|
@@ -2239,7 +2245,7 @@ type StoreAccountProfile {
|
|
|
2239
2245
|
email: String
|
|
2240
2246
|
id: String
|
|
2241
2247
|
}
|
|
2242
|
-
`,
|
|
2248
|
+
`,vo=`"""
|
|
2243
2249
|
Summary of a quote returned in list results.
|
|
2244
2250
|
"""
|
|
2245
2251
|
type UserQuoteSummary {
|
|
@@ -2304,7 +2310,7 @@ type UserQuoteListPaging {
|
|
|
2304
2310
|
"""
|
|
2305
2311
|
perPage: Int!
|
|
2306
2312
|
}
|
|
2307
|
-
`,
|
|
2313
|
+
`,Oo=`type RecommendationResponse {
|
|
2308
2314
|
products: [StoreProduct!]!
|
|
2309
2315
|
correlationId: String!
|
|
2310
2316
|
campaign: RecommendationCampaign!
|
|
@@ -2315,7 +2321,7 @@ type RecommendationCampaign {
|
|
|
2315
2321
|
title: String
|
|
2316
2322
|
type: String!
|
|
2317
2323
|
}
|
|
2318
|
-
`,
|
|
2324
|
+
`,Co=`"""
|
|
2319
2325
|
Information of a given review rating.
|
|
2320
2326
|
"""
|
|
2321
2327
|
type StoreReviewRating {
|
|
@@ -2342,7 +2348,7 @@ type StoreReview {
|
|
|
2342
2348
|
"""
|
|
2343
2349
|
author: StoreAuthor!
|
|
2344
2350
|
}
|
|
2345
|
-
`,
|
|
2351
|
+
`,bo=`"""
|
|
2346
2352
|
Search Engine Optimization (SEO) tags data.
|
|
2347
2353
|
"""
|
|
2348
2354
|
type StoreSeo {
|
|
@@ -2363,7 +2369,7 @@ type StoreSeo {
|
|
|
2363
2369
|
"""
|
|
2364
2370
|
canonical: String!
|
|
2365
2371
|
}
|
|
2366
|
-
`,
|
|
2372
|
+
`,wo=`"""
|
|
2367
2373
|
Currency information.
|
|
2368
2374
|
"""
|
|
2369
2375
|
type StoreCurrency {
|
|
@@ -2638,7 +2644,7 @@ input IStoreSession {
|
|
|
2638
2644
|
"""
|
|
2639
2645
|
refreshAfter: String
|
|
2640
2646
|
}
|
|
2641
|
-
`,
|
|
2647
|
+
`,Do=`"""
|
|
2642
2648
|
Shipping Simulation item input.
|
|
2643
2649
|
"""
|
|
2644
2650
|
input IShippingItem {
|
|
@@ -2969,7 +2975,7 @@ type MessageFields {
|
|
|
2969
2975
|
"""
|
|
2970
2976
|
skuName: String
|
|
2971
2977
|
}
|
|
2972
|
-
`,
|
|
2978
|
+
`,Po=`type SkuVariants {
|
|
2973
2979
|
"""
|
|
2974
2980
|
SKU property values for the current SKU.
|
|
2975
2981
|
"""
|
|
@@ -3064,7 +3070,7 @@ Example:
|
|
|
3064
3070
|
\`\`\`
|
|
3065
3071
|
"""
|
|
3066
3072
|
scalar FormattedVariants
|
|
3067
|
-
`,
|
|
3073
|
+
`,Ao=`"""
|
|
3068
3074
|
Status used to indicate a message type. For instance, a shopping cart informative or error message.
|
|
3069
3075
|
"""
|
|
3070
3076
|
enum StoreStatus {
|
|
@@ -3072,7 +3078,7 @@ enum StoreStatus {
|
|
|
3072
3078
|
WARNING
|
|
3073
3079
|
ERROR
|
|
3074
3080
|
}
|
|
3075
|
-
`,
|
|
3081
|
+
`,Eo=`scalar JSONObject
|
|
3076
3082
|
|
|
3077
3083
|
type UserOrder {
|
|
3078
3084
|
orderId: String
|
|
@@ -3896,4 +3902,4 @@ type UserOrderBudgetAllocationLinkedEntity {
|
|
|
3896
3902
|
type: String
|
|
3897
3903
|
id: String
|
|
3898
3904
|
}
|
|
3899
|
-
`,
|
|
3905
|
+
`,To=Object.assign({"./address.graphql":ji,"./advertisement.graphql":Wi,"./aggregateOffer.graphql":Gi,"./aggregateRating.graphql":Hi,"./author.graphql":Xi,"./brand.graphql":Yi,"./breadcrumb.graphql":Ji,"./cart.graphql":Ki,"./collection.graphql":Qi,"./deliveryPromisesBadge.graphql":Zi,"./facet.graphql":eo,"./image.graphql":no,"./mutation.graphql":to,"./newsletter.graphql":ro,"./objectOrString.graphql":io,"./offer.graphql":oo,"./order.graphql":ao,"./orderCommercialAuthorizaton.graphql":so,"./orderEntry.graphql":co,"./organization.graphql":lo,"./pageInfo.graphql":uo,"./password.graphql":po,"./person.graphql":go,"./pickupPoints.graphql":mo,"./product.graphql":ho,"./productGroup.graphql":fo,"./profile.graphql":So,"./propertyValue.graphql":yo,"./query.graphql":Io,"./quote.graphql":vo,"./recommendation.graphql":Oo,"./review.graphql":Co,"./seo.graphql":bo,"./session.graphql":wo,"./shipping.graphql":Do,"./skuVariants.graphql":Po,"./status.graphql":Ao,"./userOrder.graphql":Eo}),Uo=se.print(Object.values(To).map(e=>se.parse(e)).reduce((e,n)=>on.mergeTypeDefs([e,n],{sort:!0}))),Vn=Uo,ko=async e=>n=>(n.storage={channel:te.parse(e.channel),flags:e.flags??{},locale:e.locale,cookies:new Map},n.account=e.account,n.OTEL_ENABLED=e.OTEL_ENABLED,n.discoveryConfig=e.discoveryConfig,n.clients=Gt(e,n),n.loaders=tr(e,n),n);function _o(){const e=xi(),n={};for(const[t,r]of Object.entries(e))n[t]=Object.fromEntries(Object.entries(r).map(([i,o])=>typeof o!="function"?[i,o]:[i,tt(o,`${t}(${i})`)]));return n}function Ro(e){const t=hn([mn,gn])(_o(),Vn);return e&&se.isSchema(e)?an.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=gn;exports.BadRequestError=T;exports.CacheControlDirective=mn;exports.CommercialAuthorizationStatus=sn;exports.FastStoreError=W;exports.ForbiddenError=x;exports.GraphqlVtexContextFactory=ko;exports.GraphqlVtexSchema=Ro;exports.NotFoundError=N;exports.StoreCollectionType=cn;exports.StoreFacetType=ln;exports.StoreSort=dn;exports.StoreStatus=un;exports.UnauthorizedError=K;exports.UserOrderInvoiceType=pn;exports.isBadRequestError=it;exports.isFastStoreError=rt;exports.isForbiddenError=yn;exports.isNotFoundError=q;exports.isUnauthorizedError=ot;exports.stringifyCacheControl=Zn;exports.typeDefs=Vn;exports.withDirectives=hn;
|